<commit_before>define([
	'goo/renderer/Shader',
	'goo/util/ObjectUtil'
], function (
	Shader,
	_
) {
	'use strict';

	/**
	 * A Material defines the look of an object
	 * @param {string} [name='Default Material'] Material name
	 * @param {{ vshader, fshader }} [shaderDefinition] Optional shader to associate with the material
	 */
	function Material(name, shaderDefinition) {
		this.id = null;

		/** Material name
		 * @type {string}
		 */
		this.name = 'Default Material';

		/** [Shader]{@link Shader} to use when rendering
		 * @type {Shader}
		 */
		this.shader = null;

		//! AT: horrendous type checking follows
		// function has 2 signatures because the deprecated .createMaterial had parameters in inverse order
		if (typeof arguments[0] === 'string') {
			this.name = arguments[0];
		} else if (arguments[0] && arguments[0].vshader && arguments[0].fshader) {
			this.shader = Material.createShader(arguments[0]);
		}

		if (arguments[1] && arguments[1].vshader && arguments[1].fshader) {
			this.shader = Material.createShader(arguments[1]);
		} else if (typeof arguments[1] === 'string') {
			this.name = arguments[1];
		}

		/** Possible overrides for shader uniforms
		 * @type {Object}
		 * @default
		 */
		this.uniforms = {};

		// Texture storage
		this._textureMaps = {};
		/* REVIEW
		 * There was an idea to specify and jsdoc uniforms.materialDiffuse etc instead,
		 * since those are the ones we use now
		 */
		/* Specification of colors for this Material
		 * @type {Object}
		 * @property {number[]} ambient The ambient color, [r, g, b, a]
		 * @property {number[]} diffuse The diffuse color, [r, g, b, a]
		 * @property {number[]} emissive The emissive color, [r, g, b, a]
		 * @property {number[]} specular The specular color, [r, g, b, a]
		 * @property {number} shininess The shininess exponent.
		 * */
		/*this.materialState = {
			ambient: Shader.DEFAULT_AMBIENT,
			diffuse: Shader.DEFAULT_DIFFUSE,
			emissive: Shader.DEFAULT_EMISSIVE,
			specular: Shader.DEFAULT_SPECULAR,
			shininess: Shader.DEFAULT_SHININESS
		};

		/** Specification of culling for this Material
		 * @type {Object}
		 * @property {boolean} enabled
		 * @property {string} cullFace possible values: 'Front', 'Back', 'FrontAndBack', default 'Back'
		 * @property {string} frontFace possible values: 'CW' (clockwise) and 'CCW' (counterclockwise - default)
		 */
		this.cullState = {
			enabled: true,
			cullFace: 'Back', // Front, Back, FrontAndBack
			frontFace: 'CCW' // CW, CCW
		};

		/** Specification of blending for this Material
		 * @type {Object}
		 * @property {String} blending possible values: 'NoBlending', 'AdditiveBlending', 'SubtractiveBlending', 'MultiplyBlending', 'CustomBlending'
		 * @property {String} blendEquation possible values: 'AddEquation', 'SubtractEquation', 'ReverseSubtractEquation'
		 * @property {String} blendSrc possible values: 'SrcAlphaFactor', 'ZeroFactor', 'OneFactor', 'SrcColorFactor', 'OneMinusSrcColorFactor', 'OneMinusSrcAlphaFactor', 'OneMinusDstAlphaFactor''DstColorFactor', 'OneMinusDstColorFactor', 'SrcAlphaSaturateFactor', 'DstAlphaFactor'
		 * @property {String} blendDst possible values: 'SrcAlphaFactor', 'ZeroFactor', 'OneFactor', 'SrcColorFactor', 'OneMinusSrcColorFactor', 'OneMinusSrcAlphaFactor', 'OneMinusDstAlphaFactor''DstColorFactor', 'OneMinusDstColorFactor', 'DstAlphaFactor'
		 */
		this.blendState = {
			blending: 'NoBlending',
			blendEquation: 'AddEquation',
			blendSrc: 'SrcAlphaFactor',
			blendDst: 'OneMinusSrcAlphaFactor'
		};

		/** Specification of depth handling for this Material
		 * @type {Object}
		 * @property {boolean} enabled default: true
		 * @property {boolean} write default: true
		 */
		this.depthState = {
			enabled: true,
			write: true
		};

		/** Specification of the polygon offset for this Material
		 * @type {Object}
		 * @property {boolean} enabled
		 * @property {number} factor default: 1
		 * @property {number} units default: 1
		 */
		this.offsetState = {
			enabled: false,
			factor: 1,
			units: 1
		};

		/** Render the mesh twice with front/back-facing for double transparency rendering
		 * @type {boolean}
		 * @default
		 */
		this.dualTransparency = false;

		/** Show wireframe on this material
		 * @type {boolean}
		 * @default
		 */
		this.wireframe = false;
		this.flat = false;

		/** Determines the order in which an object is drawn. There are four pre-defined render queues:
		 *

		 *
RenderQueue.BACKGROUND = Rendered before any other objects. Commonly used for skyboxes and the likes (0-999)
		 *
RenderQueue.OPAQUE = Used for most objects, typically opaque geometry. Rendered front to back (1000-1999)
		 *
RenderQueue.TRANSPARENT = For all alpha-blended objects. Rendered back to front (2000-2999)
		 *
RenderQueue.OVERLAY = For overlay effects like lens-flares etc (3000+)
		 *

		 * By default materials use the render queue of the shader. See {@link Shader} or {@link RenderQueue} for more info
		 * @type {number}
		 */
		this.renderQueue = null;

		this.fullOverride = false;
		this.errorOnce = false;

		// #ifdef DEBUG
		Object.seal(this);
		// #endif
	}

	/**
	 * Sets a texture in a specific slot
	 *
	 * @param {String} name Name of texture slot
	 * @param {Texture} texture Texture to set
	 */
	Material.prototype.setTexture = function (name, texture) {
		this._textureMaps[name] = texture;
	};

	/**
	 * Gets a texture in a specific slot
	 *
	 * @param {String} name Name of texture slot to retrieve texture from
	 * @returns {Texture} Texture if found, or undefined if not in slot
	 */
	Material.prototype.getTexture = function (name) {
		return this._textureMaps[name];
	};

	/**
	 * Removes a texture in a specific slot
	 *
	 * @param {String} name Name of texture slot to remove
	 */
	Material.prototype.removeTexture = function (name) {
		delete this._textureMaps[name];
	};

	/**
	 * Get all textures as an array
	 *
	 * @returns {Texture[]} Array containing all set textures
	 */
	Material.prototype.getTextures = function () {
		var textures = [];
		for (var key in this._textureMaps) {
			textures.push(this._textureMaps[key]);
		}
		return textures;
	};

	/**
	 * Get the map of [slot_name]: [Texture]
	 *
	 * @returns {Object} Mapping of slot - textures
	 */
	Material.prototype.getTextureEntries = function () {
		return this._textureMaps;
	};

	/**
	 * Returns the render queue of this material
	 * @returns {number}
	 */
	Material.prototype.getRenderQueue = function () {
		if (this.renderQueue !== null) {
			return this.renderQueue;
		} else if (this.shader !== null) {
			return this.shader.renderQueue;
		}
		return 1000;
	};

	/**
	 * Sets the render queue of this material
	 * @param {number} queue See {@link RenderQueue} for options
	 */
	Material.prototype.setRenderQueue = function (queue) {
		this.renderQueue = queue;
	};

	/**
	 * Returns a clone of this material
	 * @param {Object} [options]
	 * @param {boolean} [options.shareUniforms=false] Cloning this material clones the uniforms by default
	 * @param {boolean} [options.shareTextures=false] Cloning this material clones the textures by default
	 * @returns {Material}
	 */
	Material.prototype.clone = function (options) {
		options = options || {};

		var clone = new Material(this.name);

		clone.id = this.id;
		clone.name = this.name;
		clone.shader = this.shader.clone();

		if (options.shareUniforms) {
			clone.uniforms = this.uniforms;
		} else {
			clone.uniforms = _.clone(this.uniforms);
		}

		if (options.shareTextures) {
			var textureKeys = Object.keys(this._textureMaps);
			for (var i = 0; i < textureKeys.length; i++) {
				var textureKey = textureKeys[i];
				clone._textureMaps[textureKey] = this._textureMaps[textureKey];
			}
		} else {
			var textureKeys = Object.keys(this._textureMaps);
			for (var i = 0; i < textureKeys.length; i++) {
				var textureKey = textureKeys[i];
				clone._textureMaps[textureKey] = this._textureMaps[textureKey].clone();
			}
		}

		clone.cullState.enabled = this.cullState.enabled;
		clone.cullState.cullFace = this.cullState.cullFace;
		clone.cullState.frontFace = this.cullState.frontFace;

		clone.blendState.blending = this.blendState.blending;
		clone.blendState.blendEquation = this.blendState.blendEquation;
		clone.blendState.blendSrc = this.blendState.blendSrc;
		clone.blendState.blendDst = this.blendState.blendDst;

		clone.depthState.enabled = this.depthState.enabled;
		clone.depthState.write = this.depthState.write;

		clone.offsetState.enabled = this.offsetState.enabled;
		clone.offsetState.factor = this.offsetState.factor;
		clone.offsetState.units = this.offsetState.units;

		clone.dualTransparency = this.dualTransparency;

		clone.wireframe = this.wireframe;
		clone.flat = this.flat;

		clone.renderQueue = this.renderQueue;

		clone.fullOverride = this.fullOverride;
		clone.errorOnce = this.errorOnce;

		return clone;
	};

	/**
	 * Creates a new or finds an existing, cached Shader object
	 *
	 * @param {ShaderDefinition} shaderDefinition see {@link Shader}
	 * @param {String} [name=DefaultShader]
	 * @returns {Shader}
	 */
	Material.createShader = function (shaderDefinition, name) {
		//! AT: function has parameters in reverse order than the constructor
		var shader = new Shader(name || null, shaderDefinition);
		if (shader.name === null) {
			shader.name = 'DefaultShader' + shader._id;
		}
		return shader;
	};

	/**
	 * Clears the shader cache.
	 * @deprecated Deprecated since 0.12.0 and scheduled for removal in 0.14.0
	 */
	Material.clearShaderCache = function () {
	};

	/**
	 * Creates an 'empty' material
	 * @private
	 * @param shaderDefinition see {@link Shader}
	 * @param name [name='Empty Material'] The name of the newly created material
	 * @returns {Material}
	 */
	Material.createEmptyMaterial = function (shaderDefinition, name) {
		var material = new Material(name || 'Empty Material');
		material.empty();
		if (shaderDefinition) {
			material.shader = Material.createShader(shaderDefinition);
		} else {
			material.shader = undefined;
		}
		return material;
	};

	//! AT: how about a immutable material named EMPTY and a clone method for materials instead of this mutable madness?
	/**
	 * Removed the material's properties
	 * @private
	 */
	Material.prototype.empty = function () {
		this.cullState = {};
		this.blendState = {};
		this.depthState = {};
		this.offsetState = {};
		this.wireframe = undefined;
		this.renderQueue = undefined;
		this.flat = undefined;
		this._textureMaps = {};
		this.shader = undefined;
		this.uniforms = {};
	};

	return Material;
});
<commit_msg>fixed missing TransparencyBlending in the jsdoc of Material.blendState.blending. also fixed dangerous unclosed block-comment for Material.materialState<commit_after>define([
	'goo/renderer/Shader',
	'goo/util/ObjectUtil'
], function (
	Shader,
	_
) {
	'use strict';

	/**
	 * A Material defines the look of an object
	 * @param {string} [name='Default Material'] Material name
	 * @param {{ vshader, fshader }} [shaderDefinition] Optional shader to associate with the material
	 */
	function Material(name, shaderDefinition) {
		this.id = null;

		/** Material name
		 * @type {string}
		 */
		this.name = 'Default Material';

		/** [Shader]{@link Shader} to use when rendering
		 * @type {Shader}
		 */
		this.shader = null;

		//! AT: horrendous type checking follows
		// function has 2 signatures because the deprecated .createMaterial had parameters in inverse order
		if (typeof arguments[0] === 'string') {
			this.name = arguments[0];
		} else if (arguments[0] && arguments[0].vshader && arguments[0].fshader) {
			this.shader = Material.createShader(arguments[0]);
		}

		if (arguments[1] && arguments[1].vshader && arguments[1].fshader) {
			this.shader = Material.createShader(arguments[1]);
		} else if (typeof arguments[1] === 'string') {
			this.name = arguments[1];
		}

		/** Possible overrides for shader uniforms
		 * @type {Object}
		 * @default
		 */
		this.uniforms = {};

		// Texture storage
		this._textureMaps = {};
		/* REVIEW
		 * There was an idea to specify and jsdoc uniforms.materialDiffuse etc instead,
		 * since those are the ones we use now
		 */

		/* Specification of colors for this Material
		 * @type {Object}
		 * @property {number[]} ambient The ambient color, [r, g, b, a]
		 * @property {number[]} diffuse The diffuse color, [r, g, b, a]
		 * @property {number[]} emissive The emissive color, [r, g, b, a]
		 * @property {number[]} specular The specular color, [r, g, b, a]
		 * @property {number} shininess The shininess exponent.
		 */
		/*
		this.materialState = {
			ambient: Shader.DEFAULT_AMBIENT,
			diffuse: Shader.DEFAULT_DIFFUSE,
			emissive: Shader.DEFAULT_EMISSIVE,
			specular: Shader.DEFAULT_SPECULAR,
			shininess: Shader.DEFAULT_SHININESS
		};
		*/

		/** Specification of culling for this Material
		 * @type {Object}
		 * @property {boolean} enabled
		 * @property {string} cullFace possible values: 'Front', 'Back', 'FrontAndBack', default 'Back'
		 * @property {string} frontFace possible values: 'CW' (clockwise) and 'CCW' (counterclockwise - default)
		 */
		this.cullState = {
			enabled: true,
			cullFace: 'Back', // Front, Back, FrontAndBack
			frontFace: 'CCW' // CW, CCW
		};

		/** Specification of blending for this Material
		 * @type {Object}
		 * @property {String} blending possible values: 'NoBlending', 'TransparencyBlending', 'AdditiveBlending', 'SubtractiveBlending', 'MultiplyBlending', 'CustomBlending'
		 * @property {String} blendEquation possible values: 'AddEquation', 'SubtractEquation', 'ReverseSubtractEquation'
		 * @property {String} blendSrc possible values: 'SrcAlphaFactor', 'ZeroFactor', 'OneFactor', 'SrcColorFactor', 'OneMinusSrcColorFactor', 'OneMinusSrcAlphaFactor', 'OneMinusDstAlphaFactor''DstColorFactor', 'OneMinusDstColorFactor', 'SrcAlphaSaturateFactor', 'DstAlphaFactor'
		 * @property {String} blendDst possible values: 'SrcAlphaFactor', 'ZeroFactor', 'OneFactor', 'SrcColorFactor', 'OneMinusSrcColorFactor', 'OneMinusSrcAlphaFactor', 'OneMinusDstAlphaFactor''DstColorFactor', 'OneMinusDstColorFactor', 'DstAlphaFactor'
		 */
		this.blendState = {
			blending: 'NoBlending',
			blendEquation: 'AddEquation',
			blendSrc: 'SrcAlphaFactor',
			blendDst: 'OneMinusSrcAlphaFactor'
		};

		/** Specification of depth handling for this Material
		 * @type {Object}
		 * @property {boolean} enabled default: true
		 * @property {boolean} write default: true
		 */
		this.depthState = {
			enabled: true,
			write: true
		};

		/** Specification of the polygon offset for this Material
		 * @type {Object}
		 * @property {boolean} enabled
		 * @property {number} factor default: 1
		 * @property {number} units default: 1
		 */
		this.offsetState = {
			enabled: false,
			factor: 1,
			units: 1
		};

		/** Render the mesh twice with front/back-facing for double transparency rendering
		 * @type {boolean}
		 * @default
		 */
		this.dualTransparency = false;

		/** Show wireframe on this material
		 * @type {boolean}
		 * @default
		 */
		this.wireframe = false;
		this.flat = false;

		/** Determines the order in which an object is drawn. There are four pre-defined render queues:
		 *

		 *
RenderQueue.BACKGROUND = Rendered before any other objects. Commonly used for skyboxes and the likes (0-999)
		 *
RenderQueue.OPAQUE = Used for most objects, typically opaque geometry. Rendered front to back (1000-1999)
		 *
RenderQueue.TRANSPARENT = For all alpha-blended objects. Rendered back to front (2000-2999)
		 *
RenderQueue.OVERLAY = For overlay effects like lens-flares etc (3000+)
		 *

		 * By default materials use the render queue of the shader. See {@link Shader} or {@link RenderQueue} for more info
		 * @type {number}
		 */
		this.renderQueue = null;

		this.fullOverride = false;
		this.errorOnce = false;

		// #ifdef DEBUG
		Object.seal(this);
		// #endif
	}

	/**
	 * Sets a texture in a specific slot
	 *
	 * @param {String} name Name of texture slot
	 * @param {Texture} texture Texture to set
	 */
	Material.prototype.setTexture = function (name, texture) {
		this._textureMaps[name] = texture;
	};

	/**
	 * Gets a texture in a specific slot
	 *
	 * @param {String} name Name of texture slot to retrieve texture from
	 * @returns {Texture} Texture if found, or undefined if not in slot
	 */
	Material.prototype.getTexture = function (name) {
		return this._textureMaps[name];
	};

	/**
	 * Removes a texture in a specific slot
	 *
	 * @param {String} name Name of texture slot to remove
	 */
	Material.prototype.removeTexture = function (name) {
		delete this._textureMaps[name];
	};

	/**
	 * Get all textures as an array
	 *
	 * @returns {Texture[]} Array containing all set textures
	 */
	Material.prototype.getTextures = function () {
		var textures = [];
		for (var key in this._textureMaps) {
			textures.push(this._textureMaps[key]);
		}
		return textures;
	};

	/**
	 * Get the map of [slot_name]: [Texture]
	 *
	 * @returns {Object} Mapping of slot - textures
	 */
	Material.prototype.getTextureEntries = function () {
		return this._textureMaps;
	};

	/**
	 * Returns the render queue of this material
	 * @returns {number}
	 */
	Material.prototype.getRenderQueue = function () {
		if (this.renderQueue !== null) {
			return this.renderQueue;
		} else if (this.shader !== null) {
			return this.shader.renderQueue;
		}
		return 1000;
	};

	/**
	 * Sets the render queue of this material
	 * @param {number} queue See {@link RenderQueue} for options
	 */
	Material.prototype.setRenderQueue = function (queue) {
		this.renderQueue = queue;
	};

	/**
	 * Returns a clone of this material
	 * @param {Object} [options]
	 * @param {boolean} [options.shareUniforms=false] Cloning this material clones the uniforms by default
	 * @param {boolean} [options.shareTextures=false] Cloning this material clones the textures by default
	 * @returns {Material}
	 */
	Material.prototype.clone = function (options) {
		options = options || {};

		var clone = new Material(this.name);

		clone.id = this.id;
		clone.name = this.name;
		clone.shader = this.shader.clone();

		if (options.shareUniforms) {
			clone.uniforms = this.uniforms;
		} else {
			clone.uniforms = _.clone(this.uniforms);
		}

		if (options.shareTextures) {
			var textureKeys = Object.keys(this._textureMaps);
			for (var i = 0; i < textureKeys.length; i++) {
				var textureKey = textureKeys[i];
				clone._textureMaps[textureKey] = this._textureMaps[textureKey];
			}
		} else {
			var textureKeys = Object.keys(this._textureMaps);
			for (var i = 0; i < textureKeys.length; i++) {
				var textureKey = textureKeys[i];
				clone._textureMaps[textureKey] = this._textureMaps[textureKey].clone();
			}
		}

		clone.cullState.enabled = this.cullState.enabled;
		clone.cullState.cullFace = this.cullState.cullFace;
		clone.cullState.frontFace = this.cullState.frontFace;

		clone.blendState.blending = this.blendState.blending;
		clone.blendState.blendEquation = this.blendState.blendEquation;
		clone.blendState.blendSrc = this.blendState.blendSrc;
		clone.blendState.blendDst = this.blendState.blendDst;

		clone.depthState.enabled = this.depthState.enabled;
		clone.depthState.write = this.depthState.write;

		clone.offsetState.enabled = this.offsetState.enabled;
		clone.offsetState.factor = this.offsetState.factor;
		clone.offsetState.units = this.offsetState.units;

		clone.dualTransparency = this.dualTransparency;

		clone.wireframe = this.wireframe;
		clone.flat = this.flat;

		clone.renderQueue = this.renderQueue;

		clone.fullOverride = this.fullOverride;
		clone.errorOnce = this.errorOnce;

		return clone;
	};

	/**
	 * Creates a new or finds an existing, cached Shader object
	 *
	 * @param {ShaderDefinition} shaderDefinition see {@link Shader}
	 * @param {String} [name=DefaultShader]
	 * @returns {Shader}
	 */
	Material.createShader = function (shaderDefinition, name) {
		//! AT: function has parameters in reverse order than the constructor
		var shader = new Shader(name || null, shaderDefinition);
		if (shader.name === null) {
			shader.name = 'DefaultShader' + shader._id;
		}
		return shader;
	};

	/**
	 * Clears the shader cache.
	 * @deprecated Deprecated since 0.12.0 and scheduled for removal in 0.14.0
	 */
	Material.clearShaderCache = function () {
	};

	/**
	 * Creates an 'empty' material
	 * @private
	 * @param shaderDefinition see {@link Shader}
	 * @param name [name='Empty Material'] The name of the newly created material
	 * @returns {Material}
	 */
	Material.createEmptyMaterial = function (shaderDefinition, name) {
		var material = new Material(name || 'Empty Material');
		material.empty();
		if (shaderDefinition) {
			material.shader = Material.createShader(shaderDefinition);
		} else {
			material.shader = undefined;
		}
		return material;
	};

	//! AT: how about a immutable material named EMPTY and a clone method for materials instead of this mutable madness?
	/**
	 * Removed the material's properties
	 * @private
	 */
	Material.prototype.empty = function () {
		this.cullState = {};
		this.blendState = {};
		this.depthState = {};
		this.offsetState = {};
		this.wireframe = undefined;
		this.renderQueue = undefined;
		this.flat = undefined;
		this._textureMaps = {};
		this.shader = undefined;
		this.uniforms = {};
	};

	return Material;
});
<|endoftext|>


<commit_before>import {
  GraphQLInt,
  GraphQLList,
  GraphQLObjectType,
  GraphQLString
} from "graphql"

const RSBuddyType = new GraphQLObjectType({
  name: "RSBuddy",
  description: "Financial data retrieved from the RSBuddy/OSBuddy API",
  fields: () => ({
    ts: {
      type: GraphQLString
    },
    buyingPrice: {
      type: GraphQLInt
    },
    buyingCompleted: {
      type: GraphQLInt
    },
    sellingPrice: {
      type: GraphQLInt
    },
    sellingCompleted: {
      type: GraphQLInt
    },
    overallPrice: {
      type: GraphQLInt
    },
    overallCompleted: {
      type: GraphQLInt
    }
  }),
  resolve: root => Item.findOne({ id: root.id }, { rsbuddy: true })
})

export default RSBuddyType
<commit_msg>Convert RSBuddy type declaration to Apollo<commit_after>const RSBuddy = `
	type RSBuddy {
		ts: String
		buyingPrice: Int
		buyingCompleted: Int
		sellingPrice: Int
		sellingCompleted: Int
		overallPrice: Int
		overallCompleted: Int
	}
`

export default RSBuddy
<|endoftext|>


<commit_before>Rickshaw.namespace('Rickshaw.Fixtures.LocalTime');

Rickshaw.Fixtures.LocalTime = function() {

	var tzOffset = new Date().getTimezoneOffset() * 60;

	var self = this;

	this.months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

	this.units = [
		{
			name: 'decade',
			seconds: 86400 * 365.25 * 10,
			formatter: function(d) { return (parseInt(d.getFullYear() / 10, 10) * 10) }
		}, {
			name: 'year',
			seconds: 86400 * 365.25,
			formatter: function(d) { return d.getFullYear() }
		}, {
			name: 'month',
			seconds: 86400 * 30.5,
			formatter: function(d) { return self.months[d.getMonth()] }
		}, {
			name: 'week',
			seconds: 86400 * 7,
			formatter: function(d) { return self.formatDate(d) }
		}, {
			name: 'day',
			seconds: 86400,
			formatter: function(d) { return d.getDate() }
		}, {
			name: '6 hour',
			seconds: 3600 * 6,
			formatter: function(d) { return self.formatTime(d) }
		}, {
			name: 'hour',
			seconds: 3600,
			formatter: function(d) { return self.formatTime(d) }
		}, {
			name: '15 minute',
			seconds: 60 * 15,
			formatter: function(d) { return self.formatTime(d) }
		}, {
			name: 'minute',
			seconds: 60,
			formatter: function(d) { return d.getMinutes() }
		}, {
			name: '15 second',
			seconds: 15,
			formatter: function(d) { return d.getSeconds() + 's' }
		}, {
			name: 'second',
			seconds: 1,
			formatter: function(d) { return d.getSeconds() + 's' }
		}
	];

	this.unit = function(unitName) {
		return this.units.filter( function(unit) { return unitName == unit.name } ).shift();
	};

	this.formatDate = function(d) {
		return d.toString().match(/, (\w+ \w+ \w+)/)[1];
	};

	this.formatTime = function(d) {
		return d.toString().match(/(\d+:\d+):/)[1];
	};

	this.ceil = function(time, unit) {

		var nearFuture;
		var rounded;

		if (unit.name == 'day') {

			nearFuture = new Date((time + unit.seconds - 1) * 1000);

			rounded = new Date(0);
			rounded.setFullYear(nearFuture.getFullYear());
			rounded.setMonth(nearFuture.getMonth());
			rounded.setDate(nearFuture.getDate());
			rounded.setHours(0);
			rounded.setMinutes(0);
			rounded.setSeconds(0);
			rounded.setMilliseconds(0);

			return rounded.getTime() / 1000;
		}

		if (unit.name == 'month') {

			nearFuture = new Date((time + unit.seconds - 1) * 1000);

			rounded = new Date(0);
			rounded.setFullYear(nearFuture.getFullYear());
			rounded.setMonth(nearFuture.getMonth());
			rounded.setDate(1);
			rounded.setHours(0);
			rounded.setMinutes(0);
			rounded.setSeconds(0);
			rounded.setMilliseconds(0);

			return rounded.getTime() / 1000;
		}

		if (unit.name == 'year') {

			nearFuture = new Date((time + unit.seconds - 1) * 1000);

			rounded = new Date(0);
			rounded.setFullYear(nearFuture.getFullYear());
			rounded.setMonth(0);
			rounded.setDate(1);
			rounded.setHours(0);
			rounded.setMinutes(0);
			rounded.setSeconds(0);
			rounded.setMilliseconds(0);

			return rounded.getTime() / 1000;
		}

		return Math.ceil(time / unit.seconds) * unit.seconds;
	};
};
<commit_msg>Fixed date rollup problem.<commit_after>Rickshaw.namespace('Rickshaw.Fixtures.LocalTime');

Rickshaw.Fixtures.LocalTime = function() {

	var tzOffset = new Date().getTimezoneOffset() * 60;

	var self = this;

	this.months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

	this.units = [
		{
			name: 'decade',
			seconds: 86400 * 365.25 * 10,
			formatter: function(d) { return (parseInt(d.getFullYear() / 10, 10) * 10) }
		}, {
			name: 'year',
			seconds: 86400 * 365.25,
			formatter: function(d) { return d.getFullYear() }
		}, {
			name: 'month',
			seconds: 86400 * 30.5,
			formatter: function(d) { return self.months[d.getMonth()] }
		}, {
			name: 'week',
			seconds: 86400 * 7,
			formatter: function(d) { return self.formatDate(d) }
		}, {
			name: 'day',
			seconds: 86400,
			formatter: function(d) { return d.getDate() }
		}, {
			name: '6 hour',
			seconds: 3600 * 6,
			formatter: function(d) { return self.formatTime(d) }
		}, {
			name: 'hour',
			seconds: 3600,
			formatter: function(d) { return self.formatTime(d) }
		}, {
			name: '15 minute',
			seconds: 60 * 15,
			formatter: function(d) { return self.formatTime(d) }
		}, {
			name: 'minute',
			seconds: 60,
			formatter: function(d) { return d.getMinutes() }
		}, {
			name: '15 second',
			seconds: 15,
			formatter: function(d) { return d.getSeconds() + 's' }
		}, {
			name: 'second',
			seconds: 1,
			formatter: function(d) { return d.getSeconds() + 's' }
		}
	];

	this.unit = function(unitName) {
		return this.units.filter( function(unit) { return unitName == unit.name } ).shift();
	};

	this.formatDate = function(d) {
		return d.toString().match(/, (\w+ \w+ \w+)/)[1];
	};

	this.formatTime = function(d) {
		return d.toString().match(/(\d+:\d+):/)[1];
	};

	this.ceil = function(time, unit) {

		var nearFuture;
		var rounded;

		if (unit.name == 'day') {

			nearFuture = new Date((time + unit.seconds - 1) * 1000);

			rounded = new Date(0);
			rounded.setMilliseconds(0);
			rounded.setSeconds(0);
			rounded.setMinutes(0);
			rounded.setHours(0);
			rounded.setDate(nearFuture.getDate());
			rounded.setMonth(nearFuture.getMonth());
			rounded.setFullYear(nearFuture.getFullYear());

			return rounded.getTime() / 1000;
		}

		if (unit.name == 'month') {

			nearFuture = new Date((time + unit.seconds - 1) * 1000);

			rounded = new Date(0);
			rounded.setMilliseconds(0);
			rounded.setSeconds(0);
			rounded.setMinutes(0);
			rounded.setHours(0);
			rounded.setDate(1);
			rounded.setMonth(nearFuture.getMonth());
			rounded.setFullYear(nearFuture.getFullYear());

			return rounded.getTime() / 1000;
		}

		if (unit.name == 'year') {

			nearFuture = new Date((time + unit.seconds - 1) * 1000);

			rounded = new Date(0);
			rounded.setFullYear(nearFuture.getFullYear());
			rounded.setMilliseconds(0);
			rounded.setSeconds(0);
			rounded.setMinutes(0);
			rounded.setHours(0);
			rounded.setDate(1);
			rounded.setMonth(0);

			return rounded.getTime() / 1000;
		}

		return Math.ceil(time / unit.seconds) * unit.seconds;
	};
};
<|endoftext|>


<commit_before>define(['jquery', './media_view','../inflator','utils/html','app/task/build_url'], function($, Media,inflate,html,build_url) {

	return function(mediaObject,model){
		if (typeof mediaObject == 'string'){
			mediaObject = {word:mediaObject};
		}

		// inflate the definitions
		// note that the base url is added to the media object during the sequence preload
		var definitions = inflate(mediaObject,'media');

		// if needed, build url
		if (definitions.template) {
			definitions.template = build_url(definitions.template,'template');
		}
		if (definitions.image){
			definitions.image = build_url(definitions.image,'image');
		}

		// keep the source
		definitions.source = $.extend({},definitions);
		// keep a reference to the model
		definitions.model = model;

		html(definitions,{
			trialData: model.trial.data,
			stimulusData: model.get('data')
		});

		// return a new media view
		return new Media(definitions);
	};
});

<commit_msg>added error for media not set<commit_after>define(['jquery', './media_view','../inflator','utils/html','app/task/build_url'], function($, Media,inflate,html,build_url) {

	return function(mediaObject,model){
		if (typeof mediaObject == 'string'){
			mediaObject = {word:mediaObject};
		}

		// make sure we have a media object
		if (!mediaObject){
			throw new Error('Media object not defined for ' + model.name());
		}

		// inflate the definitions
		// note that the base url is added to the media object during the sequence preload
		var definitions = inflate(mediaObject,'media');

		// if needed, build url
		if (definitions.template) {
			definitions.template = build_url(definitions.template,'template');
		}
		if (definitions.image){
			definitions.image = build_url(definitions.image,'image');
		}

		// keep the source
		definitions.source = $.extend({},definitions);
		// keep a reference to the model
		definitions.model = model;

		html(definitions,{
			trialData: model.trial.data,
			stimulusData: model.get('data')
		});

		// return a new media view
		return new Media(definitions);
	};
});

<|endoftext|>


<commit_before>/* jquery.findyourcandidate.ca
 * =====================
 *
 * Extends and overrides the jQuery.findYourRep plugin built by Dan Drinkard to
 * render a find-your-reps form into a target HTML element using the Open North
 * Represent API.
 *
 * Copyright 2014 Open North Inc. BSD3 License.
 *
 * Usage:
 * ------
 *
 * Create an HTML element to use as a target, and call findYourRep(options) on it.
 * This example shows the default options.
 *
 * ```javascript
 * $('.mytarget').findYourRep({
 *   apis: 'represent',
 *   title: 'The Title of your Widget',
 *   text: 'Enter your address to see who represents you.',
 *   action: 'Go!'
 * });
 * ```
 */
;(function(window){

$.findYourRep.represent = function(address) {
  var dfd = new $.Deferred(),
      url = "https://represent.opennorth.ca/candidates/?limit=0&callback=?",
      params = {};

  $.findYourRep.geocodeOrResolveImmediately(address).done(function(geocoded){
    params.point = geocoded.latitude + ',' + geocoded.longitude;
    $.findYourRep.apiCall(url, params).done(function(data){
        dfd.then(function(data) {
            $('.fyr-results h3').append($.findYourRep.render($.findYourRep.districtTemplate,
                $.findYourRep.getTemplateContext(data[0], {})));
        });
      dfd.resolve(data['objects']);
    });
  });
  return dfd;
};

$.findYourRep.getTemplateContext = function(rep, api){
  return {
    details: rep.elected_office,
    photoUrl: rep.photo_url,
    resultUrl: rep.url || rep.source_url,
    name: rep.name,
    district_name: rep.district_name,
    elected_office: rep.elected_office,
    source_url: rep.source_url,
    party_name: rep.party_name,
    email: rep.email,
    url: rep.url
  };
}

$.findYourRep.districtTemplate = "Your Candidates for {{ district_name }}";

$.findYourRep.formTemplate = "" +
  "
" +
    "
{{ title }}
" +
    "
{{ text }}
" +
    "
" +
      "<textarea placeholder='Enter your address'>{{ defaultValue }}</textarea>" +
      "<button class='fyr-submit'>{{ action }}</button>" +
      "
" +
      "Powered by Represent" +
  "
";

$.findYourRep.resultsTemplate = "" +
"
" +
  "

" +
  "
" +
    "

" +
  "
" +
  "« start over" +
  "Powered by Represent" +
"
";

$.findYourRep.resultTemplate = "" +
  "
" +
    "" +
    "" +
    "
{{ name }}
" +
    "
{{ party_name }} {{ details }}
" +
    "" +
  "
";

})(this);
<commit_msg>Update templates; use Handlebars.<commit_after>/* jquery.findyourcandidate.ca
 * =====================
 *
 * Extends and overrides the jQuery.findYourRep plugin built by Dan Drinkard to
 * render a find-your-reps form into a target HTML element using the Open North
 * Represent API.
 *
 * Copyright 2014 Open North Inc. BSD3 License.
 *
 * Usage:
 * ------
 *
 * Create an HTML element to use as a target, and call findYourRep(options) on it.
 * This example shows the default options.
 *
 * ```javascript
 * $('.mytarget').findYourRep({
 *   apis: 'represent',
 *   title: 'The Title of your Widget',
 *   text: 'Enter your address to see who represents you.',
 *   action: 'Go!'
 * });
 * ```
 */
;(function(window){

$.findYourRep.render = function(template, data) {
    var template = Handlebars.compile(template);
    var results = template(data);
    return results;
};

$.findYourRep.represent = function(address) {
  var dfd = new $.Deferred(),
      url = "https://represent.opennorth.ca/candidates/?limit=0&callback=?",
      params = {};

  $.findYourRep.geocodeOrResolveImmediately(address).done(function(geocoded){
    params.point = geocoded.latitude + ',' + geocoded.longitude;
    $.findYourRep.apiCall(url, params).done(function(data){
        dfd.then(function(data) {
            $('.fyr-results h3').append($.findYourRep.render($.findYourRep.districtTemplate,
                $.findYourRep.getTemplateContext(data[0], {})));
        });
      dfd.resolve(data['objects']);
    });
  });
  return dfd;
};

$.findYourRep.getTemplateContext = function(rep, api){
  var re = /(\s+)/;
  var party = rep.party_name;
  var party_slug = party.replace(re, '-').toLowerCase();
  return {
    details: rep.elected_office,
    photoUrl: rep.photo_url,
    resultUrl: rep.url || rep.source_url,
    name: rep.name,
    district_name: rep.district_name,
    elected_office: rep.elected_office,
    source_url: rep.source_url,
    personal_url: rep.personal_url,
    party_name: rep.party_name,
    party_slug: party_slug,
    email: rep.email,
    facebook: rep.extra.facebook,
    twitter: rep.extra.twitter,
    url: rep.url,
    incumbent: rep.incumbent
  };
}

$.findYourRep.districtTemplate = "Your Candidates for {{ district_name }}";

$.findYourRep.formTemplate = "" +
  "
" +
    "
{{ title }}
" +
    "
{{ text }}
" +
    "
" +
      "<textarea placeholder='Enter your address'>{{ defaultValue }}</textarea>" +
      "<button class='fyr-submit'>{{ action }}</button>" +
      "
" +
      "Powered by Represent" +
  "
";

$.findYourRep.resultsTemplate = "" +
"
" +
  "

" +
  "
" +
    "

" +
  "
" +
  "« start over" +
  "

Powered by Represent" +
"
";

$.findYourRep.resultTemplate = "" +
    "
" +
    "
" +
    "

" +
    "{{#if incumbent}}
Incumbent
{{/if}}" +
    "" +
    "
{{ name }}
" +
    "
" +
    "
" +
    "
" +
    "        {{#if website}}
Website
{{/if}}" +
    "        {{#if email}}
Email
{{/if}}" +
    "        {{#if twitter}}
Twitter
{{/if}}" +
    "        {{#if facebook}}
Facebook
{{/if}}" +
    "
" +
    "
" +
    "
";

})(this);
<|endoftext|>


<commit_before>import React from 'react';

import { conditionalClass } from '../utillities';
import BlockUser from '../components/components.block-user';

class ChatSettings extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      search: false,
    };
  }

  render() {
    const chatSettings = conditionalClass({
      's-chat-settings': true,
      'state-new': !this.props.chat,
    });

    let groupName,
        participants,
        heading,
        icon,
        styles,
        input;

    groupName = this.props.groupName ? this.props.groupName : 'Group name';

    participants = renderParticipants(this.props);

    if (this.props.participants.length === 0) {
      heading = 'Tap on the right icon above to start add participants.';
    } else {
      heading = 'Participants';
    }

    if (this.props.groupImage) {
      styles = { backgroundImage: `url(${ this.props.groupImage })` };
    } else {
      icon = ;
    }

    if (this.state.search) {
      input =

                  <button className="c-input-group__addon" onClick={ this.hideSearch.bind(this) }>

                  </button>
                  <input className="c-input-group__field" type="text" placeholder="Add participants"/>
                  <button className="c-input-group__addon submit"></button>

;
    }

    return (

                  <button className="sign-out" onClick={ this.leaveGroup.bind(this) }>

                    Leave group
                  </button>

                  <button onClick={ this.editGroupName.bind(this) }>

                  </button>

                  <button onClick={ this.addGroupImage.bind(this) }>

                  </button>

                  <button onClick={ this.showSearch.bind(this) }>

                  </button>

              { input }

{ groupName }

            { icon }

{ heading }

          { participants }

    );
  }

  leaveGroup() {
    console.info('Leave group chat.');
  }

  editGroupName() {
    console.info('Edit group name.');
  }

  addGroupImage() {
    console.info('Add group image.');
  }

  showSearch() {
    console.info('Show search bar.');

    this.setState({
      search: true,
    });
  }

  hideSearch() {
    console.info('Hide search bar.');

    this.setState({
      search: false,
    });
  }
}

ChatSettings.propTypes = {
  groupName: React.PropTypes.string,
  groupImage: React.PropTypes.string,
  participants: React.PropTypes.array,
};

function renderParticipants(props) {
  if (props.participants.length > 0) {
    return props.participants.map((user, index) => (
      <BlockUser
        key={ index }
        name={ user.firstName }
        description={ user.description }
        imageSource={ user.imageSource }
        lastSeenDate={ user.lastSeenDate }
        openChat={ () => props.openChat(user.id) }
      />
    ));
  }

  else { return []; }
}

export default ChatSettings;
<commit_msg>Fixed typo.<commit_after>import React from 'react';

import { conditionalClass } from '../utillities';
import BlockUser from '../components/components.block-user';

class ChatSettings extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      search: false,
    };
  }

  render() {
    const chatSettings = conditionalClass({
      's-chat-settings': true,
      'state-new': !this.props.chat,
    });

    let groupName,
        participants,
        heading,
        icon,
        styles,
        input;

    groupName = this.props.groupName ? this.props.groupName : 'Group name';

    participants = renderParticipants(this.props);

    if (this.props.participants.length === 0) {
      heading = 'Tap on the right icon above to start adding participants.';
    } else {
      heading = 'Participants';
    }

    if (this.props.groupImage) {
      styles = { backgroundImage: `url(${ this.props.groupImage })` };
    } else {
      icon = ;
    }

    if (this.state.search) {
      input =

                  <button className="c-input-group__addon" onClick={ this.hideSearch.bind(this) }>

                  </button>
                  <input className="c-input-group__field" type="text" placeholder="Add participants"/>
                  <button className="c-input-group__addon submit"></button>

;
    }

    return (

                  <button className="sign-out" onClick={ this.leaveGroup.bind(this) }>

                    Leave group
                  </button>

                  <button onClick={ this.editGroupName.bind(this) }>

                  </button>

                  <button onClick={ this.addGroupImage.bind(this) }>

                  </button>

                  <button onClick={ this.showSearch.bind(this) }>

                  </button>

              { input }

{ groupName }

            { icon }

{ heading }

          { participants }

    );
  }

  leaveGroup() {
    console.info('Leave group chat.');
  }

  editGroupName() {
    console.info('Edit group name.');
  }

  addGroupImage() {
    console.info('Add group image.');
  }

  showSearch() {
    console.info('Show search bar.');

    this.setState({
      search: true,
    });
  }

  hideSearch() {
    console.info('Hide search bar.');

    this.setState({
      search: false,
    });
  }
}

ChatSettings.propTypes = {
  groupName: React.PropTypes.string,
  groupImage: React.PropTypes.string,
  participants: React.PropTypes.array,
};

function renderParticipants(props) {
  if (props.participants.length > 0) {
    return props.participants.map((user, index) => (
      <BlockUser
        key={ index }
        name={ user.firstName }
        description={ user.description }
        imageSource={ user.imageSource }
        lastSeenDate={ user.lastSeenDate }
        openChat={ () => props.openChat(user.id) }
      />
    ));
  }

  else { return []; }
}

export default ChatSettings;
<|endoftext|>


<commit_before>import { clipboard, remote } from 'electron';
const isDev = process.env.NODE_ENV !== 'production';

function injectDevelopmentTemplate(event, templates) {
  if (!isDev) return templates;
  const { screenX, screenY } = event;
  const separator = { type: 'separator' };
  const developmentTemplateAddition = [
    {
      label: 'Inspect element',
      accelerator: 'CmdOrCtrl+Shift+I',
      click: () => {
        remote.getCurrentWindow().inspectElement(screenX, screenY);
      },
    },
  ];
  if (templates.length > 0) {
    templates.push(separator);
  }
  templates.push(...developmentTemplateAddition);
  return templates;
}

export function openContextMenu(event, templates = [], canEdit = false, selection = '') {
  const { type, value } = event.target;
  const isInput = event.target.matches('input') && (type === 'text' || type === 'number');
  const isTextField = canEdit || isInput || event.target.matches('textarea');
  const isSomethingSelected = selection.length > 0 || window.getSelection().toString().length > 0;

  templates.push({
    label: 'Copy',
    accelerator: 'CmdOrCtrl+C',
    role: 'copy',
    enabled: isSomethingSelected,
  });

  // If context menu is opened on Input and there is text on the input and something is selected.
  const { selectionStart, selectionEnd } = event.target;
  if (!!value && isTextField && selectionStart !== selectionEnd) {
    templates.push({ label: 'Cut', accelerator: 'CmdOrCtrl+X', role: 'cut' });
  }

  // If context menu is opened on Input and text is present on clipboard
  if (clipboard.readText().length > 0 && isTextField) {
    templates.push({
      label: 'Paste',
      accelerator: 'CmdOrCtrl+V',
      role: 'paste',
    });
  }

  // If context menu is opened on Input
  if (isTextField && value) {
    templates.push({
      label: 'Select All',
      accelerator: 'CmdOrCtrl+A',
      role: 'selectall',
    });
  }

  injectDevelopmentTemplate(event, templates);
  remote.Menu.buildFromTemplate(templates).popup({});
}

// This function is used for the markdown description on the publish page
export function openEditorMenu(codeMirror, event) {
  const value = codeMirror.doc.getValue();
  const selection = codeMirror.doc.getSelection();
  const templates = [
    {
      label: 'Select All',
      accelerator: 'CmdOrCtrl+A',
      role: 'selectall',
      click: () => {
        codeMirror.execCommand('selectAll');
      },
      enabled: value.length > 0,
    },
    {
      label: 'Cut',
      accelerator: 'CmdOrCtrl+X',
      role: 'cut',
      enabled: selection.length > 0,
    },
  ];
  openContextMenu(event, templates, true, selection);
}

// This function is used for the CodeViewer component
export function openSnippetMenu(codeMirror, event) {
  const value = codeMirror.doc.getValue();
  const selection = codeMirror.doc.getSelection();
  const templates = [
    {
      label: 'Select All',
      accelerator: 'CmdOrCtrl+A',
      role: 'selectall',
      click: () => {
        codeMirror.execCommand('selectAll');
      },
      // Enabled if there is text to select
      enabled: value.length > 0,
    },
  ];
  openContextMenu(event, templates, false, selection);
}

export function openCopyLinkMenu(text, event) {
  const templates = [
    {
      label: 'Copy link',
      click: () => {
        clipboard.writeText(text);
      },
    },
  ];
  openContextMenu(event, templates);
}

// Block context menu
export function stopContextMenu(event) {
  event.preventDefault();
  event.stopPropagation();
}
<commit_msg>Fixes #3603. Allow browser context menu<commit_after>import { clipboard, remote } from 'electron';
const isDev = process.env.NODE_ENV !== 'production';

function injectDevelopmentTemplate(event, templates) {
  if (!isDev) return templates;
  const { screenX, screenY } = event;
  const separator = { type: 'separator' };
  const developmentTemplateAddition = [
    {
      label: 'Inspect element',
      accelerator: 'CmdOrCtrl+Shift+I',
      click: () => {
        remote.getCurrentWindow().inspectElement(screenX, screenY);
      },
    },
  ];
  if (templates.length > 0) {
    templates.push(separator);
  }
  templates.push(...developmentTemplateAddition);
  return templates;
}

export function openContextMenu(event, templates = [], canEdit = false, selection = '') {
  const { type, value } = event.target;
  const isInput = event.target.matches('input') && (type === 'text' || type === 'number');
  const isTextField = canEdit || isInput || event.target.matches('textarea');
  const isSomethingSelected = selection.length > 0 || window.getSelection().toString().length > 0;

  templates.push({
    label: 'Copy',
    accelerator: 'CmdOrCtrl+C',
    role: 'copy',
    enabled: isSomethingSelected,
  });

  // If context menu is opened on Input and there is text on the input and something is selected.
  const { selectionStart, selectionEnd } = event.target;
  if (!!value && isTextField && selectionStart !== selectionEnd) {
    templates.push({ label: 'Cut', accelerator: 'CmdOrCtrl+X', role: 'cut' });
  }

  // If context menu is opened on Input and text is present on clipboard
  if (clipboard.readText().length > 0 && isTextField) {
    templates.push({
      label: 'Paste',
      accelerator: 'CmdOrCtrl+V',
      role: 'paste',
    });
  }

  // If context menu is opened on Input
  if (isTextField && value) {
    templates.push({
      label: 'Select All',
      accelerator: 'CmdOrCtrl+A',
      role: 'selectall',
    });
  }

  injectDevelopmentTemplate(event, templates);
  remote.Menu.buildFromTemplate(templates).popup({});
}

// This function is used for the markdown description on the publish page
export function openEditorMenu(codeMirror, event) {
  const value = codeMirror.doc.getValue();
  const selection = codeMirror.doc.getSelection();
  const templates = [
    {
      label: 'Select All',
      accelerator: 'CmdOrCtrl+A',
      role: 'selectall',
      click: () => {
        codeMirror.execCommand('selectAll');
      },
      enabled: value.length > 0,
    },
    {
      label: 'Cut',
      accelerator: 'CmdOrCtrl+X',
      role: 'cut',
      enabled: selection.length > 0,
    },
  ];
  openContextMenu(event, templates, true, selection);
}

// This function is used for the CodeViewer component
export function openSnippetMenu(codeMirror, event) {
  const value = codeMirror.doc.getValue();
  const selection = codeMirror.doc.getSelection();
  const templates = [
    {
      label: 'Select All',
      accelerator: 'CmdOrCtrl+A',
      role: 'selectall',
      click: () => {
        codeMirror.execCommand('selectAll');
      },
      // Enabled if there is text to select
      enabled: value.length > 0,
    },
  ];
  openContextMenu(event, templates, false, selection);
}

export function openCopyLinkMenu(text, event) {
  const templates = [
    {
      label: 'Copy link',
      click: () => {
        clipboard.writeText(text);
      },
    },
  ];
  openContextMenu(event, templates);
}

// Block context menu
export function stopContextMenu(event) {
  if (navigator.userAgent.toLowerCase().indexOf(' electron/') > -1) {
    event.preventDefault();
    event.stopPropagation();
  }
}
<|endoftext|>


<commit_before>/**
 * Created by chendi on 9/3/16.
 */
var mkdirp = require('mkdirp');
var fs = require('fs');
var app = require('../../app');
var path = require ('path');
var del = require('del');
var File = require('../models/File');

/**
 * This is the file system where you have manage how all the
 * files are actually been stored on the server disc
 *
 * WARNING: Only 5 apis are open for call, others are not safe to be called
 * directly, other wise the actual file on OS dics file system may be messed up
 *
 * #getFilePath(fileID)
 *      Get the file path on the OS using the file ID
 *
 *      @param file id generated by database when the file get stored
 *      @return This function would return the actual file path of the a user file
 *
 * #getSessionDirectory(sessionID)
 *      Get the directory for storing all the files of a tutorial session
 *
 *      @param session id that corresponding to a tutorial session
 *      @return The session folder that stores all the session files
 *
 * #getPresentationFileFolder(fileID)
 *      Get the presentation image folder path for saving images converted from PDF file
 *
 *      @param file id
 *      @return get the fild folder for storing presentation image
 *              that is converted from pdf
 *
 * #getAllSessionFiles(sessionID)
 *      Get all the files belongs to a session
 *
 *      @param userID
 *      @return queryResult {
 *      count: <number_of_files>,
 *      rows: [
 *              {
 *              id: <fileID>
 *              fileName: <fileName>
 *              userID: <userID>
 *              }
 *          ]
 *
 * #getAllUserFiles(userID)
 *      Get all the files belongs to a user
 *
 *      @param userID
 *      @return queryResult {
 *          count: <number_of_files>,
 *          rows: [
 *              {
 *                  fileName: <fileName>
 *              }
 *          ]
 *      }
 * */

// =============== User File System =============== //
// ================================================ //

/**
 * Check if a directory exists
 *
 * @param directory path
 * @return <boolean>
 * */
var dirExists = function(userDirPath) {
    try {
        fs.accessSync(userDirPath, fs.F_OK, function(){});
        return true;
    } catch (e) {
        return false;
    }
};

/**
 * Create directory
 *
 * Create directory, do nothing if directory already exists
 *
 * @param directory path
 * @return void
 * */
var createDirectory = function(path) {
    mkdirp.sync(path, function(err) {
        throw "Cannot create path" + err;
    });
};

/**
 * Remove Directory
 *
 * @param directory path
 * @return void
 * */
var removeFileOrDirectory = function(path) {
    del.sync(path, function(err) {
        console.log(err);
    })
};

/**
 * Remove a file from user directory (Cannot be recovered)
 * return a boolean indicate if the file been successfully removed
 * Ownership check will be enforced for each remove.
 *
 * @param fileID
 * @return boolean
 * */
var removeUserFile = function(fileID, userID) {
    if (isOwnerOfFile(fileID, userID)) {
        var filePath = getFilePath(fileID);
        removeFileOrDirectory(filePath);
        return true;
    } else {
        return false;
    }
};

/**
 * Check if user has permission to remove the file
 *
 * @param userID
 * @param fileID
 * */
var isOwnerOfFile = function(fileID, userID) {
    return File.getOwnerOfFile(fileID, userID).then(function(result) {
        if (result == null) {
            var filePath = getFilePath(fileID);
            removeFileOrDirectory(filePath);
            return false;
        } else {
            return true;
        }
    })
};

/**
 * File filter
 *
 * @param mimeType
 * @return boolean
 * */
var isValidFileTypeUpload = function(mimeType) {
    return mimeType == 'application/pdf' || mimeType == 'image/jpeg';
};

/**
 * Check is pdf
 *
 * @param mimeType
 * @return boolean
 * */
var isPDF = function(mimeType) {
    return mimeType == 'application/pdf';
};

/**
 * Save File to database
 *
 * @param userID
 * @filepath filepath
 * @return void
 * */
var saveFileInfoToDatabase = function(tutorialSessionID, userID, fileName, fileMimeType, filePath) {
    return File.create(
        {
            tutorialSessionID: tutorialSessionID,
            name: fileName,
            mimeType: fileMimeType,
            filePath: filePath,
            userID: userID
        }
    );

};

/**
 * Get all the files user have
 *
 * @param userID
 * @return queryResult {
 *      count: <number_of_files>,
 *      rows: [
 *          {
 *              fileName: <fileName>
 *          }
 *          ]
 * }
 * */
var getAllUserFiles = function(userID) {
    return File.getAllUserFiles(userID).then(function(result) {
        var filePageData = getFilePageData(result);
        return filePageData;
    });
};

/**
 * Get file path on disc
 *
 * @param fileID
 * @return filepath
 * */
var getFilePath = function(fileID) {
    return File.getFilePath(fileID).then(function(result) {
        return result;
    });
};

/**
 * Form file page data returned to view
 *
 * @param queryResult
 * @param FileDataList
 * */
function getFilePageData(queryResult) {
    var fileDataList = new FileDataList(queryResult.count);

    for (var index in queryResult.rows) {
        var currentFileModel = queryResult.rows[index];
        fileDataList.addFile(currentFileModel.id, currentFileModel.name, currentFileModel.userID);
    }
    return fileDataList;
}

/**
 * File Page Data Model
 *
 * @attr count
 * @attr fileList
 * */
function FileDataList(count) {
    this.count = count;
    this.fileList = [];
}

/**
 * Add file data to file page data
 *
 * @param id
 * @param fileList
 * */
FileDataList.prototype.addFile = function(id, fileName, userID){
    this.fileList.push({
        id: id,
        fileName: fileName,
        userID: userID
    });
};

// ============= Session File System ============== //
// ================================================ //

/**
 * Generate session folder path
 *
 * @param sessionID
 * @return session folder path
 * */

var generateSessionDirPath = function(sessionID) {
    var SESSION_FILE_PATH = app.get('sessionFiles');
    return path.join(SESSION_FILE_PATH, sessionID);
};

/**
 * Create the session folder if not exist
 *
 * @param sessionID
 * @return sessionFileFolder
 * */
var createSessionDirectory = function(sessionID) {
    var sessionDirPath = generateSessionDirPath(sessionID);
    if(!dirExists(sessionDirPath)) {
        createDirectory(sessionDirPath);
    }
    return sessionDirPath;
};

/**
 * Get session file folder
 * Initialize if not exist
 *
 * @param sessionID
 * @return session folder path
 * */
var getSessionDirectory = function(sessionID) {
    var sessionDirPath = generateSessionDirPath(sessionID);
    if(!dirExists(sessionDirPath)) {
        initializeSessionDirectory(sessionDirPath, sessionID);
    }
    return sessionDirPath;
};

/**
 * Initialize session folder
 * Create the folder if not exist
 * Create presentation folder inside
 *
 * @param sessionDirPath
 * @param sessionID
 * @return void
 * */
var initializeSessionDirectory = function(sessionDirPath, sessionID) {
    createDirectory(sessionDirPath);
    createPresentationFolder(sessionID);
};

/**
 * Remove session file folder
 *
 * @param sessionID
 * @return void
 * */
var removeSessionDirectory = function(sessionID) {
    var filePath = generateSessionDirPath(sessionID);
    removeFileOrDirectory(filePath);
};

/**
 * Get all the files user have
 *
 * @param userID
 * @return queryResult {
 *      count: <number_of_files>,
 *      rows: [
 *          {
 *              fileName: <fileName>
 *          }
 *          ]
 * }
 * */
var getAllSessionFiles = function(sessionID) {
    return File.getAllSessionFiles(sessionID).then(function(result) {
        var filePageData = getFilePageData(result);
        return filePageData;
    });
};

// =========== Presentation File System =========== //
// ================================================ //

/**
 * Return the session file folder for storing image file
 * Create the folder if not exist.
 * The folder would exist inside the tutorial session folder.
 *
 * @param fileID
 * @return presentation folder path
 * */
var getPresentationFileFolder = function(fileID) {
    var sessionID = undefined;
    if(process.env.MODE != 'test') {
        var sessionQueryResult = File.getSessionID(fileID);
        assert(sessionID != null);
        sessionID = sessionQueryResult.id;
    } else {
        sessionID = app.get('sessionTestID');
    }
    var presentationFolderPath = generatePresentationFileFolderPath(fileID, sessionID);
    createDirectory(presentationFolderPath);

    return presentationFolderPath;
};

/**
 * Generate the presentation folder path
 *
 * @param fileID
 * @param sessionID
 * @return presentation file folder path
 * */
var generatePresentationFileFolderPath = function(fileID, sessionID) {
    var tutorialFolder = getSessionDirectory(sessionID);
    var presentationFolderPath = path.join(tutorialFolder, app.get('presentationFileFolder'), fileID);
    return presentationFolderPath;
};

/**
 * Create presentation folder
 *
 * @param sessionID
 * @return presentation folder path
 * */
var createPresentationFolder = function(sessionID) {
    var presentationFolderPath = generatePresentationFolderPath(sessionID);
    if (!dirExists(presentationFolderPath)) {
        createDirectory(presentationFolderPath);
    }
    return presentationFolderPath;
};

/**
 * Generate session folder path
 *
 * @param sessionID
 * @return sessionFolderPath
 */
var generatePresentationFolderPath = function(sessionID) {
    var tutorialFolder = getSessionDirectory(sessionID);
    return path.join(tutorialFolder, app.get('presentationFileFolder'));
};

/**
 * Customize assert
 * */
var assert = function(condition, message) {
    if (!condition) {
        throw Error(" Assert Failed " + (typeof message !== "undefined" ? ": " + message : ""));
    }
}

// Filesys api
module.exports.dirExists = dirExists;
module.exports.createDirectory = createDirectory;
module.exports.removeFileOrDirectory = removeFileOrDirectory;

// User File API
module.exports.isValidFileTypeUpload = isValidFileTypeUpload;
module.exports.saveFileInfoToDatabase = saveFileInfoToDatabase;
module.exports.getAllUserFiles = getAllUserFiles;
module.exports.getFilePath = getFilePath;
module.exports.removeUserFile = removeUserFile;
module.exports.isPDF = isPDF;

// Session File API
module.exports.createSessionDirectory = createSessionDirectory;
module.exports.getSessionDirectory = getSessionDirectory;
module.exports.generateSessionDirPath = generateSessionDirPath;
module.exports.removeSessionDirectory = removeSessionDirectory;
module.exports.getAllSessionFiles = getAllSessionFiles;

// Presentation File API
module.exports.getPresentationFileFolder = getPresentationFileFolder;
module.exports.generatePresentationFileFolderPath = generatePresentationFileFolderPath;
module.exports.generatePresentationFolderPath = generatePresentationFolderPath;<commit_msg>Fix assert<commit_after>/**
 * Created by chendi on 9/3/16.
 */
var mkdirp = require('mkdirp');
var fs = require('fs');
var app = require('../../app');
var path = require ('path');
var del = require('del');
var File = require('../models/File');

/**
 * This is the file system where you have manage how all the
 * files are actually been stored on the server disc
 *
 * WARNING: Only 5 apis are open for call, others are not safe to be called
 * directly, other wise the actual file on OS dics file system may be messed up
 *
 * #getFilePath(fileID)
 *      Get the file path on the OS using the file ID
 *
 *      @param file id generated by database when the file get stored
 *      @return This function would return the actual file path of the a user file
 *
 * #getSessionDirectory(sessionID)
 *      Get the directory for storing all the files of a tutorial session
 *
 *      @param session id that corresponding to a tutorial session
 *      @return The session folder that stores all the session files
 *
 * #getPresentationFileFolder(fileID)
 *      Get the presentation image folder path for saving images converted from PDF file
 *
 *      @param file id
 *      @return get the fild folder for storing presentation image
 *              that is converted from pdf
 *
 * #getAllSessionFiles(sessionID)
 *      Get all the files belongs to a session
 *
 *      @param userID
 *      @return queryResult {
 *      count: <number_of_files>,
 *      rows: [
 *              {
 *              id: <fileID>
 *              fileName: <fileName>
 *              userID: <userID>
 *              }
 *          ]
 *
 * #getAllUserFiles(userID)
 *      Get all the files belongs to a user
 *
 *      @param userID
 *      @return queryResult {
 *          count: <number_of_files>,
 *          rows: [
 *              {
 *                  fileName: <fileName>
 *              }
 *          ]
 *      }
 * */

// =============== User File System =============== //
// ================================================ //

/**
 * Check if a directory exists
 *
 * @param directory path
 * @return <boolean>
 * */
var dirExists = function(userDirPath) {
    try {
        fs.accessSync(userDirPath, fs.F_OK, function(){});
        return true;
    } catch (e) {
        return false;
    }
};

/**
 * Create directory
 *
 * Create directory, do nothing if directory already exists
 *
 * @param directory path
 * @return void
 * */
var createDirectory = function(path) {
    mkdirp.sync(path, function(err) {
        throw "Cannot create path" + err;
    });
};

/**
 * Remove Directory
 *
 * @param directory path
 * @return void
 * */
var removeFileOrDirectory = function(path) {
    del.sync(path, function(err) {
        console.log(err);
    })
};

/**
 * Remove a file from user directory (Cannot be recovered)
 * return a boolean indicate if the file been successfully removed
 * Ownership check will be enforced for each remove.
 *
 * @param fileID
 * @return boolean
 * */
var removeUserFile = function(fileID, userID) {
    if (isOwnerOfFile(fileID, userID)) {
        var filePath = getFilePath(fileID);
        removeFileOrDirectory(filePath);
        return true;
    } else {
        return false;
    }
};

/**
 * Check if user has permission to remove the file
 *
 * @param userID
 * @param fileID
 * */
var isOwnerOfFile = function(fileID, userID) {
    return File.getOwnerOfFile(fileID, userID).then(function(result) {
        if (result == null) {
            var filePath = getFilePath(fileID);
            removeFileOrDirectory(filePath);
            return false;
        } else {
            return true;
        }
    })
};

/**
 * File filter
 *
 * @param mimeType
 * @return boolean
 * */
var isValidFileTypeUpload = function(mimeType) {
    return mimeType == 'application/pdf' || mimeType == 'image/jpeg';
};

/**
 * Check is pdf
 *
 * @param mimeType
 * @return boolean
 * */
var isPDF = function(mimeType) {
    return mimeType == 'application/pdf';
};

/**
 * Save File to database
 *
 * @param userID
 * @filepath filepath
 * @return void
 * */
var saveFileInfoToDatabase = function(tutorialSessionID, userID, fileName, fileMimeType, filePath) {
    return File.create(
        {
            tutorialSessionID: tutorialSessionID,
            name: fileName,
            mimeType: fileMimeType,
            filePath: filePath,
            userID: userID
        }
    );

};

/**
 * Get all the files user have
 *
 * @param userID
 * @return queryResult {
 *      count: <number_of_files>,
 *      rows: [
 *          {
 *              fileName: <fileName>
 *          }
 *          ]
 * }
 * */
var getAllUserFiles = function(userID) {
    return File.getAllUserFiles(userID).then(function(result) {
        var filePageData = getFilePageData(result);
        return filePageData;
    });
};

/**
 * Get file path on disc
 *
 * @param fileID
 * @return filepath
 * */
var getFilePath = function(fileID) {
    return File.getFilePath(fileID).then(function(result) {
        return result;
    });
};

/**
 * Form file page data returned to view
 *
 * @param queryResult
 * @param FileDataList
 * */
function getFilePageData(queryResult) {
    var fileDataList = new FileDataList(queryResult.count);

    for (var index in queryResult.rows) {
        var currentFileModel = queryResult.rows[index];
        fileDataList.addFile(currentFileModel.id, currentFileModel.name, currentFileModel.userID);
    }
    return fileDataList;
}

/**
 * File Page Data Model
 *
 * @attr count
 * @attr fileList
 * */
function FileDataList(count) {
    this.count = count;
    this.fileList = [];
}

/**
 * Add file data to file page data
 *
 * @param id
 * @param fileList
 * */
FileDataList.prototype.addFile = function(id, fileName, userID){
    this.fileList.push({
        id: id,
        fileName: fileName,
        userID: userID
    });
};

// ============= Session File System ============== //
// ================================================ //

/**
 * Generate session folder path
 *
 * @param sessionID
 * @return session folder path
 * */

var generateSessionDirPath = function(sessionID) {
    var SESSION_FILE_PATH = app.get('sessionFiles');
    return path.join(SESSION_FILE_PATH, sessionID);
};

/**
 * Create the session folder if not exist
 *
 * @param sessionID
 * @return sessionFileFolder
 * */
var createSessionDirectory = function(sessionID) {
    var sessionDirPath = generateSessionDirPath(sessionID);
    if(!dirExists(sessionDirPath)) {
        createDirectory(sessionDirPath);
    }
    return sessionDirPath;
};

/**
 * Get session file folder
 * Initialize if not exist
 *
 * @param sessionID
 * @return session folder path
 * */
var getSessionDirectory = function(sessionID) {
    var sessionDirPath = generateSessionDirPath(sessionID);
    if(!dirExists(sessionDirPath)) {
        initializeSessionDirectory(sessionDirPath, sessionID);
    }
    return sessionDirPath;
};

/**
 * Initialize session folder
 * Create the folder if not exist
 * Create presentation folder inside
 *
 * @param sessionDirPath
 * @param sessionID
 * @return void
 * */
var initializeSessionDirectory = function(sessionDirPath, sessionID) {
    createDirectory(sessionDirPath);
    createPresentationFolder(sessionID);
};

/**
 * Remove session file folder
 *
 * @param sessionID
 * @return void
 * */
var removeSessionDirectory = function(sessionID) {
    var filePath = generateSessionDirPath(sessionID);
    removeFileOrDirectory(filePath);
};

/**
 * Get all the files user have
 *
 * @param userID
 * @return queryResult {
 *      count: <number_of_files>,
 *      rows: [
 *          {
 *              fileName: <fileName>
 *          }
 *          ]
 * }
 * */
var getAllSessionFiles = function(sessionID) {
    return File.getAllSessionFiles(sessionID).then(function(result) {
        var filePageData = getFilePageData(result);
        return filePageData;
    });
};

// =========== Presentation File System =========== //
// ================================================ //

/**
 * Return the session file folder for storing image file
 * Create the folder if not exist.
 * The folder would exist inside the tutorial session folder.
 *
 * @param fileID
 * @return presentation folder path
 * */
var getPresentationFileFolder = function(fileID) {
    var sessionID = undefined;
    if(process.env.MODE != 'test') {
        var sessionQueryResult = File.getSessionID(fileID);
        sessionID = sessionQueryResult.id;
        assert(sessionID != null);
    } else {
        sessionID = app.get('sessionTestID');
    }
    var presentationFolderPath = generatePresentationFileFolderPath(fileID, sessionID);
    createDirectory(presentationFolderPath);

    return presentationFolderPath;
};

/**
 * Generate the presentation folder path
 *
 * @param fileID
 * @param sessionID
 * @return presentation file folder path
 * */
var generatePresentationFileFolderPath = function(fileID, sessionID) {
    var tutorialFolder = getSessionDirectory(sessionID);
    var presentationFolderPath = path.join(tutorialFolder, app.get('presentationFileFolder'), fileID);
    return presentationFolderPath;
};

/**
 * Create presentation folder
 *
 * @param sessionID
 * @return presentation folder path
 * */
var createPresentationFolder = function(sessionID) {
    var presentationFolderPath = generatePresentationFolderPath(sessionID);
    if (!dirExists(presentationFolderPath)) {
        createDirectory(presentationFolderPath);
    }
    return presentationFolderPath;
};

/**
 * Generate session folder path
 *
 * @param sessionID
 * @return sessionFolderPath
 */
var generatePresentationFolderPath = function(sessionID) {
    var tutorialFolder = getSessionDirectory(sessionID);
    return path.join(tutorialFolder, app.get('presentationFileFolder'));
};

/**
 * Customize assert
 * */
var assert = function(condition, message) {
    if (!condition) {
        throw Error(" Assert Failed " + (typeof message !== "undefined" ? ": " + message : ""));
    }
}

// Filesys api
module.exports.dirExists = dirExists;
module.exports.createDirectory = createDirectory;
module.exports.removeFileOrDirectory = removeFileOrDirectory;

// User File API
module.exports.isValidFileTypeUpload = isValidFileTypeUpload;
module.exports.saveFileInfoToDatabase = saveFileInfoToDatabase;
module.exports.getAllUserFiles = getAllUserFiles;
module.exports.getFilePath = getFilePath;
module.exports.removeUserFile = removeUserFile;
module.exports.isPDF = isPDF;

// Session File API
module.exports.createSessionDirectory = createSessionDirectory;
module.exports.getSessionDirectory = getSessionDirectory;
module.exports.generateSessionDirPath = generateSessionDirPath;
module.exports.removeSessionDirectory = removeSessionDirectory;
module.exports.getAllSessionFiles = getAllSessionFiles;

// Presentation File API
module.exports.getPresentationFileFolder = getPresentationFileFolder;
module.exports.generatePresentationFileFolderPath = generatePresentationFileFolderPath;
module.exports.generatePresentationFolderPath = generatePresentationFolderPath;<|endoftext|>


<commit_before>/* globals __DEV__ */
import Phaser from 'phaser'
import actionTypes from '../actions/Types'

const setAimSystem = function (range = 20, height = 20, width = 10) {
  this.aim.removeAll()

  const sight = __DEV__
    ? this.game.add.sprite(range, 0, 'atlas', 'mushroom2')
    : this.game.add.sprite(range, 0)

  sight.anchor.setTo(0.5)
  sight.height = height
  sight.width = width

  this.aim.add(sight)
}

const setMovement = function () {
  if (this.keys.left.isDown) {
    this.character.body.velocity.x = -1
  } else if (this.keys.right.isDown) {
    this.character.body.velocity.x = 1
  } else {
    this.character.body.velocity.x = 0
  }

  if (this.keys.up.isDown) {
    this.character.body.velocity.y = -1
  } else if (this.keys.down.isDown) {
    this.character.body.velocity.y = 1
  } else {
    this.character.body.velocity.y = 0
  }

  let currentSpeed = this.character.speed
  this.isHappening = 1
  this.isCooldown = 1

  let targetSpeed =
    (this.character.body.velocity.x !== 0 && this.character.body.velocity.y !== 0)
      ? currentSpeed * this.pythInverse
      : currentSpeed

  this.character.body.velocity.x *= targetSpeed
  this.character.body.velocity.y *= targetSpeed
}

export default class InputControls {
  constructor (character) {
    this.character = character
    this.game = character.game

    // Prevent directions and mouse key events bubbling up to browser
    this.game.input.keyboard.addKeyCapture([
      Phaser.Keyboard.A,
      Phaser.Keyboard.D,
      Phaser.Keyboard.W,
      Phaser.Keyboard.S,
      Phaser.Keyboard.SPACEBAR
    ])

    this.game.input.mouse.capture = true

    this.keys = {
      left: this.game.input.keyboard.addKey(Phaser.Keyboard.A),
      right: this.game.input.keyboard.addKey(Phaser.Keyboard.D),
      up: this.game.input.keyboard.addKey(Phaser.Keyboard.W),
      down: this.game.input.keyboard.addKey(Phaser.Keyboard.S),
      dash: this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR),
      attack: this.game.input.activePointer.leftButton
    }

    this.aim = this.game.add.group()
    this.character.addChild(this.aim)
    setAimSystem.call(this)

    this.pythInverse = 1 / Math.SQRT2
  }

  setAim (range, height, width) {
    setAimSystem.call(this, range, height, width)
  }

  update () {
    this.aim.rotation = this.game.physics.arcade.angleToPointer(this.character)

    if (this.character.action === actionTypes.idle ||
      this.character.action === actionTypes.move) {
      setMovement.call(this)
    }
    this.keys.attack.onDown.add(this.character.setHappeningAction.bind(this.character, actionTypes.atk))
    this.keys.dash.onDown.add(this.character.setHappeningAction.bind(this.character, actionTypes.dash))
  }
}
<commit_msg>fix: remove unused vars<commit_after>/* globals __DEV__ */
import Phaser from 'phaser'
import actionTypes from '../actions/Types'

const setAimSystem = function (range = 20, height = 20, width = 10) {
  this.aim.removeAll()

  const sight = __DEV__
    ? this.game.add.sprite(range, 0, 'atlas', 'mushroom2')
    : this.game.add.sprite(range, 0)

  sight.anchor.setTo(0.5)
  sight.height = height
  sight.width = width

  this.aim.add(sight)
}

const setMovement = function () {
  if (this.keys.left.isDown) {
    this.character.body.velocity.x = -1
  } else if (this.keys.right.isDown) {
    this.character.body.velocity.x = 1
  } else {
    this.character.body.velocity.x = 0
  }

  if (this.keys.up.isDown) {
    this.character.body.velocity.y = -1
  } else if (this.keys.down.isDown) {
    this.character.body.velocity.y = 1
  } else {
    this.character.body.velocity.y = 0
  }

  let currentSpeed = this.character.speed

  let targetSpeed =
    (this.character.body.velocity.x !== 0 && this.character.body.velocity.y !== 0)
      ? currentSpeed * this.pythInverse
      : currentSpeed

  this.character.body.velocity.x *= targetSpeed
  this.character.body.velocity.y *= targetSpeed
}

export default class InputControls {
  constructor (character) {
    this.character = character
    this.game = character.game

    // Prevent directions and mouse key events bubbling up to browser
    this.game.input.keyboard.addKeyCapture([
      Phaser.Keyboard.A,
      Phaser.Keyboard.D,
      Phaser.Keyboard.W,
      Phaser.Keyboard.S,
      Phaser.Keyboard.SPACEBAR
    ])

    this.game.input.mouse.capture = true

    this.keys = {
      left: this.game.input.keyboard.addKey(Phaser.Keyboard.A),
      right: this.game.input.keyboard.addKey(Phaser.Keyboard.D),
      up: this.game.input.keyboard.addKey(Phaser.Keyboard.W),
      down: this.game.input.keyboard.addKey(Phaser.Keyboard.S),
      dash: this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR),
      attack: this.game.input.activePointer.leftButton
    }

    this.aim = this.game.add.group()
    this.character.addChild(this.aim)
    setAimSystem.call(this)

    this.pythInverse = 1 / Math.SQRT2
  }

  setAim (range, height, width) {
    setAimSystem.call(this, range, height, width)
  }

  update () {
    this.aim.rotation = this.game.physics.arcade.angleToPointer(this.character)

    if (this.character.action === actionTypes.idle ||
      this.character.action === actionTypes.move) {
      setMovement.call(this)
    }
    this.keys.attack.onDown.add(this.character.setHappeningAction.bind(this.character, actionTypes.atk))
    this.keys.dash.onDown.add(this.character.setHappeningAction.bind(this.character, actionTypes.dash))
  }
}
<|endoftext|>


<commit_before>import { appendIfMissing, selectionChanged }  from '@zambezi/d3-utils'
import { isUndefined, find } from 'underscore'
import { select } from 'd3-selection'
import { unwrap } from '@zambezi/grid'

import './highlight-active-cell.css'

const highlightContainer = appendIfMissing('div.active-cell-highlight.zambezi-grid-overlay')
    , markerBox = appendIfMissing('div.marker-box')
    , activePositionChanged = selectionChanged().key(d => d)

export function createHighlightActiveCell() {
  let activeCell
    , rowIndex
    , columnClass

  function highlightActiveCell(s) {
    s.each(highlightActiveCellEach)
  }

  highlightActiveCell.activeCell = function(value) {
    if (!arguments.length) return activeCell
    rowIndex = undefined
    activeCell = value
    return highlightActiveCell
  }

  return highlightActiveCell

  function highlightActiveCellEach(d, i) {
    const marker = select(this)
            .on('data-dirty.invalidate-highlight-active-cell', d => rowIndex = undefined)
          .select('.zambezi-grid-body')
          .select(highlightContainer)
          .select(markerBox)
            .style('position', 'absolute')
            .style('transform', `translate(0, ${-d.scroll.top}px)`)

    let wrappedRow
      , columnClass = activeCell ? `c-${activeCell.column.id}` : ''

    if (activeCell && isUndefined(rowIndex)) {
      wrappedRow = find(d.rows.free, r => unwrap(r) == activeCell.row)
      rowIndex = wrappedRow && wrappedRow.freeRowNumber

      if (!wrappedRow) activeCell = null  // we don't have the row, quit
                                          // searching
    }

    marker.datum(`${rowIndex}×${columnClass}`)
        .select(activePositionChanged)
        .attr('data-grid-row-index', rowIndex)
        .attr('class', `marker-box zambezi-grid-row ${columnClass}`)
        .style('display', isUndefined(rowIndex) ? 'none' : null)

  }
}
<commit_msg>Fix horizontal highlight scroll.<commit_after>import { appendIfMissing, selectionChanged }  from '@zambezi/d3-utils'
import { isUndefined, find } from 'underscore'
import { select } from 'd3-selection'
import { unwrap } from '@zambezi/grid'

import './highlight-active-cell.css'

const highlightContainer = appendIfMissing('div.active-cell-highlight.zambezi-grid-overlay')
    , markerBox = appendIfMissing('div.marker-box')
    , activePositionChanged = selectionChanged().key(d => d)

export function createHighlightActiveCell() {
  let activeCell
    , rowIndex
    , columnClass

  function highlightActiveCell(s) {
    s.each(highlightActiveCellEach)
  }

  highlightActiveCell.activeCell = function(value) {
    if (!arguments.length) return activeCell
    rowIndex = undefined
    activeCell = value
    return highlightActiveCell
  }

  return highlightActiveCell

  function highlightActiveCellEach(d, i) {
    const marker = select(this)
            .on('data-dirty.invalidate-highlight-active-cell', d => rowIndex = undefined)
          .select('.zambezi-grid-body')
          .select(highlightContainer)
          .select(markerBox)
            .style('position', 'absolute')
            .style('transform', `translate(${-d.scroll.left}px, ${-d.scroll.top}px)`)

    let wrappedRow
      , columnClass = activeCell ? `c-${activeCell.column.id}` : ''

    if (activeCell && isUndefined(rowIndex)) {
      wrappedRow = find(d.rows.free, r => unwrap(r) == activeCell.row)
      rowIndex = wrappedRow && wrappedRow.freeRowNumber

      if (!wrappedRow) activeCell = null  // we don't have the row, quit
                                          // searching
    }

    marker.datum(`${rowIndex}×${columnClass}`)
        .select(activePositionChanged)
        .attr('data-grid-row-index', rowIndex)
        .attr('class', `marker-box zambezi-grid-row ${columnClass}`)
        .style('display', isUndefined(rowIndex) ? 'none' : null)

  }
}
<|endoftext|>


<commit_before>/*global angular:true, browser:true */

/**
 * @license HTTP Auth Interceptor Module for AngularJS
 * (c) 2012 Witold Szczerba
 * License: MIT
 */
(function () {
  'use strict';

  angular.module('http-auth-interceptor', ['http-auth-interceptor-buffer'])

  .factory('authService', ['$rootScope','httpBuffer', function($rootScope, httpBuffer) {
    return {
      /**
       * Call this function to indicate that authentication was successfull and trigger a
       * retry of all deferred requests.
       * @param data an optional argument to pass on to $broadcast which may be useful for
       * example if you need to pass through details of the user that was logged in
       * @param configUpdater an optional transformation function that can modify the
       * requests that are retried after having logged in.  This can be used for example
       * to add an authentication token.  It must return the request.
       */
      loginConfirmed: function(data, configUpdater) {
        var updater = configUpdater || function(config) {return config;};
        $rootScope.$broadcast('event:auth-loginConfirmed', data);
        httpBuffer.retryAll(updater);
      },

      /**
       * Call this function to indicate that authentication should not proceed.
       * All deferred requests will be abandoned or rejected (if reason is provided).
       * @param data an optional argument to pass on to $broadcast.
       * @param reason if provided, the requests are rejected; abandoned otherwise.
       */
      loginCancelled: function(data, reason) {
        httpBuffer.rejectAll(reason);
        $rootScope.$broadcast('event:auth-loginCancelled', data);
      }
    };
  }])

  /**
   * $http interceptor.
   * On 401 response (without 'ignoreAuthModule' option) stores the request
   * and broadcasts 'event:auth-loginRequired'.
   * On 403 response (without 'ignoreAuthModule' option) discards the request
   * and broadcasts 'event:auth-forbidden'.
   */
  .config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push(['$rootScope', '$q', 'httpBuffer', function($rootScope, $q, httpBuffer) {
      return {
        responseError: function(rejection) {
          if (!rejection.config.ignoreAuthModule) {
            switch (rejection.status) {
              case 401:
                var deferred = $q.defer();
                httpBuffer.append(rejection.config, deferred);
                $rootScope.$broadcast('event:auth-loginRequired', rejection);
                return deferred.promise;
              case 403:
                $rootScope.$broadcast('event:auth-forbidden', rejection);
                break;
            }
          }
          // otherwise, default behaviour
          return $q.reject(rejection);
        }
      };
    }]);
  }]);

  /**
   * Private module, a utility, required internally by 'http-auth-interceptor'.
   */
  angular.module('http-auth-interceptor-buffer', [])

  .factory('httpBuffer', ['$injector', function($injector) {
    /** Holds all the requests, so they can be re-requested in future. */
    var buffer = [];

    /** Service initialized later because of circular dependency problem. */
    var $http;

    function retryHttpRequest(config, deferred) {
      function successCallback(response) {
        deferred.resolve(response);
      }
      function errorCallback(response) {
        deferred.reject(response);
      }
      $http = $http || $injector.get('$http');
      $http(config).then(successCallback, errorCallback);
    }

    return {
      /**
       * Appends HTTP request configuration object with deferred response attached to buffer.
       */
      append: function(config, deferred) {
        buffer.push({
          config: config,
          deferred: deferred
        });
      },

      /**
       * Abandon or reject (if reason provided) all the buffered requests.
       */
      rejectAll: function(reason) {
        if (reason) {
          for (var i = 0; i < buffer.length; ++i) {
            buffer[i].deferred.reject(reason);
          }
        }
        buffer = [];
      },

      /**
       * Retries all the buffered requests clears the buffer.
       */
      retryAll: function(updater) {
        for (var i = 0; i < buffer.length; ++i) {
          retryHttpRequest(updater(buffer[i].config), buffer[i].deferred);
        }
        buffer = [];
      }
    };
  }]);
})();
<commit_msg>Error when config doesn't exist, issue #118<commit_after>/*global angular:true, browser:true */

/**
 * @license HTTP Auth Interceptor Module for AngularJS
 * (c) 2012 Witold Szczerba
 * License: MIT
 */
(function () {
  'use strict';

  angular.module('http-auth-interceptor', ['http-auth-interceptor-buffer'])

  .factory('authService', ['$rootScope','httpBuffer', function($rootScope, httpBuffer) {
    return {
      /**
       * Call this function to indicate that authentication was successfull and trigger a
       * retry of all deferred requests.
       * @param data an optional argument to pass on to $broadcast which may be useful for
       * example if you need to pass through details of the user that was logged in
       * @param configUpdater an optional transformation function that can modify the
       * requests that are retried after having logged in.  This can be used for example
       * to add an authentication token.  It must return the request.
       */
      loginConfirmed: function(data, configUpdater) {
        var updater = configUpdater || function(config) {return config;};
        $rootScope.$broadcast('event:auth-loginConfirmed', data);
        httpBuffer.retryAll(updater);
      },

      /**
       * Call this function to indicate that authentication should not proceed.
       * All deferred requests will be abandoned or rejected (if reason is provided).
       * @param data an optional argument to pass on to $broadcast.
       * @param reason if provided, the requests are rejected; abandoned otherwise.
       */
      loginCancelled: function(data, reason) {
        httpBuffer.rejectAll(reason);
        $rootScope.$broadcast('event:auth-loginCancelled', data);
      }
    };
  }])

  /**
   * $http interceptor.
   * On 401 response (without 'ignoreAuthModule' option) stores the request
   * and broadcasts 'event:auth-loginRequired'.
   * On 403 response (without 'ignoreAuthModule' option) discards the request
   * and broadcasts 'event:auth-forbidden'.
   */
  .config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push(['$rootScope', '$q', 'httpBuffer', function($rootScope, $q, httpBuffer) {
      return {
        responseError: function(rejection) {
          var config = rejection.config || {};
          if (!config.ignoreAuthModule) {
            switch (rejection.status) {
              case 401:
                var deferred = $q.defer();
                httpBuffer.append(config, deferred);
                $rootScope.$broadcast('event:auth-loginRequired', rejection);
                return deferred.promise;
              case 403:
                $rootScope.$broadcast('event:auth-forbidden', rejection);
                break;
            }
          }
          // otherwise, default behaviour
          return $q.reject(rejection);
        }
      };
    }]);
  }]);

  /**
   * Private module, a utility, required internally by 'http-auth-interceptor'.
   */
  angular.module('http-auth-interceptor-buffer', [])

  .factory('httpBuffer', ['$injector', function($injector) {
    /** Holds all the requests, so they can be re-requested in future. */
    var buffer = [];

    /** Service initialized later because of circular dependency problem. */
    var $http;

    function retryHttpRequest(config, deferred) {
      function successCallback(response) {
        deferred.resolve(response);
      }
      function errorCallback(response) {
        deferred.reject(response);
      }
      $http = $http || $injector.get('$http');
      $http(config).then(successCallback, errorCallback);
    }

    return {
      /**
       * Appends HTTP request configuration object with deferred response attached to buffer.
       */
      append: function(config, deferred) {
        buffer.push({
          config: config,
          deferred: deferred
        });
      },

      /**
       * Abandon or reject (if reason provided) all the buffered requests.
       */
      rejectAll: function(reason) {
        if (reason) {
          for (var i = 0; i < buffer.length; ++i) {
            buffer[i].deferred.reject(reason);
          }
        }
        buffer = [];
      },

      /**
       * Retries all the buffered requests clears the buffer.
       */
      retryAll: function(updater) {
        for (var i = 0; i < buffer.length; ++i) {
          retryHttpRequest(updater(buffer[i].config), buffer[i].deferred);
        }
        buffer = [];
      }
    };
  }]);
})();
<|endoftext|>