<commit_before>import { is, kTrue, check, TASK } from './utils'

export const CALL_FUNCTION_ARG_ERROR = "call/cps/fork first argument must be a function, an array [context, function] or an object {context, fn}"
export const FORK_ARG_ERROR = "fork first argument must be a generator function or an iterator"
export const JOIN_ARG_ERROR = "join argument must be a valid task (a result of a fork)"
export const CANCEL_ARG_ERROR = "cancel argument must be a valid task (a result of a fork)"
export const INVALID_PATTERN = "Invalid pattern passed to `take` (HINT: check if you didn't mispell a constant)"

const IO    = Symbol('IO')
const TAKE    = 'TAKE'
const PUT     = 'PUT'
const RACE    = 'RACE'
const CALL    = 'CALL'
const CPS     = 'CPS'
const FORK    = 'FORK'
const JOIN    = 'JOIN'
const CANCEL  = 'CANCEL'

const effect = (type, payload) => ({ [IO]: true, [type]: payload })

const matchers = {
  wildcard  : () => kTrue,
  default   : pattern => input => input.type === pattern,
  array     : patterns => input => patterns.some( p => p === input.type ),
  predicate : predicate => input => predicate(input)
}

export function matcher(pattern) {
  return (
      pattern === '*'   ? matchers.wildcard
    : is.array(pattern) ? matchers.array
    : is.func(pattern)  ? matchers.predicate
    : matchers.default
  )(pattern)
}

export function take(pattern){
  if (arguments.length > 0 && is.undef(pattern)) {
    throw new Error(INVALID_PATTERN)
  }

  return effect(TAKE, is.undef(pattern) ? '*' : pattern)
}

export function put(action) {
  return effect(PUT, action)
}

export function race(effects) {
  return effect(RACE, effects)
}

function getFnCallDesc(fn, args) {
  check(fn, is.notUndef, CALL_FUNCTION_ARG_ERROR)

  let context = null
  if(is.array(fn)) {
    [context, fn] = fn
  } else if(fn.fn) {
    ({context, fn} = fn)
  }
  check(fn, is.func, CALL_FUNCTION_ARG_ERROR)

  return {context, fn, args}
}

export function call(fn, ...args) {
  return effect(CALL, getFnCallDesc(fn, args))
}

export function apply(context, fn, args = []) {
  return effect(CALL, getFnCallDesc({context, fn}, args))
}

export function cps(fn, ...args) {
  return effect(CPS, getFnCallDesc(fn, args))
}

export function fork(fn, ...args) {
  return effect(FORK, getFnCallDesc(fn, args))
}

const isForkedTask = task => task[TASK]

export function join(taskDesc) {
  if(!isForkedTask(taskDesc))
    throw new Error(JOIN_ARG_ERROR)

  return effect(JOIN, taskDesc)
}

export function cancel(taskDesc) {
  if(!isForkedTask(taskDesc))
    throw new Error(CANCEL_ARG_ERROR)

  return effect(CANCEL, taskDesc)
}

export const asEffect = {
  take    : effect => effect && effect[IO] && effect[TAKE],
  put     : effect => effect && effect[IO] && effect[PUT],
  race    : effect => effect && effect[IO] && effect[RACE],
  call    : effect => effect && effect[IO] && effect[CALL],
  cps     : effect => effect && effect[IO] && effect[CPS],
  fork    : effect => effect && effect[IO] && effect[FORK],
  join    : effect => effect && effect[IO] && effect[JOIN],
  cancel  : effect => effect && effect[IO] && effect[CANCEL]
}
<commit_msg>added select && getState effects<commit_after>import { is, kTrue, ident, check, TASK } from './utils'

export const CALL_FUNCTION_ARG_ERROR = "call/cps/fork first argument must be a function, an array [context, function] or an object {context, fn}"
export const FORK_ARG_ERROR   = "fork first argument must be a generator function or an iterator"
export const JOIN_ARG_ERROR   = "join argument must be a valid task (a result of a fork)"
export const CANCEL_ARG_ERROR = "cancel argument must be a valid task (a result of a fork)"
export const INVALID_PATTERN  = "Invalid pattern passed to `take` (HINT: check if you didn't mispell a constant)"
export const SELECT_ARG_ERROR = "select argument `selector` must be a function"

const IO    = Symbol('IO')
const TAKE    = 'TAKE'
const PUT     = 'PUT'
const RACE    = 'RACE'
const CALL    = 'CALL'
const CPS     = 'CPS'
const FORK    = 'FORK'
const JOIN    = 'JOIN'
const CANCEL  = 'CANCEL'
const SELECT  = 'SELECT'

const effect = (type, payload) => ({ [IO]: true, [type]: payload })

const matchers = {
  wildcard  : () => kTrue,
  default   : pattern => input => input.type === pattern,
  array     : patterns => input => patterns.some( p => p === input.type ),
  predicate : predicate => input => predicate(input)
}

export function matcher(pattern) {
  return (
      pattern === '*'   ? matchers.wildcard
    : is.array(pattern) ? matchers.array
    : is.func(pattern)  ? matchers.predicate
    : matchers.default
  )(pattern)
}

export function take(pattern){
  if (arguments.length > 0 && is.undef(pattern)) {
    throw new Error(INVALID_PATTERN)
  }

  return effect(TAKE, is.undef(pattern) ? '*' : pattern)
}

export function put(action) {
  return effect(PUT, action)
}

export function race(effects) {
  return effect(RACE, effects)
}

function getFnCallDesc(fn, args) {
  check(fn, is.notUndef, CALL_FUNCTION_ARG_ERROR)

  let context = null
  if(is.array(fn)) {
    [context, fn] = fn
  } else if(fn.fn) {
    ({context, fn} = fn)
  }
  check(fn, is.func, CALL_FUNCTION_ARG_ERROR)

  return {context, fn, args}
}

export function call(fn, ...args) {
  return effect(CALL, getFnCallDesc(fn, args))
}

export function apply(context, fn, args = []) {
  return effect(CALL, getFnCallDesc({context, fn}, args))
}

export function cps(fn, ...args) {
  return effect(CPS, getFnCallDesc(fn, args))
}

export function fork(fn, ...args) {
  return effect(FORK, getFnCallDesc(fn, args))
}

const isForkedTask = task => task[TASK]

export function join(taskDesc) {
  if(!isForkedTask(taskDesc))
    throw new Error(JOIN_ARG_ERROR)

  return effect(JOIN, taskDesc)
}

export function cancel(taskDesc) {
  if(!isForkedTask(taskDesc))
    throw new Error(CANCEL_ARG_ERROR)

  return effect(CANCEL, taskDesc)
}

export function select(selector) {
  check(selector, is.func, SELECT_ARG_ERROR)
  return effect(SELECT, selector)
}

export function getState() {
  return select(ident)
}

export const asEffect = {
  take    : effect => effect && effect[IO] && effect[TAKE],
  put     : effect => effect && effect[IO] && effect[PUT],
  race    : effect => effect && effect[IO] && effect[RACE],
  call    : effect => effect && effect[IO] && effect[CALL],
  cps     : effect => effect && effect[IO] && effect[CPS],
  fork    : effect => effect && effect[IO] && effect[FORK],
  join    : effect => effect && effect[IO] && effect[JOIN],
  cancel  : effect => effect && effect[IO] && effect[CANCEL],
  select  : effect => effect && effect[IO] && effect[SELECT]
}
<|endoftext|>


<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/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

var Raster = this.Raster = Item.extend({
	/** @lends Raster# */

	beans: true,

	// TODO: Implement url / type, width, height.
	// TODO: Have PlacedSymbol & Raster inherit from a shared class?
	// DOCS: Document Raster constructor.
	/**
	 * Creates a new raster item and places it in the active layer.
	 *
	 * @constructs Raster
	 * @param {HTMLImageElement|Canvas|string} [object]
	 *
	 * @class The Raster item represents an image in a Paper.js project.
	 *
	 * @extends Item
	 */
	initialize: function(object) {
		this.base();
		if (object.getContext) {
			this.setCanvas(object);
		} else {
//#ifdef BROWSER
			// If it's a string, get the element with this id first.
			if (typeof object === 'string')
				object = document.getElementById(object);
//#endif // BROWSER
			this.setImage(object);
		}
		this.matrix = new Matrix();
	},

	clone: function() {
		var image = this._image;
		if (!image) {
			// If the Raster contains a Canvas object, we need to create
			// a new one and draw this raster's canvas on it.
			image = CanvasProvider.getCanvas(this._size);
			image.getContext('2d').drawImage(this._canvas, 0, 0);
		}
		var copy = new Raster(image);
		copy.matrix = this.matrix.clone();
		return this._clone(copy);
	},

	/**
	 * The size of the raster in pixels.
	 *
	 * @type Size
	 * @bean
	 */
	getSize: function() {
		return this._size;
	},

	setSize: function() {
		var size = Size.read(arguments),
			// Get reference to image before changing canvas
			image = this.getImage();
		// Setting canvas internally sets _size
		this.setCanvas(CanvasProvider.getCanvas(size));
		// Draw image back onto new canvas
		this.getContext().drawImage(image, 0, 0, size.width, size.height);
	},

	/**
	 * The width of the raster in pixels.
	 *
	 * @type Number
	 * @bean
	 */
	getWidth: function() {
		return this._size.width;
	},

	/**
	 * The height of the raster in pixels.
	 *
	 * @type Number
	 * @bean
	 */
	getHeight: function() {
		return this._size.height;
	},

	/**
	 * Pixels per inch of the raster at it's current size.
	 *
	 * @type Size
	 * @bean
	 */
	getPpi: function() {
		var matrix = this.matrix,
			orig = new Point(0, 0).transform(matrix),
			u = new Point(1, 0).transform(matrix).subtract(orig),
			v = new Point(0, 1).transform(matrix).subtract(orig);
		return new Size(
			72 / u.getLength(),
			72 / v.getLength()
		);
	},

	/**
	 * The Canvas 2d drawing context of the raster.
	 *
	 * @type Context
	 * @bean
	 */
	getContext: function() {
		if (!this._context) {
			this._context = this.getCanvas().getContext('2d');
		}
		return this._context;
	},

	setContext: function(context) {
		this._context = context;
	},

	getCanvas: function() {
		if (!this._canvas) {
			this._canvas = CanvasProvider.getCanvas(this._size);
			if (this._image)
				this.getContext().drawImage(this._image, 0, 0);
		}
		return this._canvas;
	},

	setCanvas: function(canvas) {
		if (this._canvas)
			CanvasProvider.returnCanvas(this._canvas);
		this._canvas = canvas;
		this._size = new Size(canvas.width, canvas.height);
		this._image = null;
		this._context = null;
		this._bounds = null;
	},

	/**
	 * The HTMLImageElement or Canvas of the raster.
	 *
	 * @type HTMLImageElement|Canvas
	 * @bean
	 */
	getImage: function() {
		return this._image || this.getCanvas();
	},

	// TODO: Support string id of image element.
	setImage: function(image) {
		if (this._canvas)
			CanvasProvider.returnCanvas(this._canvas);
		this._image = image;
		// TODO: Cross browser compatible?
		this._size = new Size(image.naturalWidth, image.naturalHeight);
		this._canvas = null;
		this._context = null;
		this._bounds = null;
	},

	// DOCS: document Raster#getSubImage
	/**
	 * @param {Rectangle} rect the boundaries of the sub image in pixel
	 * coordinates
	 *
	 * @return {Canvas}
	 */
	getSubImage: function(rect) {
		rect = Rectangle.read(arguments);
		var canvas = CanvasProvider.getCanvas(rect.getSize());
		canvas.getContext('2d').drawImage(this.getCanvas(), rect.x, rect.y,
				canvas.width, canvas.height, 0, 0, canvas.width, canvas.height);
		return canvas;
	},

	/**
	 * Draws an image on the raster.
	 *
	 * @param {HTMLImageELement|Canvas} image
	 * @param {Point} point the offset of the image as a point in pixel
	 * coordinates
	 */
	drawImage: function(image, point) {
		point = Point.read(arguments, 1);
		this.getContext().drawImage(image, point.x, point.y);
	},

	/**
	 * Calculates the average color of the image within the given path,
	 * rectangle or point. This can be used for creating raster image
	 * effects.
	 *
	 * @param {Path|Rectangle|Point} object
	 * @return {RGBColor} the average color contained in the area covered by the
	 * specified path, rectangle or point.
	 */
	getAverageColor: function(object) {
		if (!object)
			object = this.getBounds();
		var bounds, path;
		if (object instanceof PathItem) {
			// TODO: What if the path is smaller than 1 px?
			// TODO: How about rounding of bounds.size?
			path = object;
			bounds = object.getBounds();
		} else if (object.width) {
			bounds = new Rectangle(object);
		} else if (object.x) {
			bounds = Rectangle.create(object.x - 0.5, object.y - 0.5, 1, 1);
		}
		// Use a sample size of max 32 x 32 pixels, into which the path is
		// scaled as a clipping path, and then the actual image is drawn in and
		// sampled.
		var sampleSize = 32,
			width = Math.min(bounds.width, sampleSize),
			height = Math.min(bounds.height, sampleSize);
		// Reuse the same sample context for speed. Memory consumption is low
		// since it's only 32 x 32 pixels.
		var ctx = Raster._sampleContext;
		if (!ctx) {
			ctx = Raster._sampleContext = CanvasProvider.getCanvas(
					new Size(sampleSize)).getContext('2d');
		} else {
			// Clear the sample canvas:
			ctx.clearRect(0, 0, sampleSize, sampleSize);
		}
		ctx.save();
		// Scale the context so that the bounds ends up at the given sample size
		ctx.scale(width / bounds.width, height / bounds.height);
		ctx.translate(-bounds.x, -bounds.y);
		// If a path was passed, draw it as a clipping mask:
		if (path)
			path.draw(ctx, { clip: true });
		// Now draw the image clipped into it.
		this.matrix.applyToContext(ctx);
		ctx.drawImage(this._canvas || this._image,
				-this._size.width / 2, -this._size.height / 2);
		ctx.restore();
		// Get pixel data from the context and calculate the average color value
		// from it, taking alpha into account.
		var pixels = ctx.getImageData(0.5, 0.5, Math.ceil(width),
				Math.ceil(height)).data,
			channels = [0, 0, 0],
			total = 0;
		for (var i = 0, l = pixels.length; i < l; i += 4) {
			var alpha = pixels[i + 3];
			total += alpha;
			alpha /= 255;
			channels[0] += pixels[i] * alpha;
			channels[1] += pixels[i + 1] * alpha;
			channels[2] += pixels[i + 2] * alpha;
		}
		for (var i = 0; i < 3; i++)
			channels[i] /= total;
		return total ? Color.read(channels) : null;
	},

	/**
	 * {@grouptitle Pixels}
	 * Gets the color of a pixel in the raster.
	 *
	 * @name Raster#getPixel
	 * @function
	 * @param x the x offset of the pixel in pixel coordinates
	 * @param y the y offset of the pixel in pixel coordinates
	 * @return {RGBColor} the color of the pixel
	 */
	/**
	 * Gets the color of a pixel in the raster.
	 * @param point the offset of the pixel as a point in pixel coordinates
	 * @return {RGBColor} the color of the pixel
	 */
	getPixel: function(point) {
		point = Point.read(arguments);
		var pixels = this.getContext().getImageData(point.x, point.y, 1, 1).data,
			channels = new Array(4);
		for (var i = 0; i < 4; i++)
			channels[i] = pixels[i] / 255;
		return RGBColor.read(channels);
	},

	/**
	 * Sets the color of the specified pixel to the specified color.
	 *
	 * @name Raster#setPixel
	 * @function
	 * @param x the x offset of the pixel in pixel coordinates
	 * @param y the y offset of the pixel in pixel coordinates
	 * @param color the color that the pixel will be set to
	 */
	/**
	 * Sets the color of the specified pixel to the specified color.
	 * @param point the offset of the pixel as a point in pixel coordinates
	 * @param color the color that the pixel will be set to
	 */
	setPixel: function(point, color) {
		var hasPoint = arguments.length == 2;
		point = Point.read(arguments, 0, hasPoint ? 1 : 2);
		color = Color.read(arguments, hasPoint ? 1 : 2);
		var ctx = this.getContext(),
			imageData = ctx.createImageData(1, 1),
			alpha = color.getAlpha();
		imageData.data[0] = color.getRed() * 255;
		imageData.data[1] = color.getGreen() * 255;
		imageData.data[2] = color.getBlue() * 255;
		imageData.data[3] = alpha != null ? alpha * 255 : 255;
		ctx.putImageData(imageData, point.x, point.y);
	},

	// DOCS: document Raster#createData
	/**
	 * {@grouptitle Image Data}
	 * @param {Size} size
	 * @return {ImageData}
	 */
	createData: function(size) {
		size = Size.read(arguments);
		return this.getContext().createImageData(size.width, size.height);
	},

	// DOCS: document Raster#getData
	/**
	 * @param {Rectangle} rect
	 * @return {ImageData}
	 */
	getData: function(rect) {
		rect = Rectangle.read(arguments);
		if (rect.isEmpty())
			rect = new Rectangle(this.getSize());
		return this.getContext().getImageData(rect.x, rect.y,
				rect.width, rect.height);
	},

	// DOCS: document Raster#setData
	/**
	 * @param {ImageData} data
	 * @param {Point} point
	 * @return {ImageData}
	 */
	setData: function(data, point) {
		point = Point.read(arguments, 1);
		this.getContext().putImageData(data, point.x, point.y);
	},

	_transform: function(matrix, flags) {
		// In order to set the right context transformation when drawing the
		// raster, simply preconcatenate the internal matrix with the provided
		// one.
		this.matrix.preConcatenate(matrix);
		this._bounds = null;
	},

	getBounds: function() {
		if (!this._bounds) {
			this._bounds = this.matrix._transformBounds(
					new Rectangle(this._size).setCenter(0, 0));
		}
		return this._bounds;
	},

	getStrokeBounds: function() {
		return this.getBounds();
	},

	draw: function(ctx, param) {
		if (param.selection) {
			var bounds = new Rectangle(this._size).setCenter(0, 0);
			Item.drawSelectedBounds(bounds, ctx, this.matrix);
		} else {
			ctx.save();
			this.matrix.applyToContext(ctx);
			ctx.drawImage(this._canvas || this._image,
					-this._size.width / 2, -this._size.height / 2);
			ctx.restore();
		}
	}
});
<commit_msg>Documentation: Fix typo.<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/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

var Raster = this.Raster = Item.extend({
	/** @lends Raster# */

	beans: true,

	// TODO: Implement url / type, width, height.
	// TODO: Have PlacedSymbol & Raster inherit from a shared class?
	// DOCS: Document Raster constructor.
	/**
	 * Creates a new raster item and places it in the active layer.
	 *
	 * @constructs Raster
	 * @param {HTMLImageElement|Canvas|string} [object]
	 *
	 * @class The Raster item represents an image in a Paper.js project.
	 *
	 * @extends Item
	 */
	initialize: function(object) {
		this.base();
		if (object.getContext) {
			this.setCanvas(object);
		} else {
//#ifdef BROWSER
			// If it's a string, get the element with this id first.
			if (typeof object === 'string')
				object = document.getElementById(object);
//#endif // BROWSER
			this.setImage(object);
		}
		this.matrix = new Matrix();
	},

	clone: function() {
		var image = this._image;
		if (!image) {
			// If the Raster contains a Canvas object, we need to create
			// a new one and draw this raster's canvas on it.
			image = CanvasProvider.getCanvas(this._size);
			image.getContext('2d').drawImage(this._canvas, 0, 0);
		}
		var copy = new Raster(image);
		copy.matrix = this.matrix.clone();
		return this._clone(copy);
	},

	/**
	 * The size of the raster in pixels.
	 *
	 * @type Size
	 * @bean
	 */
	getSize: function() {
		return this._size;
	},

	setSize: function() {
		var size = Size.read(arguments),
			// Get reference to image before changing canvas
			image = this.getImage();
		// Setting canvas internally sets _size
		this.setCanvas(CanvasProvider.getCanvas(size));
		// Draw image back onto new canvas
		this.getContext().drawImage(image, 0, 0, size.width, size.height);
	},

	/**
	 * The width of the raster in pixels.
	 *
	 * @type Number
	 * @bean
	 */
	getWidth: function() {
		return this._size.width;
	},

	/**
	 * The height of the raster in pixels.
	 *
	 * @type Number
	 * @bean
	 */
	getHeight: function() {
		return this._size.height;
	},

	/**
	 * Pixels per inch of the raster at its current size.
	 *
	 * @type Size
	 * @bean
	 */
	getPpi: function() {
		var matrix = this.matrix,
			orig = new Point(0, 0).transform(matrix),
			u = new Point(1, 0).transform(matrix).subtract(orig),
			v = new Point(0, 1).transform(matrix).subtract(orig);
		return new Size(
			72 / u.getLength(),
			72 / v.getLength()
		);
	},

	/**
	 * The Canvas 2d drawing context of the raster.
	 *
	 * @type Context
	 * @bean
	 */
	getContext: function() {
		if (!this._context) {
			this._context = this.getCanvas().getContext('2d');
		}
		return this._context;
	},

	setContext: function(context) {
		this._context = context;
	},

	getCanvas: function() {
		if (!this._canvas) {
			this._canvas = CanvasProvider.getCanvas(this._size);
			if (this._image)
				this.getContext().drawImage(this._image, 0, 0);
		}
		return this._canvas;
	},

	setCanvas: function(canvas) {
		if (this._canvas)
			CanvasProvider.returnCanvas(this._canvas);
		this._canvas = canvas;
		this._size = new Size(canvas.width, canvas.height);
		this._image = null;
		this._context = null;
		this._bounds = null;
	},

	/**
	 * The HTMLImageElement or Canvas of the raster.
	 *
	 * @type HTMLImageElement|Canvas
	 * @bean
	 */
	getImage: function() {
		return this._image || this.getCanvas();
	},

	// TODO: Support string id of image element.
	setImage: function(image) {
		if (this._canvas)
			CanvasProvider.returnCanvas(this._canvas);
		this._image = image;
		// TODO: Cross browser compatible?
		this._size = new Size(image.naturalWidth, image.naturalHeight);
		this._canvas = null;
		this._context = null;
		this._bounds = null;
	},

	// DOCS: document Raster#getSubImage
	/**
	 * @param {Rectangle} rect the boundaries of the sub image in pixel
	 * coordinates
	 *
	 * @return {Canvas}
	 */
	getSubImage: function(rect) {
		rect = Rectangle.read(arguments);
		var canvas = CanvasProvider.getCanvas(rect.getSize());
		canvas.getContext('2d').drawImage(this.getCanvas(), rect.x, rect.y,
				canvas.width, canvas.height, 0, 0, canvas.width, canvas.height);
		return canvas;
	},

	/**
	 * Draws an image on the raster.
	 *
	 * @param {HTMLImageELement|Canvas} image
	 * @param {Point} point the offset of the image as a point in pixel
	 * coordinates
	 */
	drawImage: function(image, point) {
		point = Point.read(arguments, 1);
		this.getContext().drawImage(image, point.x, point.y);
	},

	/**
	 * Calculates the average color of the image within the given path,
	 * rectangle or point. This can be used for creating raster image
	 * effects.
	 *
	 * @param {Path|Rectangle|Point} object
	 * @return {RGBColor} the average color contained in the area covered by the
	 * specified path, rectangle or point.
	 */
	getAverageColor: function(object) {
		if (!object)
			object = this.getBounds();
		var bounds, path;
		if (object instanceof PathItem) {
			// TODO: What if the path is smaller than 1 px?
			// TODO: How about rounding of bounds.size?
			path = object;
			bounds = object.getBounds();
		} else if (object.width) {
			bounds = new Rectangle(object);
		} else if (object.x) {
			bounds = Rectangle.create(object.x - 0.5, object.y - 0.5, 1, 1);
		}
		// Use a sample size of max 32 x 32 pixels, into which the path is
		// scaled as a clipping path, and then the actual image is drawn in and
		// sampled.
		var sampleSize = 32,
			width = Math.min(bounds.width, sampleSize),
			height = Math.min(bounds.height, sampleSize);
		// Reuse the same sample context for speed. Memory consumption is low
		// since it's only 32 x 32 pixels.
		var ctx = Raster._sampleContext;
		if (!ctx) {
			ctx = Raster._sampleContext = CanvasProvider.getCanvas(
					new Size(sampleSize)).getContext('2d');
		} else {
			// Clear the sample canvas:
			ctx.clearRect(0, 0, sampleSize, sampleSize);
		}
		ctx.save();
		// Scale the context so that the bounds ends up at the given sample size
		ctx.scale(width / bounds.width, height / bounds.height);
		ctx.translate(-bounds.x, -bounds.y);
		// If a path was passed, draw it as a clipping mask:
		if (path)
			path.draw(ctx, { clip: true });
		// Now draw the image clipped into it.
		this.matrix.applyToContext(ctx);
		ctx.drawImage(this._canvas || this._image,
				-this._size.width / 2, -this._size.height / 2);
		ctx.restore();
		// Get pixel data from the context and calculate the average color value
		// from it, taking alpha into account.
		var pixels = ctx.getImageData(0.5, 0.5, Math.ceil(width),
				Math.ceil(height)).data,
			channels = [0, 0, 0],
			total = 0;
		for (var i = 0, l = pixels.length; i < l; i += 4) {
			var alpha = pixels[i + 3];
			total += alpha;
			alpha /= 255;
			channels[0] += pixels[i] * alpha;
			channels[1] += pixels[i + 1] * alpha;
			channels[2] += pixels[i + 2] * alpha;
		}
		for (var i = 0; i < 3; i++)
			channels[i] /= total;
		return total ? Color.read(channels) : null;
	},

	/**
	 * {@grouptitle Pixels}
	 * Gets the color of a pixel in the raster.
	 *
	 * @name Raster#getPixel
	 * @function
	 * @param x the x offset of the pixel in pixel coordinates
	 * @param y the y offset of the pixel in pixel coordinates
	 * @return {RGBColor} the color of the pixel
	 */
	/**
	 * Gets the color of a pixel in the raster.
	 * @param point the offset of the pixel as a point in pixel coordinates
	 * @return {RGBColor} the color of the pixel
	 */
	getPixel: function(point) {
		point = Point.read(arguments);
		var pixels = this.getContext().getImageData(point.x, point.y, 1, 1).data,
			channels = new Array(4);
		for (var i = 0; i < 4; i++)
			channels[i] = pixels[i] / 255;
		return RGBColor.read(channels);
	},

	/**
	 * Sets the color of the specified pixel to the specified color.
	 *
	 * @name Raster#setPixel
	 * @function
	 * @param x the x offset of the pixel in pixel coordinates
	 * @param y the y offset of the pixel in pixel coordinates
	 * @param color the color that the pixel will be set to
	 */
	/**
	 * Sets the color of the specified pixel to the specified color.
	 * @param point the offset of the pixel as a point in pixel coordinates
	 * @param color the color that the pixel will be set to
	 */
	setPixel: function(point, color) {
		var hasPoint = arguments.length == 2;
		point = Point.read(arguments, 0, hasPoint ? 1 : 2);
		color = Color.read(arguments, hasPoint ? 1 : 2);
		var ctx = this.getContext(),
			imageData = ctx.createImageData(1, 1),
			alpha = color.getAlpha();
		imageData.data[0] = color.getRed() * 255;
		imageData.data[1] = color.getGreen() * 255;
		imageData.data[2] = color.getBlue() * 255;
		imageData.data[3] = alpha != null ? alpha * 255 : 255;
		ctx.putImageData(imageData, point.x, point.y);
	},

	// DOCS: document Raster#createData
	/**
	 * {@grouptitle Image Data}
	 * @param {Size} size
	 * @return {ImageData}
	 */
	createData: function(size) {
		size = Size.read(arguments);
		return this.getContext().createImageData(size.width, size.height);
	},

	// DOCS: document Raster#getData
	/**
	 * @param {Rectangle} rect
	 * @return {ImageData}
	 */
	getData: function(rect) {
		rect = Rectangle.read(arguments);
		if (rect.isEmpty())
			rect = new Rectangle(this.getSize());
		return this.getContext().getImageData(rect.x, rect.y,
				rect.width, rect.height);
	},

	// DOCS: document Raster#setData
	/**
	 * @param {ImageData} data
	 * @param {Point} point
	 * @return {ImageData}
	 */
	setData: function(data, point) {
		point = Point.read(arguments, 1);
		this.getContext().putImageData(data, point.x, point.y);
	},

	_transform: function(matrix, flags) {
		// In order to set the right context transformation when drawing the
		// raster, simply preconcatenate the internal matrix with the provided
		// one.
		this.matrix.preConcatenate(matrix);
		this._bounds = null;
	},

	getBounds: function() {
		if (!this._bounds) {
			this._bounds = this.matrix._transformBounds(
					new Rectangle(this._size).setCenter(0, 0));
		}
		return this._bounds;
	},

	getStrokeBounds: function() {
		return this.getBounds();
	},

	draw: function(ctx, param) {
		if (param.selection) {
			var bounds = new Rectangle(this._size).setCenter(0, 0);
			Item.drawSelectedBounds(bounds, ctx, this.matrix);
		} else {
			ctx.save();
			this.matrix.applyToContext(ctx);
			ctx.drawImage(this._canvas || this._image,
					-this._size.width / 2, -this._size.height / 2);
			ctx.restore();
		}
	}
});
<|endoftext|>


<commit_before>// Create jController object
$.jController = new Object();

// @private : _plugins object contains the function & parameters that will be used in this function
$.jController._plugins = new Object();

// JQuery Plugin definition.
$.fn.jController = function( callback ) {

 	// Get context of canvas
 	var _ctx = this[0].getContext("2d");

	// get all plugins previously used
 	$.each($.jController._plugins,function(PluginName,p){

 		// smaller is better isn't ?
 		var n = PluginName;

 		// Get all params
 		$.each(p.paramsList,function(i,params){

 			//@TODO : Put default params by using $.extend({},default,params) to skip errors when some params are absent
 			// call the plugin function with params
 			p.fn(_ctx,params);
 		})

 	});

 	return this;
};

// Add new plugin
$.jController.addPlugin = function(plugin)
{
	// check wether the name has been set
    if (plugin.name)
    {
    	// Create new object of plugin
    	$.jController._plugins[plugin.name] = new Object();

    	//Create paramsList[] this will contain all params of PluginName
    	$.jController._plugins[plugin.name].paramsList = []

        // Register plugin function into _plugins[name].fn
        $.jController._plugins[plugin.name].fn = plugin.fn;

        // add plugin function
        // When we call a plugin Ex : $.jController.arc this one will insert all parameters into $.jController._plugins.arc.params
        $.jController[plugin.name] = function(params)
        {
           $.jController._plugins[plugin.name].paramsList.push (params);
        }

        //console.log($.jController);
    }
}

//@TODO use the same method as addPlugin to create addEvent (Ex : click,touch etc..) & AddProperty (Ex : draggable:true)

// -------- PLUGINS ----------

// TODO : Add >> http://www.w3schools.com/tags/ref_canvas.asp

// Add arc plugin
$.jController.addPlugin({
	name:"arc",
	fn : function(ctx,params)
	{
		// Data processing

		// smaller is better isn't ?
		var p = params;

		// canvas api
		ctx.beginPath();
		ctx.arc(p.x,p.y,p.r,p.sAngle,p.eAngle);
		ctx.stroke();
	}

});

// Add rect plugin
$.jController.addPlugin({
	name:"rect",
	fn : function(ctx,params)
	{
		// smaller is better isn't ?
		var p = params;

		// canvas api
		ctx.rect(p.x,p.y,p.width,p.height);
		ctx.stroke();
	}

});

//@TODO add svg plugin, transform an svg file to canvas code check http://www.professorcloud.com/svg-to-canvas/ [use Canvg library]<commit_msg>Add an example of event<commit_after>// Create jController object
$.jController = new Object();

// @private : _plugins object contains the function & parameters that will be used in this function
$.jController._plugins = new Object();

// JQuery Plugin definition.
$.fn.jController = function( callback ) {

 	// Get context of canvas
 	var _ctx = this[0].getContext("2d");

	// get all plugins previously used
 	$.each($.jController._plugins,function(PluginName,p){

 		// smaller is better isn't ?
 		var n = PluginName;

 		// Get all params
 		$.each(p.paramsList,function(i,params){

 			//@TODO : Put default params by using $.extend({},default,params) to skip errors when some params are absent
 			// call the plugin function with params
 			p.fn(_ctx,params);
 		})

 	});

 	return this;
};

// Add new plugin
$.jController.addPlugin = function(plugin)
{
	// check wether the name has been set
    if (plugin.name)
    {
    	// Create new object of plugin
    	$.jController._plugins[plugin.name] = new Object();

    	//Create paramsList[] this will contain all params of PluginName
    	$.jController._plugins[plugin.name].paramsList = []

        // Register plugin function into _plugins[name].fn
        $.jController._plugins[plugin.name].fn = plugin.fn;

        // add plugin function
        // When we call a plugin Ex : $.jController.arc this one will insert all parameters into $.jController._plugins.arc.params
        $.jController[plugin.name] = function(params)
        {
           $.jController._plugins[plugin.name].paramsList.push (params);
        }

        //console.log($.jController);
    }
}

/*
@TODO use the same method as addPlugin to create addEvent (Ex : click,touch etc..) & AddProperty (Ex : draggable:true)
We can use .on & .trigger from jquery cf : http://api.jquery.com/trigger/
Each plugin can use either the default event or a specific one (so we have to edit addPlugin)

Ex of event :
$.jController.addEvent({
	name:"click",
	fn : function()
	{

	}

});

*/

// -------- PLUGINS ----------

// TODO : Add >> http://www.w3schools.com/tags/ref_canvas.asp

// Add arc plugin
$.jController.addPlugin({
	name:"arc",
	fn : function(ctx,params)
	{
		// Data processing

		// smaller is better isn't ?
		var p = params;

		// canvas api
		ctx.beginPath();
		ctx.arc(p.x,p.y,p.r,p.sAngle,p.eAngle);
		ctx.stroke();
	}

});

// Add rect plugin
$.jController.addPlugin({
	name:"rect",
	fn : function(ctx,params)
	{
		// smaller is better isn't ?
		var p = params;

		// canvas api
		ctx.rect(p.x,p.y,p.width,p.height);
		ctx.stroke();
	}

});

//@TODO add svg plugin, transform an svg file to canvas code check http://www.professorcloud.com/svg-to-canvas/ [use Canvg library]<|endoftext|>


<commit_before>import React from "react";
import moment from 'moment';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group'

import NewsItem from "./NewsItem";
import NewsCow from "./NewsCow";

// const NewsItem = ({info}) => (
//

//     {info.title} {info.sitelink}
//

//       <img src={`/dist/icons/${info.sitehost}.jpg`} />
//

//

// )

export default class NewsList extends React.Component {
  render () {

    if (this.props.loading) {
      return
Loading

    }

    if (this.props.newsItems.length === 0) {
      return (

      );
    } else {
      var makeList = x =>
<NewsItem info={x}/>
;

      return (
          <ReactCSSTransitionGroup component="ul" className="newsWrapper"
            transitionName="example"
            transitionAppear={true}
            transitionAppearTimeout={500}
            transitionEnterTimeout={500}
            transitionLeaveTimeout={300}>
            { this.props.newsItems.map(makeList) }
          </ReactCSSTransitionGroup>
  		);
    }
	}
};<commit_msg>Use itemID as react list key.<commit_after>import React from "react";
import moment from 'moment';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group'

import NewsItem from "./NewsItem";
import NewsCow from "./NewsCow";

// const NewsItem = ({info}) => (
//

//     {info.title} {info.sitelink}
//

//       <img src={`/dist/icons/${info.sitehost}.jpg`} />
//

//

// )

export default class NewsList extends React.Component {
  render () {

    if (this.props.loading) {
      return
Loading

    }

    if (this.props.newsItems.length === 0) {
      return (

      );
    } else {
      var makeList = x =>
<NewsItem info={x}/>
;

      return (
          <ReactCSSTransitionGroup component="ul" className="newsWrapper"
            transitionName="example"
            transitionAppear={true}
            transitionAppearTimeout={500}
            transitionEnterTimeout={500}
            transitionLeaveTimeout={300}>
            { this.props.newsItems.map(makeList) }
          </ReactCSSTransitionGroup>
  		);
    }
	}
};<|endoftext|>


<commit_before>define([
    'text!template_dir/playlist/pane.html',
    'text!template_dir/playlist/progress.html',
    'text!template_dir/playlist/item.html',
    'text!template_dir/playlist/related.html',
    'ui-sortable',
    './Services',
    'angular'
], function (PaneTemplate, ProgressTemplate, ItemTemplate, RelatedTemplate) {
    function mouseCoords (event) {
        var totalOffsetX = 0,
            totalOffsetY = 0,
            canvasX = 0,
            canvasY = 0,
            currentElement = event.target;

        do{
            totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
            totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
            currentElement = currentElement.offsetParent;
        }
        while (currentElement);

        canvasX = event.pageX - totalOffsetX;
        canvasY = event.pageY - totalOffsetY;

        return {
            x: canvasX,
            y: canvasY
        };
    }

    return angular.module('ui.playlist', ['services', 'filters', 'ui.sortable'])
            .directive('playlistPane', ['$rootScope', '$http', 'youtubeAPI', 'playList', function ($rootScope, $http, youtubeAPI, playList) {
                var definitions = {
                        restrict: 'E',
                        template: PaneTemplate,
                        replace: true,
                        scope: true,
                        link: function ($scope, $element, $attrs) {
                            var media = window.matchMedia('(max-width:960px),(max-device-width:960px)');

                            if (media.matches) {
                                $scope.ready = true;
                            }
                            else {
                                $rootScope.$on('searchPane:loaded', function () {
                                    $scope.ready = true;
                                    if (!$scope.$$phase) $scope.$digest();
                                });
                            }

                            if (playList.playlist.length) {
                                $rootScope.$broadcast('setCurrentView', 'playlist');
                            }

                            $rootScope.$on('playList:stateChanged', function (e, state) {
                                $scope.nowPlayingIdx = playList.getNowPlayingIdx();
                                if (!$scope.$$phase) $scope.$digest();
                            });

                            $scope.sortableOpts = {
                                axis: 'y',
                                handle: '.mover',
                                stop: function (e, ui) {
                                    // Fix the playlist's currently playing track
                                    var fromIdx     = ui.item.sortable.index,
                                        toIdx       = ui.item.sortable.dropindex,
                                        nowPlaying  = playList.getNowPlayingIdx();

                                    if (typeof nowPlaying === 'number') {
                                        if (fromIdx < nowPlaying &&
                                            toIdx >= nowPlaying) {
                                            playList.setNowPlaying(nowPlaying - 1);
                                        }
                                        else if (fromIdx > nowPlaying &&
                                            toIdx <= nowPlaying) {
                                            playList.setNowPlaying(nowPlaying + 1);
                                        }
                                        else if (fromIdx === nowPlaying) {
                                            playList.setNowPlaying(toIdx);
                                        }
                                    }

                                    playList.save();
                                }
                            };
                        },
                        controller: function ($scope, $element, $attrs, $transclude) {
                            $scope.items = playList.playlist;
                        }
                    };

                return definitions;
            }]).directive('playlistProgress', ['$rootScope', 'youtubePlayer', function ($rootScope, youtubePlayer) {
                var definitions = {
                        restrict: 'E',
                        template: ProgressTemplate,
                        replace: true,
                        scope: true,
                        link: function ($scope, $element, $attrs) {
                            $element.on('click', function (e) {
                                var coords, time;

                                if (e.target.classList.contains('progress')) {
                                    coords = mouseCoords(e);
                                    time = $scope.duration * (coords.x / e.target.clientWidth);

                                    youtubePlayer.seek(time);
                                }
                            });
                        },
                        controller: function ($scope, $element, $attrs) {
                            $scope.duration = 0;
                            $scope.progress = 0;

                            $rootScope.$on('youtubePlayer:infoDelivery', function (e, data) {
                                if (data.info.duration)
                                    $scope.duration = data.info.duration;

                                if (data.info.currentTime)
                                    $scope.progress = data.info.currentTime;

                                if (!$scope.$$phase) $scope.$digest();
                            });
                        }
                    };

                return definitions;
            }]).directive('playlistItem', ['$rootScope', '$http', 'playList', function ($rootScope, $http, playList) {
                var definitions = {
                        restrict: 'E',
                        template: ItemTemplate,
                        replace: true,
                        scope: {
                            'videoId': '@videoId',
                            'title': '@title',
                            'thumbnail': '@thumbnail',
                            'autoplay': '@autoplay',
                            'index': '@index'
                        },
                        controller: function ($scope, $element, $attrs, $transclude) {
                            $rootScope.$on('youtubePlayer:infoDelivery', function (e, state) {
                                $scope.nowPlaying = playList.getNowPlayingIdx() === $scope.getIndex();
                                $scope.isActive = ($scope.nowPlaying &&
                                    playList.getState() === playList.st.PLAYING);

                                if (!$scope.$$phase) $scope.$digest();
                            });
                            $rootScope.$on('playList:stateChanged', function (e, state) {
                                $scope.nowPlaying = playList.getNowPlayingIdx() === $scope.getIndex();
                                $scope.isActive = ($scope.nowPlaying && state === playList.st.PLAYING);
                                $scope.isBuffering = $scope.nowPlaying && [
                                    playList.st.PLAYING,
                                    playList.st.PAUSING,
                                    playList.st.STOPPED
                                ].indexOf(state) < 0;

                                // Scroll element into view if it is currently
                                // playing
                                if ($scope.getIndex() === playList.getNowPlayingIdx())
                                    $element[0].scrollIntoView();

                                if (!$scope.$$phase) $scope.$digest();
                            });

                            $scope.getIndex = function () {
                                return parseInt($scope.index, 10);
                            };

                            $scope.pause = function () {
                                playList.pause();
                            };

                            $scope.togglePlay = function () {
                                if ($scope.isActive)
                                    playList.pause();
                                else
                                    playList.play($scope.getIndex());
                            };

                            $scope.removeItem = function () {
                                playList.remove($scope.getIndex());
                            };
                        }
                    };

                return definitions;
            }]).directive('playlistRelated', ['$rootScope', 'youtubePlayer', 'youtubeAPI', 'playList', function ($rootScope, youtubePlayer, youtubeAPI, playList) {
                var definitions = {
                        restrict: 'E',
                        template: RelatedTemplate,
                        replace: true,
                        scope: {
                        },
                        controller: function ($scope, $element, $attrs, $transclude) {
                            $scope.addItem = function (videoId) {
                                playList.addLast(videoId);
                            };
                            $scope.$watch(playList.getNowPlaying, function (item) {
                                if (item) {
                                    youtubeAPI.getRelated(item.id).then(function (items) {
                                        $scope.items = items;
                                    });
                                }
                            });
                        }
                    };
                return definitions;
            }]);
});
<commit_msg>Fixed issue here playlist wouldnt show on 960<width<1280<commit_after>define([
    'text!template_dir/playlist/pane.html',
    'text!template_dir/playlist/progress.html',
    'text!template_dir/playlist/item.html',
    'text!template_dir/playlist/related.html',
    'ui-sortable',
    './Services',
    'angular'
], function (PaneTemplate, ProgressTemplate, ItemTemplate, RelatedTemplate) {
    function mouseCoords (event) {
        var totalOffsetX = 0,
            totalOffsetY = 0,
            canvasX = 0,
            canvasY = 0,
            currentElement = event.target;

        do{
            totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
            totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
            currentElement = currentElement.offsetParent;
        }
        while (currentElement);

        canvasX = event.pageX - totalOffsetX;
        canvasY = event.pageY - totalOffsetY;

        return {
            x: canvasX,
            y: canvasY
        };
    }

    return angular.module('ui.playlist', ['services', 'filters', 'ui.sortable'])
            .directive('playlistPane', ['$rootScope', '$http', 'youtubeAPI', 'playList', function ($rootScope, $http, youtubeAPI, playList) {
                var definitions = {
                        restrict: 'E',
                        template: PaneTemplate,
                        replace: true,
                        scope: true,
                        link: function ($scope, $element, $attrs) {
                            var media = window.matchMedia('(max-width:1280px),(max-device-width:1280px)');

                            if (media.matches) {
                                $scope.ready = true;
                            }
                            else {
                                $rootScope.$on('searchPane:loaded', function () {
                                    $scope.ready = true;
                                    if (!$scope.$$phase) $scope.$digest();
                                });
                            }

                            if (playList.playlist.length) {
                                $rootScope.$broadcast('setCurrentView', 'playlist');
                            }

                            $rootScope.$on('playList:stateChanged', function (e, state) {
                                $scope.nowPlayingIdx = playList.getNowPlayingIdx();
                                if (!$scope.$$phase) $scope.$digest();
                            });

                            $scope.sortableOpts = {
                                axis: 'y',
                                handle: '.mover',
                                stop: function (e, ui) {
                                    // Fix the playlist's currently playing track
                                    var fromIdx     = ui.item.sortable.index,
                                        toIdx       = ui.item.sortable.dropindex,
                                        nowPlaying  = playList.getNowPlayingIdx();

                                    if (typeof nowPlaying === 'number') {
                                        if (fromIdx < nowPlaying &&
                                            toIdx >= nowPlaying) {
                                            playList.setNowPlaying(nowPlaying - 1);
                                        }
                                        else if (fromIdx > nowPlaying &&
                                            toIdx <= nowPlaying) {
                                            playList.setNowPlaying(nowPlaying + 1);
                                        }
                                        else if (fromIdx === nowPlaying) {
                                            playList.setNowPlaying(toIdx);
                                        }
                                    }

                                    playList.save();
                                }
                            };
                        },
                        controller: function ($scope, $element, $attrs, $transclude) {
                            $scope.items = playList.playlist;
                        }
                    };

                return definitions;
            }]).directive('playlistProgress', ['$rootScope', 'youtubePlayer', function ($rootScope, youtubePlayer) {
                var definitions = {
                        restrict: 'E',
                        template: ProgressTemplate,
                        replace: true,
                        scope: true,
                        link: function ($scope, $element, $attrs) {
                            $element.on('click', function (e) {
                                var coords, time;

                                if (e.target.classList.contains('progress')) {
                                    coords = mouseCoords(e);
                                    time = $scope.duration * (coords.x / e.target.clientWidth);

                                    youtubePlayer.seek(time);
                                }
                            });
                        },
                        controller: function ($scope, $element, $attrs) {
                            $scope.duration = 0;
                            $scope.progress = 0;

                            $rootScope.$on('youtubePlayer:infoDelivery', function (e, data) {
                                if (data.info.duration)
                                    $scope.duration = data.info.duration;

                                if (data.info.currentTime)
                                    $scope.progress = data.info.currentTime;

                                if (!$scope.$$phase) $scope.$digest();
                            });
                        }
                    };

                return definitions;
            }]).directive('playlistItem', ['$rootScope', '$http', 'playList', function ($rootScope, $http, playList) {
                var definitions = {
                        restrict: 'E',
                        template: ItemTemplate,
                        replace: true,
                        scope: {
                            'videoId': '@videoId',
                            'title': '@title',
                            'thumbnail': '@thumbnail',
                            'autoplay': '@autoplay',
                            'index': '@index'
                        },
                        controller: function ($scope, $element, $attrs, $transclude) {
                            $rootScope.$on('youtubePlayer:infoDelivery', function (e, state) {
                                $scope.nowPlaying = playList.getNowPlayingIdx() === $scope.getIndex();
                                $scope.isActive = ($scope.nowPlaying &&
                                    playList.getState() === playList.st.PLAYING);

                                if (!$scope.$$phase) $scope.$digest();
                            });
                            $rootScope.$on('playList:stateChanged', function (e, state) {
                                $scope.nowPlaying = playList.getNowPlayingIdx() === $scope.getIndex();
                                $scope.isActive = ($scope.nowPlaying && state === playList.st.PLAYING);
                                $scope.isBuffering = $scope.nowPlaying && [
                                    playList.st.PLAYING,
                                    playList.st.PAUSING,
                                    playList.st.STOPPED
                                ].indexOf(state) < 0;

                                // Scroll element into view if it is currently
                                // playing
                                if ($scope.getIndex() === playList.getNowPlayingIdx())
                                    $element[0].scrollIntoView();

                                if (!$scope.$$phase) $scope.$digest();
                            });

                            $scope.getIndex = function () {
                                return parseInt($scope.index, 10);
                            };

                            $scope.pause = function () {
                                playList.pause();
                            };

                            $scope.togglePlay = function () {
                                if ($scope.isActive)
                                    playList.pause();
                                else
                                    playList.play($scope.getIndex());
                            };

                            $scope.removeItem = function () {
                                playList.remove($scope.getIndex());
                            };
                        }
                    };

                return definitions;
            }]).directive('playlistRelated', ['$rootScope', 'youtubePlayer', 'youtubeAPI', 'playList', function ($rootScope, youtubePlayer, youtubeAPI, playList) {
                var definitions = {
                        restrict: 'E',
                        template: RelatedTemplate,
                        replace: true,
                        scope: {
                        },
                        controller: function ($scope, $element, $attrs, $transclude) {
                            $scope.addItem = function (videoId) {
                                playList.addLast(videoId);
                            };
                            $scope.$watch(playList.getNowPlaying, function (item) {
                                if (item) {
                                    youtubeAPI.getRelated(item.id).then(function (items) {
                                        $scope.items = items;
                                    });
                                }
                            });
                        }
                    };
                return definitions;
            }]);
});
<|endoftext|>


<commit_before>var domHooks = {
  sources: {
    document_location_hash: function() {
      var original_document_location_hash = document.location.hash;
      Object.defineProperty(document.location, "hash", {
        get: function() {
          track.sources.add(new Object({
            'type': 'document.location.hash',
            'data': original_document_location_hash,
            'meta': functionCallTracer()
          }));
          return original_document_location_hash;
        }
      });
    },
    document_cookie: function() {
      var original_document_cookie = document.cookie;
      Object.defineProperty(document, "cookie", {
        get: function() {
          track.sources.add(new Object({
            'type': 'document.cookie',
            'data': original_document_cookie,
            'meta': functionCallTracer()
          }));
          return original_document_cookie;
        }
      });
    }
  },

  sinks: {
    window_eval: function() {
      var original_window_eval = window.eval;
      window.eval = function() {
        track.sinks.add(new Object({
          'type': 'eval',
          'data': arguments[0],
          'meta': functionCallTracer()
        }));
        return original_window_eval.apply(this, arguments);
      }
    },
    document_write: function() {
      var original_document_write = document.write;
      document.write = function() {
        track.sinks.add(new Object({
          'type': 'document.write',
          'data': arguments[0],
          'meta': functionCallTracer()
        }));
        return original_document_write.apply(this, arguments);
      }
    },
    window_setTimeout: function() {
      var original_window_setTimeout = window.setTimeout;
      window.setTimeout = function() {
        track.sinks.add(new Object({
          'type': 'setTimeout',
          'data': arguments[0].toString(),
          'meta': functionCallTracer()
        }));
        return original_window_setTimeout.apply(this, arguments)
      }
    },
    window_setInterval: function() {
      var original_window_setInterval = window.setInterval;
      window.setInterval = function() {
        track.sinks.add(new Object({
          'type': 'setInterval',
          'data': arguments[0].toString(),
          'meta': functionCallTracer()
        }));
        return original_window_setInterval.apply(this, arguments)
      }
    }
  },

  xhook: function() {
    xhook.enable();
    xhook.after(function(req, res) {
      console.log(req);
      console.log(res);
      track.xhr.add({ // need to add more OBJECTs!!
        method: req.method,
        url: req.url,
        reqBody: req.body
      });
    })
  },

  wshook: function() {
    wsHook.onMessage = function(event) {
      console.log("ws recieved: " + event);
      track.ws.add({
        data: event.data,
        url: event.url,
        type: 'response' // onMessage from the server
      });
    }

    wsHook.onSend = function(event) {
      console.log("ws sent: " + event);
      track.ws.add({
        data: event.data,
        url: event.url,
        type: 'request' // onSend to the server
      });
    }
  },

  unsafeAnchors: function() {
    // https://hackerone.com/reports/23386
    var hookUnsafeAnchors = function() {
      console.log('Hooking into all Anchor tags to analyze them for unsafe usage of target="_blank"');
      var anchors = document.getElementsByTagName('a');
      // Convert HTMLCollection to Array
      anchors = [].slice.call(anchors);
      anchors.forEach(function(anchor) {
        if ('target' in anchor && anchor.target == '_blank') {
          var tmpNode = document.createElement("div");
          tmpNode.appendChild(anchor);
          track.unsafeAnchors.add({
            href: anchor.href,
            target: anchor.target,
            hostname: anchor.hostname,
            string: tmpNode.innerHTML.toString()
          });
          delete tmpNode;
        }
      })
      console.log(anchors);
    }
    window.addEventListener("load", hookUnsafeAnchors, false);
  },

  init: function() {
    var original_document_domain = document.domain;
    var track = {};
    track.domain = original_document_domain; // How funny, we could have used a hooked value.
    track.href = document.location.href; // This cannot be hooked in browsers today.
    track.sources = [];
    track.sinks = [];
    track.xhr = [];
    track.ws = [];
    track.unsafeAnchors = [];

    track.sources.add = function(obj) {
      track.sources.push(obj);
      console.log(obj.type + " called with value " + obj.data.slice(0, 100));
      obj.nature = 'source';
      obj.domain = track.domain;
      obj.href = track.href;
      window.postMessage({
        type: "FROM_HOOKISH",
        'obj': obj
      }, "*");
    }

    track.sinks.add = function(obj) {
      track.sinks.push(obj);
      console.log(obj.type + " called with value " + obj.data.toString().slice(0, 100));
      obj.nature = 'sink';
      obj.domain = track.domain;
      obj.href = track.href;
      window.postMessage({
        type: "FROM_HOOKISH",
        'obj': obj
      }, "*");
    }

    track.xhr.add = function(obj) {
      track.xhr.push(obj);
      console.log(obj.method + "  " + obj.url);
      obj.nature = 'xhr';
      window.postMessage({
        type: "FROM_HOOKISH",
        'obj': obj
      }, "*");
    }

    track.unsafeAnchors.add = function(obj) {
      track.unsafeAnchors.push(obj);
      obj.nature = 'unsafeAnchors';
      window.postMessage({
        type: "FROM_HOOKISH",
        'obj': obj
      }, "*");
    }

    track.ws.add = function(obj) {
      track.ws.push(obj);
      console.log(obj.url + "  " + obj.data + " " + obj.type);
      obj.nature = 'ws';
      window.postMessage({
        type: "FROM_HOOKISH",
        'obj': obj
      }, "*");
    }

  }

}<commit_msg>fix anchor remove bug<commit_after>var domHooks = {
  sources: {
    document_location_hash: function() {
      var original_document_location_hash = document.location.hash;
      Object.defineProperty(document.location, "hash", {
        get: function() {
          track.sources.add(new Object({
            'type': 'document.location.hash',
            'data': original_document_location_hash,
            'meta': functionCallTracer()
          }));
          return original_document_location_hash;
        }
      });
    },
    document_cookie: function() {
      var original_document_cookie = document.cookie;
      Object.defineProperty(document, "cookie", {
        get: function() {
          track.sources.add(new Object({
            'type': 'document.cookie',
            'data': original_document_cookie,
            'meta': functionCallTracer()
          }));
          return original_document_cookie;
        }
        // TODO: FIXME - Define the setter for Cookies.
        // https://github.com/skepticfx/hookish/issues/2
      });
    }
  },

  sinks: {
    window_eval: function() {
      var original_window_eval = window.eval;
      window.eval = function() {
        track.sinks.add(new Object({
          'type': 'eval',
          'data': arguments[0],
          'meta': functionCallTracer()
        }));
        return original_window_eval.apply(this, arguments);
      }
    },
    document_write: function() {
      var original_document_write = document.write;
      document.write = function() {
        track.sinks.add(new Object({
          'type': 'document.write',
          'data': arguments[0],
          'meta': functionCallTracer()
        }));
        return original_document_write.apply(this, arguments);
      }
    },
    window_setTimeout: function() {
      var original_window_setTimeout = window.setTimeout;
      window.setTimeout = function() {
        track.sinks.add(new Object({
          'type': 'setTimeout',
          'data': arguments[0].toString(),
          'meta': functionCallTracer()
        }));
        return original_window_setTimeout.apply(this, arguments)
      }
    },
    window_setInterval: function() {
      var original_window_setInterval = window.setInterval;
      window.setInterval = function() {
        track.sinks.add(new Object({
          'type': 'setInterval',
          'data': arguments[0].toString(),
          'meta': functionCallTracer()
        }));
        return original_window_setInterval.apply(this, arguments)
      }
    }
  },

  xhook: function() {
    xhook.enable();
    xhook.after(function(req, res) {
      console.log(req);
      console.log(res);
      track.xhr.add({ // need to add more OBJECTs!!
        method: req.method,
        url: req.url,
        reqBody: req.body
      });
    })
  },

  wshook: function() {
    wsHook.onMessage = function(event) {
      console.log("ws recieved: " + event);
      track.ws.add({
        data: event.data,
        url: event.url,
        type: 'response' // onMessage from the server
      });
    }

    wsHook.onSend = function(event) {
      console.log("ws sent: " + event);
      track.ws.add({
        data: event.data,
        url: event.url,
        type: 'request' // onSend to the server
      });
    }
  },

  unsafeAnchors: function() {
    // https://hackerone.com/reports/23386
    var hookUnsafeAnchors = function() {
      console.log('Hooking into all Anchor tags to analyze them for unsafe usage of target="_blank"');
      var anchors = document.getElementsByTagName('a');
      // Convert HTMLCollection to Array
      anchors = [].slice.call(anchors);
      anchors.forEach(function(anchor) {
        if ('target' in anchor && anchor.target == '_blank') {
          var anchorCopy = anchor.cloneNode();
          var tmpNode = document.createElement("div");
          tmpNode.appendChild(anchorCopy);
          track.unsafeAnchors.add({
            href: anchor.href,
            target: anchor.target,
            hostname: anchor.hostname,
            string: tmpNode.innerHTML.toString()
          });
          delete tmpNode;
        }
      })
      console.log(anchors);
    }
    window.addEventListener("load", hookUnsafeAnchors, false);
  },

  init: function() {
    var original_document_domain = document.domain;
    var track = {};
    track.domain = original_document_domain; // How funny, we could have used a hooked value.
    track.href = document.location.href; // This cannot be hooked in browsers today.
    track.sources = [];
    track.sinks = [];
    track.xhr = [];
    track.ws = [];
    track.unsafeAnchors = [];

    track.sources.add = function(obj) {
      track.sources.push(obj);
      console.log(obj.type + " called with value " + obj.data.slice(0, 100));
      obj.nature = 'source';
      obj.domain = track.domain;
      obj.href = track.href;
      window.postMessage({
        type: "FROM_HOOKISH",
        'obj': obj
      }, "*");
    }

    track.sinks.add = function(obj) {
      track.sinks.push(obj);
      console.log(obj.type + " called with value " + obj.data.toString().slice(0, 100));
      obj.nature = 'sink';
      obj.domain = track.domain;
      obj.href = track.href;
      window.postMessage({
        type: "FROM_HOOKISH",
        'obj': obj
      }, "*");
    }

    track.xhr.add = function(obj) {
      track.xhr.push(obj);
      console.log(obj.method + "  " + obj.url);
      obj.nature = 'xhr';
      window.postMessage({
        type: "FROM_HOOKISH",
        'obj': obj
      }, "*");
    }

    track.unsafeAnchors.add = function(obj) {
      track.unsafeAnchors.push(obj);
      obj.nature = 'unsafeAnchors';
      window.postMessage({
        type: "FROM_HOOKISH",
        'obj': obj
      }, "*");
    }

    track.ws.add = function(obj) {
      track.ws.push(obj);
      console.log(obj.url + "  " + obj.data + " " + obj.type);
      obj.nature = 'ws';
      window.postMessage({
        type: "FROM_HOOKISH",
        'obj': obj
      }, "*");
    }

  }

}<|endoftext|>


<commit_before>import * as $ from './utilities';

const REGEXP_ACTIONS = /^(e|w|s|n|se|sw|ne|nw|all|crop|move|zoom)$/;

function getPointer({ pageX, pageY }, endOnly) {
  const end = {
    endX: pageX,
    endY: pageY,
  };

  if (endOnly) {
    return end;
  }

  return $.extend({
    startX: pageX,
    startY: pageY,
  }, end);
}

export default {
  resize() {
    const self = this;
    const restore = self.options.restore;
    const container = self.container;
    const containerData = self.containerData;

    // Check `container` is necessary for IE8
    if (self.disabled || !containerData) {
      return;
    }

    const ratio = container.offsetWidth / containerData.width;
    let canvasData;
    let cropBoxData;

    // Resize when width changed or height changed
    if (ratio !== 1 || container.offsetHeight !== containerData.height) {
      if (restore) {
        canvasData = self.getCanvasData();
        cropBoxData = self.getCropBoxData();
      }

      self.render();

      if (restore) {
        self.setCanvasData($.each(canvasData, (n, i) => {
          canvasData[i] = n * ratio;
        }));
        self.setCropBoxData($.each(cropBoxData, (n, i) => {
          cropBoxData[i] = n * ratio;
        }));
      }
    }
  },

  dblclick() {
    const self = this;

    if (self.disabled) {
      return;
    }

    self.setDragMode($.hasClass(self.dragBox, 'cropper-crop') ? 'move' : 'crop');
  },

  wheel(event) {
    const self = this;
    const e = $.getEvent(event);
    const ratio = Number(self.options.wheelZoomRatio) || 0.1;
    let delta = 1;

    if (self.disabled) {
      return;
    }

    e.preventDefault();

    // Limit wheel speed to prevent zoom too fast (#21)
    if (self.wheeling) {
      return;
    }

    self.wheeling = true;

    setTimeout(() => {
      self.wheeling = false;
    }, 50);

    if (e.deltaY) {
      delta = e.deltaY > 0 ? 1 : -1;
    } else if (e.wheelDelta) {
      delta = -e.wheelDelta / 120;
    } else if (e.detail) {
      delta = e.detail > 0 ? 1 : -1;
    }

    self.zoom(-delta * ratio, e);
  },

  cropStart(event) {
    const self = this;

    if (self.disabled) {
      return;
    }

    const options = self.options;
    const pointers = self.pointers;
    const e = $.getEvent(event);
    let action;

    if (e.changedTouches) {
      // Handle touch event
      $.each(e.changedTouches, (touch) => {
        pointers[touch.identifier] = getPointer(touch);
      });
    } else {
      // Handle mouse event and pointer event
      pointers[e.pointerId || 0] = getPointer(e);
    }

    if (Object.keys(pointers).length > 1 && options.zoomable && options.zoomOnTouch) {
      action = 'zoom';
    } else {
      action = $.getData(e.target, 'action');
    }

    if (REGEXP_ACTIONS.test(action)) {
      if ($.dispatchEvent(self.element, 'cropstart', {
        originalEvent: e,
        action,
      }) === false) {
        return;
      }

      e.preventDefault();

      self.action = action;
      self.cropping = false;

      if (action === 'crop') {
        self.cropping = true;
        $.addClass(self.dragBox, 'cropper-modal');
      }
    }
  },

  cropMove(event) {
    const self = this;
    const action = self.action;

    if (self.disabled || !action) {
      return;
    }

    const pointers = self.pointers;
    const e = $.getEvent(event);

    e.preventDefault();

    if ($.dispatchEvent(self.element, 'cropmove', {
      originalEvent: e,
      action,
    }) === false) {
      return;
    }

    if (e.changedTouches) {
      $.each(e.changedTouches, (touch) => {
        $.extend(pointers[touch.identifier], getPointer(touch, true));
      });
    } else {
      $.extend(pointers[e.pointerId || 0], getPointer(e, true));
    }

    self.change(e);
  },

  cropEnd(event) {
    const self = this;
    const action = self.action;

    if (self.disabled || !action) {
      return;
    }

    const options = self.options;
    const pointers = self.pointers;
    const e = $.getEvent(event);

    e.preventDefault();

    if (e.changedTouches) {
      $.each(e.changedTouches, (touch) => {
        delete pointers[touch.identifier];
      });
    } else {
      delete pointers[e.pointerId || 0];
    }

    if (!Object.keys(pointers).length) {
      self.action = '';
    }

    if (self.cropping) {
      self.cropping = false;
      $.toggleClass(self.dragBox, 'cropper-modal', self.cropped && options.modal);
    }

    $.dispatchEvent(self.element, 'cropend', {
      originalEvent: e,
      action,
    });
  },
};
<commit_msg>Simplify code<commit_after>import * as $ from './utilities';

const REGEXP_ACTIONS = /^(e|w|s|n|se|sw|ne|nw|all|crop|move|zoom)$/;

function getPointer({ pageX, pageY }, endOnly) {
  const end = {
    endX: pageX,
    endY: pageY,
  };

  if (endOnly) {
    return end;
  }

  return $.extend({
    startX: pageX,
    startY: pageY,
  }, end);
}

export default {
  resize() {
    const self = this;
    const restore = self.options.restore;
    const container = self.container;
    const containerData = self.containerData;

    // Check `container` is necessary for IE8
    if (self.disabled || !containerData) {
      return;
    }

    const ratio = container.offsetWidth / containerData.width;
    let canvasData;
    let cropBoxData;

    // Resize when width changed or height changed
    if (ratio !== 1 || container.offsetHeight !== containerData.height) {
      if (restore) {
        canvasData = self.getCanvasData();
        cropBoxData = self.getCropBoxData();
      }

      self.render();

      if (restore) {
        self.setCanvasData($.each(canvasData, (n, i) => {
          canvasData[i] = n * ratio;
        }));
        self.setCropBoxData($.each(cropBoxData, (n, i) => {
          cropBoxData[i] = n * ratio;
        }));
      }
    }
  },

  dblclick() {
    const self = this;

    if (self.disabled) {
      return;
    }

    self.setDragMode($.hasClass(self.dragBox, 'cropper-crop') ? 'move' : 'crop');
  },

  wheel(event) {
    const self = this;
    const e = $.getEvent(event);
    const ratio = Number(self.options.wheelZoomRatio) || 0.1;
    let delta = 1;

    if (self.disabled) {
      return;
    }

    e.preventDefault();

    // Limit wheel speed to prevent zoom too fast (#21)
    if (self.wheeling) {
      return;
    }

    self.wheeling = true;

    setTimeout(() => {
      self.wheeling = false;
    }, 50);

    if (e.deltaY) {
      delta = e.deltaY > 0 ? 1 : -1;
    } else if (e.wheelDelta) {
      delta = -e.wheelDelta / 120;
    } else if (e.detail) {
      delta = e.detail > 0 ? 1 : -1;
    }

    self.zoom(-delta * ratio, e);
  },

  cropStart(event) {
    const self = this;

    if (self.disabled) {
      return;
    }

    const options = self.options;
    const pointers = self.pointers;
    const e = $.getEvent(event);
    let action;

    if (e.changedTouches) {
      // Handle touch event
      $.each(e.changedTouches, (touch) => {
        pointers[touch.identifier] = getPointer(touch);
      });
    } else {
      // Handle mouse event and pointer event
      pointers[e.pointerId || 0] = getPointer(e);
    }

    if (Object.keys(pointers).length > 1 && options.zoomable && options.zoomOnTouch) {
      action = 'zoom';
    } else {
      action = $.getData(e.target, 'action');
    }

    if (REGEXP_ACTIONS.test(action)) {
      if ($.dispatchEvent(self.element, 'cropstart', {
        originalEvent: e,
        action,
      }) === false) {
        return;
      }

      e.preventDefault();

      self.action = action;
      self.cropping = false;

      if (action === 'crop') {
        self.cropping = true;
        $.addClass(self.dragBox, 'cropper-modal');
      }
    }
  },

  cropMove(event) {
    const self = this;
    const action = self.action;

    if (self.disabled || !action) {
      return;
    }

    const pointers = self.pointers;
    const e = $.getEvent(event);

    e.preventDefault();

    if ($.dispatchEvent(self.element, 'cropmove', {
      originalEvent: e,
      action,
    }) === false) {
      return;
    }

    if (e.changedTouches) {
      $.each(e.changedTouches, (touch) => {
        $.extend(pointers[touch.identifier], getPointer(touch, true));
      });
    } else {
      $.extend(pointers[e.pointerId || 0], getPointer(e, true));
    }

    self.change(e);
  },

  cropEnd(event) {
    const self = this;
    const action = self.action;

    if (self.disabled || !action) {
      return;
    }

    const pointers = self.pointers;
    const e = $.getEvent(event);

    e.preventDefault();

    if (e.changedTouches) {
      $.each(e.changedTouches, (touch) => {
        delete pointers[touch.identifier];
      });
    } else {
      delete pointers[e.pointerId || 0];
    }

    if (!Object.keys(pointers).length) {
      self.action = '';
    }

    if (self.cropping) {
      self.cropping = false;
      $.toggleClass(self.dragBox, 'cropper-modal', self.cropped && this.options.modal);
    }

    $.dispatchEvent(self.element, 'cropend', {
      originalEvent: e,
      action,
    });
  },
};
<|endoftext|>


<commit_before>'use strict';
$(document).ready(function () {

  var $counter = $('#boLBCounter');
  var $description = $('#boLbCounterDescription');

  function updateCounter() {
    var counter = {
      current: Date.now(),
      start: $counter.data('start'),
      end: $counter.data('end'),
      time: {}
    };

    if (counter.current < counter.start) {
      //Before event
      counter.state = window.states.pre;
      counter.value = counter.start - counter.current;

    } else if (counter.current <= counter.end) {
      //During event
      counter.state = window.states.during;
      counter.value = counter.end - counter.current;
    } else {
      //Post event
      counter.state = window.states.post;
      counter.value = counter.current - counter.end;
    }

    counter.time.days = Math.floor(counter.value / (24 * 60 * 60 * 1000));
    counter.time.hours = Math.floor((counter.value - (counter.time.days * 24 * 60 * 60 * 1000)) / (60 * 60 * 1000));
    counter.time.minutes = Math.floor(
      (counter.value
      - (counter.time.days * 24 * 60 * 60 * 1000)
      - (counter.time.hours * 60 * 60 * 1000)) / (60 * 1000));
    counter.time.seconds = Math.floor(
      (counter.value
      - (counter.time.days * 24 * 60 * 60 * 1000)
      - (counter.time.hours * 60 * 60 * 1000)
      - (counter.time.minutes * 60 * 1000)) / 1000);

    if (counter.time.days > 1) {
      $counter.html(leftPad(counter.time.days) + ':' + leftPad(counter.time.hours) + ':' + leftPad(counter.time.minutes) + ':' + leftPad(counter.time.seconds));
    } else {
      $counter.html(leftPad(counter.time.hours + (counter.time.days * 24)) + ':' + leftPad(counter.time.minutes) + ':' + leftPad(counter.time.seconds));
    }

    $description.html(counter.state);

  }

  function leftPad(time) {
    var string = '00' + time;
    return string.substring(string.length - 2);
  }

  updateCounter();
  setInterval(updateCounter, 1000);

  //SCROLLING

  var $marker = $('#boTeamPostScroll');
  var $teamPosts = $('#teamPosts');
  var loading = false;
  var finished = false;
  var current = 0;
  $(window).on('load', function () {
    $(window).scroll(function () {

      if ($marker.offset().top - 100 < window.scrollY + $(window).height()) {
        if (!loading && !finished) {
          loading = true;
          $.post('/liveblog/posting/', {
              limit: 30,
              offset: current + 1
            })
            .success(function (postingsHTML) {
              var $postings = $(postingsHTML);
              if ($postings.length === 0) {
                finished = true;
                $marker.html('
Keine weiteren Posts verfügbar!
')
              } else {
                current++;
                $teamPosts.append($postings);
                window.msnry.appended($postings);
                //LOLOL DIRTY HACK FOR SLOW BROWSERS
                setTimeout(function () {
                  window.msnry.layout();
                }, 200);
                loading = false;
              }
            })
            .error(function () {
              $marker.html('
Konnte keine weiteren Posts laden.
')
              loading = false;
            })
        }
      }
    });
  });
  (function ($) {
    $.fn.countTo = function (options) {
      // merge the default plugin settings with the custom options
      options = $.extend({}, $.fn.countTo.defaults, options || {});

      // how many times to update the value, and how much to increment the value on each update
      var loops = Math.ceil(options.speed / options.refreshInterval),
        increment = (options.to - options.from) / loops;

      return $(this).each(function () {
        var _this = this,
          loopCount = 0,
          value = options.from,
          interval = setInterval(updateTimer, options.refreshInterval);

        function updateTimer() {
          value += increment;
          loopCount++;
          $(_this).html(value.toFixed(0).toString().replace(/\B(?=(\d{3})+(?!\d))/g, "."));

          if (typeof(options.onUpdate) == 'function') {
            options.onUpdate.call(_this, value);
          }

          if (loopCount >= loops) {
            clearInterval(interval);
            value = options.to;

            if (typeof(options.onComplete) == 'function') {
              options.onComplete.call(_this, value);
            }
          }
        }
      });
    };

    $.fn.countTo.defaults = {
      from: 0,  // the number the element should start at
      to: 100,  // the number the element should end at
      speed: 1000,  // how long it should take to count between the target numbers
      refreshInterval: 100,  // how often the element should be updated
      decimals: 0,  // the number of decimal places to show
      onUpdate: null,  // callback method for every time the element is updated,
      onComplete: null  // callback method for when the element finishes updating
    };
  })(jQuery);

  $(window).on('load', function () {
    var socket = io('/');

    socket.on('newPostings', function (data) {
      console.log(data);
      var $postings = $(data.postings);
      var $teamPosts = $('#teamPosts');
      //console.log($postings);
      $teamPosts.prepend($postings);
      window.msnry.prepended($postings);
      //LOLOL DIRTY HACK FOR SLOW BROWSERS
      setTimeout(function () {
        window.msnry.layout();
      }, 200);
    });

    var donateCounting = false;
    var distanceCounting = false;

    socket.on('newEventInfos', function (data) {

      //console.log(data);

      var oldDonateSum = parseInt($('#bo-donate-sum').text().replace('.', ''));
      var newDonateSum = parseInt(data.global.donatesum.toFixed(0).toString().replace('.', ''));

      console.log($('#bo-donate-sum'));
      console.log(data.global.donatesum);

      if (oldDonateSum < newDonateSum && !donateCounting) {
        donateCounting = true;
        $('#bo-donate-sum').countTo({
          from: oldDonateSum,
          to: newDonateSum,
          speed: 180000,
          refreshInterval: 100,
          onComplete: function () {
            donateCounting = false;
          }
        });

        $('.bo-donate-sum').each(function (i, e) {
          $(e).countTo({
            from: parseInt($(e).text().replace('.', '')),
            to: parseInt(data.individual[i].donatesum.full_sum.toFixed(0).toString().replace('.', '')),
            speed: 180000,
            refreshInterval: 100
          });
        });

      }

      var oldDistance = parseInt($('#bo-distance-sum').text().replace('.', ''));
      var newDistance = parseInt(data.global.distance.toFixed(0).toString().replace('.', ''));

      if (oldDistance < newDistance && !distanceCounting) {
        distanceCounting = true;
        $('#bo-distance-sum').countTo({
          from: oldDistance,
          to: newDistance,
          speed: 180000,
          refreshInterval: 100,
          onComplete: function () {
            distanceCounting = false;
          }
        });

        $('.bo-distance-sum').each(function (i, e) {
          $(e).countTo({
            from: parseInt($(e).text().replace('.', '')),
            to: parseInt(data.individual[i].distance.linear_distance.toFixed(0).toString().replace('.', '')),
            speed: 180000,
            refreshInterval: 100
          });
        });
      }
    });
  });
});<commit_msg>Removes logs<commit_after>'use strict';
$(document).ready(function () {

  var $counter = $('#boLBCounter');
  var $description = $('#boLbCounterDescription');

  function updateCounter() {
    var counter = {
      current: Date.now(),
      start: $counter.data('start'),
      end: $counter.data('end'),
      time: {}
    };

    if (counter.current < counter.start) {
      //Before event
      counter.state = window.states.pre;
      counter.value = counter.start - counter.current;

    } else if (counter.current <= counter.end) {
      //During event
      counter.state = window.states.during;
      counter.value = counter.end - counter.current;
    } else {
      //Post event
      counter.state = window.states.post;
      counter.value = counter.current - counter.end;
    }

    counter.time.days = Math.floor(counter.value / (24 * 60 * 60 * 1000));
    counter.time.hours = Math.floor((counter.value - (counter.time.days * 24 * 60 * 60 * 1000)) / (60 * 60 * 1000));
    counter.time.minutes = Math.floor(
      (counter.value
      - (counter.time.days * 24 * 60 * 60 * 1000)
      - (counter.time.hours * 60 * 60 * 1000)) / (60 * 1000));
    counter.time.seconds = Math.floor(
      (counter.value
      - (counter.time.days * 24 * 60 * 60 * 1000)
      - (counter.time.hours * 60 * 60 * 1000)
      - (counter.time.minutes * 60 * 1000)) / 1000);

    if (counter.time.days > 1) {
      $counter.html(leftPad(counter.time.days) + ':' + leftPad(counter.time.hours) + ':' + leftPad(counter.time.minutes) + ':' + leftPad(counter.time.seconds));
    } else {
      $counter.html(leftPad(counter.time.hours + (counter.time.days * 24)) + ':' + leftPad(counter.time.minutes) + ':' + leftPad(counter.time.seconds));
    }

    $description.html(counter.state);

  }

  function leftPad(time) {
    var string = '00' + time;
    return string.substring(string.length - 2);
  }

  updateCounter();
  setInterval(updateCounter, 1000);

  //SCROLLING

  var $marker = $('#boTeamPostScroll');
  var $teamPosts = $('#teamPosts');
  var loading = false;
  var finished = false;
  var current = 0;
  $(window).on('load', function () {
    $(window).scroll(function () {

      if ($marker.offset().top - 100 < window.scrollY + $(window).height()) {
        if (!loading && !finished) {
          loading = true;
          $.post('/liveblog/posting/', {
              limit: 30,
              offset: current + 1
            })
            .success(function (postingsHTML) {
              var $postings = $(postingsHTML);
              if ($postings.length === 0) {
                finished = true;
                $marker.html('
Keine weiteren Posts verfügbar!
')
              } else {
                current++;
                $teamPosts.append($postings);
                window.msnry.appended($postings);
                //LOLOL DIRTY HACK FOR SLOW BROWSERS
                setTimeout(function () {
                  window.msnry.layout();
                }, 200);
                loading = false;
              }
            })
            .error(function () {
              $marker.html('
Konnte keine weiteren Posts laden.
')
              loading = false;
            })
        }
      }
    });
  });
  (function ($) {
    $.fn.countTo = function (options) {
      // merge the default plugin settings with the custom options
      options = $.extend({}, $.fn.countTo.defaults, options || {});

      // how many times to update the value, and how much to increment the value on each update
      var loops = Math.ceil(options.speed / options.refreshInterval),
        increment = (options.to - options.from) / loops;

      return $(this).each(function () {
        var _this = this,
          loopCount = 0,
          value = options.from,
          interval = setInterval(updateTimer, options.refreshInterval);

        function updateTimer() {
          value += increment;
          loopCount++;
          $(_this).html(value.toFixed(0).toString().replace(/\B(?=(\d{3})+(?!\d))/g, "."));

          if (typeof(options.onUpdate) == 'function') {
            options.onUpdate.call(_this, value);
          }

          if (loopCount >= loops) {
            clearInterval(interval);
            value = options.to;

            if (typeof(options.onComplete) == 'function') {
              options.onComplete.call(_this, value);
            }
          }
        }
      });
    };

    $.fn.countTo.defaults = {
      from: 0,  // the number the element should start at
      to: 100,  // the number the element should end at
      speed: 1000,  // how long it should take to count between the target numbers
      refreshInterval: 100,  // how often the element should be updated
      decimals: 0,  // the number of decimal places to show
      onUpdate: null,  // callback method for every time the element is updated,
      onComplete: null  // callback method for when the element finishes updating
    };
  })(jQuery);

  $(window).on('load', function () {
    var socket = io('/');

    socket.on('newPostings', function (data) {
      console.log(data);
      var $postings = $(data.postings);
      var $teamPosts = $('#teamPosts');
      //console.log($postings);
      $teamPosts.prepend($postings);
      window.msnry.prepended($postings);
      //LOLOL DIRTY HACK FOR SLOW BROWSERS
      setTimeout(function () {
        window.msnry.layout();
      }, 200);
    });

    var donateCounting = false;
    var distanceCounting = false;

    socket.on('newEventInfos', function (data) {

      //console.log(data);

      var oldDonateSum = parseInt($('#bo-donate-sum').text().replace('.', ''));
      var newDonateSum = parseInt(data.global.donatesum.toFixed(0).toString().replace('.', ''));

      if (oldDonateSum < newDonateSum && !donateCounting) {
        donateCounting = true;
        $('#bo-donate-sum').countTo({
          from: oldDonateSum,
          to: newDonateSum,
          speed: 180000,
          refreshInterval: 100,
          onComplete: function () {
            donateCounting = false;
          }
        });

        $('.bo-donate-sum').each(function (i, e) {
          $(e).countTo({
            from: parseInt($(e).text().replace('.', '')),
            to: parseInt(data.individual[i].donatesum.full_sum.toFixed(0).toString().replace('.', '')),
            speed: 180000,
            refreshInterval: 100
          });
        });

      }

      var oldDistance = parseInt($('#bo-distance-sum').text().replace('.', ''));
      var newDistance = parseInt(data.global.distance.toFixed(0).toString().replace('.', ''));

      if (oldDistance < newDistance && !distanceCounting) {
        distanceCounting = true;
        $('#bo-distance-sum').countTo({
          from: oldDistance,
          to: newDistance,
          speed: 180000,
          refreshInterval: 100,
          onComplete: function () {
            distanceCounting = false;
          }
        });

        $('.bo-distance-sum').each(function (i, e) {
          $(e).countTo({
            from: parseInt($(e).text().replace('.', '')),
            to: parseInt(data.individual[i].distance.linear_distance.toFixed(0).toString().replace('.', '')),
            speed: 180000,
            refreshInterval: 100
          });
        });
      }
    });
  });
});<|endoftext|>


<commit_before>import parser from './parser/javascript.js';
import Snap from 'snapsvg';
import Q from 'q';

export default class Regexper {
  constructor(root) {
    this.root = root;
    this.form = root.querySelector('#regexp-form');
    this.field = root.querySelector('#regexp-input');
    this.error = root.querySelector('#error');
    this.permalink = root.querySelector('a[data-glyph="link-intact"]');
    this.download = root.querySelector('a[data-glyph="data-transfer-download"]');
    this.percentage = root.querySelector('#progress div');
    this.svg = root.querySelector('#regexp-render svg');

    this.padding = 10;
    this.snap = Snap(this.svg);
  }

  keypressListener(event) {
    var evt;

    if (event.shiftKey && event.keyCode === 13) {
      event.returnValue = false;
      if (event.preventDefault) {
        event.preventDefault();
      }

      evt = document.createEvent('Event');
      evt.initEvent('submit', true, true);
      this.form.dispatchEvent(evt);
    }
  }

  submitListener(event) {
    event.preventDefault();

    try {
      this.disablePermalink = false;
      location.hash = this.field.value;
    }
    catch(e) {
      // Most likely failed to set the URL has (probably because the expression
      // is too long). Turn off the permalink and just show the expression
      this.disablePermalink = true;
      this.showExpression(this.field.value);
    }
  }

  hashchangeListener() {
    var expression = decodeURIComponent(location.hash.slice(1));

    this.showExpression(expression);
  }

  showExpression(expression) {
    if (expression !== '') {
      this.field.value = expression;

      this.setState('is-loading');

      this.renderRegexp(expression.replace(/\n/g, '\\n'))
        .then(() => {
          this.setState('has-results');
          this.updateLinks();
        })
        .done();
    }
  }

  updatePercentage(event) {
    this.percentage.style.width = event.detail.percentage * 100 + '%';
  }

  bindListeners() {
    this.field.addEventListener('keypress', this.keypressListener.bind(this));

    this.form.addEventListener('submit', this.submitListener.bind(this));

    window.addEventListener('hashchange', this.hashchangeListener.bind(this));

    this.root.addEventListener('updateStatus', this.updatePercentage.bind(this));
  }

  setState(state) {
    this.root.className = state;
  }

  showError(message) {
    this.setState('has-error');
    this.error.innerHTML = '';
    this.error.appendChild(document.createTextNode(message));

    throw message;
  }

  updateLinks() {
    var blob, url;

    try {
      blob = new Blob([this.svg.parentNode.innerHTML], { type: 'image/svg+xml' });
      url = URL.createObjectURL(blob);
      window.blob = blob; // Blob object has to stick around for IE

      this.download.setAttribute('href', url);
    }
    catch(e) {
      // Blobs or URLs created from them don't work here.
      // Giving up on the download link
      this.download.parentNode.style.display = 'none';
    }

    if (this.disablePermalink) {
      this.permalink.parentNode.style.display = 'none';
    } else {
      this.permalink.parentNode.style.display = null;
      this.permalink.setAttribute('href', location.toString());
    }
  }

  renderRegexp(expression) {
    var snap = Snap(this.svg);

    snap.selectAll('g').remove();

    parser.resetGroupCounter();

    return Q.fcall(parser.parse.bind(parser), expression)
      .then(null, this.showError.bind(this))
      .invoke('render', snap.group())
      .then(result => {
        var box;

        box = result.getBBox();
        result.container.transform(Snap.matrix()
          .translate(this.padding - box.x, this.padding - box.y));
        snap.attr({
          width: box.width + this.padding * 2,
          height: box.height + this.padding * 2
        });
      });
  }
}
<commit_msg>Hiding results element when told to display an empty expression<commit_after>import parser from './parser/javascript.js';
import Snap from 'snapsvg';
import Q from 'q';

export default class Regexper {
  constructor(root) {
    this.root = root;
    this.form = root.querySelector('#regexp-form');
    this.field = root.querySelector('#regexp-input');
    this.error = root.querySelector('#error');
    this.permalink = root.querySelector('a[data-glyph="link-intact"]');
    this.download = root.querySelector('a[data-glyph="data-transfer-download"]');
    this.percentage = root.querySelector('#progress div');
    this.svg = root.querySelector('#regexp-render svg');

    this.padding = 10;
    this.snap = Snap(this.svg);
  }

  keypressListener(event) {
    var evt;

    if (event.shiftKey && event.keyCode === 13) {
      event.returnValue = false;
      if (event.preventDefault) {
        event.preventDefault();
      }

      evt = document.createEvent('Event');
      evt.initEvent('submit', true, true);
      this.form.dispatchEvent(evt);
    }
  }

  submitListener(event) {
    event.preventDefault();

    try {
      this.disablePermalink = false;
      location.hash = this.field.value;
    }
    catch(e) {
      // Most likely failed to set the URL has (probably because the expression
      // is too long). Turn off the permalink and just show the expression
      this.disablePermalink = true;
      this.showExpression(this.field.value);
    }
  }

  hashchangeListener() {
    var expression = decodeURIComponent(location.hash.slice(1));

    this.showExpression(expression);
  }

  showExpression(expression) {
    this.field.value = expression;
    this.setState('');

    if (expression !== '') {
      this.setState('is-loading');

      this.renderRegexp(expression.replace(/\n/g, '\\n'))
        .then(() => {
          this.setState('has-results');
          this.updateLinks();
        })
        .done();
    }
  }

  updatePercentage(event) {
    this.percentage.style.width = event.detail.percentage * 100 + '%';
  }

  bindListeners() {
    this.field.addEventListener('keypress', this.keypressListener.bind(this));

    this.form.addEventListener('submit', this.submitListener.bind(this));

    window.addEventListener('hashchange', this.hashchangeListener.bind(this));

    this.root.addEventListener('updateStatus', this.updatePercentage.bind(this));
  }

  setState(state) {
    this.root.className = state;
  }

  showError(message) {
    this.setState('has-error');
    this.error.innerHTML = '';
    this.error.appendChild(document.createTextNode(message));

    throw message;
  }

  updateLinks() {
    var blob, url;

    try {
      blob = new Blob([this.svg.parentNode.innerHTML], { type: 'image/svg+xml' });
      url = URL.createObjectURL(blob);
      window.blob = blob; // Blob object has to stick around for IE

      this.download.setAttribute('href', url);
    }
    catch(e) {
      // Blobs or URLs created from them don't work here.
      // Giving up on the download link
      this.download.parentNode.style.display = 'none';
    }

    if (this.disablePermalink) {
      this.permalink.parentNode.style.display = 'none';
    } else {
      this.permalink.parentNode.style.display = null;
      this.permalink.setAttribute('href', location.toString());
    }
  }

  renderRegexp(expression) {
    var snap = Snap(this.svg);

    snap.selectAll('g').remove();

    parser.resetGroupCounter();

    return Q.fcall(parser.parse.bind(parser), expression)
      .then(null, this.showError.bind(this))
      .invoke('render', snap.group())
      .then(result => {
        var box;

        box = result.getBBox();
        result.container.transform(Snap.matrix()
          .translate(this.padding - box.x, this.padding - box.y));
        snap.attr({
          width: box.width + this.padding * 2,
          height: box.height + this.padding * 2
        });
      });
  }
}
<|endoftext|>