<commit_before>(function() {

//utils
function assert(x,str) {
	if (x===false) throw new Error(str)
}

var logic = {}

/*
	frames
*/

function Frame(a,b) {
	this.first = a
	this.rest = b
	this.type = 'frame'
}

Frame.prototype = {
	is_empty : function () {
		var s = this
		return typeof s.rest === 'undefined'
	}
	,append : function (s2) {
		var s1 = this
		if (s1.is_empty())
			return s2
		else
			return new Frame(s1.first, s1.append(s2));
	}
	,interleave : function (s2) {
		var s1 = this
		if (s1.is_empty())
			return s2
		else
			return logic.make_frame(s1.first, s2.interleave(s1.rest));
	}
	,forEach : function (f) {
		var s = this
		if(s.is_empty()) return;
		else {
			f(s.first)
			s.rest.forEach(f)
		}
	}
	,foldr : function (f, initial) {
		var s=this
		if (s.is_empty()) {
			return initial
		}
		else {
			return f(s.first, s.rest.foldr(f, initial))
		}
	}
	,map : function (f) {
		var s=this
		if(s.is_empty())
			return EMPTY_STREAM
		else {
			var _rest = s.rest.map(f)
			return logic.make_frame(f(s.first), _rest);
		}
	 }
	,extend : function (val) {
		return logic.make_frame(val, this)
	}
	,toString : function() {
		var str = '|'
		var s=this
		while(!s.is_empty()) {
			str += s.first.toString()+(s.rest.is_empty()?'':', ')
			s=s.rest
		}
		str+='|'
		return str
	}
	,write : function () {
		write(this.toString())
	}
	,lookup_binding_helper : function (frame, variable) {
		if(frame===EMPTY_FRAME) return false
		else if(frame.first.variable===variable) return frame.first
		else return frame.rest.lookup_binding(variable)
	}
	,lookup_binding : function (variable) {
		return this.lookup_binding_helper(this, variable)
	}
}

/*
	streams
*/

function Stream(a,b) {
	this.first = a
	this.rest = b
	this.type = 'stream'
}

Stream.prototype = {
	is_empty : function () {
		var s = this
		return typeof s.rest === 'undefined'
	}
	,iterate : function (f, j, i) {
		var s = this
		i = i||0
		if(i>=j || s.is_empty()) return;
		else {
			f(s.first)
			s.rest().iterate(f,j,i+1)
		}
	}
	,forEach : function (f) {
		var s = this
		if(s.is_empty()) return;
		else {
			f(s.first)
			s.rest().iterate(f)
		}
	}
	,foldr : function (f, initial) {
		var s=this
		if (s.is_empty()) {
			return initial
		}
		else {
			return f(s.first, s.rest().foldr(f, initial))
		}
	}
	,map : function (f) {
		var s=this
		if(s.is_empty())
			return EMPTY_STREAM
		else {
			var _rest = s.rest().map(f)
			return logic.make_stream(f(s.first), function() { return _rest; });
		}
	 }
	 ,flatten : function () {
		var s = this
		if (s.is_empty())
			return s
		else if(logic.is_stream(s.first)) {
			var s1 = s.first
				,s2 = s.rest()
			return (s1).append(s2.flatten());
		}
		else
			return logic.make_stream(s.first).append(s.rest().flatten())
	}
	,append : function (s2) {
		var s1 = this
		if (s1.is_empty())
			return s2
		else
			return logic.make_stream(s1.first, function() { return s1.rest().append(s2); });
	}
	,interleave : function (s2) {
		var s1 = this
		if (s1.is_empty())
			return s2
		else
			return logic.make_stream(s1.first, function() {
				return s2.interleave(s1.rest());
			});
	}
	,extend : function (val) {
		var frame=this
		return logic.make_stream(val, function() { return frame; });
	}
	,toString : function() {
		var str = '('
		var s=this
		while(!s.is_empty()) {
			str += s.first.toString()+(s.rest().is_empty()?'':', ')
			s=s.rest()
		}
		str+=')'
		return str
	}
	,write : function () {
		write(this.toString())
	}
}

/*
	bindings
*/

function Binding(variable, val) {
	//frame is a list of bindings
	this.variable = variable
	this.val = val
	this.type = 'binding'
}

Binding.prototype.toString = function () { return (typeof this.variable.name!=='undefined'?this.variable.name:'_') + '=' + this.val.toString() }

/*
	types
*/

var EMPTY_STREAM = new Stream(undefined, undefined)
var EMPTY_FRAME = new Frame(undefined, undefined)

logic.nil = EMPTY_FRAME
logic.EMPTY_STREAM = EMPTY_STREAM
logic.EMPTY_FRAME = EMPTY_FRAME

logic.is_stream = function (s) {
	return typeof s==='object' && s.type && s.type==='stream'
}

logic.is_frame = function (s) {
	return typeof s==='object' && s.type && s.type==='stream'
}

logic.is_binding = function (s) {
	return typeof s==='object' && s.type && s.type==='binding'
}

logic.is_lvar = function (v) {
	return (typeof v==='object') && (typeof v.type!=='undefined') && v.type==='lvar'
}

logic.is_array = function (v) {
	return Object.prototype.toString.call( v ) === '[object Array]'
}

logic.is_object = function (v) {
	return Object.prototype.toString.call( v ) === '[object Object]'
}

logic.lvar = function (name) { //name is optional (for debugging)
	return {type : 'lvar', name : name}
}

logic.make_binding = function (variable, val, name) {
	var b = new Binding(variable, val)
	return b
}

logic.make_stream = function (a,b) {
	if(typeof b==='undefined') b = function() { return EMPTY_STREAM; }
	assert(typeof b==='function', '#2 argument must be function.')
	return new Stream(a,b)
}

logic.make_frame = function (a,b) {
	if(typeof b==='undefined') b = EMPTY_LIST
	assert(typeof b==='object', '#2 argument must be object.')
	return new Frame(a,b)
}

logic.unify = function (a, b, frame) {
	if(frame===false)
		return false
	a = walk(a, frame)
	b = walk(b, frame)
	if(a===b)
		return frame
	else if(logic.is_lvar(a)) { //is variable
		return frame.extend(logic.make_binding(a,b))
	}
	else if(logic.is_lvar(b)) //is variable
		return frame.extend(logic.make_binding(b,a))
	else if(typeof a === 'object') {
		if(logic.is_array(a) && logic.is_array(b)) {
			//match two arrays
			if(a.length!==b.length) return false;
			for(var i=0;i<a.length;++i)
				frame = logic.unify(a[i], b[i], frame)
			return frame
		}
		else if(logic.is_object(a) && logic.is_object(b)) {
			//match two objects
			for(var prop in a) {
				if(a.hasOwnProperty(prop))
					if(typeof b[prop]!=='undefined') frame = logic.unify(a[prop], b[prop], frame)
			}
			for(var prop in b) {
				if(b.hasOwnProperty(prop))
					if(typeof a[prop]!=='undefined') frame = logic.unify(b[prop], a[prop], frame)
			}
			return frame
		}
		else
			return false
	}
	else return false
}

function walk(variable, frame) {
	//finds out what value a variable is associated with, e.g.
	//walk(x, |x=2|) ==> 2
	//walk(x, |x=y|) ==> y
	//walk(x, |x=y;y=w;w=2|) ==> 2
	//walk(x, |w=y|) ==> x
	var frame0 = frame
	if(logic.is_lvar(variable)) {
		while(!frame.is_empty()) {
			var binding = frame.first
			if(binding.variable===variable) {
				return walk(binding.val, frame0)
			}
			frame = frame.rest
		}
		return variable
	}
	else
		return variable
}

logic.walk = walk

/*
	a goal/relation takes a frame and returns a stream of frames (an empty stream stands for a 'fail'/'false' goal)
*/

logic.eq = function (a, b) { //'goal' version of unify
	return function(f) {
		var f2 = logic.unify(a, b, f)
		if(f2) return logic.win(f2)
		else return logic.fail()
	}
}

logic.win = function (frame) { return logic.make_stream(frame||logic.nil) }
logic.fail = function (frame) { return EMPTY_STREAM }

/*
	some functions that operate on goals
*/

logic.disj = function (g1, g2) {
	return function(f) {
		return g1(f).append(g2(f))
	}
}
logic.or = logic.disj

logic.conj = function (g1, g2) {
	return function(f) {
		var s1 = g1(f)
		return s1.map(function(f) {
			return g2(f)
		}).flatten();
	}
}
logic.and = logic.conj

/*
	non-fundamental goals
*/

var _between = function (a,b,x) {
	if(a>b)
		return logic.fail
	else
		return logic.disj(logic.eq(x,a), logic.between(a+1,b,x))
}

logic.between = function (a,b,x) {
	assert(typeof(a) === 'number', '#1 argument of between is number')
	assert(typeof(b) === 'number', '#2 argument of between is number')
	return _between(a,b,x)
}

logic.run = function (g, v, n) {
	//runs goal getting the first n results of variables
	//n is optional (n=n or infinity)
	//v is variable or array of variables
	assert(logic.is_lvar(v) || logic.is_array(v), '#2 must be variable/array')
	n = ((typeof n==='undefined')?(1/0):n)
	var s = g(logic.nil)
		,result = []
	for(var i=0; i<n && !s.is_empty();++i) {
		var frame = s.first
		if(logic.is_lvar(v)) { //get variable into result
			var v2 = walk(v, frame)
			var _temp = logic.is_lvar(v2) ? frame.lookup_binding(v).val : v2
			result.push(_temp)
		}
		else { //get array of variables into result
			var vals = []
			for(var j=0;j<v.length;++j) {
				var v2 = walk(v[j], frame)
				var _temp = logic.is_lvar(v2) ? frame.lookup_binding(v2).val : v2
				vals.push(_temp)
			}
			result.push(vals)
		}
		s=s.rest()
	}
	return result
}

//export module to nodejs/browser
if (typeof exports !== 'undefined') {
	if (typeof module !== 'undefined' && module.exports) {
	  exports = module.exports = logic;
	}
	exports.logic = logic;
}
else {
	this.logic = logic;
}

}).call(this);
<commit_msg>replaced 'frame' by 'package'; frame class replaced by list class<commit_after>(function() {

//utils
function assert(x,str) {
	if (x===false) throw new Error(str)
}

inherit = function (P,Q){
	P.prototype = new Q()
	P.prototype.constructor = P
}

var logic = {}

/*
	lists
*/

function List(a,b) {
	this.first = a
	this.rest = b
	this.type = 'list'
}

List.prototype = {
	is_empty : function () {
		var s = this
		return typeof s.rest === 'undefined'
	}
	,append : function (s2) {
		var s1 = this
		if (s1.is_empty())
			return s2
		else
			return logic.make_list(s1.first, s1.append(s2));
	}
	,interleave : function (s2) {
		var s1 = this
		if (s1.is_empty())
			return s2
		else
			return logic.make_list(s1.first, s2.interleave(s1.rest));
	}
	,forEach : function (f) {
		var s = this
		if(s.is_empty()) return;
		else {
			f(s.first)
			s.rest.forEach(f)
		}
	}
	,foldr : function (f, initial) {
		var s=this
		if (s.is_empty()) {
			return initial
		}
		else {
			return f(s.first, s.rest.foldr(f, initial))
		}
	}
	,map : function (f) {
		var s=this
		if(s.is_empty())
			return EMPTY_STREAM
		else {
			var _rest = s.rest.map(f)
			return logic.make_list(f(s.first), _rest);
		}
	 }
	,extend : function (val) {
		return logic.make_list(val, this)
	}
	,toString : function() {
		var str = '|'
		var s=this
		while(!s.is_empty()) {
			str += s.first.toString()+(s.rest.is_empty()?'':'; ')
			s=s.rest
		}
		str+='|'
		return str
	}
	,write : function () {
		write(this.toString())
	}
}

/*
	packages hold a **frame** and a **constraint store**
*/

function Package(f, cs) {
	this.frame = f
	this.store = cs
	this.type = 'package'
}

Package.prototype.lookup_binding_helper = function (frame, variable) {
	if(frame===EMPTY_LIST) return false
	else if(frame.first.variable===variable) return frame.first
	else return this.lookup_binding_helper(frame.rest, variable)
}

Package.prototype.lookup_binding = function (variable) {
	return this.lookup_binding_helper(this.frame, variable)
}

Package.prototype.is_empty = function (arguments) {
	return this.frame.is_empty(arguments)
}

Package.prototype.extend_frame = function (f) {
	return logic.make_package(f, this.store)
}

Package.prototype.extend_store = function (cs) {
	return logic.make_package(this.frame, cs)
}

Package.prototype.extend = function (arguments) {
	return logic.make_package(this.frame.extend(arguments), this.store)
}

Package.prototype.toString = function() {
	var str = '{'+this.frame.toString()+', '+this.store+'}'
	return str
}

Package.prototype.write = function () {
	write(this.toString())
}

/*
	streams
*/

function Stream(a,b) {
	this.first = a
	this.rest = b
	this.type = 'stream'
}

Stream.prototype = {
	is_empty : function () {
		var s = this
		return typeof s.rest === 'undefined'
	}
	,iterate : function (f, j, i) {
		var s = this
		i = i||0
		if(i>=j || s.is_empty()) return;
		else {
			f(s.first)
			s.rest().iterate(f,j,i+1)
		}
	}
	,forEach : function (f) {
		var s = this
		if(s.is_empty()) return;
		else {
			f(s.first)
			s.rest().iterate(f)
		}
	}
	,foldr : function (f, initial) {
		var s=this
		if (s.is_empty()) {
			return initial
		}
		else {
			return f(s.first, s.rest().foldr(f, initial))
		}
	}
	,map : function (f) {
		var s=this
		if(s.is_empty())
			return EMPTY_STREAM
		else {
			var _rest = s.rest().map(f)
			return logic.make_stream(f(s.first), function() { return _rest; });
		}
	 }
	 ,flatten : function () {
		var s = this
		if (s.is_empty())
			return s
		else if(logic.is_stream(s.first)) {
			var s1 = s.first
				,s2 = s.rest()
			return (s1).append(s2.flatten());
		}
		else
			return logic.make_stream(s.first).append(s.rest().flatten())
	}
	,append : function (s2) {
		var s1 = this
		if (s1.is_empty())
			return s2
		else
			return logic.make_stream(s1.first, function() { return s1.rest().append(s2); });
	}
	,interleave : function (s2) {
		var s1 = this
		if (s1.is_empty())
			return s2
		else
			return logic.make_stream(s1.first, function() {
				return s2.interleave(s1.rest());
			});
	}
	,extend : function (val) {
		var frame=this
		return logic.make_stream(val, function() { return frame; });
	}
	,toString : function() {
		var str = '('
		var s=this
		while(!s.is_empty()) {
			str += s.first.toString()+(s.rest().is_empty()?'':', ')
			s=s.rest()
		}
		str+=')'
		return str
	}
	,write : function () {
		write(this.toString())
	}
}

/*
	bindings
*/

function Binding(variable, val) {
	//frame is a list of bindings
	this.variable = variable
	this.val = val
	this.type = 'binding'
}

Binding.prototype.toString = function () { return (typeof this.variable.name!=='undefined'?this.variable.name:'_') + '=' + this.val.toString() }

/*
	types
*/

var EMPTY_STREAM = new Stream(undefined, undefined)
var EMPTY_LIST = new List(undefined, undefined)
var EMPTY_PACKAGE = new Package(EMPTY_LIST, EMPTY_LIST)

logic.nil = EMPTY_PACKAGE //a goal needs a package; therefore it initially receives 'nil' (the first package)
logic.EMPTY_STREAM = EMPTY_STREAM
logic.EMPTY_LIST = EMPTY_LIST

function has_type(obj, type) {
	return (typeof obj==='object') && (typeof obj.type!=='undefined') && obj.type===type
}

logic.is_stream = function (v) {
	return has_type(v, 'stream')
}

logic.is_list = function (v) {
	return has_type(v, 'list')
}

logic.is_package = function (v) {
	return has_type(v, 'package')
}

logic.is_binding = function (v) {
	return has_type(v, 'binding')
}

logic.is_lvar = function (v) {
	return has_type(v, 'lvar')
}

logic.is_array = function (v) {
	return Object.prototype.toString.call( v ) === '[object Array]'
}

logic.is_object = function (v) {
	return Object.prototype.toString.call( v ) === '[object Object]'
}

logic.lvar = function (name) { //name is optional (for debugging)
	return {type : 'lvar', name : name}
}

logic.make_binding = function (variable, val, name) {
	var b = new Binding(variable, val)
	return b
}

logic.make_stream = function (a,b) {
	if(typeof b==='undefined') b = function() { return EMPTY_STREAM; }
	assert(typeof b==='function', '#2 argument must be function.')
	return new Stream(a,b)
}

logic.make_list = function (a,b) {
	if(typeof b==='undefined') b = EMPTY_LIST
	assert(typeof b==='object', '#2 argument must be object.')
	return new List(a,b)
}

logic.make_package = function (f, cs) {
	assert(logic.is_list(f) && logic.is_list(cs), "#1 and #2 arguments of package must be list")
	return new Package(f,cs)
}

logic.unify = function (a, b, frame) {
	if(frame===false)
		return false
	a = walk(a, frame)
	b = walk(b, frame)
	if(a===b)
		return frame
	else if(logic.is_lvar(a)) { //is variable
		return frame.extend(logic.make_binding(a,b))
	}
	else if(logic.is_lvar(b)) //is variable
		return frame.extend(logic.make_binding(b,a))
	else if(typeof a === 'object') {
		if(logic.is_array(a) && logic.is_array(b)) {
			//match two arrays
			if(a.length!==b.length) return false;
			for(var i=0;i<a.length;++i)
				frame = logic.unify(a[i], b[i], frame)
			return frame
		}
		else if(logic.is_object(a) && logic.is_object(b)) {
			//match two objects
			for(var prop in a) {
				if(a.hasOwnProperty(prop))
					if(typeof b[prop]!=='undefined') frame = logic.unify(a[prop], b[prop], frame)
			}
			for(var prop in b) {
				if(b.hasOwnProperty(prop))
					if(typeof a[prop]!=='undefined') frame = logic.unify(b[prop], a[prop], frame)
			}
			return frame
		}
		else
			return false
	}
	else return false
}

function walk(variable, frame) {
	//finds out what value a variable is associated with, e.g.
	//walk(x, |x=2|) ==> 2
	//walk(x, |x=y|) ==> y
	//walk(x, |x=y;y=w;w=2|) ==> 2
	//walk(x, |w=y|) ==> x
	var frame0 = frame
	if(logic.is_lvar(variable)) {
		while(!frame.is_empty()) {
			var binding = frame.first
			if(binding.variable===variable) {
				return walk(binding.val, frame0)
			}
			frame = frame.rest
		}
		return variable
	}
	else
		return variable
}

logic.walk = walk

/*
	a goal/relation takes a package and returns a stream of packages (an empty stream stands for a 'fail'/'false' goal)
*/

logic.eq = function (a, b) { //'goal' version of unify
	return function(p) {
		var f = p.frame
		var f2 = logic.unify(a, b, f)
		if(f2)
			return logic.win(p.extend_frame(f2))
		else
			return logic.fail()
	}
}

logic.win = function (pack) { return logic.make_stream(pack||logic.nil) }
logic.fail = function (pack) { return EMPTY_STREAM }

/*
	some functions that operate on goals
*/

logic.disj = function (g1, g2) {
	return function(f) {
		return g1(f).append(g2(f))
	}
}
logic.or = logic.disj

logic.conj = function (g1, g2) {
	return function(f) {
		var s1 = g1(f)
		return s1.map(function(f) {
			return g2(f)
		}).flatten();
	}
}
logic.and = logic.conj

/*
	non-fundamental goals
*/

var _between = function (a,b,x) {
	if(a>b)
		return logic.fail
	else
		return logic.disj(logic.eq(x,a), logic.between(a+1,b,x))
}

logic.between = function (a,b,x) {
	assert(typeof(a) === 'number', '#1 argument of between is number')
	assert(typeof(b) === 'number', '#2 argument of between is number')
	return _between(a,b,x)
}

logic.run = function (g, v, n) {
	//runs goal getting the first n results of variables
	//n is optional (n=n or infinity)
	//v is variable or array of variables
	assert(logic.is_lvar(v) || logic.is_array(v), '#2 must be variable/array')
	n = ((typeof n==='undefined')?(1/0):n)
	var s = g(logic.nil)
		,result = []
	for(var i=0; i<n && !s.is_empty();++i) {
		var pack = s.first
			,frame = pack.frame
		if(logic.is_lvar(v)) { //get variable into result
			var v2 = walk(v, frame)
			var _temp = logic.is_lvar(v2) ? pack.lookup_binding(v).val : v2
			result.push(_temp)
		}
		else { //get array of variables into result
			var vals = []
			for(var j=0;j<v.length;++j) {
				var v2 = walk(v[j], frame)
				var _temp = logic.is_lvar(v2) ? pack.lookup_binding(v2).val : v2
				vals.push(_temp)
			}
			result.push(vals)
		}
		s=s.rest()
	}
	return result
}

//export module to nodejs/browser
if (typeof exports !== 'undefined') {
	if (typeof module !== 'undefined' && module.exports) {
	  exports = module.exports = logic;
	}
	exports.logic = logic;
}
else {
	this.logic = logic;
}

}).call(this);
<|endoftext|>


<commit_before>var Promise = require('es6-promise').Promise;

var Game = require('../models/game');
var utils = require('../../lib/utils');

module.exports = {
  all: function (request) {
    return Game.objects.all(request.pg.client,
      request.params);
  },
  create: function (request) {
    return Game.objects.create(request.pg.client,
      request.payload
    );
  },
  get: function (request) {
    return Game.objects.get(request.pg.client, {
      idOrSlug: request.params.idOrSlug
    });
  },
  remove: function (request) {
    return Game.objects.remove(request.pg.client, {
      idOrSlug: request.params.idOrSlug
    });
  },
  update: function () {
  }
};
<commit_msg>game controllers: simplify arguments and remove unused `utils`<commit_after>var Promise = require('es6-promise').Promise;

var Game = require('../models/game');

module.exports = {
  all: function (request) {
    return Game.objects.all(request.pg.client,
      request.params);
  },
  create: function (request) {
    return Game.objects.create(request.pg.client,
      request.payload);
  },
  get: function (request) {
    return Game.objects.get(request.pg.client,
      request.params);
  },
  remove: function (request) {
    return Game.objects.remove(request.pg.client,
      request.params);
  },
  update: function () {
  }
};
<|endoftext|>


<commit_before>;(function(undefined) {
  'use strict';

  /**
   * artoo save methods
   * ===================
   *
   * Some helpers to save data to a file that will be downloaded by the
   * browser. Works mainly with chrome for the time being.
   *
   */
  var _root = this,
      helpers = artoo.helpers;

  // Polyfills
  var URL = _root.URL || _root.webkitURL || _root;

  // Utilities
  function selectorOuterHTML($sel) {
    return ($sel[0].documentElement && $sel[0].documentElement.outerHTML) ||
           $sel[0].outerHTML;
  }

  // Main abstraction
  function Saver() {
    var _saver;

    // Properties
    this.defaultFilename = 'artoo_data';
    this.defaultEncoding = 'utf-8';
    this.forceDownloadMimeType = 'application/octet-stream';
    this.defaultMimeType = 'text/plain';
    this.xmlns = 'http://www.w3.org/1999/xhtml';
    this.mimeShortcuts = {
      csv: 'text/csv',
      tsv: 'text/tab-separated-values',
      json: 'application/json',
      txt: 'text/plain',
      html: 'text/html',
      yaml: 'text/yaml'
    };

    // Methods
    this.createBlob = function(data, mime, encoding) {
      mime = this.mimeShortcuts[mime] || mime || this.defaultMime;
      return new Blob(
        [data],
        {type: mime + ';charset=' + encoding || this.defaultEncoding}
      );
    };

    this.createBlobFromDataURL = function(url) {
      var byteString = atob(url.split(',')[1]),
          ba = new Uint8Array(byteString.length),
          i,
          l;

      for (i = 0, l = byteString.length; i < l; i++)
        ba[i] = byteString.charCodeAt(i);

      return new Blob([ba.buffer], {
        type: url.split(',')[0].split(':')[1].split(';')[0]
      });
    };

    this.blobURL = function(blob) {
      var oURL = URL.createObjectURL(blob);
      return oURL;
    };

    this.saveResource = function(href, params) {
      var a = document.createElementNS(this.xmlns, 'a');
      a.href = href;

      a.setAttribute('download', params.filename || '');

      artoo.$(a).simulate('click');
      a = null;
    };

    // Main interface
    this.saveData = function(data, params) {
      params = params || {};

      // Creating the blob
      var blob = this.createBlob(data, params.mime, params.encoding);

      // Saving the blob
      this.saveResource(
        this.blobURL(blob),
        {filename: params.filename || this.defaultFilename}
      );
    };

    this.saveDataURL = function(url, params) {
      params = params || {};

      // Creating the blob
      var blob = this.createBlobFromDataURL(url);

      // Saving the blob
      this.saveResource(
        blob,
        {filename: params.filename || this.defaultFilename}
      );
    };
  }

  var _saver = new Saver();

  // Exporting
  artoo.save = function(data, params) {
    _saver.saveData(data, params);
  };

  artoo.saveJson = function(data, params) {
    params = params || {};

    // Enforcing json
    if (typeof data !== 'string') {
      if (params.pretty || params.indent)
        data = JSON.stringify(data, undefined, params.indent || 2);
      else
        data = JSON.stringify(data);
    }
    else {
      if (params.pretty || params.indent)
        data = JSON.stringify(JSON.parse(data), undefined, params.indent || 2);
    }

    // Extending params
    artoo.save(
      data,
      helpers.extend(params, {filename: 'data.json', mime: 'json'})
    );
  };

  artoo.savePrettyJson = function(data, params) {
    artoo.saveJson(data, helpers.extend(params, {pretty: true}));
  };

  artoo.saveYaml = function(data, params) {
    params = params || {};
    artoo.save(
      helpers.toYAMLString(data),
      helpers.extend(params, {filename: 'data.yml', mime: 'yaml'})
    );
  };

  artoo.saveCsv = function(data, params) {
    params = params || {};

    data = (typeof data !== 'string') ?
      helpers.toCSVString(data, params.delimiter, params.escape) :
      data;

    artoo.save(
      data,
      helpers.extend(params, {mime: 'csv', filename: 'data.csv'})
    );
  };

  artoo.saveTsv = function(data, params) {
    artoo.saveCsv(
      data,
      helpers.extend(params, {
        mime: 'tsv',
        delimiter: '\t',
        filename: 'data.tsv'
      })
    );
  };

  artoo.saveXml = function(data, params) {
    var s = (helpers.isSelector(data) && selectorOuterHTML(data)) ||
            (helpers.isDocument(data) && data.documentElement.outerHTML) ||
            data;

    artoo.save(
      s,
      helpers.extend(params, {mime: 'html', filename: 'document.xml'})
    );
  };

  artoo.saveHtml = function(data, params) {
    artoo.saveXml(
      data,
      helpers.extend(params || {}, {filename: 'document.html', type: 'html'})
    );
  };

  artoo.savePageHtml = function(params) {
    artoo.saveHtml(
      document,
      helpers.extend(params || {}, {filename: 'page.html'})
    );
  };

  artoo.saveStore = function(params) {
    params = params || {};
    artoo.savePrettyJson(
      artoo.store.get(params.key),
      helpers.extend(params, {filename: 'store.json'})
    );
  };

  artoo.saveInstructions = function(params) {
    artoo.save(
      artoo.instructions.getScript(),
      helpers.extend(params, {
        mime: 'text/javascript',
        filename: 'artoo_script.js'
      })
    );
  };

  artoo.saveResource = function(url, params) {
    _saver.saveResource(url, params || {});
  };

  artoo.saveImage = function(sel, params) {
    params = params || {};

    var $sel = artoo.$(sel);

    if (!$sel.is('img') && !$sel.attr('src'))
      throw Error('artoo.saveImage: selector is not an image.');

    var ext = helpers.getExtension($sel.attr('src')),
        alt = $sel.attr('alt');

    artoo.saveResource(
      $sel.attr('src'),
      helpers.extend(
        params,
        {
          filename: alt ? alt + (ext ? '.' + ext : '') : false
        }
      )
    );
  };
}).call(this);
<commit_msg>Fix #107 - save polymorphism for filename<commit_after>;(function(undefined) {
  'use strict';

  /**
   * artoo save methods
   * ===================
   *
   * Some helpers to save data to a file that will be downloaded by the
   * browser. Works mainly with chrome for the time being.
   *
   */
  var _root = this,
      helpers = artoo.helpers;

  // Polyfills
  var URL = _root.URL || _root.webkitURL || _root;

  // Utilities
  function selectorOuterHTML($sel) {
    return ($sel[0].documentElement && $sel[0].documentElement.outerHTML) ||
           $sel[0].outerHTML;
  }

  function filenamePolymorphism(params) {
    return (typeof params === 'string') ? {filename: params} : params || {};
  }

  // Main abstraction
  function Saver() {
    var _saver;

    // Properties
    this.defaultFilename = 'artoo_data';
    this.defaultEncoding = 'utf-8';
    this.forceDownloadMimeType = 'application/octet-stream';
    this.defaultMimeType = 'text/plain';
    this.xmlns = 'http://www.w3.org/1999/xhtml';
    this.mimeShortcuts = {
      csv: 'text/csv',
      tsv: 'text/tab-separated-values',
      json: 'application/json',
      txt: 'text/plain',
      html: 'text/html',
      yaml: 'text/yaml'
    };

    // Methods
    this.createBlob = function(data, mime, encoding) {
      mime = this.mimeShortcuts[mime] || mime || this.defaultMime;
      return new Blob(
        [data],
        {type: mime + ';charset=' + encoding || this.defaultEncoding}
      );
    };

    this.createBlobFromDataURL = function(url) {
      var byteString = atob(url.split(',')[1]),
          ba = new Uint8Array(byteString.length),
          i,
          l;

      for (i = 0, l = byteString.length; i < l; i++)
        ba[i] = byteString.charCodeAt(i);

      return new Blob([ba.buffer], {
        type: url.split(',')[0].split(':')[1].split(';')[0]
      });
    };

    this.blobURL = function(blob) {
      var oURL = URL.createObjectURL(blob);
      return oURL;
    };

    this.saveResource = function(href, params) {
      var a = document.createElementNS(this.xmlns, 'a');
      a.href = href;

      a.setAttribute('download', params.filename || '');

      artoo.$(a).simulate('click');
      a = null;
    };

    // Main interface
    this.saveData = function(data, params) {
      params = params || {};

      // Creating the blob
      var blob = this.createBlob(data, params.mime, params.encoding);

      // Saving the blob
      this.saveResource(
        this.blobURL(blob),
        {filename: params.filename || this.defaultFilename}
      );
    };

    this.saveDataURL = function(url, params) {
      params = params || {};

      // Creating the blob
      var blob = this.createBlobFromDataURL(url);

      // Saving the blob
      this.saveResource(
        blob,
        {filename: params.filename || this.defaultFilename}
      );
    };
  }

  var _saver = new Saver();

  // Exporting
  artoo.save = function(data, params) {
    _saver.saveData(data, filenamePolymorphism(params));
  };

  artoo.saveJson = function(data, params) {
    params = filenamePolymorphism(params);

    // Enforcing json
    if (typeof data !== 'string') {
      if (params.pretty || params.indent)
        data = JSON.stringify(data, undefined, params.indent || 2);
      else
        data = JSON.stringify(data);
    }
    else {
      if (params.pretty || params.indent)
        data = JSON.stringify(JSON.parse(data), undefined, params.indent || 2);
    }

    // Extending params
    artoo.save(
      data,
      helpers.extend(params, {filename: 'data.json', mime: 'json'})
    );
  };

  artoo.savePrettyJson = function(data, params) {
    params = filenamePolymorphism(params);
    artoo.saveJson(data, helpers.extend(params, {pretty: true}));
  };

  artoo.saveYaml = function(data, params) {
    params = filenamePolymorphism(params);
    artoo.save(
      helpers.toYAMLString(data),
      helpers.extend(params, {filename: 'data.yml', mime: 'yaml'})
    );
  };

  artoo.saveCsv = function(data, params) {
    params = filenamePolymorphism(params);

    data = (typeof data !== 'string') ?
      helpers.toCSVString(data, params.delimiter, params.escape) :
      data;

    artoo.save(
      data,
      helpers.extend(params, {mime: 'csv', filename: 'data.csv'})
    );
  };

  artoo.saveTsv = function(data, params) {
    artoo.saveCsv(
      data,
      helpers.extend(filenamePolymorphism(params), {
        mime: 'tsv',
        delimiter: '\t',
        filename: 'data.tsv'
      })
    );
  };

  artoo.saveXml = function(data, params) {
    var s = (helpers.isSelector(data) && selectorOuterHTML(data)) ||
            (helpers.isDocument(data) && data.documentElement.outerHTML) ||
            data;

    artoo.save(
      s,
      helpers.extend(
        filenamePolymorphism(params),
        {mime: 'html', filename: 'document.xml'})
    );
  };

  artoo.saveHtml = function(data, params) {
    artoo.saveXml(
      data,
      helpers.extend(
        filenamePolymorphism(params),
        {filename: 'document.html', type: 'html'}
      )
    );
  };

  artoo.savePageHtml = function(params) {
    artoo.saveHtml(
      document,
      helpers.extend(filenamePolymorphism(params), {filename: 'page.html'})
    );
  };

  artoo.saveStore = function(params) {
    params = filenamePolymorphism(params);
    artoo.savePrettyJson(
      artoo.store.get(params.key),
      helpers.extend(params, {filename: 'store.json'})
    );
  };

  artoo.saveInstructions = function(params) {
    artoo.save(
      artoo.instructions.getScript(),
      helpers.extend(filenamePolymorphism(params), {
        mime: 'text/javascript',
        filename: 'artoo_script.js'
      })
    );
  };

  artoo.saveResource = function(url, params) {
    _saver.saveResource(url, filenamePolymorphism(params));
  };

  artoo.saveImage = function(sel, params) {
    params = filenamePolymorphism(params);

    var $sel = artoo.$(sel);

    if (!$sel.is('img') && !$sel.attr('src'))
      throw Error('artoo.saveImage: selector is not an image.');

    var ext = helpers.getExtension($sel.attr('src')),
        alt = $sel.attr('alt');

    artoo.saveResource(
      $sel.attr('src'),
      helpers.extend(
        params,
        {
          filename: alt ? alt + (ext ? '.' + ext : '') : false
        }
      )
    );
  };
}).call(this);
<|endoftext|>


<commit_before>var gameState = {
    votedScore: null,
    objectiveScore: null,
    currentDance: null,
    currentDancer: null,
    currentDanceIndex: 0,
    isKeyDown: 0,
    maxScore: 20,
    minScore: 0,
    scoreArrow: null,
    voteBar: null,
    voteMoveWidth: null,
    dancer: null,
    judge2: null,
    judge3: null,
    judge1: null,
    russianJudge: null,
    emote1: null,
    emote2: null,
    emote3: null
};

var rightKey;
var leftKey;
var music;

var dancing = function(game) {
    return {
        preload: function() {

              game.stage.backgroundColor = "#aaaaaa";

        },

        create: function() {
            music = game.add.audio('polka');
            music.play();

            drawBackground();
            drawJudges();
            gameState.dancer = constructDancer();

            //draw the score bar
            gameState.voteBar = game.add.sprite(200, 500, 'voteScoreBar');
            gameState.voteBar.scale.setTo(0.5, 0.75);
            gameState.scoreArrow = game.add.sprite(200, 505, 'meterArrow');
            gameState.scoreArrow.scale.setTo(0.25, 0.36);

            gameState.votedScore = (gameState.maxScore / 2);
            gameState.voteMoveWidth = gameState.voteBar.width / gameState.maxScore;

            repositionScoreBar();

            rightKey = game.input.keyboard.addKey(Phaser.Keyboard.RIGHT);
            rightKey.onDown.add(function() {
                if (gameState.votedScore < gameState.maxScore) {
                    gameState.votedScore++;
                    repositionScoreBar();
                }

            });
            leftKey = game.input.keyboard.addKey(Phaser.Keyboard.LEFT);
            leftKey.onDown.add(function() {
                if (gameState.votedScore > gameState.minScore) {
                    gameState.votedScore--;
                    repositionScoreBar();
                }
            });
            gameState.currentDance = createDance();
            gameState.currentDanceIndex = 0;
            var style = {
                font: "32px Arial",
                fill: "#ff0044",
                wordWrap: false,
                align: "center",
            };
            this.danceLabel = game.add.text(10, 460, "Dancing!", style);
            gameState.emote1 = game.add.sprite(gameState.judge2.centerX - 5, 0, 'neutralEmote');
            //gameState.emote1 = game.add.text(gameState.judge2.centerX - 5, 30, "", style);
            //gameState.emote1.anchor.setTo(0.5, 0.5);
            gameState.emote2 = game.add.text(gameState.judge3.centerX - 5, 30, "", style);
            //gameState.emote2.anchor.setTo(0.5, 0.5);
            gameState.emote3 = game.add.text(gameState.judge1.centerX - 5, 30, "", style);
            //gameState.emote3.anchor.setTo(0.5, 0.5);
            game.time.events.loop(Phaser.Timer.SECOND * 3, function() {
              emote();
                gameState.currentDanceIndex++;
                if (gameState.currentDanceIndex > gameState.currentDance.length - 1) {
                    gameState.emote1.kill();
                    gameState.emote2.kill();
                    gameState.emote3.kill();
                    game.state.start("judge_Result", 0);
                }
                //gameState.currentDancer.x = gameState.currentDancer.x + (800/5) - (gameState.currentDancer.width / 2);
                //gameState.emote1.text = "";
                game.add.tween(gameState.currentDancer).to({
                    x: ('+160')
                }, 1000, pickRandomTween(), true);

            }, this);
            scoreDance();
        },

        update: function() {
            this.danceLabel.text = gameState.currentDance[gameState.currentDanceIndex].name;

            gameState.currentDance.text = gameState.currentDance.name;
            pose();
        },

    };
};

function emote(){
  if (gameState.currentDanceIndex <= gameState.currentDance.length - 1) {
    gameState.emote1.kill();
    gameState.emote2.kill();
    gameState.emote3.kill();

    switch(gameState.currentDance[gameState.currentDanceIndex].score()) {
      case 3:
        gameState.emote1 = drawEmote('happyEmote', gameState.judge1.centerX - 5);
        gameState.emote2 = drawEmote('happyEmote', gameState.judge2.centerX - 5);
        gameState.emote3 = drawEmote('happyEmote', gameState.judge3.centerX - 5);
        break;
      case 2:
      gameState.emote1 = drawEmote('happyEmote', gameState.judge1.centerX - 5);
      gameState.emote2 = drawEmote('happyEmote', gameState.judge2.centerX - 5);
      gameState.emote3 = drawEmote('neutralEmote', gameState.judge3.centerX - 5);
      break;
      case 1:
      gameState.emote1 = drawEmote('happyEmote', gameState.judge1.centerX - 5);
      gameState.emote2 = drawEmote('neutralEmote', gameState.judge2.centerX - 5);
      gameState.emote3 = drawEmote('neutralEmote', gameState.judge3.centerX - 5);
      break;
      case 0:
      gameState.emote1 = drawEmote('neutralEmote', gameState.judge1.centerX - 5);
      gameState.emote2 = drawEmote('neutralEmote', gameState.judge2.centerX - 5);
      gameState.emote3 = drawEmote('neutralEmote', gameState.judge3.centerX - 5);
        break;
      case -1:
      gameState.emote1 = drawEmote('madEmote', gameState.judge1.centerX - 5);
      gameState.emote2 = drawEmote('neutralEmote', gameState.judge2.centerX - 5);
      gameState.emote3 = drawEmote('neutralEmote', gameState.judge3.centerX - 5);
        break;
      case -2:
      gameState.emote1 = drawEmote('madEmote', gameState.judge1.centerX - 5);
      gameState.emote2 = drawEmote('neutralEmote', gameState.judge2.centerX - 5);
      gameState.emote3 = drawEmote('madEmote', gameState.judge3.centerX - 5);
        break;
      case -3:
      gameState.emote1 = drawEmote('madEmote', gameState.judge1.centerX - 5);
      gameState.emote2 = drawEmote('madEmote', gameState.judge2.centerX - 5);
      gameState.emote3 = drawEmote('madEmote', gameState.judge3.centerX - 5);
        break;
}

}
}

function drawEmote(emoteToDraw, xPosition){
    newEmote = game.add.sprite(xPosition, 0, emoteToDraw);
    //newEmote.scale.setTo(64, 64);
    return newEmote;
}
function pickRandomTween() {
    var easingFunctions = [Phaser.Easing.Exponential.Out, Phaser.Easing.Exponential.In, Phaser.Easing.Cubic.Out, Phaser.Easing.Cubic.In, Phaser.Easing.Circular.Out, Phaser.Easing.Quartic.Out];
    var i = (Math.random() * 100) % easingFunctions.length;
    return easingFunctions[i];
}

function pose() {
    var currentDance = gameState.currentDance[gameState.currentDanceIndex];
    if (!gameState.dancer || !currentDance) {
        return;
    }
    var tweenSpeed = 0.1;
    gameState.dancer.leftArm.angle += (currentDance.pose.leftArm - gameState.dancer.leftArm.angle) * tweenSpeed;
    gameState.dancer.leftHand.angle = 180 + gameState.dancer.leftArm.angle;
    gameState.dancer.rightArm.angle += (currentDance.pose.rightArm - gameState.dancer.rightArm.angle) * tweenSpeed;
    gameState.dancer.rightHand.angle = 180 + gameState.dancer.rightArm.angle;
    gameState.dancer.leftLeg.angle += (currentDance.pose.leftLeg - gameState.dancer.leftLeg.angle) * tweenSpeed;
    gameState.dancer.leftFoot.angle = gameState.dancer.leftLeg.angle;
    gameState.dancer.rightLeg.angle += (currentDance.pose.rightLeg - gameState.dancer.rightLeg.angle) * tweenSpeed;
    gameState.dancer.rightFoot.angle = gameState.dancer.rightLeg.angle;

}

function constructDancer() {
    var dancer = {};
    gameState.currentDancer = game.add.group();
    dancer.wholeBody = gameState.currentDancer;
    dancer.torso = makeBodyPart('dancer-torso', 0, 0, gameState.currentDancer);
    dancer.head = makeBodyPart('dancer-head', 0, -80, gameState.currentDancer);
    dancer.leftArm = makeBodyPart('dancer-leftArm', -25, -50, gameState.currentDancer);
    dancer.leftArm.anchor.setTo(0.5, 0);
    dancer.rightArm = makeBodyPart('dancer-rightArm', 25, -50, gameState.currentDancer);
    dancer.rightArm.anchor.setTo(0.5, 0);

    dancer.leftHand = makeBodyPart('dancer-leftHand', -30, -45, gameState.currentDancer);
    dancer.leftHand.anchor.setTo(0.5, 0.5);
    dancer.leftHand.angle = 180;
    dancer.leftHand.pivot.y = dancer.leftArm.height;
    dancer.rightHand = makeBodyPart('dancer-rightHand', 30, -45, gameState.currentDancer);
    dancer.rightHand.anchor.setTo(0.5, 0.5);
    dancer.rightHand.angle = 180;
    dancer.rightHand.pivot.y = dancer.rightArm.height;

    dancer.leftLeg = makeBodyPart('dancer-leftLeg', -20, 35, gameState.currentDancer);
    dancer.leftLeg.anchor.setTo(0.5, 0);
    dancer.rightLeg = makeBodyPart('dancer-rightLeg', 20, 35, gameState.currentDancer);
    dancer.rightLeg.anchor.setTo(0.5, 0);

    dancer.leftFoot = makeBodyPart('dancer-leftFoot', -25, 135 - dancer.leftLeg.height, gameState.currentDancer);
    dancer.leftFoot.anchor.setTo(0.5, 0.5);
    dancer.leftFoot.pivot.y = -dancer.leftLeg.height;
    dancer.rightFoot = makeBodyPart('dancer-rightFoot', 25, 135 - dancer.leftLeg.height, gameState.currentDancer);
    dancer.rightFoot.anchor.setTo(0.5, 0.5);
    dancer.rightFoot.pivot.y = -dancer.rightLeg.height;

    return dancer;
}

function makeBodyPart(spriteName, offsetX, offsetY, group) {
    var sprite = game.add.sprite(-45 + offsetX, 200 + offsetY, spriteName);
    sprite.anchor.setTo(0.5, 0.5);
    group.add(sprite);
    return sprite;
}

function drawBackground() {
    audience = game.add.sprite(0, 0, "audience");
    sprite = game.add.tileSprite(0, 200, 800, 300, 'floor');
}

function drawJudges() {
    tmpXJudgePadder = 30;
    tmpXJudgePosition = 0;
    gameState.judge2 = game.add.sprite(tmpXJudgePosition, 0, 'judge2');
    tmpXJudgePosition = tmpXJudgePosition + gameState.judge2.width + tmpXJudgePadder;
    gameState.judge3 = game.add.sprite(tmpXJudgePosition, 0, 'judge3');
    tmpXJudgePosition = tmpXJudgePosition + gameState.judge3.width + tmpXJudgePadder;
    gameState.judge1 = game.add.sprite(tmpXJudgePosition, 0, 'judge1');
    tmpXJudgePosition = tmpXJudgePosition + gameState.judge1.width + tmpXJudgePadder * 2;
    gameState.russianJudge = game.add.sprite(tmpXJudgePosition, 0, 'russianJudge');

}

function repositionScoreBar() {
    //console.log("Current votedScore: ", gameState.votedScore);
    gameState.scoreArrow.x = (gameState.voteMoveWidth * (gameState.votedScore)) - (gameState.scoreArrow.width / 2) + (gameState.voteBar.x);
}

function scoreDance() {
    gameState.objectiveScore = 0;
    for (var i in gameState.currentDance) {
        gameState.objectiveScore = gameState.objectiveScore + gameState.currentDance[i].score();
    }
}

game.state.add('dancing', dancing);
<commit_msg>Resized and repositioned judge emotes<commit_after>var gameState = {
    votedScore: null,
    objectiveScore: null,
    currentDance: null,
    currentDancer: null,
    currentDanceIndex: 0,
    isKeyDown: 0,
    maxScore: 20,
    minScore: 0,
    scoreArrow: null,
    voteBar: null,
    voteMoveWidth: null,
    dancer: null,
    judge2: null,
    judge3: null,
    judge1: null,
    russianJudge: null,
    emote1: null,
    emote2: null,
    emote3: null
};

var rightKey;
var leftKey;
var music;

var dancing = function(game) {
    return {
        preload: function() {

              game.stage.backgroundColor = "#aaaaaa";

        },

        create: function() {
            music = game.add.audio('polka');
            music.play();

            drawBackground();
            drawJudges();
            gameState.dancer = constructDancer();

            //draw the score bar
            gameState.voteBar = game.add.sprite(200, 500, 'voteScoreBar');
            gameState.voteBar.scale.setTo(0.5, 0.75);
            gameState.scoreArrow = game.add.sprite(200, 505, 'meterArrow');
            gameState.scoreArrow.scale.setTo(0.25, 0.36);

            gameState.votedScore = (gameState.maxScore / 2);
            gameState.voteMoveWidth = gameState.voteBar.width / gameState.maxScore;

            repositionScoreBar();

            rightKey = game.input.keyboard.addKey(Phaser.Keyboard.RIGHT);
            rightKey.onDown.add(function() {
                if (gameState.votedScore < gameState.maxScore) {
                    gameState.votedScore++;
                    repositionScoreBar();
                }

            });
            leftKey = game.input.keyboard.addKey(Phaser.Keyboard.LEFT);
            leftKey.onDown.add(function() {
                if (gameState.votedScore > gameState.minScore) {
                    gameState.votedScore--;
                    repositionScoreBar();
                }
            });
            gameState.currentDance = createDance();
            gameState.currentDanceIndex = 0;
            var style = {
                font: "32px Arial",
                fill: "#ff0044",
                wordWrap: false,
                align: "center",
            };
            this.danceLabel = game.add.text(10, 460, "Dancing!", style);
            game.time.events.loop(Phaser.Timer.SECOND * 3, function() {
              emote();
                gameState.currentDanceIndex++;
                if (gameState.currentDanceIndex > gameState.currentDance.length - 1) {
                  if (!!gameState.emote1){
                    gameState.emote1.kill();
                    gameState.emote2.kill();
                    gameState.emote3.kill();
                  }
                    game.state.start("judge_Result", 0);
                }
                //gameState.currentDancer.x = gameState.currentDancer.x + (800/5) - (gameState.currentDancer.width / 2);
                //gameState.emote1.text = "";
                game.add.tween(gameState.currentDancer).to({
                    x: ('+160')
                }, 1000, pickRandomTween(), true);

            }, this);
            scoreDance();
        },

        update: function() {
            this.danceLabel.text = gameState.currentDance[gameState.currentDanceIndex].name;

            gameState.currentDance.text = gameState.currentDance.name;
            pose();
        },

    };
};

function emote(){
  if (gameState.currentDanceIndex <= gameState.currentDance.length - 1) {
    if (!!gameState.emote1){
      gameState.emote1.kill();
      gameState.emote2.kill();
      gameState.emote3.kill();
    }
    var emoteOffset = 45;

    switch(gameState.currentDance[gameState.currentDanceIndex].score()) {
      case 3:
        gameState.emote1 = drawEmote('happyEmote', gameState.judge1.centerX - emoteOffset);
        gameState.emote2 = drawEmote('happyEmote', gameState.judge2.centerX - emoteOffset);
        gameState.emote3 = drawEmote('happyEmote', gameState.judge3.centerX - emoteOffset);
        break;
      case 2:
      gameState.emote1 = drawEmote('happyEmote', gameState.judge1.centerX - emoteOffset);
      gameState.emote2 = drawEmote('happyEmote', gameState.judge2.centerX - emoteOffset);
      gameState.emote3 = drawEmote('neutralEmote', gameState.judge3.centerX - emoteOffset);
      break;
      case 1:
      gameState.emote1 = drawEmote('happyEmote', gameState.judge1.centerX - emoteOffset);
      gameState.emote2 = drawEmote('neutralEmote', gameState.judge2.centerX - emoteOffset);
      gameState.emote3 = drawEmote('neutralEmote', gameState.judge3.centerX - emoteOffset);
      break;
      case 0:
      gameState.emote1 = drawEmote('neutralEmote', gameState.judge1.centerX - emoteOffset);
      gameState.emote2 = drawEmote('neutralEmote', gameState.judge2.centerX - emoteOffset);
      gameState.emote3 = drawEmote('neutralEmote', gameState.judge3.centerX - emoteOffset);
        break;
      case -1:
      gameState.emote1 = drawEmote('madEmote', gameState.judge1.centerX - emoteOffset);
      gameState.emote2 = drawEmote('neutralEmote', gameState.judge2.centerX - emoteOffset);
      gameState.emote3 = drawEmote('neutralEmote', gameState.judge3.centerX - emoteOffset);
        break;
      case -2:
      gameState.emote1 = drawEmote('madEmote', gameState.judge1.centerX - emoteOffset);
      gameState.emote2 = drawEmote('neutralEmote', gameState.judge2.centerX - emoteOffset);
      gameState.emote3 = drawEmote('madEmote', gameState.judge3.centerX - emoteOffset);
        break;
      case -3:
      gameState.emote1 = drawEmote('madEmote', gameState.judge1.centerX - emoteOffset);
      gameState.emote2 = drawEmote('madEmote', gameState.judge2.centerX - emoteOffset);
      gameState.emote3 = drawEmote('madEmote', gameState.judge3.centerX - emoteOffset);
        break;
}

}
}

function drawEmote(emoteToDraw, xPosition){
    newEmote = game.add.sprite(xPosition, 0, emoteToDraw);
    newEmote.scale.setTo(0.5, 0.5);
    return newEmote;
}
function pickRandomTween() {
    var easingFunctions = [Phaser.Easing.Exponential.Out, Phaser.Easing.Exponential.In, Phaser.Easing.Cubic.Out, Phaser.Easing.Cubic.In, Phaser.Easing.Circular.Out, Phaser.Easing.Quartic.Out];
    var i = (Math.random() * 100) % easingFunctions.length;
    return easingFunctions[i];
}

function pose() {
    var currentDance = gameState.currentDance[gameState.currentDanceIndex];
    if (!gameState.dancer || !currentDance) {
        return;
    }
    var tweenSpeed = 0.1;
    gameState.dancer.leftArm.angle += (currentDance.pose.leftArm - gameState.dancer.leftArm.angle) * tweenSpeed;
    gameState.dancer.leftHand.angle = 180 + gameState.dancer.leftArm.angle;
    gameState.dancer.rightArm.angle += (currentDance.pose.rightArm - gameState.dancer.rightArm.angle) * tweenSpeed;
    gameState.dancer.rightHand.angle = 180 + gameState.dancer.rightArm.angle;
    gameState.dancer.leftLeg.angle += (currentDance.pose.leftLeg - gameState.dancer.leftLeg.angle) * tweenSpeed;
    gameState.dancer.leftFoot.angle = gameState.dancer.leftLeg.angle;
    gameState.dancer.rightLeg.angle += (currentDance.pose.rightLeg - gameState.dancer.rightLeg.angle) * tweenSpeed;
    gameState.dancer.rightFoot.angle = gameState.dancer.rightLeg.angle;

}

function constructDancer() {
    var dancer = {};
    gameState.currentDancer = game.add.group();
    dancer.wholeBody = gameState.currentDancer;
    dancer.torso = makeBodyPart('dancer-torso', 0, 0, gameState.currentDancer);
    dancer.head = makeBodyPart('dancer-head', 0, -80, gameState.currentDancer);
    dancer.leftArm = makeBodyPart('dancer-leftArm', -25, -50, gameState.currentDancer);
    dancer.leftArm.anchor.setTo(0.5, 0);
    dancer.rightArm = makeBodyPart('dancer-rightArm', 25, -50, gameState.currentDancer);
    dancer.rightArm.anchor.setTo(0.5, 0);

    dancer.leftHand = makeBodyPart('dancer-leftHand', -30, -45, gameState.currentDancer);
    dancer.leftHand.anchor.setTo(0.5, 0.5);
    dancer.leftHand.angle = 180;
    dancer.leftHand.pivot.y = dancer.leftArm.height;
    dancer.rightHand = makeBodyPart('dancer-rightHand', 30, -45, gameState.currentDancer);
    dancer.rightHand.anchor.setTo(0.5, 0.5);
    dancer.rightHand.angle = 180;
    dancer.rightHand.pivot.y = dancer.rightArm.height;

    dancer.leftLeg = makeBodyPart('dancer-leftLeg', -20, 35, gameState.currentDancer);
    dancer.leftLeg.anchor.setTo(0.5, 0);
    dancer.rightLeg = makeBodyPart('dancer-rightLeg', 20, 35, gameState.currentDancer);
    dancer.rightLeg.anchor.setTo(0.5, 0);

    dancer.leftFoot = makeBodyPart('dancer-leftFoot', -25, 135 - dancer.leftLeg.height, gameState.currentDancer);
    dancer.leftFoot.anchor.setTo(0.5, 0.5);
    dancer.leftFoot.pivot.y = -dancer.leftLeg.height;
    dancer.rightFoot = makeBodyPart('dancer-rightFoot', 25, 135 - dancer.leftLeg.height, gameState.currentDancer);
    dancer.rightFoot.anchor.setTo(0.5, 0.5);
    dancer.rightFoot.pivot.y = -dancer.rightLeg.height;

    return dancer;
}

function makeBodyPart(spriteName, offsetX, offsetY, group) {
    var sprite = game.add.sprite(-45 + offsetX, 200 + offsetY, spriteName);
    sprite.anchor.setTo(0.5, 0.5);
    group.add(sprite);
    return sprite;
}

function drawBackground() {
    audience = game.add.sprite(0, 0, "audience");
    sprite = game.add.tileSprite(0, 200, 800, 300, 'floor');
}

function drawJudges() {
    tmpXJudgePadder = 30;
    tmpXJudgePosition = 0;
    gameState.judge2 = game.add.sprite(tmpXJudgePosition, 0, 'judge2');
    tmpXJudgePosition = tmpXJudgePosition + gameState.judge2.width + tmpXJudgePadder;
    gameState.judge3 = game.add.sprite(tmpXJudgePosition, 0, 'judge3');
    tmpXJudgePosition = tmpXJudgePosition + gameState.judge3.width + tmpXJudgePadder;
    gameState.judge1 = game.add.sprite(tmpXJudgePosition, 0, 'judge1');
    tmpXJudgePosition = tmpXJudgePosition + gameState.judge1.width + tmpXJudgePadder * 2;
    gameState.russianJudge = game.add.sprite(tmpXJudgePosition, 0, 'russianJudge');

}

function repositionScoreBar() {
    //console.log("Current votedScore: ", gameState.votedScore);
    gameState.scoreArrow.x = (gameState.voteMoveWidth * (gameState.votedScore)) - (gameState.scoreArrow.width / 2) + (gameState.voteBar.x);
}

function scoreDance() {
    gameState.objectiveScore = 0;
    for (var i in gameState.currentDance) {
        gameState.objectiveScore = gameState.objectiveScore + gameState.currentDance[i].score();
    }
}

game.state.add('dancing', dancing);
<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

define(function(require, exports, module) {

// Implementation
function DomProvider(store) {
  this.store = store;
}

/**
 * This object provides data for the tree displayed in the tooltip
 * content.
 * TODO: move to FBSDK
 */
DomProvider.prototype =
/** @lends DomProvider */
{
  /**
   * Fetches properties from the backend. These properties might be
   * displayed as child objects in e.g. a tree UI widget.
   */
  getChildren: function(object) {
    var value = this.getValue(object);
    Trace.sysout("DomProvider.getChildren; for: " +
      value.actor, object);

    var grip = object;

    if (object instanceof Property) {
      grip = this.getValue(object);
    }

    if (!grip || !grip.actor) {
      Trace.sysout("DomProvider.getChildren; ERROR invalid grip!", grip);
      return;
    }

    var properties = this.store.getPrototypeAndProperties(grip);
    if (properties instanceof Promise) {
      return properties;
    }

    // Compute list of requested children.
    var children = Object.keys(properties).map(key => {
      return new Property(key, properties[key]);
    });

    function sortName(a, b) { return a.name > b.name ? 1 : -1; }
    children.sort(sortName);

    var length = children ? children.length : "";
    Trace.sysout("DomProvider.getChildren; result: " + length, {
      properties: properties,
      children: children
    });

    return children;
  },

  hasChildren: function(object) {
    if (object instanceof Property) {
      var value = this.getValue(object);
      if (!value) {
        return false;
      }

      var hasChildren = value.ownPropertyLength > 0;

      // xxxHonza: Support for Fx40 (grip.ownPropertyLength doesn't exist)
      if (value.preview) {
        hasChildren = hasChildren || value.preview.ownPropertiesLength > 0;
      }

      // xxxHonza: Support (rather a workaround) for Fx39
      // (grip.preview.ownPropertiesLength doesn't exist)
      if (value.preview) {
        var preview = value.preview;
        var kind = preview.kind;
        var objectsWithProps = ["DOMNode", "ObjectWithURL"];
        hasChildren = hasChildren || (objectsWithProps.indexOf(kind) != -1);
        hasChildren = hasChildren || (kind == "ArrayLike" && preview.length > 0);
      }

      return (value.type == "object" && hasChildren);
    }
  },

  getValue: function(object) {
    if (object instanceof Property) {
      var value = object.value;
      return (typeof value.value != "undefined") ? value.value :
        value.getterValue;
    }

    return object;
  },

  getLabel: function(object) {
    if (object instanceof Property) {
      return object.name;
    }

    return object;
  },

  // ID Provider. Used e.g. for tree persistence (list of expanded nodes).
  getId: function(object) {
  },
};

function Property(name, value) {
  this.name = name;
  this.value = value;
}

// Exports from this module
exports.DomProvider = DomProvider;
});
<commit_msg>Display enumerable props at the end (DOM panel)<commit_after>/* See license.txt for terms of usage */

define(function(require, exports, module) {

// Implementation
function DomProvider(store) {
  this.store = store;
}

/**
 * This object provides data for the tree displayed in the tooltip
 * content.
 * TODO: move to FBSDK
 */
DomProvider.prototype =
/** @lends DomProvider */
{
  /**
   * Fetches properties from the backend. These properties might be
   * displayed as child objects in e.g. a tree UI widget.
   */
  getChildren: function(object) {
    var value = this.getValue(object);
    Trace.sysout("DomProvider.getChildren; for: " +
      value.actor, object);

    var grip = object;

    if (object instanceof Property) {
      grip = this.getValue(object);
    }

    if (!grip || !grip.actor) {
      Trace.sysout("DomProvider.getChildren; ERROR invalid grip!", grip);
      return;
    }

    var properties = this.store.getPrototypeAndProperties(grip);
    if (properties instanceof Promise) {
      return properties;
    }

    // Compute list of requested children.
    var children = Object.keys(properties).map(key => {
      return new Property(key, properties[key]);
    });

    function sortName(a, b) {
      // Display non-enumerable properties at the end.
      if (!a.value.enumerable && b.value.enumerable) {
        return 1;
      }
      if (a.value.enumerable && !b.value.enumerable) {
        return -1;
      }

      return a.name > b.name ? 1 : -1;
    }
    children.sort(sortName);

    var length = children ? children.length : "";
    Trace.sysout("DomProvider.getChildren; result: " + length, {
      properties: properties,
      children: children
    });

    return children;
  },

  hasChildren: function(object) {
    if (object instanceof Property) {
      var value = this.getValue(object);
      if (!value) {
        return false;
      }

      var hasChildren = value.ownPropertyLength > 0;

      // xxxHonza: Support for Fx40 (grip.ownPropertyLength doesn't exist)
      if (value.preview) {
        hasChildren = hasChildren || value.preview.ownPropertiesLength > 0;
      }

      // xxxHonza: Support (rather a workaround) for Fx39
      // (grip.preview.ownPropertiesLength doesn't exist)
      if (value.preview) {
        var preview = value.preview;
        var kind = preview.kind;
        var objectsWithProps = ["DOMNode", "ObjectWithURL"];
        hasChildren = hasChildren || (objectsWithProps.indexOf(kind) != -1);
        hasChildren = hasChildren || (kind == "ArrayLike" && preview.length > 0);
      }

      return (value.type == "object" && hasChildren);
    }
  },

  getValue: function(object) {
    if (object instanceof Property) {
      var value = object.value;
      return (typeof value.value != "undefined") ? value.value :
        value.getterValue;
    }

    return object;
  },

  getLabel: function(object) {
    if (object instanceof Property) {
      return object.name;
    }

    return object;
  },

  // ID Provider. Used e.g. for tree persistence (list of expanded nodes).
  getId: function(object) {
  },
};

function Property(name, value) {
  this.name = name;
  this.value = value;
}

// Exports from this module
exports.DomProvider = DomProvider;
});
<|endoftext|>


<commit_before>"use strict";

var setup = require("../../common/setup-base"),
    desired = require('./desired'),
    unorm = require('unorm');

describe('testapp - accented characters @skip-ios-all', function () {
  var driver;
  setup(this, desired).then(function (d) { driver = d; });

  it('should send accented text', function (done) {
    var testText = unorm.nfd("é Œ ù ḍ");
    driver
      .elementsByTagName('textField').at(1)
        .sendKeys(testText)
        .text()
        .should.become(testText)
      .nodeify(done);
  });

  it('should send delete key', function (done) {
    driver
      .elementsByTagName('textField').at(1)
        .sendKeys("abc")
        .sendKeys('\uE003')
        .text()
        .should.become("")
      .nodeify(done);
  });
});
<commit_msg>don't quarantine working tests<commit_after>"use strict";

var setup = require("../../common/setup-base"),
    desired = require('./desired'),
    unorm = require('unorm');

describe('testapp - accented characters', function () {
  var driver;
  setup(this, desired).then(function (d) { driver = d; });

  it('should send accented text', function (done) {
    var testText = unorm.nfd("é Œ ù ḍ");
    driver
      .elementsByTagName('textField').at(1)
        .sendKeys(testText)
        .text()
        .should.become(testText)
      .nodeify(done);
  });

  it('should send delete key', function (done) {
    driver
      .elementsByTagName('textField').at(1)
        .sendKeys("abc")
        .sendKeys('\uE003')
        .text()
        .should.become("")
      .nodeify(done);
  });
});
<|endoftext|>


<commit_before>const EXPORT = ["HttpWatcher"];

const HTTP_ON_MODIFY_REQUEST = "http-on-modify-request";
const HTTP_ON_EXAMINE_RESPONSE = "http-on-examine-response";

var HttpWatcher = shared.get("HttpWatcher") || {
    get taskSet HW_get_taskSet() {
        let taskSet = null;
        if (shared.has("HttpWatcherTaskSet")) {
            taskSet = shared.get("HttpWatcherTaskSet");
        } else {
            taskSet = {};
            shared.set("HttpWatcherTaskSet", taskSet);
        }
        delete this.taskSet;
        return this.taskSet = taskSet;
    },

    pushTask: function HW__pushTask(url, data) {
        //if (url in this.taskSet) return;
        this.taskSet[url] = data;
    },

    popTask: function HW__popTask(url) {
        let task = null;
        if (url in this.taskSet) {
            task = this.taskSet[url];
            delete this.taskSet[url];
        }
        return task;
    },

    onRequest: function HW_onRequest(channel) {
        let data = this._getPostData(channel);
        this.pushTask(data.url, data);
    },

    _getPostData: function HW__getPostData(channel) {
        if (!(channel instanceof Ci.nsIUploadChannel)) return;
        let rawStream = channel.uploadStream;
        if (!(rawStream instanceof Ci.nsISeekableStream)) return;
        let hasHeaders = rawStream instanceof Ci.nsIMIMEInputStream;
        let stream = Cc["@mozilla.org/scriptableinputstream;1"].
                     createInstance(Ci.nsIScriptableInputStream);
        stream.init(rawStream);
        let body = stream.read(stream.available());
        rawStream.seek(Ci.nsISeekableStream.NS_SEEK_SET, 0);
        if (hasHeaders)
            body = body.replace(/^[\s\S]*?\r\n\r\n/, "");
        return this._toMap(body);
    },

    _toMap: function HW__toMap(string) {
        let result = {};
        string.replace(/\+/g, "%20").split("&").forEach(function (pair) {
            let [key, value] = pair.split("=");
            try {
                value = decodeURIComponent(value);
            } catch (ex) {}
            result[key] = value;
        });
        return result;
    },

    onResponse: function HW_onResponse(channel) {
        let url = this._getBookmakedURL(channel);
        if (!url) return;
        let task = this.popTask(url);
        if (!task) return;
        this.performTask(task);
    },

    _getBookmakedURL: function HW__getBookmarkedURL(channel) {
        try {
            return channel.getResponseHeader("X-Bookmark-URL");
        } catch (ex) {
            return null;
        }
    },

    performTask: function HW_performTask(task) {
        // ブックマーク成功したら、sync する
        // これにより、リモートとのデータの同期がとれる
        // XXX: Sync に依存してしまう
        let listener = Sync.createListener("complete", function onSync() {
            p('Sync completed');
            listener.unlisten();
            HTTPCache.entry.cache.clear(task.url);
            if (!Model.Bookmark.findByUrl(task.url).length) {
                p(task.url + ' is not registered.  Retry sync.');
                // 同期が間に合わなかったら少し待ってもう一度だけ同期する。
                setTimeout(method(Sync, 'sync'), 2000);
            }
        }, null, 0, false);
        Sync.sync();

        let bookmark = Model.Bookmark.findByUrl(task.url)[0];
        if (bookmark) {
            // すでに存在するブックマークは Sync で
            // 同期できないので、ここで DB を更新しておく。
            if (task.title)
                bookmark.title = task.title;
            bookmark.comment = task.comment;
            bookmark.save();
            EventService.dispatch('BookmarksUpdated');
        }
    },

    startObserving: function HW_startObserving() {
        ObserverService.addObserver(this, HTTP_ON_MODIFY_REQUEST, false);
        ObserverService.addObserver(this, HTTP_ON_EXAMINE_RESPONSE, false);
        ObserverService.addObserver(this.quitObserver, "quit-application", false);
    },

    stopObserving: function HW_stopObserving() {
        p('stop HttpWatcher observing');
        ObserverService.removeObserver(this, HTTP_ON_MODIFY_REQUEST);
        ObserverService.removeObserver(this, HTTP_ON_EXAMINE_RESPONSE);
        ObserverService.removeObserver(this.quitObserver, "quit-application");
    },

    quitObserver: {
        observe: function HW_QO_observe(subject, topic, data) {
            HttpWatcher.stopObserving();
        }
    },

    observe: function HW_observe(subject, topic, data) {
        if (!(subject instanceof Ci.nsIHttpChannel) ||
            !this._isHBookmarkOperation(subject))
            return;
        switch (topic) {
        case HTTP_ON_MODIFY_REQUEST:
            this.onRequest(subject);
            break;

        case HTTP_ON_EXAMINE_RESPONSE:
            this.onResponse(subject);
            break;
        }
    },

    _isHBookmarkOperation: function HW__isHBookmarkOperation(channel) {
        let uri = channel.URI;
        return /\.hatena\.ne\.jp$/.test(uri.host) &&
               /^\/(?:bookmarklet\.edit|[\w-]+\/add\.edit)\b/.test(uri.path);
    }
};

if (!shared.has("HttpWatcher")) {
    HttpWatcher.startObserving();
    shared.set("HttpWatcher", HttpWatcher);
}
<commit_msg>HttpWatcherの実装を簡潔に。<commit_after>const EXPORT = ["HttpWatcher"];

var HttpWatcher = shared.get("HttpWatcher") || {
    // 監視するホスト
    targetHostsArray: [
        "b.hatena.ne.jp",
        //"bbeta.hatena.ne.jp",
        //"localhost",
    ],

    get targetHosts HW_get_targetHosts() {
        let hosts = this.targetHostsArray.reduce(function (hosts, host) {
            hosts[host] = true;
            return hosts;
        }, new DictionaryObject());
        delete this.targetHosts;
        return this.targetHosts = hosts;
    },

    onBookmarkEdit: function HW_onBookmarkEdit(channel) {
        let url = this._getBookmakedURL(channel);
        if (!url) return;
        let data = this._getPostData(channel);
        if (!data) return;
        this.syncBookmark(data);
    },

    _getBookmakedURL: function HW__getBookmarkedURL(channel) {
        try {
            return channel.getResponseHeader("X-Bookmark-URL");
        } catch (ex) {
            return null;
        }
    },

    syncBookmark: function HW_syncBookmark(data) {
        // ブックマーク成功したら、sync する
        // これにより、リモートとのデータの同期がとれる
        // XXX: Sync に依存してしまう
        let listener = Sync.createListener("complete", function onSync() {
            p('Sync completed');
            listener.unlisten();
            HTTPCache.entry.cache.clear(data.url);
            if (!Model.Bookmark.findByUrl(data.url).length) {
                p(data.url + ' is not registered.  Retry sync.');
                // 同期が間に合わなかったら少し待ってもう一度だけ同期する。
                setTimeout(method(Sync, 'sync'), 2000);
            }
        }, null, 0, false);
        Sync.sync();

        let bookmark = Model.Bookmark.findByUrl(data.url)[0];
        if (bookmark) {
            // すでに存在するブックマークは Sync で
            // 同期できないので、ここで DB を更新しておく。
            if (data.title)
                bookmark.title = data.title;
            bookmark.comment = data.comment;
            bookmark.save();
            EventService.dispatch('BookmarksUpdated');
        }
    },

    _getPostData: function HW__getPostData(channel) {
        let rawStream = channel.uploadStream;
        if (!(rawStream instanceof Ci.nsISeekableStream)) return null;
        rawStream.seek(Ci.nsISeekableStream.NS_SEEK_SET, 0);
        let stream = Cc["@mozilla.org/scriptableinputstream;1"].
                     createInstance(Ci.nsIScriptableInputStream);
        stream.init(rawStream);
        let body = stream.read(stream.available());
        if (rawStream instanceof Ci.nsIMIMEInputStream)
            body = body.replace(/^(?:.+\r\n)+\r\n/, "");
        return this._toMap(body);
    },

    _toMap: function HW__toMap(string) {
        let result = {};
        string.replace(/\+/g, "%20").split("&").forEach(function (pair) {
            let [key, value] = pair.split("=");
            try {
                value = decodeURIComponent(value);
            } catch (ex) {}
            result[key] = value;
        });
        return result;
    },

    EDIT_PATTERN: /^\/(?:bookmarklet\.edit|[\w-]+\/add\.edit)\b/,

    observe: function HW_observe(subject, topic, data) {
        if (!(subject instanceof Ci.nsIHttpChannel) ||
            !(subject instanceof Ci.nsIUploadChannel) ||
            !(subject.URI.host in this.targetHosts))
            return;
        let path = subject.URI.path;
        if (this.EDIT_PATTERN.test(path)) {
            this.onBookmarkEdit(subject);
        }
    },

    startObserving: function HW_startObserving() {
        ObserverService.addObserver(this, "http-on-examine-response", false);
        ObserverService.addObserver(this.quitObserver, "quit-application", false);
    },

    stopObserving: function HW_stopObserving() {
        p('stop HttpWatcher observing');
        ObserverService.removeObserver(this, "http-on-examine-response");
        ObserverService.removeObserver(this.quitObserver, "quit-application");
    },

    quitObserver: {
        observe: function HW_QO_observe(subject, topic, data) {
            HttpWatcher.stopObserving();
        }
    }
};

if (!shared.has("HttpWatcher")) {
    HttpWatcher.startObserving();
    shared.set("HttpWatcher", HttpWatcher);
}
<|endoftext|>


<commit_before>require("requirish")._(module);
var should = require("should");
var path = require("path");
var fs = require("fs");
var crypto_utils = require("lib/misc/crypto_utils");
var assert = require("assert");
var hexDump = require("../../lib/misc/utils").hexDump;

var exploreCertificate = require("../../lib/misc/crypto_explore_certificate").exploreCertificate;

describe(" exploring Certificates",function() {

    this.timeout(100000);
    it("should extract the information out of a 1024-bits certificate",function() {

        var certificate = crypto_utils.readCertificate(path.join(__dirname,"../fixtures/certs/server_cert_1024.pem"));

        //xx console.log(hexDump(certificate));
        var certificate_info = exploreCertificate(certificate);

        //xx console.log(certificate_info.tbsCertificate);
        console.log(" Version                   : ",certificate_info.tbsCertificate.version);
        console.log(" issuer.commonName         : ",certificate_info.tbsCertificate.issuer.commonName);
        console.log(" uniformResourceIdentifier : ",certificate_info.tbsCertificate.extensions.subjectAltName.uniformResourceIdentifier);
        console.log(" dNSName                   : ",certificate_info.tbsCertificate.extensions.subjectAltName.dNSName);

        //xx console.log(require("util").inspect(certificate_info,{colors:true, depth:10}));
        certificate_info.tbsCertificate.version.should.eql(2);
        certificate_info.tbsCertificate.subjectPublicKeyInfo.keyLength.should.eql(128);
        certificate_info.tbsCertificate.extensions.subjectAltName.uniformResourceIdentifier.length.should.eql(1);

    });

    it("should extract the information out of a 2048-bits certificate ",function() {

        var certificate = crypto_utils.readCertificate(path.join(__dirname,"../fixtures/certs/server_cert_2048.pem"));

        // console.log(hexDump(certificate))
        var certificate_info = exploreCertificate(certificate);

        certificate_info.tbsCertificate.version.should.eql(2);
        certificate_info.tbsCertificate.subjectPublicKeyInfo.keyLength.should.eql(256);
        certificate_info.tbsCertificate.extensions.subjectAltName.uniformResourceIdentifier.length.should.eql(1);

    });

    it("should read a certificate containing extra information",function() {

        var filename = path.join(__dirname,"../fixtures/certs/demo_certificate.pem");
        fs.existsSync(filename).should.equal(true);

        var certificate = crypto_utils.readCertificate(filename);
        console.log(certificate.toString("base64"));

        var certificate_info = exploreCertificate(certificate);
        console.log(certificate_info);
        console.log(" Version                   : ",certificate_info.tbsCertificate.version);

    });
});

describe("exploring certificate chains",function() {

    var combine_der = require("../../lib/misc/crypto_explore_certificate").combine_der;
    var split_der = require("../../lib/misc/crypto_explore_certificate").split_der;

    xit("should combine certificates in a single block",function(){

        var cert1_name = path.join(__dirname,"../fixtures/certs/client_cert_2048.pem");
        var cert2_name = path.join(__dirname,"../fixtures/certs/server_cert_1024.pem");

        var cert1 = crypto_utils.readPEM(cert1_name);
        var cert2 = crypto_utils.readPEM(cert2_name);

        var combined = combine_der([cert1,cert2]);
        combined.toString("hex").should.equal(cert1.toString("hex")+cert2.toString("hex"));

        combined.length.should.eql(cert1.length+ cert2.length);

        var chain  = split_der(combined);

        chain.length.should.eql(2);

        console.log(chain[0].toString("hex"));
        console.log(cert1.toString("hex"));
        console.log("-------")
        console.log(chain[1].toString("hex"));
        console.log(cert2.toString("hex"));

        chain[0].length.should.eql(cert1.length);
        chain[1].length.should.eql(cert2.length);

    })
});
<commit_msg>remove unwanted log<commit_after>require("requirish")._(module);
var should = require("should");
var path = require("path");
var fs = require("fs");
var crypto_utils = require("lib/misc/crypto_utils");
var assert = require("assert");
var hexDump = require("../../lib/misc/utils").hexDump;

var exploreCertificate = require("../../lib/misc/crypto_explore_certificate").exploreCertificate;

describe(" exploring Certificates",function() {

    this.timeout(100000);
    it("should extract the information out of a 1024-bits certificate",function() {

        var certificate = crypto_utils.readCertificate(path.join(__dirname,"../fixtures/certs/server_cert_1024.pem"));

        //xx console.log(hexDump(certificate));
        var certificate_info = exploreCertificate(certificate);

        //xx console.log(certificate_info.tbsCertificate);
        console.log(" Version                   : ",certificate_info.tbsCertificate.version);
        console.log(" issuer.commonName         : ",certificate_info.tbsCertificate.issuer.commonName);
        console.log(" uniformResourceIdentifier : ",certificate_info.tbsCertificate.extensions.subjectAltName.uniformResourceIdentifier);
        console.log(" dNSName                   : ",certificate_info.tbsCertificate.extensions.subjectAltName.dNSName);

        //xx console.log(require("util").inspect(certificate_info,{colors:true, depth:10}));
        certificate_info.tbsCertificate.version.should.eql(2);
        certificate_info.tbsCertificate.subjectPublicKeyInfo.keyLength.should.eql(128);
        certificate_info.tbsCertificate.extensions.subjectAltName.uniformResourceIdentifier.length.should.eql(1);

    });

    it("should extract the information out of a 2048-bits certificate ",function() {

        var certificate = crypto_utils.readCertificate(path.join(__dirname,"../fixtures/certs/server_cert_2048.pem"));

        // console.log(hexDump(certificate))
        var certificate_info = exploreCertificate(certificate);

        certificate_info.tbsCertificate.version.should.eql(2);
        certificate_info.tbsCertificate.subjectPublicKeyInfo.keyLength.should.eql(256);
        certificate_info.tbsCertificate.extensions.subjectAltName.uniformResourceIdentifier.length.should.eql(1);

    });

    it("should read a certificate containing extra information",function() {

        var filename = path.join(__dirname,"../fixtures/certs/demo_certificate.pem");
        fs.existsSync(filename).should.equal(true);

        var certificate = crypto_utils.readCertificate(filename);
        //xx console.log(certificate.toString("base64"));

        var certificate_info = exploreCertificate(certificate);
        //xx console.log(certificate_info);
        //xx console.log(" Version                   : ",certificate_info.tbsCertificate.version);

    });
});

describe("exploring certificate chains",function() {

    var combine_der = require("../../lib/misc/crypto_explore_certificate").combine_der;
    var split_der = require("../../lib/misc/crypto_explore_certificate").split_der;

    xit("should combine certificates in a single block",function(){

        var cert1_name = path.join(__dirname,"../fixtures/certs/client_cert_2048.pem");
        var cert2_name = path.join(__dirname,"../fixtures/certs/server_cert_1024.pem");

        var cert1 = crypto_utils.readPEM(cert1_name);
        var cert2 = crypto_utils.readPEM(cert2_name);

        var combined = combine_der([cert1,cert2]);
        combined.toString("hex").should.equal(cert1.toString("hex")+cert2.toString("hex"));

        combined.length.should.eql(cert1.length+ cert2.length);

        var chain  = split_der(combined);

        chain.length.should.eql(2);

        console.log(chain[0].toString("hex"));
        console.log(cert1.toString("hex"));
        console.log("-------")
        console.log(chain[1].toString("hex"));
        console.log(cert2.toString("hex"));

        chain[0].length.should.eql(cert1.length);
        chain[1].length.should.eql(cert2.length);

    })
});
<|endoftext|>


<commit_before>(function() {

  var degreesToRadians = fabric.util.degreesToRadians,
      originXOffset = {
        left: -0.5,
        center: 0,
        right: 0.5
      },
      originYOffset = {
        top: -0.5,
        center: 0,
        bottom: 0.5
      };

  fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {

    /**
     * Translates the coordinates from origin to center coordinates (based on the object's dimensions)
     * @param {fabric.Point} point The point which corresponds to the originX and originY params
     * @param {String} fromOriginX Horizontal origin: 'left', 'center' or 'right'
     * @param {String} fromOriginY Vertical origin: 'top', 'center' or 'bottom'
     * @param {String} toOriginX Horizontal origin: 'left', 'center' or 'right'
     * @param {String} toOriginY Vertical origin: 'top', 'center' or 'bottom'
     * @return {fabric.Point}
     */
    translateToGivenOrigin: function(point, fromOriginX, fromOriginY, toOriginX, toOriginY) {
      var x = point.x,
          y = point.y,
          offsetX = originXOffset[toOriginX] - originXOffset[fromOriginX],
          offsetY = originYOffset[toOriginY] - originYOffset[fromOriginY],
          dim;
      if (offsetX || offsetY) {
        dim = this._getTransformedDimensions();
        x = point.x + offsetX * dim.x;
        y = point.y + offsetY * dim.y;
      }
      return new fabric.Point(x, y);
    },

    /**
     * Translates the coordinates from origin to center coordinates (based on the object's dimensions)
     * @param {fabric.Point} point The point which corresponds to the originX and originY params
     * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
     * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
     * @return {fabric.Point}
     */
    translateToCenterPoint: function(point, originX, originY) {
      var p = this.translateToGivenOrigin(point, originX, originY, 'center', 'center');
      if (this.angle) {
        return fabric.util.rotatePoint(p, point, degreesToRadians(this.angle));
      }
      return p;
    },

    /**
     * Translates the coordinates from center to origin coordinates (based on the object's dimensions)
     * @param {fabric.Point} center The point which corresponds to center of the object
     * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
     * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
     * @return {fabric.Point}
     */
    translateToOriginPoint: function(center, originX, originY) {
      var p = this.translateToGivenOrigin(center, 'center', 'center', originX, originY);
      if (this.angle) {
        return fabric.util.rotatePoint(p, center, degreesToRadians(this.angle));
      }
      return p;
    },

    /**
     * Returns the real center coordinates of the object
     * @return {fabric.Point}
     */
    getCenterPoint: function() {
      var leftTop = new fabric.Point(this.left, this.top);
      return this.translateToCenterPoint(leftTop, this.originX, this.originY);
    },

    /**
     * Returns the coordinates of the object based on center coordinates
     * @param {fabric.Point} point The point which corresponds to the originX and originY params
     * @return {fabric.Point}
     */
    // getOriginPoint: function(center) {
    //   return this.translateToOriginPoint(center, this.originX, this.originY);
    // },

    /**
     * Returns the coordinates of the object as if it has a different origin
     * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
     * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
     * @return {fabric.Point}
     */
    getPointByOrigin: function(originX, originY) {
      var center = this.getCenterPoint();
      return this.translateToOriginPoint(center, originX, originY);
    },

    /**
     * Returns the point in local coordinates
     * @param {fabric.Point} point The point relative to the global coordinate system
     * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
     * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
     * @return {fabric.Point}
     */
    toLocalPoint: function(point, originX, originY) {
      var center = this.getCenterPoint(),
          p, dim;

      if (originX && originY) {
        p = this.translateToGivenOrigin(center, 'center', 'center', originX, originY);
      }
      else {
        p = new fabric.Point(this.left, this.top);
      }

      return fabric.util.rotatePoint(new fabric.Point(point.x, point.y), center, -degreesToRadians(this.angle))
        .subtractEquals(p);
    },

    /**
     * Returns the point in global coordinates
     * @param {fabric.Point} The point relative to the local coordinate system
     * @return {fabric.Point}
     */
    // toGlobalPoint: function(point) {
    //   return fabric.util.rotatePoint(point, this.getCenterPoint(), degreesToRadians(this.angle)).addEquals(new fabric.Point(this.left, this.top));
    // },

    /**
     * Sets the position of the object taking into consideration the object's origin
     * @param {fabric.Point} pos The new position of the object
     * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
     * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
     * @return {void}
     */
    setPositionByOrigin: function(pos, originX, originY) {
      var center = this.translateToCenterPoint(pos, originX, originY),
          position = this.translateToOriginPoint(center, this.originX, this.originY);

      this.set('left', position.x);
      this.set('top', position.y);
    },

    /**
     * @param {String} to One of 'left', 'center', 'right'
     */
    adjustPosition: function(to) {
      var angle = degreesToRadians(this.angle),
          hypotHalf = this.getWidth() / 2,
          xHalf = Math.cos(angle) * hypotHalf,
          yHalf = Math.sin(angle) * hypotHalf,
          hypotFull = this.getWidth(),
          xFull = Math.cos(angle) * hypotFull,
          yFull = Math.sin(angle) * hypotFull;

      //TODO: this function does not consider mixed situation like top, center.
      this.left += xFull * (originXOffset[to] - originXOffset[this.originX]);
      this.top += yFull * (originXOffset[to] - originXOffset[this.originX]);

      this.setCoords();
      this.originX = to;
    },

    /**
     * Sets the origin/position of the object to it's center point
     * @private
     * @return {void}
     */
    _setOriginToCenter: function() {
      this._originalOriginX = this.originX;
      this._originalOriginY = this.originY;

      var center = this.getCenterPoint();

      this.originX = 'center';
      this.originY = 'center';

      this.left = center.x;
      this.top = center.y;
    },

    /**
     * Resets the origin/position of the object to it's original origin
     * @private
     * @return {void}
     */
    _resetOrigin: function() {
      var originPoint = this.translateToOriginPoint(
        this.getCenterPoint(),
        this._originalOriginX,
        this._originalOriginY);

      this.originX = this._originalOriginX;
      this.originY = this._originalOriginY;

      this.left = originPoint.x;
      this.top = originPoint.y;

      this._originalOriginX = null;
      this._originalOriginY = null;
    },

    /**
     * @private
     */
    _getLeftTopCoords: function() {
      return this.translateToOriginPoint(this.getCenterPoint(), 'left', 'top');
    }
  });

})();
<commit_msg>Update object_origin.mixin.js<commit_after>(function() {

  var degreesToRadians = fabric.util.degreesToRadians,
      originXOffset = {
        left: -0.5,
        center: 0,
        right: 0.5
      },
      originYOffset = {
        top: -0.5,
        center: 0,
        bottom: 0.5
      };

  fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {

    /**
     * Translates the coordinates from origin to center coordinates (based on the object's dimensions)
     * @param {fabric.Point} point The point which corresponds to the originX and originY params
     * @param {String} fromOriginX Horizontal origin: 'left', 'center' or 'right'
     * @param {String} fromOriginY Vertical origin: 'top', 'center' or 'bottom'
     * @param {String} toOriginX Horizontal origin: 'left', 'center' or 'right'
     * @param {String} toOriginY Vertical origin: 'top', 'center' or 'bottom'
     * @return {fabric.Point}
     */
    translateToGivenOrigin: function(point, fromOriginX, fromOriginY, toOriginX, toOriginY) {
      var x = point.x,
          y = point.y,
          offsetX = originXOffset[toOriginX] - originXOffset[fromOriginX],
          offsetY = originYOffset[toOriginY] - originYOffset[fromOriginY],
          dim;
      if (offsetX || offsetY) {
        dim = this._getTransformedDimensions();
        x = point.x + offsetX * dim.x;
        y = point.y + offsetY * dim.y;
      }
      return new fabric.Point(x, y);
    },

    /**
     * Translates the coordinates from origin to center coordinates (based on the object's dimensions)
     * @param {fabric.Point} point The point which corresponds to the originX and originY params
     * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
     * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
     * @return {fabric.Point}
     */
    translateToCenterPoint: function(point, originX, originY) {
      var p = this.translateToGivenOrigin(point, originX, originY, 'center', 'center');
      if (this.angle) {
        return fabric.util.rotatePoint(p, point, degreesToRadians(this.angle));
      }
      return p;
    },

    /**
     * Translates the coordinates from center to origin coordinates (based on the object's dimensions)
     * @param {fabric.Point} center The point which corresponds to center of the object
     * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
     * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
     * @return {fabric.Point}
     */
    translateToOriginPoint: function(center, originX, originY) {
      var p = this.translateToGivenOrigin(center, 'center', 'center', originX, originY);
      if (this.angle) {
        return fabric.util.rotatePoint(p, center, degreesToRadians(this.angle));
      }
      return p;
    },

    /**
     * Returns the real center coordinates of the object
     * @return {fabric.Point}
     */
    getCenterPoint: function() {
      var leftTop = new fabric.Point(this.left, this.top);
      return this.translateToCenterPoint(leftTop, this.originX, this.originY);
    },

    /**
     * Returns the coordinates of the object based on center coordinates
     * @param {fabric.Point} point The point which corresponds to the originX and originY params
     * @return {fabric.Point}
     */
    // getOriginPoint: function(center) {
    //   return this.translateToOriginPoint(center, this.originX, this.originY);
    // },

    /**
     * Returns the coordinates of the object as if it has a different origin
     * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
     * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
     * @return {fabric.Point}
     */
    getPointByOrigin: function(originX, originY) {
      var center = this.getCenterPoint();
      return this.translateToOriginPoint(center, originX, originY);
    },

    /**
     * Returns the point in local coordinates
     * @param {fabric.Point} point The point relative to the global coordinate system
     * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
     * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
     * @return {fabric.Point}
     */
    toLocalPoint: function(point, originX, originY) {
      var center = this.getCenterPoint(),
          p, dim, p2;

      if (originX && originY) {
        p = this.translateToGivenOrigin(center, 'center', 'center', originX, originY);
      }
      else {
        p = new fabric.Point(this.left, this.top);
      }

      p2 = new fabric.Point(point.x, point.y);
      if (this.angle) {
        p2 = fabric.util.rotatePoint(p2, center, -degreesToRadians(this.angle));
      }
      return p2.subtractEquals(p);
    },

    /**
     * Returns the point in global coordinates
     * @param {fabric.Point} The point relative to the local coordinate system
     * @return {fabric.Point}
     */
    // toGlobalPoint: function(point) {
    //   return fabric.util.rotatePoint(point, this.getCenterPoint(), degreesToRadians(this.angle)).addEquals(new fabric.Point(this.left, this.top));
    // },

    /**
     * Sets the position of the object taking into consideration the object's origin
     * @param {fabric.Point} pos The new position of the object
     * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
     * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
     * @return {void}
     */
    setPositionByOrigin: function(pos, originX, originY) {
      var center = this.translateToCenterPoint(pos, originX, originY),
          position = this.translateToOriginPoint(center, this.originX, this.originY);

      this.set('left', position.x);
      this.set('top', position.y);
    },

    /**
     * @param {String} to One of 'left', 'center', 'right'
     */
    adjustPosition: function(to) {
      var angle = degreesToRadians(this.angle),
          hypotHalf = this.getWidth() / 2,
          xHalf = Math.cos(angle) * hypotHalf,
          yHalf = Math.sin(angle) * hypotHalf,
          hypotFull = this.getWidth(),
          xFull = Math.cos(angle) * hypotFull,
          yFull = Math.sin(angle) * hypotFull;

      //TODO: this function does not consider mixed situation like top, center.
      this.left += xFull * (originXOffset[to] - originXOffset[this.originX]);
      this.top += yFull * (originXOffset[to] - originXOffset[this.originX]);

      this.setCoords();
      this.originX = to;
    },

    /**
     * Sets the origin/position of the object to it's center point
     * @private
     * @return {void}
     */
    _setOriginToCenter: function() {
      this._originalOriginX = this.originX;
      this._originalOriginY = this.originY;

      var center = this.getCenterPoint();

      this.originX = 'center';
      this.originY = 'center';

      this.left = center.x;
      this.top = center.y;
    },

    /**
     * Resets the origin/position of the object to it's original origin
     * @private
     * @return {void}
     */
    _resetOrigin: function() {
      var originPoint = this.translateToOriginPoint(
        this.getCenterPoint(),
        this._originalOriginX,
        this._originalOriginY);

      this.originX = this._originalOriginX;
      this.originY = this._originalOriginY;

      this.left = originPoint.x;
      this.top = originPoint.y;

      this._originalOriginX = null;
      this._originalOriginY = null;
    },

    /**
     * @private
     */
    _getLeftTopCoords: function() {
      return this.translateToOriginPoint(this.getCenterPoint(), 'left', 'top');
    }
  });

})();
<|endoftext|>