<commit_before>module.exports = {
  normalizeEntityName: function() {
    // this prevents an error when the entityName is
    // not specified (since that doesn't actually matter
    // to us
  },

  afterInstall: function() {
    return this.addBowerPackagesToProject([
      { name: 'qunit',                           target: '~1.17.0' },
      { name: 'stefanpenner/ember-cli-shims',    target: '0.0.3'   },
      { name: 'ember-cli/ember-cli-test-loader', target: '0.1.0'   },
      { name: 'ember-qunit-notifications',       target: '0.0.5'   },
      { name: 'ember-qunit',                     target: 'rwjblue/ember-qunit-builds#0.2.0' }
    ]);
  }
};
<commit_msg>Bump ember-qunit to v0.2.1<commit_after>module.exports = {
  normalizeEntityName: function() {
    // this prevents an error when the entityName is
    // not specified (since that doesn't actually matter
    // to us
  },

  afterInstall: function() {
    return this.addBowerPackagesToProject([
      { name: 'qunit',                           target: '~1.17.0' },
      { name: 'stefanpenner/ember-cli-shims',    target: '0.0.3'   },
      { name: 'ember-cli/ember-cli-test-loader', target: '0.1.0'   },
      { name: 'ember-qunit-notifications',       target: '0.0.5'   },
      { name: 'ember-qunit',                     target: 'rwjblue/ember-qunit-builds#0.2.1' }
    ]);
  }
};
<|endoftext|>


<commit_before>/*
---

name: ART.Path

description: Class to generate a valid SVG path using method calls.

authors: [Valerio Proietti](http://mad4milk.net)

provides: ART.Path

requires: ART

...
*/

(function(){

/* private functions */

var parse = function(path){

	path = path.replace(/\s*([A-Za-z,-])\s*/ig, function(f, m, i){
		switch (m){
			case '-': return ' ' + m;
			case ',': return ' ';
			default: return (i == 0) ? m + ' ' : ' ' + m + ' ';
		}
	});

	var parts = [], index = -1, bits = path.split(/\s+/);

	for (var i = 0, l = bits.length; i < l; i++){
		var bit = bits[i];
		if (bit.match(/[A-Za-z]/i)) parts[++index] = [bit];
		else parts[index].push(Number(bit));
	}

	return parts;

};

var circle = Math.PI * 2, north = circle / 2, west = north / 2, east = -west, south = 0;

var calculateArc = function(rx, ry, rotation, large, clockwise, x, y, tX, tY){
	var cx = x / 2, cy = y / 2,
		rxry = rx * rx * ry * ry, ryxp = ry * ry * cx * cx, rxyp = rx * rx * cy * cy,
		a = rxry - rxyp - ryxp;

	if (a < 0){
		a = Math.sqrt(1 - a / rxry);
		rx *= a; ry *= a;
	} else {
		a = Math.sqrt(a / (rxyp + ryxp));
		if (large == clockwise) a = -a;
		cx += -a * cy * rx / ry; cy += a * x / 2 / rx * ry;
	}

	var sa = Math.atan2(cx, -cy), ea = Math.atan2(-x + cx, y - cy);
	if (!+clockwise){ var t = sa; sa = ea; ea = t; }
	if (ea < sa) ea += circle;

	cx += tX; cy += tY;

	return {
		circle: [cx - rx, cy - ry, cx + rx, cy + ry],
		boundsX: [
			ea > circle + west || (sa < west && ea > west) ? cx - rx : tX,
			ea > circle + east || (sa < east && ea > east) ? cx + rx : tX
		],
		boundsY: [
			ea > north ? cy - ry : tY,
			ea > circle + south || (sa < south && ea > south) ? cy + ry : tY
		]
	};
};

var measureAndTransform = function(parts, precision){

	var boundsX = [], boundsY = [];

	var ux = function(x){
		boundsX.push(x);
		return (precision) ? Math.round(x * precision) : x;
	}, uy = function(y){
		boundsY.push(y);
		return (precision) ? Math.round(y * precision) : y;
	}, np = function(v){
		return (precision) ? Math.round(v * precision) : v;
	};

	var reflect = function(sx, sy, ex, ey){
		return [ex * 2 - sx, ey * 2 - sy];
	};

	var X = 0, Y = 0, px = 0, py = 0, r;

	var path = '';

	for (i = 0; i < parts.length; i++){
		var v = Array.slice(parts[i]), f = v.shift(), l = f.toLowerCase();
		var refX = l == f ? X : 0, refY = l == f ? Y : 0;

		switch (l){

			case 'm':
				path += 'm' + ux(X = refX + v[0]) + ',' + uy(Y = refY + v[1]);
			break;

			case 'l':
				path += 'l' + ux(X = refX + v[0]) + ',' + uy(Y = refY + v[1]);
			break;

			case 'c':
				px = refX + v[2]; py = refY + v[3];
				path += 'c' + ux(X + v[0]) + ',' + uy(Y + v[1]) + ',' + ux(px) + ',' + uy(py) + ',' + ux(X = refX + v[4]) + ',' + uy(Y = refY + v[5]);
			break;

			case 's':
				r = reflect(px, py, X, Y);
				px = refX + v[0]; py = refY + v[1];
				path += 'c' + ux(r[0]) + ',' + uy(r[1]) + ',' + ux(px) + ',' + uy(py) + ',' + ux(X = refX + v[2]) + ',' + uy(Y = refY + v[3]);
			break;

			case 'q':
				px = refX + v[0]; py = refY + v[1];
				path += 'c' + ux(refX + v[0]) + ',' + uy(refY + v[1]) + ',' + ux(px) + ',' + uy(py) + ',' + ux(X = refX + v[2]) + ',' + uy(Y = refY + v[3]);
			break;

			case 't':
				r = reflect(px, py, X, Y);
				px = refX + r[0]; py = refY + r[1];
				path += 'c' + ux(px) + ',' + uy(py) + ',' + ux(px) + ',' + uy(py) + ',' + ux(X = refX + v[0]) + ',' + uy(Y = refY + v[1]);
			break;

			case 'a':
				px = refX + v[5]; py = refY + v[6];

				if (!+v[0] || !+v[1] || (px == X && py == Y)){
					path += 'l' + ux(X = px) + ',' + uy(Y = py);
					break;
				}

				v.push(X, Y);
				r = calculateArc.apply(null, v);

				boundsX.push.apply(boundsX, r.boundsX);
				boundsY.push.apply(boundsY, r.boundsY);

				path += (v[4] == 1 ? 'wa' : 'at') + r.circle.map(np) + ',' + ux(X) + ',' + uy(Y) + ',' + ux(X = px) + ',' + uy(Y = py);
			break;

			case 'h':
				path += 'l' + ux(X = refX + v[0]) + ',' + uy(Y);
			break;

			case 'v':
				path += 'l' + ux(X) + ',' + uy(Y = refY + v[0]);
			break;

			case 'z':
				path += 'x';
			break;

		}
	}

	var right = Math.max.apply(Math, boundsX),
		bottom = Math.max.apply(Math, boundsY),
		left = Math.min.apply(Math, boundsX),
		top = Math.min.apply(Math, boundsY),
		height = bottom - top,
		width = right - left;

	return [path, {left: left, top: top, right: right, bottom: bottom, width: width, height: height}];

};

/* Path Class */

ART.Path = new Class({

	initialize: function(path){
		this.boundingBox = null;
		if (path == null) this.path = [];  //no path
		else if (path.path) this.path = Array.slice(path.path); //already a path
		else this.path = parse(path); //string path
	},

	push: function(){
		this.boundingBox = null;
		this.path.push(Array.slice(arguments));
		return this;
	},

	/*utility*/

	move: function(x, y){
		return this.push('m', x, y);
	},

	line: function(x, y){
		return this.push('l', x, y);
	},

	close: function(){
		return this.push('z');
	},

	bezier: function(c1x, c1y, c2x, c2y, ex, ey){
		return this.push('c', c1x, c1y, c2x, c2y, ex, ey);
	},

	arc: function(x, y, rx, ry, large){
		return this.push('a', Math.abs(rx || x), Math.abs(ry || rx || y), 0, large ? 1 : 0, 1, x, y);
	},

	counterArc: function(x, y, rx, ry, large){
		return this.push('a', Math.abs(rx || x), Math.abs(ry || rx || y), 0, large ? 1 : 0, 0, x, y);
	},

	/* transformation, measurement */

	toSVG: function(){
		var path = '';
		for (var i = 0, l = this.path.length; i < l; i++) path += this.path[i].join(' ');
		return path;
	},

	toVML: function(precision){;
		var data = measureAndTransform(this.path, precision);
		this.boundingBox = data[1];
		return data[0];
	},

	measure: function(){
		if (this.boundingBox) return this.boundingBox;
		if (this.path.length) return this.boundingBox = measureAndTransform(this.path)[1];
		else return {left: 0, top: 0, right: 0, bottom: 0, width: 0, height: 0};
	}

});

ART.Path.prototype.toString = ART.Path.prototype.toSVG;

})();
<commit_msg>Fixed absolute curves Minor readability clean up on arc math<commit_after>/*
---

name: ART.Path

description: Class to generate a valid SVG path using method calls.

authors: [Valerio Proietti](http://mad4milk.net)

provides: ART.Path

requires: ART

...
*/

(function(){

/* private functions */

var parse = function(path){

	path = path.replace(/\s*([A-Za-z,-])\s*/ig, function(f, m, i){
		switch (m){
			case '-': return ' ' + m;
			case ',': return ' ';
			default: return (i == 0) ? m + ' ' : ' ' + m + ' ';
		}
	});

	var parts = [], index = -1, bits = path.split(/\s+/);

	for (var i = 0, l = bits.length; i < l; i++){
		var bit = bits[i];
		if (bit.match(/[A-Za-z]/i)) parts[++index] = [bit];
		else parts[index].push(Number(bit));
	}

	return parts;

};

var circle = Math.PI * 2, north = circle / 2, west = north / 2, east = -west, south = 0;

var calculateArc = function(rx, ry, rotation, large, clockwise, x, y, tX, tY){
	var cx = x / 2, cy = y / 2,
		rxry = rx * rx * ry * ry, rycx = ry * ry * cx * cx, rxcy = rx * rx * cy * cy,
		a = rxry - rxcy - rycx;

	if (a < 0){
		a = Math.sqrt(1 - a / rxry);
		rx *= a; ry *= a;
	} else {
		a = Math.sqrt(a / (rxcy + rycx));
		if (large == clockwise) a = -a;
		cx += -a * y / 2 * rx / ry;
		cy +=  a * x / 2 * ry / rx;
	}

	var sa = Math.atan2(cx, -cy), ea = Math.atan2(-x + cx, y - cy);
	if (!+clockwise){ var t = sa; sa = ea; ea = t; }
	if (ea < sa) ea += circle;

	cx += tX; cy += tY;

	return {
		circle: [cx - rx, cy - ry, cx + rx, cy + ry],
		boundsX: [
			ea > circle + west || (sa < west && ea > west) ? cx - rx : tX,
			ea > circle + east || (sa < east && ea > east) ? cx + rx : tX
		],
		boundsY: [
			ea > north ? cy - ry : tY,
			ea > circle + south || (sa < south && ea > south) ? cy + ry : tY
		]
	};
};

var measureAndTransform = function(parts, precision){

	var boundsX = [], boundsY = [];

	var ux = function(x){
		boundsX.push(x);
		return (precision) ? Math.round(x * precision) : x;
	}, uy = function(y){
		boundsY.push(y);
		return (precision) ? Math.round(y * precision) : y;
	}, np = function(v){
		return (precision) ? Math.round(v * precision) : v;
	};

	var reflect = function(sx, sy, ex, ey){
		return [ex * 2 - sx, ey * 2 - sy];
	};

	var X = 0, Y = 0, px = 0, py = 0, r;

	var path = '';

	for (i = 0; i < parts.length; i++){
		var v = Array.slice(parts[i]), f = v.shift(), l = f.toLowerCase();
		var refX = l == f ? X : 0, refY = l == f ? Y : 0;

		switch (l){

			case 'm':
				path += 'm' + ux(X = refX + v[0]) + ',' + uy(Y = refY + v[1]);
			break;

			case 'l':
				path += 'l' + ux(X = refX + v[0]) + ',' + uy(Y = refY + v[1]);
			break;

			case 'c':
				px = refX + v[2]; py = refY + v[3];
				path += 'c' + ux(refX + v[0]) + ',' + uy(refY + v[1]) + ',' + ux(px) + ',' + uy(py) + ',' + ux(X = refX + v[4]) + ',' + uy(Y = refY + v[5]);
			break;

			case 's':
				r = reflect(px, py, X, Y);
				px = refX + v[0]; py = refY + v[1];
				path += 'c' + ux(r[0]) + ',' + uy(r[1]) + ',' + ux(px) + ',' + uy(py) + ',' + ux(X = refX + v[2]) + ',' + uy(Y = refY + v[3]);
			break;

			case 'q':
				px = refX + v[0]; py = refY + v[1];
				path += 'c' + ux(refX + v[0]) + ',' + uy(refY + v[1]) + ',' + ux(px) + ',' + uy(py) + ',' + ux(X = refX + v[2]) + ',' + uy(Y = refY + v[3]);
			break;

			case 't':
				r = reflect(px, py, X, Y);
				px = refX + r[0]; py = refY + r[1];
				path += 'c' + ux(px) + ',' + uy(py) + ',' + ux(px) + ',' + uy(py) + ',' + ux(X = refX + v[0]) + ',' + uy(Y = refY + v[1]);
			break;

			case 'a':
				px = refX + v[5]; py = refY + v[6];

				if (!+v[0] || !+v[1] || (px == X && py == Y)){
					path += 'l' + ux(X = px) + ',' + uy(Y = py);
					break;
				}

				v.push(X, Y);
				r = calculateArc.apply(null, v);

				boundsX.push.apply(boundsX, r.boundsX);
				boundsY.push.apply(boundsY, r.boundsY);

				path += (v[4] == 1 ? 'wa' : 'at') + r.circle.map(np) + ',' + ux(X) + ',' + uy(Y) + ',' + ux(X = px) + ',' + uy(Y = py);
			break;

			case 'h':
				path += 'l' + ux(X = refX + v[0]) + ',' + uy(Y);
			break;

			case 'v':
				path += 'l' + ux(X) + ',' + uy(Y = refY + v[0]);
			break;

			case 'z':
				path += 'x';
			break;

		}
	}

	var right = Math.max.apply(Math, boundsX),
		bottom = Math.max.apply(Math, boundsY),
		left = Math.min.apply(Math, boundsX),
		top = Math.min.apply(Math, boundsY),
		height = bottom - top,
		width = right - left;

	return [path, {left: left, top: top, right: right, bottom: bottom, width: width, height: height}];

};

/* Path Class */

ART.Path = new Class({

	initialize: function(path){
		this.boundingBox = null;
		if (path == null) this.path = [];  //no path
		else if (path.path) this.path = Array.slice(path.path); //already a path
		else this.path = parse(path); //string path
	},

	push: function(){
		this.boundingBox = null;
		this.path.push(Array.slice(arguments));
		return this;
	},

	/*utility*/

	move: function(x, y){
		return this.push('m', x, y);
	},

	line: function(x, y){
		return this.push('l', x, y);
	},

	close: function(){
		return this.push('z');
	},

	bezier: function(c1x, c1y, c2x, c2y, ex, ey){
		return this.push('c', c1x, c1y, c2x, c2y, ex, ey);
	},

	arc: function(x, y, rx, ry, large){
		return this.push('a', Math.abs(rx || x), Math.abs(ry || rx || y), 0, large ? 1 : 0, 1, x, y);
	},

	counterArc: function(x, y, rx, ry, large){
		return this.push('a', Math.abs(rx || x), Math.abs(ry || rx || y), 0, large ? 1 : 0, 0, x, y);
	},

	/* transformation, measurement */

	toSVG: function(){
		var path = '';
		for (var i = 0, l = this.path.length; i < l; i++) path += this.path[i].join(' ');
		return path;
	},

	toVML: function(precision){;
		var data = measureAndTransform(this.path, precision);
		this.boundingBox = data[1];
		return data[0];
	},

	measure: function(){
		if (this.boundingBox) return this.boundingBox;
		if (this.path.length) return this.boundingBox = measureAndTransform(this.path)[1];
		else return {left: 0, top: 0, right: 0, bottom: 0, width: 0, height: 0};
	}

});

ART.Path.prototype.toString = ART.Path.prototype.toSVG;

})();
<|endoftext|>


<commit_before>export default [
  'config',
  'hs.common.laymanService',
  function (config, laymanService) {
    const me = this;

    function getItemsPerPageConfig(ds) {
      return angular.isDefined(ds.paging) &&
        angular.isDefined(ds.paging.itemsPerPage)
        ? ds.paging.itemsPerPage
        : config.dsPaging || 20;
    }

    angular.extend(me, {
      endpoints: [
        {
          type: 'statusmanager',
          title: 'Status manager',
          url: config.status_manager_url,
        },
        ...(config.datasources || []).map((ds) => {
          return {
            url: ds.url,
            type: ds.type,
            title: ds.title,
            datasourcePaging: {
              start: 0,
              limit: getItemsPerPageConfig(ds),
              loaded: false,
            },
            compositionsPaging: {
              start: 0,
              limit: getItemsPerPageConfig(ds),
            },
            paging: {
              itemsPerPage: getItemsPerPageConfig(ds),
            },
            user: ds.user,
            liferayProtocol: ds.liferayProtocol,
            originalConfiguredUser: ds.user,
            getCurrentUserIfNeeded: laymanService.getCurrentUserIfNeeded,
          };
        }),
      ],
    });
    return me;
  },
];
<commit_msg>If statusmanager url is not specified, dont add it to endpoints<commit_after>export default [
  'config',
  'hs.common.laymanService',
  function (config, laymanService) {
    const me = this;

    function getItemsPerPageConfig(ds) {
      return angular.isDefined(ds.paging) &&
        angular.isDefined(ds.paging.itemsPerPage)
        ? ds.paging.itemsPerPage
        : config.dsPaging || 20;
    }

    angular.extend(me, {
      endpoints: [
        ...(config.status_manager_url
          ? {
              type: 'statusmanager',
              title: 'Status manager',
              url: config.status_manager_url,
            }
          : []),
        ...(config.datasources || []).map((ds) => {
          return {
            url: ds.url,
            type: ds.type,
            title: ds.title,
            datasourcePaging: {
              start: 0,
              limit: getItemsPerPageConfig(ds),
              loaded: false,
            },
            compositionsPaging: {
              start: 0,
              limit: getItemsPerPageConfig(ds),
            },
            paging: {
              itemsPerPage: getItemsPerPageConfig(ds),
            },
            user: ds.user,
            liferayProtocol: ds.liferayProtocol,
            originalConfiguredUser: ds.user,
            getCurrentUserIfNeeded: laymanService.getCurrentUserIfNeeded,
          };
        }),
      ],
    });
    return me;
  },
];
<|endoftext|>


<commit_before>
var fs = require('fs'),
    PNG = require('../lib/png').PNG; // note require('pngjs') outside this project

fs.createReadStream('test/in/basi0g01.png')
    .pipe(new PNG({
        filterType: 4
    }))
    .on('parsed', function() {

        for (var y = 0; y < this.height; y++) {
            for (var x = 0; x < this.width; x++) {
                var idx = (this.width * y + x) << 2;

                // invert color
                this.data[idx] = 255 - this.data[idx];
                this.data[idx+1] = 255 - this.data[idx+1];
                this.data[idx+2] = 255 - this.data[idx+2];

                // and reduce opacity
                this.data[idx+3] = this.data[idx+3] >> 1;
            }
        }

        this.pack().pipe(fs.createWriteStream('out.png'));
    });
<commit_msg>don't include filter type when parsing<commit_after>
var fs = require('fs'),
    PNG = require('../lib/png').PNG; // note require('pngjs') outside this project

fs.createReadStream('test/in/basi0g01.png')
    .pipe(new PNG({
    }))
    .on('parsed', function() {

        for (var y = 0; y < this.height; y++) {
            for (var x = 0; x < this.width; x++) {
                var idx = (this.width * y + x) << 2;

                // invert color
                this.data[idx] = 255 - this.data[idx];
                this.data[idx+1] = 255 - this.data[idx+1];
                this.data[idx+2] = 255 - this.data[idx+2];

                // and reduce opacity
                this.data[idx+3] = this.data[idx+3] >> 1;
            }
        }

        this.pack().pipe(fs.createWriteStream('out.png'));
    });
<|endoftext|>


<commit_before><commit_msg>added debug code<commit_after><|endoftext|>


<commit_before>/**
 * jQuery Funnel
 *
 * Funnels online activity from different websites into a webpage
 * ordered by time according to user specified templates.
 *
 * Copyright (c) 2011 Jeroen van der Tuin <jeroen@vandertuin.nl>
 * Licensed under the MIT license.
 */

/**
 * Overload the String object with a Tweetify which creates links
 * from URLs, @usernames and #hashtags.
 *
 * From: http://css-tricks.com/snippets/jquery/jquery-tweetify-text/
 */
String.prototype.tweetify = function() {
	return this.replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi,'$1').replace(/(^|\s)#(\w+)/g,'$1#$2').replace(/(^|\s|.)@(\w+)/g,'$1@$2');
};

(function($) {

$.funnel = function(element, options) {
	/**
	 * Default plugin options
	 */
	var defaults = {
		/**
		 * Services to load the timeline of.
		 */
		services: null,

		/**
		 * Max number of items to show in total.
		 */
		max_items: 10
	}

	/**
	 * Reference to the current instance of the object.
	 */
	var plugin = this;

	// this will hold the merged default, and user-provided options
	// plugin's properties will be available through this object like:
	// plugin.options.propertyName from inside the plugin or
	// element.data('pluginName').options.propertyName from outside the plugin, where "element" is the
	// element the plugin is attached to;
	plugin.options = {}

	/**
	 * Reference to the jQuery version of the DOM element.
	 */
	var $element = $(element);

	/**
	 * Constructor
	 *
	 * Loads the data of each service. The handler of each service then
	 * merges its items into the timeline and displays it asynchronously.
	 */
	plugin.init = function() {
		plugin.options = $.extend({}, defaults, options);

		// Request each timeline
		for (var i = 0; i < plugin.options.services.length; i++) {
			services[plugin.options.services[i].name](
				plugin.options.services[i].user,
				plugin.options.services[i].tpl
			);
		}
	}

	/**
	 * Public vars and functions
	 *
	 * Can be reached inside the plugin as:
	 * plugin.methodName(arg1, arg2, ... argn)
	 * and from outside as:
	 * element.data('pluginName').publicMethod(arg1, arg2)
	 */

	/**
	 * This array contains the items selected by the different services.
	 */
	plugin.items = new Array();

	/**
	 * Private vars and functions
	 */

	/**
	 * Container of services functions
	 */
	var services = {};

	/**
	 * Twitter service
	 */
	services.twitter = function(user, tpl) {
		var max_items = Math.ceil(
			plugin.options.max_items / plugin.options.services.length
		);

		var url = 'http://twitter.com/status/user_timeline/' + user
			+ '.json?count=' + max_items + '&callback=?';

		$.getJSON(url, function(data) {
			$.each(data, function(i, item) {
				var tweet = {
					"date": item.created_at,
					"relative_date": new Date(item.created_at).relative(),
					"msg": item.text.tweetify(),
					"user": user,
					"id": item.id_str
				};

				plugin.items.push({
					"item": tweet,
					"html": $('#' + tpl).tmpl(tweet)
				});
			});

			// Display all items.
			sort();
			display();
		});
	};

	/**
	 * Delicious
	 *
	 * Based on http://itp.nyu.edu/~cs220/dwd/class10-delicious.html
	 */
	services.delicious = function(user, tpl) {
		var max_items = Math.ceil(
			plugin.options.max_items / plugin.options.services.length
		);

		// Define the URL to be called
		var url = 'http://feeds.delicious.com/v2/json/' + user +
			'?plain&callback=?&count=' + max_items;

		// Get the data from the web service and process
		$.getJSON(url, function(data) {
			$.each(data, function(i, item) {
				var bookmark = {
					"date": item.dt,
					"relative_date": new Date(item.dt).relative(),
					"url": item.u,
					"title": item.d,
					"tags": item.t,
					"msg": item.n,
					"user": user
				};

				plugin.items.push({
					"item": bookmark,
					"html": $('#' + tpl).tmpl(bookmark)
				});
			});

			// Display all items.
			sort();
			display();
		});
	};

	services.tumblr = function(user, tpl) {
		var max_items = Math.ceil(
			plugin.options.max_items / plugin.options.services.length
		);

		// Define the URL to be called
		var url = 'http://' + user + '.tumblr.com/api/read/json';

		var process_photo = function(item) {
			var photo = {
				"date": item['date'],
				"relative_date": new Date(item['date']).relative(),
				"src": item['photo-url-250'],
				"caption": item['photo-caption'],
				"url": item['photo-link-url'],
				"user": user
			};

			plugin.items.push({
				"item": photo,
				"html": $('#' + tpl.photo).tmpl(photo)
			});
		};

		var process_video = function(item) {
			var video = {
				"date": item['date'],
				"relative_date": new Date(item['date']).relative(),
				"video_player": item['video-player-250'],
				"caption": item['video-caption'],
				"user": user
			};

			plugin.items.push({
				"item": video,
				"html": $('#' + tpl.video).tmpl(video)
			});
		};

		// Get the data from the web service and process
		$.ajax({
			"url": url,
			"dataType": 'jsonp',
			"success": function (data, textStatus, jqXHR) {
				var posts = data.posts;

				$.each(posts, function(i, item) {
					// There can be different types of posts.
					// photo, video, quote

					if (item.type == 'photo') {
						process_photo(item);
						return;
					}

					if (item.type == 'video') {
						process_video(item);
					}
				});

				// Display all items.
				sort();
				display();
			}
		});
	};

	services.youtube = function(user, tpl) {};
	services.github = function(user, tpl) {};

	/**
	 * Sorts the items by date.
	 */
	var sort = function() {
		plugin.items.sort(function(a, b) {
			var a = Date.parse(a.item.date);
			var b = Date.parse(b.item.date);
			return b - a;
		});
	};

	/**
	 * Appends each item to the target element.
	 */
	var display = function() {
		$element.html('');

		for (var i = 0; i < plugin.items.length; i++) {
			if (i == plugin.options.max_items) break;
			plugin.items[i].html.appendTo($element);
		}
	};

	// Call the constructor
	plugin.init();
}

// add the plugin to the jQuery.fn object
$.fn.funnel = function(options) {
	// iterate through the DOM elements we are attaching the plugin to
	return this.each(function() {
		// if plugin has not already been attached to the element
		if (undefined == $(this).data('funnel')) {
			// create a new instance of the plugin
			// pass the DOM element and the user-provided options as arguments
			var plugin = new $.funnel(this, options);

			// in the jQuery version of the element
			// store a reference to the plugin object
			// you can later access the plugin and its methods and properties like
			// element.data('pluginName').publicMethod(arg1, arg2, ... argn) or
			// element.data('pluginName').options.propertyName
			$(this).data('funnel', plugin);
		}
	});
}

})(jQuery);
<commit_msg>Indented the replace functions for clarity.<commit_after>/**
 * jQuery Funnel
 *
 * Funnels online activity from different websites into a webpage
 * ordered by time according to user specified templates.
 *
 * Copyright (c) 2011 Jeroen van der Tuin <jeroen@vandertuin.nl>
 * Licensed under the MIT license.
 */

/**
 * Overload the String object with a Tweetify which creates links
 * from URLs, @usernames and #hashtags.
 *
 * From: http://css-tricks.com/snippets/jquery/jquery-tweetify-text/
 */
String.prototype.tweetify = function() {
	return this
		.replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi,'$1')
		.replace(/(^|\s)#(\w+)/g,'$1#$2')
		.replace(/(^|\s|.)@(\w+)/g,'$1@$2');
};

(function($) {

$.funnel = function(element, options) {
	/**
	 * Default plugin options
	 */
	var defaults = {
		/**
		 * Services to load the timeline of.
		 */
		services: null,

		/**
		 * Max number of items to show in total.
		 */
		max_items: 10
	}

	/**
	 * Reference to the current instance of the object.
	 */
	var plugin = this;

	// this will hold the merged default, and user-provided options
	// plugin's properties will be available through this object like:
	// plugin.options.propertyName from inside the plugin or
	// element.data('pluginName').options.propertyName from outside the plugin, where "element" is the
	// element the plugin is attached to;
	plugin.options = {}

	/**
	 * Reference to the jQuery version of the DOM element.
	 */
	var $element = $(element);

	/**
	 * Constructor
	 *
	 * Loads the data of each service. The handler of each service then
	 * merges its items into the timeline and displays it asynchronously.
	 */
	plugin.init = function() {
		plugin.options = $.extend({}, defaults, options);

		// Request each timeline
		for (var i = 0; i < plugin.options.services.length; i++) {
			services[plugin.options.services[i].name](
				plugin.options.services[i].user,
				plugin.options.services[i].tpl
			);
		}
	}

	/**
	 * Public vars and functions
	 *
	 * Can be reached inside the plugin as:
	 * plugin.methodName(arg1, arg2, ... argn)
	 * and from outside as:
	 * element.data('pluginName').publicMethod(arg1, arg2)
	 */

	/**
	 * This array contains the items selected by the different services.
	 */
	plugin.items = new Array();

	/**
	 * Private vars and functions
	 */

	/**
	 * Container of services functions
	 */
	var services = {};

	/**
	 * Twitter service
	 */
	services.twitter = function(user, tpl) {
		var max_items = Math.ceil(
			plugin.options.max_items / plugin.options.services.length
		);

		var url = 'http://twitter.com/status/user_timeline/' + user
			+ '.json?count=' + max_items + '&callback=?';

		$.getJSON(url, function(data) {
			$.each(data, function(i, item) {
				var tweet = {
					"date": item.created_at,
					"relative_date": new Date(item.created_at).relative(),
					"msg": item.text.tweetify(),
					"user": user,
					"id": item.id_str
				};

				plugin.items.push({
					"item": tweet,
					"html": $('#' + tpl).tmpl(tweet)
				});
			});

			// Display all items.
			sort();
			display();
		});
	};

	/**
	 * Delicious
	 *
	 * Based on http://itp.nyu.edu/~cs220/dwd/class10-delicious.html
	 */
	services.delicious = function(user, tpl) {
		var max_items = Math.ceil(
			plugin.options.max_items / plugin.options.services.length
		);

		// Define the URL to be called
		var url = 'http://feeds.delicious.com/v2/json/' + user +
			'?plain&callback=?&count=' + max_items;

		// Get the data from the web service and process
		$.getJSON(url, function(data) {
			$.each(data, function(i, item) {
				var bookmark = {
					"date": item.dt,
					"relative_date": new Date(item.dt).relative(),
					"url": item.u,
					"title": item.d,
					"tags": item.t,
					"msg": item.n,
					"user": user
				};

				plugin.items.push({
					"item": bookmark,
					"html": $('#' + tpl).tmpl(bookmark)
				});
			});

			// Display all items.
			sort();
			display();
		});
	};

	services.tumblr = function(user, tpl) {
		var max_items = Math.ceil(
			plugin.options.max_items / plugin.options.services.length
		);

		// Define the URL to be called
		var url = 'http://' + user + '.tumblr.com/api/read/json';

		var process_photo = function(item) {
			var photo = {
				"date": item['date'],
				"relative_date": new Date(item['date']).relative(),
				"src": item['photo-url-250'],
				"caption": item['photo-caption'],
				"url": item['photo-link-url'],
				"user": user
			};

			plugin.items.push({
				"item": photo,
				"html": $('#' + tpl.photo).tmpl(photo)
			});
		};

		var process_video = function(item) {
			var video = {
				"date": item['date'],
				"relative_date": new Date(item['date']).relative(),
				"video_player": item['video-player-250'],
				"caption": item['video-caption'],
				"user": user
			};

			plugin.items.push({
				"item": video,
				"html": $('#' + tpl.video).tmpl(video)
			});
		};

		// Get the data from the web service and process
		$.ajax({
			"url": url,
			"dataType": 'jsonp',
			"success": function (data, textStatus, jqXHR) {
				var posts = data.posts;

				$.each(posts, function(i, item) {
					// There can be different types of posts.
					// photo, video, quote

					if (item.type == 'photo') {
						process_photo(item);
						return;
					}

					if (item.type == 'video') {
						process_video(item);
					}
				});

				// Display all items.
				sort();
				display();
			}
		});
	};

	services.youtube = function(user, tpl) {};
	services.github = function(user, tpl) {};

	/**
	 * Sorts the items by date.
	 */
	var sort = function() {
		plugin.items.sort(function(a, b) {
			var a = Date.parse(a.item.date);
			var b = Date.parse(b.item.date);
			return b - a;
		});
	};

	/**
	 * Appends each item to the target element.
	 */
	var display = function() {
		$element.html('');

		for (var i = 0; i < plugin.items.length; i++) {
			if (i == plugin.options.max_items) break;
			plugin.items[i].html.appendTo($element);
		}
	};

	// Call the constructor
	plugin.init();
}

// add the plugin to the jQuery.fn object
$.fn.funnel = function(options) {
	// iterate through the DOM elements we are attaching the plugin to
	return this.each(function() {
		// if plugin has not already been attached to the element
		if (undefined == $(this).data('funnel')) {
			// create a new instance of the plugin
			// pass the DOM element and the user-provided options as arguments
			var plugin = new $.funnel(this, options);

			// in the jQuery version of the element
			// store a reference to the plugin object
			// you can later access the plugin and its methods and properties like
			// element.data('pluginName').publicMethod(arg1, arg2, ... argn) or
			// element.data('pluginName').options.propertyName
			$(this).data('funnel', plugin);
		}
	});
}

})(jQuery);
<|endoftext|>


<commit_before>/* eslint-env node */
module.exports = {
  description:
    'Install Showbie code style enforcement configuration and tooling',

  normalizeEntityName() {}, // no-op since we're just adding dependencies

  afterInstall() {
    // eslint-disable-next-line ember/named-functions-in-promises
    return this.addPackagesToProject([
      // Used for config/release.
      { name: 'lodash.samplesize', target: '~4.2.0' },
      { name: 'node-slack', target: '~0.0.7' },

      // Linting & formatting packages.
      { name: 'eslint-plugin-ember', target: '~5.0.3' },
      { name: 'prettier-eslint-cli', target: '~4.7.0' },
      { name: 'prettier-stylelint', target: '~0.4.2' },
      { name: 'stylelint', target: '~9.0.0' },
      {
        name: 'stylelint-config-property-sort-order-smacss',
        target: '~2.0.0',
      },
      { name: 'stylelint-config-sass-guidelines', target: '~5.0.0' },
      { name: 'stylelint-order', target: '~0.8.0' },
      { name: 'stylelint-scss', target: '~2.2.0' },
    ]).then(() => {
      return this.addAddonsToProject({
        packages: [
          { name: 'ember-cli-eslint', target: '~4.2.3' },
          { name: 'ember-cli-code-coverage', target: '~0.3.12' },
          { name: 'ember-cli-template-lint', target: '~0.7.5' },
          { name: 'ember-cli-release', target: '~0.2.9' },
        ],
      });
    });
  },
};
<commit_msg>:gift: Add object-rest-spread Babel plugin to blueprint<commit_after>/* eslint-env node */
module.exports = {
  description:
    'Install Showbie code style enforcement configuration and tooling',

  normalizeEntityName() {}, // no-op since we're just adding dependencies

  afterInstall() {
    // eslint-disable-next-line ember/named-functions-in-promises
    return this.addPackagesToProject([
      // Used for config/release.
      { name: 'lodash.samplesize', target: '~4.2.0' },
      { name: 'node-slack', target: '~0.0.7' },

      // Linting & formatting packages.
      { name: 'babel-plugin-transform-object-rest-spread', target: '~6.26.0' },
      { name: 'eslint-plugin-ember', target: '~5.0.3' },
      { name: 'prettier-eslint-cli', target: '~4.7.0' },
      { name: 'prettier-stylelint', target: '~0.4.2' },
      { name: 'stylelint', target: '~9.0.0' },
      {
        name: 'stylelint-config-property-sort-order-smacss',
        target: '~2.0.0',
      },
      { name: 'stylelint-config-sass-guidelines', target: '~5.0.0' },
      { name: 'stylelint-order', target: '~0.8.0' },
      { name: 'stylelint-scss', target: '~2.2.0' },
    ]).then(() => {
      return this.addAddonsToProject({
        packages: [
          { name: 'ember-cli-eslint', target: '~4.2.3' },
          { name: 'ember-cli-code-coverage', target: '~0.3.12' },
          { name: 'ember-cli-template-lint', target: '~0.7.5' },
          { name: 'ember-cli-release', target: '~0.2.9' },
        ],
      });
    });
  },
};
<|endoftext|>


<commit_before>/*
---
name: Behavior
description: Auto-instantiates widgets/classes based on parsed, declarative HTML.
requires: [Core/Class.Extras, Core/Element, Core/Selectors, /Element.Data, More/Table]
provides: [DashSelectors, Behavior]
...
*/

(function(){

	var spaceOrCommaRegex = /\s*,\s*|\s+/g;

	this.Behavior = new Class({

		Implements: [Options, Events],

		options: {
			//by default, errors thrown by filters are caught; the onError event is fired.
			//set this to *true* to NOT catch these errors to allow them to be handled by the browser.
			// breakOnErrors: false,

			//default error behavior when a filter cannot be applied
			onError: function(){
				if (window.console && console.warn){
					if(console.warn.apply) console.warn.apply(console, arguments);
					else console.warn($A(arguments).join(' '));
				}
			}
			//Components that have a Behavior instance (like an ART.Window)
			//call these events to tell filters that need to know that the state
			//has changed:
			// onResize: $empty, //the element's dimensions have changed
			// onShow: $empty, //the element is displayed
			// onHide: $empty //the element is hidden
		},

		initialize: function(options){
			this.setOptions(options);
			this.passMethods({
				addEvent: this.addEvent.bind(this),
				removeEvent: this.removeEvent.bind(this),
				addEvents: this.addEvents.bind(this),
				removeEvents: this.removeEvents.bind(this),
				fireEvent: this.fireEvent.bind(this),
				applyFilters: this.apply.bind(this),
				applyFilter: this.applyFilter.bind(this),
				getContentElement: $lambda(this.options.container || document.body),
				//this doesn't really stand up; the container is variable - one behavior instance
				//can handle numerous containers... TODO: revisit
				getContainerSize: function() { return this.currentSize; }.bind(this),
				error: function(){ this.fireEvent('error', arguments); }.bind(this)
			});
		},

		//pass a method pointer through to a filter
		//by default the methods for add/remove events are passed to the filter
		//pointed to this instance of behavior. you could use this to pass along
		//other methods to your filters. For example, a method to close a popup
		//for filters presented inside popups.
		_passedMethods: {},
		passMethod: function(method, fn){
			var self = this;
			this._passedMethods[method] = function(){
				return fn.apply(this, arguments);
			};
			return this;
		},

		passMethods: function(methods){
			for (var method in methods) {
				this.passMethod(method, methods[method]);
			}
			return this;
		},

		//These methods don't change the element's state but rather are used
		//to tell filters that need to adapt to the new element state that
		//it has changed.
		show: function(){
			return this.fireEvent('show');
		},

		//the element is hidden
		hide: function(){
			return this.fireEvent('hide');
		},

		//the element's dimensions are now the specified width and height
		resize: function(x, y){
			this.currentSize = {x: x, y: y};
			return this.fireEvent('resize', [x, y]);
		},

		//Applies all the behavior filters for an element.
		//container - (element) an element to apply the filters registered with this Behavior instance to.
		//force - (boolean; optional) passed through to applyFilter (see it for docs)
		apply: function(container, force){
			document.id(container).getElements('[data-filters]').each(function(element){
				var plugins = [];
				element.getDataFilters().each(function(name){
					var behavior = this.getFilter(name.trim());
					if (!behavior) {
						this.fireEvent('error', ['There is no behavior registered with this name: ', name, element]);
					} else {
						plugins.extend(this.applyFilter(element, behavior, force, true));
					}
				}, this);
				plugins.each(function(plugin){ plugin(); });
			}, this);
			return this;
		},

		//Applies a specific behavior to a specific element.
		//element - the element to which to apply the behavior
		//filter - (object) a specific behavior filter, typically one registered with this instance or registered globally.
		//force - (boolean; optional) apply the behavior to each element it matches, even if it was previously applied. Defaults to *false*.
		//returnPlugins - (boolean; optional) if true, plugins are not rendered but instead returned as an array of functions
		applyFilter: function(element, filter, force, returnPlugins){
			var pluginsToReturn = [];
			var run = function(){
				element = document.id(element);
				//get the filters already applied to this element
				var applied = getApplied(element);
				//if this filter is not yet applied to the element, or we are forcing the filter
				if (!applied[filter.name] || force) {
					//if it was previously applied, garbage collect it
					if (applied[filter.name]) applied[filter.name].cleanup(element);
					//apply the filter
					filter.attach(element, this._passedMethods);
					//and mark it as having been previously applied
					applied[filter.name] = filter;
					//apply all the plugins for this filter
					var plugins = this.getPlugins(filter.name);
					if (plugins) {
						for (var name in plugins) {
							if (returnPlugins) {
								pluginsToReturn.push(this.applyFilter.pass([element, plugins[name], force], this));
							} else {
								this.applyFilter(element, plugins[name], force);
							}
						}
					}
				}
			}.bind(this);
			if (this.options.breakOnErrors) {
				run();
			} else {
				try {
					run();
				} catch (e) {
					this.fireEvent('error', ['Could not apply the behavior ' + filter.name, e]);
				}
			}
			return returnPlugins ? pluginsToReturn : this;
		},

		//given a name, returns a registered behavior
		getFilter: function(name){
			return this._registered[name] || Behavior._registered[name];
		},

		getPlugins: function(name){
			return this._plugins[name] || Behavior._plugins[name];
		},

		//Garbage collects all applied filters for an element and its children.
		//element - (*element*) container to cleanup
		//ignoreChildren - (*boolean*; optional) if *true* only the element will be cleaned, otherwise the element and all the
		//	  children with filters applied will be cleaned. Defaults to *false*.
		cleanup: function(element, ignoreChildren){
			element = document.id(element);
			var applied = getApplied(element);
			for (var behavior in applied) {
				applied[behavior].cleanup(element);
				delete applied[behavior];
			}
			if (!ignoreChildren) element.getElements(':hasBehaviors').each(this.cleanup, this);
			return this;
		}

	});

	//Returns the applied behaviors for an element.
	var getApplied = function(el){
		return el.retrieve('_appliedBehaviors', {});
	};

	//Registers a behavior filter.
	//name - the name of the filter
	//fn - a function that applies the filter to the given element
	//overwrite - (boolean) if true, will overwrite existing filter if one exists; defaults to false.
	var addFilter = function(name, fn, overwrite){
		if (!this._registered[name] || overwrite) this._registered[name] = new Behavior.Filter(name, fn);
	};

	var addFilters = function(obj, overwrite) {
		for (var name in obj) {
			addFilter.apply(this, [name, obj[name], overwrite]);
		}
	};

	//Registers a behavior plugin
	//filterName - (*string*) the filter (or plugin) this is a plugin for
	//name - (*string*) the name of this plugin
	//attacher - a function that applies the filter to the given element
	var addPlugin = function(filterName, name, attacher, overwrite) {
		if (!this._plugins[filterName]) this._plugins[filterName] = {};
		if (!this._plugins[filterName][name] || overwrite) this._plugins[filterName][name] = new Behavior.Filter(name, attacher);
	};

	var addPlugins = function(obj, overwrite) {
		for (var name in obj) {
			addPlugin.apply(this, [obj[name].fitlerName, obj[name].name, obj[name].attacher], overwrite);
		}
	};

	//Add methods to the Behavior namespace for global registration.
	$extend(Behavior, {
		_registered: {},
		_plugins: {},
		addGlobalFilter: addFilter,
		addGlobalFilters: addFilters,
		addGlobalPlugin: addPlugin,
		addGlobalPlugins: addPlugins
	});
	//Add methods to the Behavior class for instance registration.
	Behavior.implement({
		_registered: {},
		_plugins: {},
		addFilter: addFilter,
		addFilters: addFilters,
		addPlugin: addPlugin,
		addPlugins: addPlugins
	});

	//This class is an actual filter that, given an element, alters it with specific behaviors.
	Behavior.Filter = new Class({

		//Pass in an object with the following properties:
		//name - the name of this filter
		//attacher - a function that applies the filter to the given element
		initialize: function(name, attacher){
			this.name = name;
			this.attach = attacher;
			this._marks = new Table();
		},

		//Stores a garbage collection pointer for a specific element.
		//Example: if your filter enhances all the inputs in the container
		//you might have a function that removes that enhancement for garbage collection.
		//You would mark each input matched with its own cleanup function.
		//NOTE: this MUST be the element passed to the filter - the element with this filters
		//      name in its data-filter property. I.E.:
		//<form data-filter="FormValidator">
		//  <input type="text" name="email"/>
		//</form>
		//If this filter is FormValidator, you can mark the form for cleanup, but not, for example
		//the input. Only elements that match this filter can be marked.
		markForCleanup: function(element, fn){
			var marks = this._marks.get(element);
			if (!marks) marks = [];
			marks.include(fn);
			this._marks.set(element, marks);
			return this;
		},

		//Garbage collect a specific element.
		//NOTE: this should be an element that has a data-filter property that matches this filter.
		cleanup: function(element){
			var marks = this._marks.get(element);
			if (marks) {
				marks.each(function(fn){ fn(); });
				this._marks.erase(element);
			}
			return this;
		}

	});

})();

//a selector to find all elements that have behaviors applied to them.
Selectors.Pseudo.hasBehaviors = function(){
	return !!Element.retrieve(this, '_appliedBehaviors');
};

Element.implement({

	addDataFilter: function(name){
		return this.set('data', 'filters', this.getDataFilters().include(name).join(' '));
	},

	removeDataFilter: function(name){
		return this.set('data', 'filters', this.getDataFilters().erase(name).join(' '));
	},

	getDataFilters: function(){
		var filters = this.getData('filters');
		if (!filters) return [];
		return filters.trim().split(spaceOrCommaRegex).map(String.trim);
	},

	hasDataFilter: function(name){
		return this.getDataFilters().contains(name);
	}

});

//allows for selectors like $$('[data-foo-bar]'); TODO: Note that it'll be in Moo 1.3; remove then.
if (window.Selectors && Selectors.RegExps) {
	Selectors.RegExps.combined = (/\.([\w-]+)|\[([\w-]+)(?:([!*^$~|]?=)(["']?)([^\4]*?)\4)?\]|:([\w-]+)(?:\(["']?(.*?)?["']?\)|$)/g);
}
<commit_msg>Moving my closure end so that the regex is available.<commit_after>/*
---
name: Behavior
description: Auto-instantiates widgets/classes based on parsed, declarative HTML.
requires: [Core/Class.Extras, Core/Element, Core/Selectors, /Element.Data, More/Table]
provides: [DashSelectors, Behavior]
...
*/

(function(){

	var spaceOrCommaRegex = /\s*,\s*|\s+/g;

	this.Behavior = new Class({

		Implements: [Options, Events],

		options: {
			//by default, errors thrown by filters are caught; the onError event is fired.
			//set this to *true* to NOT catch these errors to allow them to be handled by the browser.
			// breakOnErrors: false,

			//default error behavior when a filter cannot be applied
			onError: function(){
				if (window.console && console.warn){
					if(console.warn.apply) console.warn.apply(console, arguments);
					else console.warn($A(arguments).join(' '));
				}
			}
			//Components that have a Behavior instance (like an ART.Window)
			//call these events to tell filters that need to know that the state
			//has changed:
			// onResize: $empty, //the element's dimensions have changed
			// onShow: $empty, //the element is displayed
			// onHide: $empty //the element is hidden
		},

		initialize: function(options){
			this.setOptions(options);
			this.passMethods({
				addEvent: this.addEvent.bind(this),
				removeEvent: this.removeEvent.bind(this),
				addEvents: this.addEvents.bind(this),
				removeEvents: this.removeEvents.bind(this),
				fireEvent: this.fireEvent.bind(this),
				applyFilters: this.apply.bind(this),
				applyFilter: this.applyFilter.bind(this),
				getContentElement: $lambda(this.options.container || document.body),
				//this doesn't really stand up; the container is variable - one behavior instance
				//can handle numerous containers... TODO: revisit
				getContainerSize: function() { return this.currentSize; }.bind(this),
				error: function(){ this.fireEvent('error', arguments); }.bind(this)
			});
		},

		//pass a method pointer through to a filter
		//by default the methods for add/remove events are passed to the filter
		//pointed to this instance of behavior. you could use this to pass along
		//other methods to your filters. For example, a method to close a popup
		//for filters presented inside popups.
		_passedMethods: {},
		passMethod: function(method, fn){
			var self = this;
			this._passedMethods[method] = function(){
				return fn.apply(this, arguments);
			};
			return this;
		},

		passMethods: function(methods){
			for (var method in methods) {
				this.passMethod(method, methods[method]);
			}
			return this;
		},

		//These methods don't change the element's state but rather are used
		//to tell filters that need to adapt to the new element state that
		//it has changed.
		show: function(){
			return this.fireEvent('show');
		},

		//the element is hidden
		hide: function(){
			return this.fireEvent('hide');
		},

		//the element's dimensions are now the specified width and height
		resize: function(x, y){
			this.currentSize = {x: x, y: y};
			return this.fireEvent('resize', [x, y]);
		},

		//Applies all the behavior filters for an element.
		//container - (element) an element to apply the filters registered with this Behavior instance to.
		//force - (boolean; optional) passed through to applyFilter (see it for docs)
		apply: function(container, force){
			document.id(container).getElements('[data-filters]').each(function(element){
				var plugins = [];
				element.getDataFilters().each(function(name){
					var behavior = this.getFilter(name.trim());
					if (!behavior) {
						this.fireEvent('error', ['There is no behavior registered with this name: ', name, element]);
					} else {
						plugins.extend(this.applyFilter(element, behavior, force, true));
					}
				}, this);
				plugins.each(function(plugin){ plugin(); });
			}, this);
			return this;
		},

		//Applies a specific behavior to a specific element.
		//element - the element to which to apply the behavior
		//filter - (object) a specific behavior filter, typically one registered with this instance or registered globally.
		//force - (boolean; optional) apply the behavior to each element it matches, even if it was previously applied. Defaults to *false*.
		//returnPlugins - (boolean; optional) if true, plugins are not rendered but instead returned as an array of functions
		applyFilter: function(element, filter, force, returnPlugins){
			var pluginsToReturn = [];
			var run = function(){
				element = document.id(element);
				//get the filters already applied to this element
				var applied = getApplied(element);
				//if this filter is not yet applied to the element, or we are forcing the filter
				if (!applied[filter.name] || force) {
					//if it was previously applied, garbage collect it
					if (applied[filter.name]) applied[filter.name].cleanup(element);
					//apply the filter
					filter.attach(element, this._passedMethods);
					//and mark it as having been previously applied
					applied[filter.name] = filter;
					//apply all the plugins for this filter
					var plugins = this.getPlugins(filter.name);
					if (plugins) {
						for (var name in plugins) {
							if (returnPlugins) {
								pluginsToReturn.push(this.applyFilter.pass([element, plugins[name], force], this));
							} else {
								this.applyFilter(element, plugins[name], force);
							}
						}
					}
				}
			}.bind(this);
			if (this.options.breakOnErrors) {
				run();
			} else {
				try {
					run();
				} catch (e) {
					this.fireEvent('error', ['Could not apply the behavior ' + filter.name, e]);
				}
			}
			return returnPlugins ? pluginsToReturn : this;
		},

		//given a name, returns a registered behavior
		getFilter: function(name){
			return this._registered[name] || Behavior._registered[name];
		},

		getPlugins: function(name){
			return this._plugins[name] || Behavior._plugins[name];
		},

		//Garbage collects all applied filters for an element and its children.
		//element - (*element*) container to cleanup
		//ignoreChildren - (*boolean*; optional) if *true* only the element will be cleaned, otherwise the element and all the
		//	  children with filters applied will be cleaned. Defaults to *false*.
		cleanup: function(element, ignoreChildren){
			element = document.id(element);
			var applied = getApplied(element);
			for (var behavior in applied) {
				applied[behavior].cleanup(element);
				delete applied[behavior];
			}
			if (!ignoreChildren) element.getElements(':hasBehaviors').each(this.cleanup, this);
			return this;
		}

	});

	//Returns the applied behaviors for an element.
	var getApplied = function(el){
		return el.retrieve('_appliedBehaviors', {});
	};

	//Registers a behavior filter.
	//name - the name of the filter
	//fn - a function that applies the filter to the given element
	//overwrite - (boolean) if true, will overwrite existing filter if one exists; defaults to false.
	var addFilter = function(name, fn, overwrite){
		if (!this._registered[name] || overwrite) this._registered[name] = new Behavior.Filter(name, fn);
	};

	var addFilters = function(obj, overwrite) {
		for (var name in obj) {
			addFilter.apply(this, [name, obj[name], overwrite]);
		}
	};

	//Registers a behavior plugin
	//filterName - (*string*) the filter (or plugin) this is a plugin for
	//name - (*string*) the name of this plugin
	//attacher - a function that applies the filter to the given element
	var addPlugin = function(filterName, name, attacher, overwrite) {
		if (!this._plugins[filterName]) this._plugins[filterName] = {};
		if (!this._plugins[filterName][name] || overwrite) this._plugins[filterName][name] = new Behavior.Filter(name, attacher);
	};

	var addPlugins = function(obj, overwrite) {
		for (var name in obj) {
			addPlugin.apply(this, [obj[name].fitlerName, obj[name].name, obj[name].attacher], overwrite);
		}
	};

	//Add methods to the Behavior namespace for global registration.
	$extend(Behavior, {
		_registered: {},
		_plugins: {},
		addGlobalFilter: addFilter,
		addGlobalFilters: addFilters,
		addGlobalPlugin: addPlugin,
		addGlobalPlugins: addPlugins
	});
	//Add methods to the Behavior class for instance registration.
	Behavior.implement({
		_registered: {},
		_plugins: {},
		addFilter: addFilter,
		addFilters: addFilters,
		addPlugin: addPlugin,
		addPlugins: addPlugins
	});

	//This class is an actual filter that, given an element, alters it with specific behaviors.
	Behavior.Filter = new Class({

		//Pass in an object with the following properties:
		//name - the name of this filter
		//attacher - a function that applies the filter to the given element
		initialize: function(name, attacher){
			this.name = name;
			this.attach = attacher;
			this._marks = new Table();
		},

		//Stores a garbage collection pointer for a specific element.
		//Example: if your filter enhances all the inputs in the container
		//you might have a function that removes that enhancement for garbage collection.
		//You would mark each input matched with its own cleanup function.
		//NOTE: this MUST be the element passed to the filter - the element with this filters
		//      name in its data-filter property. I.E.:
		//<form data-filter="FormValidator">
		//  <input type="text" name="email"/>
		//</form>
		//If this filter is FormValidator, you can mark the form for cleanup, but not, for example
		//the input. Only elements that match this filter can be marked.
		markForCleanup: function(element, fn){
			var marks = this._marks.get(element);
			if (!marks) marks = [];
			marks.include(fn);
			this._marks.set(element, marks);
			return this;
		},

		//Garbage collect a specific element.
		//NOTE: this should be an element that has a data-filter property that matches this filter.
		cleanup: function(element){
			var marks = this._marks.get(element);
			if (marks) {
				marks.each(function(fn){ fn(); });
				this._marks.erase(element);
			}
			return this;
		}

	});

	//a selector to find all elements that have behaviors applied to them.
	Selectors.Pseudo.hasBehaviors = function(){
		return !!Element.retrieve(this, '_appliedBehaviors');
	};

	Element.implement({

		addDataFilter: function(name){
			return this.set('data', 'filters', this.getDataFilters().include(name).join(' '));
		},

		removeDataFilter: function(name){
			return this.set('data', 'filters', this.getDataFilters().erase(name).join(' '));
		},

		getDataFilters: function(){
			var filters = this.getData('filters');
			if (!filters) return [];
			return filters.trim().split(spaceOrCommaRegex);
		},

		hasDataFilter: function(name){
			return this.getDataFilters().contains(name);
		}

	});

})();

//allows for selectors like $$('[data-foo-bar]'); TODO: Note that it'll be in Moo 1.3; remove then.
if (window.Selectors && Selectors.RegExps) {
	Selectors.RegExps.combined = (/\.([\w-]+)|\[([\w-]+)(?:([!*^$~|]?=)(["']?)([^\4]*?)\4)?\]|:([\w-]+)(?:\(["']?(.*?)?["']?\)|$)/g);
}
<|endoftext|>


<commit_before>function draw(){
    buffer.clearRect(
      0,
      0,
      width,
      height
    );

    // Draw layers.
    var loop_counter = layers.length - 1;
    do{
        if(loop_counter <= 0){
            continue;
        }

        // Calculate movement towards parent layer.
        var dx = Math.abs(layers[loop_counter][0] - layers[loop_counter][3]);
        var dy = Math.abs(layers[loop_counter][1] - layers[loop_counter][4]);

        if(dx > dy){
            dy = dy / dx * 5;
            dx = 5;

        }else if(dy > dx){
            dx = dx / dy * 5;
            dy = 5;

        }else{
            dx = 2;
            dy = 2;
        }

        // Move towards parent layer.
        layers[loop_counter][0] +=
          layers[loop_counter][0] > layers[loop_counter][3]
            ? -dx
            : dx;
        layers[loop_counter][1] +=
          layers[loop_counter][1] > layers[loop_counter][4]
            ? -dy
            : dy;

        // Remember position of parent layer.
        layers[loop_counter][3] = layers[loop_counter - 1][0];
        layers[loop_counter][4] = layers[loop_counter - 1][1];

        // Draw layer.
        buffer.fillStyle = layers[loop_counter][2];
        buffer.fillRect(
          layers[loop_counter][0],
          layers[loop_counter][1],
          100,
          100
        );
    }while(loop_counter--);

    canvas.clearRect(
      0,
      0,
      width,
      height
    );
    canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );
}

function generate_layers(){
    layers.length = 0;

    // Generate 100 layers.
    var loop_counter = 99;
    do{
        layers.push([
          Math.floor(Math.random() * width) - 50,
          Math.floor(Math.random() * height) - 50,
          random_hex(),
          0,
          0,
        ]);
    }while(loop_counter--);

    // Set target position of topmost layer to current mouse position.
    layers[0][0] = mouse_x - 50;
    layers[0][1] = mouse_y - 50;
}

function init(){
    generate_layers();

    setInterval(
      'draw()',
      50
    );
}

function random_hex(){
    var choices = '0123456789abcdef';
    return '#'
      + choices.charAt(Math.floor(Math.random() * 16))
      + choices.charAt(Math.floor(Math.random() * 16))
      + choices.charAt(Math.floor(Math.random() * 16));
}

function resize(){
    height = window.innerHeight;
    document.getElementById('buffer').height = height;
    document.getElementById('canvas').height = height;

    width = window.innerWidth;
    document.getElementById('buffer').width = width;
    document.getElementById('canvas').width = width;
}

var buffer = document.getElementById('buffer').getContext('2d');
var canvas = document.getElementById('canvas').getContext('2d');
var height = 0;
var layers = [];
var mouse_x = 0;
var mouse_y = 0;
var width = 0;

window.onresize = resize;
resize();

window.onkeydown = generate_layers;

window.onload = init;

window.onmousemove = function(e){
    // Set target position of topmost layer to current mouse position.
    layers[0][0] = mouse_x - 50;
    layers[0][1] = mouse_y - 50;

    mouse_x = e.pageX;
    mouse_y = e.pageY;
};
<commit_msg>added touch support<commit_after>function draw(){
    buffer.clearRect(
      0,
      0,
      width,
      height
    );

    // Draw layers.
    var loop_counter = layers.length - 1;
    do{
        if(loop_counter <= 0){
            continue;
        }

        // Calculate movement towards parent layer.
        var dx = Math.abs(layers[loop_counter][0] - layers[loop_counter][3]);
        var dy = Math.abs(layers[loop_counter][1] - layers[loop_counter][4]);

        if(dx > dy){
            dy = dy / dx * 5;
            dx = 5;

        }else if(dy > dx){
            dx = dx / dy * 5;
            dy = 5;

        }else{
            dx = 2;
            dy = 2;
        }

        // Move towards parent layer.
        layers[loop_counter][0] +=
          layers[loop_counter][0] > layers[loop_counter][3]
            ? -dx
            : dx;
        layers[loop_counter][1] +=
          layers[loop_counter][1] > layers[loop_counter][4]
            ? -dy
            : dy;

        // Remember position of parent layer.
        layers[loop_counter][3] = layers[loop_counter - 1][0];
        layers[loop_counter][4] = layers[loop_counter - 1][1];

        // Draw layer.
        buffer.fillStyle = layers[loop_counter][2];
        buffer.fillRect(
          layers[loop_counter][0],
          layers[loop_counter][1],
          100,
          100
        );
    }while(loop_counter--);

    canvas.clearRect(
      0,
      0,
      width,
      height
    );
    canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );
}

function generate_layers(){
    layers.length = 0;

    // Generate 100 layers.
    var loop_counter = 99;
    do{
        layers.push([
          Math.floor(Math.random() * width) - 50,
          Math.floor(Math.random() * height) - 50,
          random_hex(),
          0,
          0,
        ]);
    }while(loop_counter--);

    set_target(
      mouse_x - 50,
      mouse_y - 50
    );
}

function init(){
    generate_layers();

    setInterval(
      'draw()',
      50
    );
}

function random_hex(){
    var choices = '0123456789abcdef';
    return '#'
      + choices.charAt(Math.floor(Math.random() * 16))
      + choices.charAt(Math.floor(Math.random() * 16))
      + choices.charAt(Math.floor(Math.random() * 16));
}

function resize(){
    height = window.innerHeight;
    document.getElementById('buffer').height = height;
    document.getElementById('canvas').height = height;

    width = window.innerWidth;
    document.getElementById('buffer').width = width;
    document.getElementById('canvas').width = width;
}

function set_target(x, y){
    layers[0][0] = x;
    layers[0][1] = y;
}

var buffer = document.getElementById('buffer').getContext('2d');
var canvas = document.getElementById('canvas').getContext('2d');
var height = 0;
var layers = [];
var mouse_x = 0;
var mouse_y = 0;
var width = 0;

window.onresize = resize;
resize();

window.onkeydown = generate_layers;

window.onload = init;

window.onmousemove =
  window.ontouchstart = function(e){
    set_target(
      mouse_x - 50,
      mouse_y - 50
    );

    mouse_x = e.pageX;
    mouse_y = e.pageY;
};
<|endoftext|>


<commit_before>/*globals console sparks $ breadModel getBreadBoard */

(function() {
  sparks.ActivityConstructor = function(jsonActivity, assessment){
    this.jsonActivity = jsonActivity;
    this.assessment = assessment;
  };

  sparks.ActivityConstructor.prototype = {
    /*
      Creates the breadboard from the JSON representation of the
      circuit. See tests/jspc/spec/spec.common/spec.circuit_constructor
      for examples of json circuits
    */
    createBreadboard: function() {

      if (!this.jsonActivity.circuit){
        console.log("ERROR: No circuit defined");
        return;
      }

      breadModel("createCircuit", this.jsonActivity.circuit);
    },

    /*
      Creates questions from the JSON represenation of the questions,
      and optionally embeds them in the jquery element provided
    */
    createQuestions: function($element){
      if (!this.jsonActivity.questions){
        console.log("ERROR: No questions defined");
        return;
      }

      var assessment = this.assessment;
      var self = this;
      var id = 0;
      $.each(this.jsonActivity.questions, function(i, question){

        function addQuestion(question, preprompt){
          question.correct_answer = self.calculateCorrectAnswer(question.correct_answer);
          var oldPrompt = question.prompt;
          if (!!preprompt){
            question.prompt = preprompt + " " + question.prompt;
          }
          assessment.addQuestion(question,id);
          id++;

          question.prompt = oldPrompt;
        }

        if (!question.subquestions){
          addQuestion(question);
        } else {
          $.each(question.subquestions, function(i, subquestion){
            addQuestion(subquestion, question.prompt);
          });
        }

      });

      if (!!$element) {
        this.embedQuestions($element);
      }
    },

    /*
      When passed a string such as "100 + ${r1.resistance} / ${r2.nominalResistance}"
      This will first substitute the actual values of the variables in ${...}, assuming
      the components and their properties exist in the circuit, and then perform the
      calculation.
    */
    calculateCorrectAnswer: function(answer){
      if (!isNaN(Number(answer))){
        return answer;
      }

      var self = this;

      var sumPattern = /\[[^\]]+\]/g
      var matches= answer.match(sumPattern);
      if (!!matches){
   	   $.each(matches, function(i, match){
    	  	var expression = match;//.substring(1,match.length-1);
    	  	var result = self.calculateSum(expression);
    	  	answer = answer.replace(match,result);
    	  });
       }
      return answer;
    },

   calculateSum: function(sum){
   	  var varPattern = /\${[^}]+}/g
      var matches = sum.match(varPattern);
      if(!!matches){
       $.each(matches, function(i, match){
        var variable = match.substring(2,match.length-1).split('.');
        var component = variable[0];
        var property = variable[1];

        var components = getBreadBoard().components;

        if (!components[component]){
          console.log("ERROR calculating sum: No component name '"+component+"' in circuit");
          sum = -1;
          return;
        }

        if (components[component][property] === undefined || components[component][property] === null){
          console.log("ERROR calculating sum: No property name '"+property+"' in component '"+component+"'");
          sum = -1;
          return;
        }

        var value = components[component][property];
        sum = sum.replace(match, value);
       });
      }

      var calculatedSum = eval(sum);
      if (!isNaN(Number(calculatedSum))){
        return calculatedSum;
      }

      console.log("ERROR calculating Sum: Cannot compute the value of "+sum);
      return -1;
   },

    embedQuestions: function($element){
      var questions = this.jsonActivity.questions;

      var self = this;

      var id = 0;

      $.each(questions, function(i, question){
        var $form = $("<form>");
        $form.addClass("question_form");

        function addInputs($html, question){
		  if (!question.multichoice){

           $html.append(
             $("<input>").attr("id",id+"_input"), "   "
           );
		  } else {
		  	var $select = $("<select>").attr("id",id+"_multichoice");

		  	$.each(question.multichoice, function(i,answer_option){
		  	 //if val is a calculation and not a string, calculate some_answer_option using self.calculateCorrectAnswer()
//		  	 if(answer_option.charAt(0)=='$'){
		  	  answer_option = self.calculateCorrectAnswer(answer_option);
//		  	 }
			//reformat units
			  answer_option = answer_option.replace("ohm","Ω"); //reformat "ohm" to the letter omega
		  	  answer_option = answer_option.replace("micro","µ"); //reformat "micro" to greek letter mu

		  	 $select.append($("<option>").html(answer_option).attr("defaultSelected",i===0));
		  	});
		  	$html.append($select, "   ");
		  }

		  if (!!question.correct_units){
             var $select = $("<select>").attr("id",id+"_units");
             var options = ["Units...","µV","mV","V","Ω","kΩ","MΩ","µA","mA","A"];
             $.each(options, function(i, val){
               $select.append($("<option>").html(val).attr("defaultSelected", i===0));
             });
             $html.append($select, "   ");
          }

          $html.append(
            $("
")
          );
          id++;
        }

        $form.append(
          $("").addClass("prompt").html((i+1) + ".  " + question.prompt), "   "
        );

        if (!question.subquestions){
          addInputs($form, question);
        } else {

          $form.append(
            $('
')
          );

          var $subquestionDiv = $('
').attr('style', 'margin-left: 20px; margin-top: 10px');

          $.each(question.subquestions, function(i, question){
            $subquestionDiv.append(
              $("").addClass("prompt").html(question.prompt), "   "
            );
            addInputs($subquestionDiv, question);
          });

          $form.append($subquestionDiv);
        }

        $form.find('br:last').replaceWith(
          $("<button>").addClass("submit").text("Submit")
        )

        $element.append($form);
      });
    }
  };
})();<commit_msg>"ohms"<commit_after>/*globals console sparks $ breadModel getBreadBoard */

(function() {
  sparks.ActivityConstructor = function(jsonActivity, assessment){
    this.jsonActivity = jsonActivity;
    this.assessment = assessment;
  };

  sparks.ActivityConstructor.prototype = {
    /*
      Creates the breadboard from the JSON representation of the
      circuit. See tests/jspc/spec/spec.common/spec.circuit_constructor
      for examples of json circuits
    */
    createBreadboard: function() {

      if (!this.jsonActivity.circuit){
        console.log("ERROR: No circuit defined");
        return;
      }

      breadModel("createCircuit", this.jsonActivity.circuit);
    },

    /*
      Creates questions from the JSON represenation of the questions,
      and optionally embeds them in the jquery element provided
    */
    createQuestions: function($element){
      if (!this.jsonActivity.questions){
        console.log("ERROR: No questions defined");
        return;
      }

      var assessment = this.assessment;
      var self = this;
      var id = 0;
      $.each(this.jsonActivity.questions, function(i, question){

        function addQuestion(question, preprompt){
          question.correct_answer = self.calculateCorrectAnswer(question.correct_answer);
          var oldPrompt = question.prompt;
          if (!!preprompt){
            question.prompt = preprompt + " " + question.prompt;
          }
          assessment.addQuestion(question,id);
          id++;

          question.prompt = oldPrompt;
        }

        if (!question.subquestions){
          addQuestion(question);
        } else {
          $.each(question.subquestions, function(i, subquestion){
            addQuestion(subquestion, question.prompt);
          });
        }

      });

      if (!!$element) {
        this.embedQuestions($element);
      }
    },

    /*
      When passed a string such as "100 + ${r1.resistance} / ${r2.nominalResistance}"
      This will first substitute the actual values of the variables in ${...}, assuming
      the components and their properties exist in the circuit, and then perform the
      calculation.
    */
    calculateCorrectAnswer: function(answer){
      if (!isNaN(Number(answer))){
        return answer;
      }

      var self = this;

      var sumPattern = /\[[^\]]+\]/g
      var matches= answer.match(sumPattern);
      if (!!matches){
   	   $.each(matches, function(i, match){
    	  	var expression = match;//.substring(1,match.length-1);
    	  	var result = self.calculateSum(expression);
    	  	answer = answer.replace(match,result);

    	  	/*
    	  	var num1 = answer - Math.floor(answer);
    	  	answer = answer.toPrecision(3);
    	  	if(answer < 0){
    	  		//answer = answer.toPrecision(3);
    	  	} else if( answer - Math.floor(answer) != 0 ) {
    	  		//answer = answer.toFixed(3);
    	  	}

    	  	console.log('here too '+answer);

    	  	var anumber=123.45;
    	  	var anumber2=.0034567;
			console.log('toFixed 123.45 '+anumber.toFixed(2)); //returns 123.450 (padding)
			console.log('truncate 0.0034567 '+anumber2.toPrecision(2)); //returns 123.450 (padding)
    	  	*/

    	  	//truncate long answers
    	  });
       }
      return answer;
    },

   calculateSum: function(sum){
   	  var varPattern = /\${[^}]+}/g
      var matches = sum.match(varPattern);
      if(!!matches){
       $.each(matches, function(i, match){
        var variable = match.substring(2,match.length-1).split('.');
        var component = variable[0];
        var property = variable[1];

        var components = getBreadBoard().components;

        if (!components[component]){
          console.log("ERROR calculating sum: No component name '"+component+"' in circuit");
          sum = -1;
          return;
        }

        if (components[component][property] === undefined || components[component][property] === null){
          console.log("ERROR calculating sum: No property name '"+property+"' in component '"+component+"'");
          sum = -1;
          return;
        }

        var value = components[component][property];
        sum = sum.replace(match, value);
       });
      }

      var calculatedSum = eval(sum);
      if (!isNaN(Number(calculatedSum))){
        return calculatedSum;
      }

      console.log("ERROR calculating Sum: Cannot compute the value of "+sum);
      return -1;
   },

    embedQuestions: function($element){
      var questions = this.jsonActivity.questions;

      var self = this;

      var id = 0;

      $.each(questions, function(i, question){
        var $form = $("<form>");
        $form.addClass("question_form");

        function addInputs($html, question){
		  if (!question.multichoice){

           $html.append(
             $("<input>").attr("id",id+"_input"), "   "
           );
		  } else {
		  	var $select = $("<select>").attr("id",id+"_multichoice");

		  	$.each(question.multichoice, function(i,answer_option){
		  	 //if val is a calculation and not a string, calculate some_answer_option using self.calculateCorrectAnswer()
//		  	 if(answer_option.charAt(0)=='$'){
		  	  answer_option = self.calculateCorrectAnswer(answer_option);
//		  	 }
			//reformat units
			  answer_option = answer_option.replace("ohms","Ω"); //reformat "ohm" to the letter omega
		  	  answer_option = answer_option.replace("micro","µ"); //reformat "micro" to greek letter mu

		  	 $select.append($("<option>").html(answer_option).attr("defaultSelected",i===0));
		  	});
		  	$html.append($select, "   ");
		  }

		  if (!!question.correct_units){
             var $select = $("<select>").attr("id",id+"_units");
             var options = ["Units...","µV","mV","V","Ω","kΩ","MΩ","µA","mA","A"];
             $.each(options, function(i, val){
               $select.append($("<option>").html(val).attr("defaultSelected", i===0));
             });
             $html.append($select, "   ");
          }

          $html.append(
            $("
")
          );
          id++;
        }

        $form.append(
          $("").addClass("prompt").html((i+1) + ".  " + question.prompt), "   "
        );

        if (!question.subquestions){
          addInputs($form, question);
        } else {

          $form.append(
            $('
')
          );

          var $subquestionDiv = $('
').attr('style', 'margin-left: 20px; margin-top: 10px');

          $.each(question.subquestions, function(i, question){
            $subquestionDiv.append(
              $("").addClass("prompt").html(question.prompt), "   "
            );
            addInputs($subquestionDiv, question);
          });

          $form.append($subquestionDiv);
        }

        $form.find('br:last').replaceWith(
          $("<button>").addClass("submit").text("Submit")
        )

        $element.append($form);
      });
    }
  };
})();<|endoftext|>


<commit_before>function updateChart (data) {
	var list = [];
	var records = data.responseJSON.Records;
	var len = records;
	for (var i = 0; i < len; i++) {
		list.push([records[i].Date, records[i].Power])
	}
	$.jqplot('futureplot', [list], {
		title:'Predicted Power Usage for the next 24 Hours',
		axes:{xaxis:{renderer:$.jqplot.DateAxisRenderer}},
		series:[{lineWidth:4, markerOptions:{style:'square'}}]
	});
}

function getData () {
	$.getJSON("/data", updateChart);
}
<commit_msg>js fixes<commit_after>function updateChart (data) {
	console.log(data);
	var list = [];
	var records = data.responseJSON.Records;
	var len = records;
	for (var i = 0; i < len; i++) {
		list.push([records[i].Date, records[i].Power])
	}
	$.jqplot('futureplot', [list], {
		title:'Predicted Power Usage for the next 24 Hours',
		axes:{xaxis:{renderer:$.jqplot.DateAxisRenderer}},
		series:[{lineWidth:4, markerOptions:{style:'square'}}]
	});
}

function getData () {
	$.getJSON("/data", updateChart);
}
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Component.extend({
  classNames: ['ember-content-editable'],
  classNameBindings: ['extraClass'],
  attributeBindings: ['contenteditable', 'placeholder'],
  contenteditable: true,
  isText: false,

  setup: Ember.on('didInsertElement', function() {
    this.setValue();
    this._processInput();
  }),

  _observeValue: true,
  valueChanged: Ember.observer('value', function() {
    console.log("Value changed triggered");
    if (this.get('_observeValue')) {
      this.setValue();
    }
  }),

  setValue() {
    if (this.element) {
      this.$().html(this.get('value'));
    }
  },

  stringInterpolator(s) { return s; },

  _processInput() {
    this.set('_observeValue', false);

    let val;
    if (this.get('isText')) {
      val = this.element.innerText || this.element.textContent;
    } else {
      val = this.$().html();
    }

    val = this.stringInterpolator(val);

    if (!this.get('isText')) {
      val = Ember.String.htmlSafe(val);
    }

    this.set('value', val);
    this.set('_observeValue', true);
  },

  updateValue: Ember.on('keyUp', function(event) {
    this._processInput();
    this.handleKeyUp(event);
  }),

  handleKeyUp(event) {
    this.sendAction('key-up', this.get('value'), event);

    if (event.keyCode === 27) {
      // Escape
      this.sendAction('escape-press', this, event);
    } else if (event.keyCode === 13) {
      // Enter
      this.sendAction('enter', this, event);
      this.sendAction('insert-newline', this, event);
    }
  },

  /* Events */
  keyDown(event) {
    this.sendAction('key-down', this.get('value'), event);
  },

  keyPress(event) {
    this.sendAction('key-press', this, event);
  },

  focusIn(event) {
    this.sendAction('focus-in', this, event);
  },

  focusOut(event) {
    this.sendAction('focus-out', this, event);
  },

  mouseEnter(event) {
    this.sendAction('mouse-enter', this, event);
  },

  mouseLeave(event) {
    this.sendAction('mouse-leave', this, event);
  },
});
<commit_msg>Remove logging<commit_after>import Ember from 'ember';

export default Ember.Component.extend({
  classNames: ['ember-content-editable'],
  classNameBindings: ['extraClass'],
  attributeBindings: ['contenteditable', 'placeholder'],
  contenteditable: true,
  isText: false,

  setup: Ember.on('didInsertElement', function() {
    this.setValue();
    this._processInput();
  }),

  _observeValue: true,
  valueChanged: Ember.observer('value', function() {
    if (this.get('_observeValue')) {
      this.setValue();
    }
  }),

  setValue() {
    if (this.element) {
      this.$().html(this.get('value'));
    }
  },

  stringInterpolator(s) { return s; },

  _processInput() {
    this.set('_observeValue', false);

    let val;
    if (this.get('isText')) {
      val = this.element.innerText || this.element.textContent;
    } else {
      val = this.$().html();
    }

    val = this.stringInterpolator(val);

    if (!this.get('isText')) {
      val = Ember.String.htmlSafe(val);
    }

    this.set('value', val);
    this.set('_observeValue', true);
  },

  updateValue: Ember.on('keyUp', function(event) {
    this._processInput();
    this.handleKeyUp(event);
  }),

  handleKeyUp(event) {
    this.sendAction('key-up', this.get('value'), event);

    if (event.keyCode === 27) {
      // Escape
      this.sendAction('escape-press', this, event);
    } else if (event.keyCode === 13) {
      // Enter
      this.sendAction('enter', this, event);
      this.sendAction('insert-newline', this, event);
    }
  },

  /* Events */
  keyDown(event) {
    this.sendAction('key-down', this.get('value'), event);
  },

  keyPress(event) {
    this.sendAction('key-press', this, event);
  },

  focusIn(event) {
    this.sendAction('focus-in', this, event);
  },

  focusOut(event) {
    this.sendAction('focus-out', this, event);
  },

  mouseEnter(event) {
    this.sendAction('mouse-enter', this, event);
  },

  mouseLeave(event) {
    this.sendAction('mouse-leave', this, event);
  },
});
<|endoftext|>


<commit_before>/**
 * jquery.github.js <https://github.com/kmacrow/jquery.github.js>
 *
 * Copyright (C) Kalan MacRow, 2013
 * Simple GitHub widget to display most recent commits to a user's repos.
 *
 * This code is MIT licensed <http://opensource.org/licenses/MIT>
 * You may use it for personal or commercial projects with or without
 * attribution.
*/

(function($)
{
	"use strict";

	var api_base = 'https://api.github.com';

	// defaults
	var settings = {
		'display': 5,
		'user': null
	};

	function debug(msg)
	{
		console.log('github:', msg);
	}

	// for date as iso8601 for github
	function iso8601(date)
	{
		var  year = date.getFullYear(),
		    month = '' + date.getMonth() + 1,
		      day = '' + date.getDate();

		return year + '-'
			   + (month.length == 1 ? '0' + month : month) + '-' +
			   + (day.length   == 1 ? '0' + day   : day);
	}

	// generates string indicating how many
	// minutes/hours/days/months/years ago date was
	function ago(date)
	{
		var diff = Date.now() - date.getTime();

		function pl(qt, unit)
		{
			var m = Math.ceil(diff/qt), u = unit;
			if(m > 1) u += 's'
			return m + ' ' + u + ' ago';
		}

		if(diff < 60*1000){ // a minute
			return 'less than a minute ago';
		}

		diff = Math.ceil(diff/1000); // seconds

		if(diff < 60*60){ // an hour
			return pl(60, 'minute');
		}

		if(diff < 60*60*24){ // a day
			return pl(60*60, 'hour');
		}

		if(diff < 60*60*24*31){ // a month
			return pl(60*60*24, 'day');
		}

		if(diff < 60*60*24*365){ // a year
			return pl(60*60*24*31, 'month');
		}

		return pl(60*60*24*365, 'year');
	}

	// [(name,url)] of all user's repos
	function getRepos(cb)
	{
		var repos = [];

		$.ajax({
				   'url': api_base + '/users/' + settings.user + '/repos',
			   'success': function(data)
			   {
			   		if( !(data instanceof Array) ) {
			   			cb(repos)
			   			return;
			   		}

			   		for(var i = 0; i < data.length; i++) {
			   			var repo = data[i];
			   			repos.push({
			   				   'name': repo.name,
			   				    'url': repo.html_url
			   			});
			   		}

			   		cb(repos);
			   }
		});
	}

	// [(repo,msg,link)] of n most recent commits
	function getCommits(repos, cb)
	{
		var   index = {},
			commits = [],
			    bar = repos.length,
			  since = iso8601(new Date(Date.now() - 2629740000));;

		function lower() {
			if(--bar == 0) {
				complete();
			}
		}

		function complete() {
			// sort by time
			commits.sort(function(a, b) {
				return b.date.getTime() - a.date.getTime();
			});

			cb(commits.slice(0, settings.display));
		}

		$.each(repos, function(i, repo){

			$.ajax({
				    'url': (api_base + '/repos/'
							         + settings.user
							         + '/' + repo.name + '/commits'),
				   'data': {'since': since},
				'success': function(data)
				{
					if( !(data instanceof Array) ) {
						lower();
						return;
					}

					for(var i = 0; i < data.length; i++) {
						var commit = data[i];
						commits.push({
							'repo': repo,
							'user': {
								  'name': commit.author.login,
								'avatar': commit.author.avatar_url,
								   'url': 'https://github.com/'
								   		  + commit.author.login
							 },
							 'msg': commit.commit.message,
							 'sha': commit.sha,
							 'url': ('https://github.com/' + settings.user
							 		+ '/' + repo.name + '/commit/' + commit.sha),
							'tree': ('https://github.com/' + settings.user
									+ '/' + repo.name + '/tree/' + commit.sha),
							'date': new Date(Date.parse(commit.commit.author.date))
						});
					}

					lower();
				}
			});
		});

	}

	$.fn.github = function(options)
	{
		var $this = this;

		for(var key in settings) {
			if(options.hasOwnProperty(key)
				&& typeof options[key] != 'undefined') {
				settings[key] = options[key];
			}
		}

		if(!settings.user) {
			console.error('github: please provide username');
			return;
		}

		debug(settings);

		getRepos(function(repos)
		{
			debug(repos);

			getCommits(repos, function(commits)
			{
				debug(commits);

				var html = '
'
						  +'
'
						  	+''
						  		+' '
						  		+':stream / '
						  		+''
						  		+ settings.user+''
						  	+'	'
						  +'
';

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

					var commit = commits[i];
					html += '
'
								+''
								+'	'
								+''
									+'' + commit.msg + '
'
									+'
'
										+ commit.user.name + ' '
										+ ago(commit.date) + ' to '
										+''+commit.repo.name+''
									+'
'
								+'	'
								+''
									+''
										+ commit.sha.substring(0,10) + '
'
									+'Browse code »'
									+ ''
								+'	'
							+'
';
				}

				html += '
';
				$this.html(html);
			});
		});
	}

})(jQuery);
<commit_msg>tweaks to source header<commit_after>/**
 * jquery.github.js <https://github.com/kmacrow/jquery.github.js>
 * The easiest way to display your most recent GitHub contributions.
 *
 * Copyright (C) Kalan MacRow, 2013
 *
 * This code is MIT licensed <http://opensource.org/licenses/MIT>
 *
*/

(function($)
{
	"use strict";

	var api_base = 'https://api.github.com';

	// defaults
	var settings = {
		'display': 5,
		'user': null
	};

	function debug(msg)
	{
		console.log('github:', msg);
	}

	// for date as iso8601 for github
	function iso8601(date)
	{
		var  year = date.getFullYear(),
		    month = '' + date.getMonth() + 1,
		      day = '' + date.getDate();

		return year + '-'
			   + (month.length == 1 ? '0' + month : month) + '-' +
			   + (day.length   == 1 ? '0' + day   : day);
	}

	// generates string indicating how many
	// minutes/hours/days/months/years ago date was
	function ago(date)
	{
		var diff = Date.now() - date.getTime();

		function pl(qt, unit)
		{
			var m = Math.ceil(diff/qt), u = unit;
			if(m > 1) u += 's'
			return m + ' ' + u + ' ago';
		}

		if(diff < 60*1000){ // a minute
			return 'less than a minute ago';
		}

		diff = Math.ceil(diff/1000); // seconds

		if(diff < 60*60){ // an hour
			return pl(60, 'minute');
		}

		if(diff < 60*60*24){ // a day
			return pl(60*60, 'hour');
		}

		if(diff < 60*60*24*31){ // a month
			return pl(60*60*24, 'day');
		}

		if(diff < 60*60*24*365){ // a year
			return pl(60*60*24*31, 'month');
		}

		return pl(60*60*24*365, 'year');
	}

	// [(name,url)] of all user's repos
	function getRepos(cb)
	{
		var repos = [];

		$.ajax({
				   'url': api_base + '/users/' + settings.user + '/repos',
			   'success': function(data)
			   {
			   		if( !(data instanceof Array) ) {
			   			cb(repos)
			   			return;
			   		}

			   		for(var i = 0; i < data.length; i++) {
			   			var repo = data[i];
			   			repos.push({
			   				   'name': repo.name,
			   				    'url': repo.html_url
			   			});
			   		}

			   		cb(repos);
			   }
		});
	}

	// [(repo,msg,link)] of n most recent commits
	function getCommits(repos, cb)
	{
		var   index = {},
			commits = [],
			    bar = repos.length,
			  since = iso8601(new Date(Date.now() - 2629740000));;

		function lower() {
			if(--bar == 0) {
				complete();
			}
		}

		function complete() {
			// sort by time
			commits.sort(function(a, b) {
				return b.date.getTime() - a.date.getTime();
			});

			cb(commits.slice(0, settings.display));
		}

		$.each(repos, function(i, repo){

			$.ajax({
				    'url': (api_base + '/repos/'
							         + settings.user
							         + '/' + repo.name + '/commits'),
				   'data': {'since': since},
				'success': function(data)
				{
					if( !(data instanceof Array) ) {
						lower();
						return;
					}

					for(var i = 0; i < data.length; i++) {
						var commit = data[i];
						commits.push({
							'repo': repo,
							'user': {
								  'name': commit.author.login,
								'avatar': commit.author.avatar_url,
								   'url': 'https://github.com/'
								   		  + commit.author.login
							 },
							 'msg': commit.commit.message,
							 'sha': commit.sha,
							 'url': ('https://github.com/' + settings.user
							 		+ '/' + repo.name + '/commit/' + commit.sha),
							'tree': ('https://github.com/' + settings.user
									+ '/' + repo.name + '/tree/' + commit.sha),
							'date': new Date(Date.parse(commit.commit.author.date))
						});
					}

					lower();
				}
			});
		});

	}

	$.fn.github = function(options)
	{
		var $this = this;

		for(var key in settings) {
			if(options.hasOwnProperty(key)
				&& typeof options[key] != 'undefined') {
				settings[key] = options[key];
			}
		}

		if(!settings.user) {
			console.error('github: please provide username');
			return;
		}

		debug(settings);

		getRepos(function(repos)
		{
			debug(repos);

			getCommits(repos, function(commits)
			{
				debug(commits);

				var html = '
'
						  +'
'
						  	+''
						  		+' '
						  		+':stream / '
						  		+''
						  		+ settings.user+''
						  	+'	'
						  +'
';

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

					var commit = commits[i];
					html += '
'
								+''
								+'	'
								+''
									+'' + commit.msg + '
'
									+'
'
										+ commit.user.name + ' '
										+ ago(commit.date) + ' to '
										+''+commit.repo.name+''
									+'
'
								+'	'
								+''
									+''
										+ commit.sha.substring(0,10) + '
'
									+'Browse code »'
									+ ''
								+'	'
							+'
';
				}

				html += '
';
				$this.html(html);
			});
		});
	}

})(jQuery);
<|endoftext|>


<commit_before>var lumbarLoader = exports.loader = {
  loadPrefix: '',

  loadModule: function(moduleName, callback) {
    var loadCount = 0,
        expected = 1,
        allInit = false;
    function complete() {
      loadCount++;
      if (allInit && loadCount >= expected) {
        callback();
      }
    }

    expected += lumbarLoader.loadCSS(moduleName, complete);
    expected += lumbarLoader.loadJS(moduleName, complete);

    // If everything was done sync then fire away
    allInit = true;
    complete();
  },

  loadInlineCSS: function(content) {
    var style = document.createElement('style');
    style.textContent = content;
    document.body.appendChild(style);
    return style;
  }
};

function loadResources(moduleName, field, attr, create) {
  var module = moduleName === 'base' ? lumbarLoader.map.base : lumbarLoader.modules[moduleName], // Special case for the base case
      field = module[field] || [],
      loaded = [];

  if (Array.isArray ? !Array.isArray(field) :field.toString() !== '[object Array]') {
    field = [field];
  }
  for (var i = 0, len = field.length; i < len; i++) {
    var object = field[i];
    var href = checkLoadResource(object, attr);
    if (href) {
      var el = create(href);
      if (el && el.nodeType === 1) {
        document.body.appendChild(el);
      }
      loaded.push(el);
    }
  }
  return loaded;
}

var devicePixelRatio = window.devicePixelRatio || 1;
function checkLoadResource(object, attr) {
  var href = lumbarLoader.loadPrefix + (object.href || object);
  if ((!object.maxRatio || devicePixelRatio < object.maxRatio) && (!object.minRatio || object.minRatio <= devicePixelRatio)) {
    if (document.querySelector('[' + attr + '="' + href + '"]')) {
      return;
    }

    return href;
  }
}

exports.moduleMap = function(map, loadPrefix) {
  lumbarLoader.map = map;
  lumbarLoader.modules = map.modules;
  lumbarLoader.loadPrefix = loadPrefix || '';
};
<commit_msg>update lumbar-loader to latest<commit_after>var lumbarLoader = exports.loader = {
  loadPrefix: lumbarLoadPrefix || '',

  loadModule: function(moduleName, callback) {
    var loadCount = 0,
        expected = 1,
        allInit = false;
    function complete() {
      loadCount++;
      if (allInit && loadCount >= expected) {
        callback();
      }
    }

    expected += lumbarLoader.loadCSS(moduleName, complete);
    expected += lumbarLoader.loadJS(moduleName, complete);

    // If everything was done sync then fire away
    allInit = true;
    complete();
  },

  loadInlineCSS: function(content) {
    var style = document.createElement('style');
    style.textContent = content;
    document.body.appendChild(style);
    return style;
  }
};

function loadResources(moduleName, field, attr, create) {
  var module = moduleName === 'base' ? lumbarLoader.map.base : lumbarLoader.modules[moduleName], // Special case for the base case
      field = module[field] || [],
      loaded = [];

  if (Array.isArray ? !Array.isArray(field) :field.toString() !== '[object Array]') {
    field = [field];
  }
  for (var i = 0, len = field.length; i < len; i++) {
    var object = field[i];
    var href = checkLoadResource(object, attr);
    if (href) {
      var el = create(href);
      if (el && el.nodeType === 1) {
        document.body.appendChild(el);
      }
      loaded.push(el);
    }
  }
  return loaded;
}

var devicePixelRatio = window.devicePixelRatio || 1;
function checkLoadResource(object, attr) {
  var href = lumbarLoader.loadPrefix + (object.href || object);
  if ((!object.maxRatio || devicePixelRatio < object.maxRatio) && (!object.minRatio || object.minRatio <= devicePixelRatio)) {
    if (document.querySelector('[' + attr + '="' + href + '"]')) {
      return;
    }

    return href;
  }
}

exports.moduleMap = function(map, loadPrefix) {
  lumbarLoader.map = map;
  lumbarLoader.modules = map.modules;
  lumbarLoader.loadPrefix = loadPrefix || lumbarLoader.loadPrefix;
};
<|endoftext|>