<commit_before>var Base = require('../../index');
var List  = Base.List;
var utils  = require('../../base/utils');
var expect = require('chai').expect;
var Variable = Base.Variable;

describe('List construction', function() {
   it('takes no arguments', function() {
      var l = List();
      expect(l).to.be.instanceof(List);
      expect(l.length()).to.equal(0);
      var l = List([]);
      expect(l).to.be.instanceof(List);
      expect(l.length()).to.equal(0);
   });
   it('takes object', function() {
      var l = new List({ a: 4, b: 2 });
      expect(l).to.be.instanceof(List);
      expect(l.length()).to.equal(2);
      expect(l.get(1)).to.equal(4);
      expect(l.get("a")).to.equal(4);
      expect(l.get(2)).to.equal(2);
      expect(utils.isMissing(l.get("c"))).to.be.true;
      expect(utils.isMissing(l.get(3))).to.be.true;
      expect(utils.isMissing(l.get(0))).to.be.true;
   });
   it('takes array', function() {
      var l = new List([4, 3, 2, 1]);
      expect(l).to.be.instanceof(List);
      expect(l.length()).to.equal(4);
      expect(l.get()).to.deep.equal([4, 3, 2, 1]);
   });
   it('takes list of values', function() {
      var l = List([2, 4, 5, 6]);
      expect(l).to.be.instanceof(List);
      expect(l.length()).to.equal(4);
      expect(l.get()).to.deep.equal([2, 4, 5, 6]);
   });
});
describe('List names', function() {
   var l = new List({a: 4, b: 7, c: -1});
   it('can be provided to the constructor', function() {
      expect(l.get('a')).to.equal(4);
      expect(l.get('b')).to.equal(7);
      expect(l.get('c')).to.equal(-1);
   })
   it('can be retrieved using the names function', function() {
      expect(l.names().toArray()).to.deep.equal(['a','b','c']); // unintentionally tests order, sorry...
      expect(l.names(3)).to.equal('c');
   })
   it('can be set using the names function', function() {
      expect(l.names(3, 'z').get('z')).to.equal(l.get(3));
      expect(l.names(['p','q','r']).names().toArray()).to.deep.equal(['p','q','r']);
      expect(l.names(new Variable(['p','q','x'])).names()
                     .toArray()).to.deep.equal(['p','q','x']);
   })
   it('cannot be used to partially set the names', function() {
      expect(function () { l.names(['no','maybe']); }).to.throw(Error);
      expect(function () { l.names([]); }).to.throw(Error);
      expect(utils.isMissing(l.names())).to.be.false;
   })
   it('can be deleted by calling with utils.missing', function() {
      var l = (new List({a: 4, b: 7, c: -1}))
               .names(['a','b','c']).names(utils.missing);
      expect(utils.isMissing(l.names())).to.be.true;
   })
});
describe('List set', function() {
   it('works when i is a single number (reset/append/error)', function() {
      var l = new List({a: 4, b: 7, c: -1});
      expect(l.set(1, 18).get(1)).to.equal(18);
      expect(l.set(2, 28).get(2)).to.equal(28);
      expect(l.set(3, 38).get(3)).to.equal(38);
      expect(l.set(4, 48).get(4)).to.equal(48);
      expect(l.set(10, 108).get(10)).to.equal(108);
      expect(l.set(5.8, 1.8).get(5)).to.equal(1.8);
      expect(function() { l.set(-2, 18); }).to.throw(Error);
   });
   it('works when i is a name-string, either existing or new', function() {
      var l = new List({a: 4, b: 7, c: -1});
      expect(l.set('a', 6.2).get('a')).to.equal(6.2);
      expect(l.set('z', 6.2).get('z')).to.equal(6.2);
      expect(l.length()).to.equal(4);
      expect(l.set('z', 10.5).get('z')).to.equal(10.5);
      expect(l.length()).to.equal(4);
   });
   it('works when i is an object of name-value pairs', function() {
      var l = new List({a: 4, b: 7, c: -1});
      var obj = {b: 22, d: -3};
      expect(l.set(obj).get('b')).to.equal(obj.b);
      expect(l.get('d')).to.equal(obj.d);
      expect(l.length()).to.equal(4);
      expect(l.get(4)).to.equal(obj.d);
   });
   it('works when i is an array of values to append', function() {
      var l = new List({a: 4, b: 7, c: -1});
      expect(l.set([3.2, 3.3, 3.4, 3.5]).get(7)).to.equal(3.5);
      expect(l.length()).to.equal(7);
      //l.names(['x','y','z','p',,,'a']);
   });
   it('works when i is a List', function() {
      var l = new List({a: 4, b: 7, c: -1});
      var l2 = new List({b: 2 });
      l2.set([6]);
      l.set(l2);
      expect(l.get(4)).to.equal(6);
      expect(l.get(2)).to.equal(2);
      expect(l.get('b')).to.equal(2);
      expect(l.length()).to.equal(4);
   });
});
describe('List delete', function() {
   it('by index', function() {
      var l = new List({a: 4, b: 7, c: -1});
      expect(l.delete(2).get(2)).to.equal(-1);
      expect(l.length()).to.equal(2);
      expect(l.names().toArray()).to.deep.equal(['a', 'c']);
      expect(l.delete(3).length()).to.equal(2);
      expect(l.names().toArray()).to.deep.equal(['a', 'c']);
      expect(l.delete(-1).length()).to.equal(2);
      expect(l.names().toArray()).to.deep.equal(['a', 'c']);
   });
   it('by name', function() {
      var l = new List({a: 4, b: 7, c: -1});
      expect(l.delete('b').get(2)).to.equal(-1);
      expect(l.length()).to.equal(2);
      expect(l.names().toArray()).to.deep.equal(['a', 'c']);
      expect(l.delete('b').length()).to.equal(2);
      expect(l.names().toArray()).to.deep.equal(['a', 'c']);
      expect(l.delete('d').length()).to.equal(2);
      expect(l.names().toArray()).to.deep.equal(['a', 'c']);
   });
});
describe('List push:', function() {
   it('works by specifying just a value', function() {
      var l = new List({a: 4, b: 7, c: -1});
      expect(l).to.respondTo('push');
      expect(function() { l.push(5); }).to.not.throw(Error);
      expect(l.length()).to.equal(4);
      expect(l.get(4)).to.equal(5);
      expect(l.names().toArray()).to.deep.equal(['a', 'b', 'c']);
   });
});
describe('List has:', function() {
   it('finds named entry by index', function() {
      var l = new List({a: 4, b: 7, c: -1});
      expect(l).to.respondTo('has');
      expect(function() { l.has(2); }).to.not.throw(Error);
      expect(l.has(2)).to.equal(true);
      expect(l.has(4)).to.equal(false);
   });
   it('finds named entry', function() {
      var l = new List({a: 4, b: 7, c: -1});
      expect(l).to.respondTo('has');
      expect(function() { l.has('b'); }).to.not.throw(Error);
      expect(l.has('b')).to.equal(true);
      expect(l.has('d')).to.equal(false);
   });
});
describe('List deepGet:', function() {
   it('descends into lists', function() {
      var l = new List({a: new Variable([2, 4]), b: List({c: 5, d: 2})});
      expect(l.deepGet(["a"])).to.be.an.instanceof(Variable);
      expect(l.deepGet(["b", "c"])).to.equal(5);
      expect(l.deepGet([1, 1])).to.equal(2);
      expect(l.deepGet([1])).to.be.an.instanceof(Variable);
      expect(l.deepGet([2, 1])).to.equal(5);
      expect(l.deepGet(new Variable([2, 1]))).to.equal(5);
   });
   it('errors if going too wide or deep', function() {
      var l = new List({a: new Variable([2, 4]), b: List({c: 5, d: 2})});
      expect(function() { l.deepGet([3]) }).to.throw(Error);
      expect(function() { l.deepGet([1, 3]) }).to.throw(Error);
      expect(function() { l.deepGet(["a", "c"]) }).to.throw(Error);
      expect(function() { l.deepGet([2, 1, 1]) }).to.throw(Error);
   });
});
describe('List deepSet:', function() {
   it('descends into lists and makes assignment', function() {
      var l = new List({a: new Variable([2, 4]), b: List({c: 5, d: 2})});
      l.deepSet([1, 1], 5);
      expect(l.get('a').get(1)).to.equal(5);
      l.deepSet(['b','c'], 20);
      expect(l.get('b').get('c')).to.equal(20);
      l.deepSet(['b','e'], 77);
      expect(l.get('b').length()).to.equal(3);
      expect(l.get('b').get('e')).to.equal(77);
   });
   it('errors if going too wide or deep', function() {
      var l = new List({a: new Variable([2, 4]), b: List({c: 5, d: 2})});
      expect(function() { l.deepSet([3, 1], 10) }).to.throw(Error);
      expect(function() { l.deepSet([1, 3, 1], 10) }).to.throw(Error);
      expect(function() { l.deepSet(["a", "c", "x"], 10) }).to.throw(Error);
   });
});
<commit_msg>Fix List test comment.<commit_after>var Base = require('../../index');
var List  = Base.List;
var utils  = require('../../base/utils');
var expect = require('chai').expect;
var Variable = Base.Variable;

describe('List construction', function() {
   it('takes no arguments', function() {
      var l = List();
      expect(l).to.be.instanceof(List);
      expect(l.length()).to.equal(0);
      var l = List([]);
      expect(l).to.be.instanceof(List);
      expect(l.length()).to.equal(0);
   });
   it('takes object', function() {
      var l = new List({ a: 4, b: 2 });
      expect(l).to.be.instanceof(List);
      expect(l.length()).to.equal(2);
      expect(l.get(1)).to.equal(4);
      expect(l.get("a")).to.equal(4);
      expect(l.get(2)).to.equal(2);
      expect(utils.isMissing(l.get("c"))).to.be.true;
      expect(utils.isMissing(l.get(3))).to.be.true;
      expect(utils.isMissing(l.get(0))).to.be.true;
   });
   it('takes array', function() {
      var l = new List([4, 3, 2, 1]);
      expect(l).to.be.instanceof(List);
      expect(l.length()).to.equal(4);
      expect(l.get()).to.deep.equal([4, 3, 2, 1]);
   });
   it('can be called without new', function() {
      var l = List([2, 4, 5, 6]);
      expect(l).to.be.instanceof(List);
      expect(l.length()).to.equal(4);
      expect(l.get()).to.deep.equal([2, 4, 5, 6]);
   });
});
describe('List names', function() {
   var l = new List({a: 4, b: 7, c: -1});
   it('can be provided to the constructor', function() {
      expect(l.get('a')).to.equal(4);
      expect(l.get('b')).to.equal(7);
      expect(l.get('c')).to.equal(-1);
   })
   it('can be retrieved using the names function', function() {
      expect(l.names().toArray()).to.deep.equal(['a','b','c']); // unintentionally tests order, sorry...
      expect(l.names(3)).to.equal('c');
   })
   it('can be set using the names function', function() {
      expect(l.names(3, 'z').get('z')).to.equal(l.get(3));
      expect(l.names(['p','q','r']).names().toArray()).to.deep.equal(['p','q','r']);
      expect(l.names(new Variable(['p','q','x'])).names()
                     .toArray()).to.deep.equal(['p','q','x']);
   })
   it('cannot be used to partially set the names', function() {
      expect(function () { l.names(['no','maybe']); }).to.throw(Error);
      expect(function () { l.names([]); }).to.throw(Error);
      expect(utils.isMissing(l.names())).to.be.false;
   })
   it('can be deleted by calling with utils.missing', function() {
      var l = (new List({a: 4, b: 7, c: -1}))
               .names(['a','b','c']).names(utils.missing);
      expect(utils.isMissing(l.names())).to.be.true;
   })
});
describe('List set', function() {
   it('works when i is a single number (reset/append/error)', function() {
      var l = new List({a: 4, b: 7, c: -1});
      expect(l.set(1, 18).get(1)).to.equal(18);
      expect(l.set(2, 28).get(2)).to.equal(28);
      expect(l.set(3, 38).get(3)).to.equal(38);
      expect(l.set(4, 48).get(4)).to.equal(48);
      expect(l.set(10, 108).get(10)).to.equal(108);
      expect(l.set(5.8, 1.8).get(5)).to.equal(1.8);
      expect(function() { l.set(-2, 18); }).to.throw(Error);
   });
   it('works when i is a name-string, either existing or new', function() {
      var l = new List({a: 4, b: 7, c: -1});
      expect(l.set('a', 6.2).get('a')).to.equal(6.2);
      expect(l.set('z', 6.2).get('z')).to.equal(6.2);
      expect(l.length()).to.equal(4);
      expect(l.set('z', 10.5).get('z')).to.equal(10.5);
      expect(l.length()).to.equal(4);
   });
   it('works when i is an object of name-value pairs', function() {
      var l = new List({a: 4, b: 7, c: -1});
      var obj = {b: 22, d: -3};
      expect(l.set(obj).get('b')).to.equal(obj.b);
      expect(l.get('d')).to.equal(obj.d);
      expect(l.length()).to.equal(4);
      expect(l.get(4)).to.equal(obj.d);
   });
   it('works when i is an array of values to append', function() {
      var l = new List({a: 4, b: 7, c: -1});
      expect(l.set([3.2, 3.3, 3.4, 3.5]).get(7)).to.equal(3.5);
      expect(l.length()).to.equal(7);
      //l.names(['x','y','z','p',,,'a']);
   });
   it('works when i is a List', function() {
      var l = new List({a: 4, b: 7, c: -1});
      var l2 = new List({b: 2 });
      l2.set([6]);
      l.set(l2);
      expect(l.get(4)).to.equal(6);
      expect(l.get(2)).to.equal(2);
      expect(l.get('b')).to.equal(2);
      expect(l.length()).to.equal(4);
   });
});
describe('List delete', function() {
   it('by index', function() {
      var l = new List({a: 4, b: 7, c: -1});
      expect(l.delete(2).get(2)).to.equal(-1);
      expect(l.length()).to.equal(2);
      expect(l.names().toArray()).to.deep.equal(['a', 'c']);
      expect(l.delete(3).length()).to.equal(2);
      expect(l.names().toArray()).to.deep.equal(['a', 'c']);
      expect(l.delete(-1).length()).to.equal(2);
      expect(l.names().toArray()).to.deep.equal(['a', 'c']);
   });
   it('by name', function() {
      var l = new List({a: 4, b: 7, c: -1});
      expect(l.delete('b').get(2)).to.equal(-1);
      expect(l.length()).to.equal(2);
      expect(l.names().toArray()).to.deep.equal(['a', 'c']);
      expect(l.delete('b').length()).to.equal(2);
      expect(l.names().toArray()).to.deep.equal(['a', 'c']);
      expect(l.delete('d').length()).to.equal(2);
      expect(l.names().toArray()).to.deep.equal(['a', 'c']);
   });
});
describe('List push:', function() {
   it('works by specifying just a value', function() {
      var l = new List({a: 4, b: 7, c: -1});
      expect(l).to.respondTo('push');
      expect(function() { l.push(5); }).to.not.throw(Error);
      expect(l.length()).to.equal(4);
      expect(l.get(4)).to.equal(5);
      expect(l.names().toArray()).to.deep.equal(['a', 'b', 'c']);
   });
});
describe('List has:', function() {
   it('finds named entry by index', function() {
      var l = new List({a: 4, b: 7, c: -1});
      expect(l).to.respondTo('has');
      expect(function() { l.has(2); }).to.not.throw(Error);
      expect(l.has(2)).to.equal(true);
      expect(l.has(4)).to.equal(false);
   });
   it('finds named entry', function() {
      var l = new List({a: 4, b: 7, c: -1});
      expect(l).to.respondTo('has');
      expect(function() { l.has('b'); }).to.not.throw(Error);
      expect(l.has('b')).to.equal(true);
      expect(l.has('d')).to.equal(false);
   });
});
describe('List deepGet:', function() {
   it('descends into lists', function() {
      var l = new List({a: new Variable([2, 4]), b: List({c: 5, d: 2})});
      expect(l.deepGet(["a"])).to.be.an.instanceof(Variable);
      expect(l.deepGet(["b", "c"])).to.equal(5);
      expect(l.deepGet([1, 1])).to.equal(2);
      expect(l.deepGet([1])).to.be.an.instanceof(Variable);
      expect(l.deepGet([2, 1])).to.equal(5);
      expect(l.deepGet(new Variable([2, 1]))).to.equal(5);
   });
   it('errors if going too wide or deep', function() {
      var l = new List({a: new Variable([2, 4]), b: List({c: 5, d: 2})});
      expect(function() { l.deepGet([3]) }).to.throw(Error);
      expect(function() { l.deepGet([1, 3]) }).to.throw(Error);
      expect(function() { l.deepGet(["a", "c"]) }).to.throw(Error);
      expect(function() { l.deepGet([2, 1, 1]) }).to.throw(Error);
   });
});
describe('List deepSet:', function() {
   it('descends into lists and makes assignment', function() {
      var l = new List({a: new Variable([2, 4]), b: List({c: 5, d: 2})});
      l.deepSet([1, 1], 5);
      expect(l.get('a').get(1)).to.equal(5);
      l.deepSet(['b','c'], 20);
      expect(l.get('b').get('c')).to.equal(20);
      l.deepSet(['b','e'], 77);
      expect(l.get('b').length()).to.equal(3);
      expect(l.get('b').get('e')).to.equal(77);
   });
   it('errors if going too wide or deep', function() {
      var l = new List({a: new Variable([2, 4]), b: List({c: 5, d: 2})});
      expect(function() { l.deepSet([3, 1], 10) }).to.throw(Error);
      expect(function() { l.deepSet([1, 3, 1], 10) }).to.throw(Error);
      expect(function() { l.deepSet(["a", "c", "x"], 10) }).to.throw(Error);
   });
});
<|endoftext|>


<commit_before>(function (window, undefined)
{

	window.console._RELAY_TO_DOC = false;
	window.console._USE_JSON = false;
	window.console._SHOW_COOL_NUMBERS = false;
	window.console._SHOW_TYPES = false;
	window.console._SHOW_STRING_LENGTH = false;

	if (window.console.log.toString() != window.Math.log.toString() && window.console.warn)
	{
		window.console.warn('The current console.log() may not be the native method!');
	}

	var messages = [],
		old_console_log = window.console.log,
		escapeHTML = function (string)
		{
			return string.replace(/[&<>"'\/]/g, function (c)
			{
				return {
					'&': '&',
					'<': '<',
					'>': '>',
					'"': '"',
					'\'': ''',
					'/': '/'
				}[c];
			});
		},
		isEmpty = function (o)
		{
			for (var k in o)
			{
				return false;
			}
			return true;
		},
		format = function (string)
		{
			return string.replace(/%([difs])(?:\.(\d+))?/g, function (all, type, size)
			{
				if ((i + 1) < args.length)
				{
					i++;
				}

				switch (type)
				{
				case 's':
					return args[i] + '';
				case 'd':
				case 'i':
					return (args[i] / 1).toFixed(0);
				case 'f':
					if (size)
					{
						return (args[i] / 1).toFixed(size);
					}
					else
					{
						return args[i] / 1;
					}
				}
			});
		},

		args, i,
		pre_style = 'border:none;background:white;color:black;margin:0;padding:3px 0px 0px 3px;font-family:monospace;word-wrap:break-word;',

		generateHTML = function (args, sub, recursion)
		{

			switch (typeof args)
			{
			case 'undefined':
			case 'boolean':
			case 'function':
				return (window.console._SHOW_TYPES ? '(' + (typeof args) + ') ' : '') + escapeHTML(args ? args.toString() : 'undefined');
			case 'number':
				return (window.console._SHOW_TYPES ? '(number) ' : '') + args + (window.console._SHOW_COOL_NUMBERS && args == args ? ' (0x' + args.toString(16) + ', 0o' + args.toString(8) + ', 0b' + args.toString(2) + ')' : '');
			case 'string':
				var tmp = format(args.toString());
				return (window.console._SHOW_TYPES ? '(string) ' : '') + '"' + escapeHTML(tmp) + '"' + (window.console._SHOW_STRING_LENGTH ? ' (length: ' + tmp.length + ')' : '');
			case 'object':
				if (args == null)
				{
					return (window.console._SHOW_TYPES ? '(object) ' : '') + 'null';
				}
				else if (args instanceof window.String)
				{
					return '[object String]: "' + escapeHTML(args) + '"' + (window.console._SHOW_STRING_LENGTH ? ' (length: ' + args.length + ')' : '');
				}
				else if (args instanceof window.RegExp)
				{
					return '[object RegExp]: ' + escapeHTML(args.toString());
				}
				else if (isEmpty(args))
				{
					var tmp;
					return window.Object.prototype.toString.call(args) + (
						args.valueOf ? ': ' + ((tmp = args.valueOf()) == args && (typeof tmp == 'object') ? ('length' in tmp ? '[]' : '{}') : tmp) : ''
					);
				}
				else
				{
					var html = '
▶<input type="checkbox" style="display:none;" onchange="this.parentNode.parentNode.getElementsByTagName(\'div\')[0].style.display=this.checked?\'block\':\'none\';this.parentNode.getElementsByTagName(\'span\')[0].innerText=this.checked?\'▼\':\'▶\';">' + Object.prototype.toString.call(args) + '
';

					for (var k in args)
					{
						if(recursion)
						{
							html += '
' + k + ': ' + generateHTML(args[k], true, !(args instanceof Element) && args.self!=args) + '
';
						}
						else
						{
							if((typeof args[k])=='object')
							{
								html += '
' + k + ': ' + (args[k]||'null').toString() + '
';
							}
							else
							{
								html += '
' + k + ': ' + generateHTML(args[k], true, false) + '
';
							}

						}
					}

					return html + '

';
				}
			}

		},

		redirect_log = window.console.log = function ()
		{

			old_console_log.apply(window.console, arguments);

			if (window.console._RELAY_TO_DOC)
			{
				var div = window.document.createElement('div');

				messages[messages.length] = div;

				args = arguments;

				div.style.border = '1px solid #333';
				div.style.background = '#666';
				div.className = 'console-log';
				div.innerHTML = 'Console message at ' + (new Date()) + '×';

				for (i = 0, l = args.length; i < l; i++)
				{
					div.innerHTML += '
' + (window.console._USE_JSON ? escapeHTML(JSON.stringify(args[i])) : generateHTML(args[i],false,true)) + '
';
				}

				if (window.console._RELAY_TO_DOC instanceof window.Element)
				{
					window.console._RELAY_TO_DOC.appendChild(div);
				}
				else
				{
					window.document.body.appendChild(div);
				}
			}

		},
		old_console_clear = window.console.clear,
		redirect_clear = window.console.clear = function(){
			old_console_clear.apply(window.console);

			for(var k in messages)
			{
				if(messages[k] && messages[k].parentNode)
				{
					messages[k].parentNode.removeChild(messages[k]);
					messages[k] = null;
				}
			}

			messages = [];
		};

	window.console._restore_old_log = function ()
	{
		window.console.log = old_console_log;
	};
	window.console._restore_redirect_log = function ()
	{
		window.console.log = redirect_log;
	};

	window.console._restore_old_clear = function ()
	{
		window.console.clear = old_console_clear;
	};
	window.console._restore_redirect_clear = function ()
	{
		window.console.log = redirect_clear;
	};

	window.addEventListener('error', function (e)
	{
		var x = new Error(e.message);

		x.message = e.message;
		x.filename = e.filename;
		x.lineno = e.lineno;
		x.colno = e.colno;

		console.log(e.message, x);
	});

})(Function('return this')());
<commit_msg>Removed recovering methods, added icons and aditional methods<commit_after>(function (window, undefined)
{

	window.console._RELAY_TO_DOC = false;
	window.console._USE_JSON = false;
	window.console._SHOW_COOL_NUMBERS = false;
	window.console._SHOW_TYPES = false;
	window.console._SHOW_STRING_LENGTH = false;

	if (window.console.log.toString() != window.Math.log.toString() && window.console.warn)
	{
		window.console.warn('The current console.log() may not be the native method!');
	}

	var messages = [],
		times = {},
		icons = {
			log:'',
			error:'× ',
			info:'i ',
			warning:'! ',
			time:'L ',
			timeEnd:'L '
		},
		old_console = {
			log:window.console.log,
			error:window.console.error,
			info:window.console.info,
			warning:window.console.warning,
			time:window.console.time,
			timeEnd:window.console.timeEnd,
			clear:window.console.clear
		},
		escapeHTML = function (string)
		{
			return string.replace(/[&<>"'\/]/g, function (c)
			{
				return {
					'&': '&',
					'<': '<',
					'>': '>',
					'"': '"',
					'\'': ''',
					'/': '/'
				}[c];
			});
		},
		isEmpty = function (o)
		{
			for (var k in o)
			{
				return false;
			}
			return true;
		},
		format = function (string)
		{
			return string.replace(/%([difs])(?:\.(\d+))?/g, function (all, type, size)
			{
				if ((i + 1) < args.length)
				{
					i++;
				}

				switch (type)
				{
				case 's':
					return args[i] + '';
				case 'd':
				case 'i':
					return (args[i] / 1).toFixed(0);
				case 'f':
					if (size)
					{
						return (args[i] / 1).toFixed(size);
					}
					else
					{
						return args[i] / 1;
					}
				}
			});
		},

		args, i,
		pre_style = 'border:none;background:white;color:black;margin:0;padding:3px 0px 0px 3px;font-family:monospace;word-wrap:break-word;',

		generateHTML = function (args, sub, recursion)
		{

			switch (typeof args)
			{
			case 'undefined':
			case 'boolean':
			case 'function':
				return (window.console._SHOW_TYPES ? '(' + (typeof args) + ') ' : '') + escapeHTML(args ? args.toString() : 'undefined');
			case 'number':
				return (window.console._SHOW_TYPES ? '(number) ' : '') + args + (window.console._SHOW_COOL_NUMBERS && args == args ? ' (0x' + args.toString(16) + ', 0o' + args.toString(8) + ', 0b' + args.toString(2) + ')' : '');
			case 'string':
				var tmp = format(args.toString());
				return (window.console._SHOW_TYPES ? '(string) ' : '') + '"' + escapeHTML(tmp) + '"' + (window.console._SHOW_STRING_LENGTH ? ' (length: ' + tmp.length + ')' : '');
			case 'object':
				if (args == null)
				{
					return (window.console._SHOW_TYPES ? '(object) ' : '') + 'null';
				}
				else if (args instanceof window.String)
				{
					return '[object String]: "' + escapeHTML(args) + '"' + (window.console._SHOW_STRING_LENGTH ? ' (length: ' + args.length + ')' : '');
				}
				else if (args instanceof window.RegExp)
				{
					return '[object RegExp]: ' + escapeHTML(args.toString());
				}
				else if (isEmpty(args))
				{
					var tmp;
					return window.Object.prototype.toString.call(args) + (
						args.valueOf ? ': ' + ((tmp = args.valueOf()) == args && (typeof tmp == 'object') ? ('length' in tmp ? '[]' : '{}') : tmp) : ''
					);
				}
				else
				{
					var html = '
▶<input type="checkbox" style="display:none;" onchange="this.parentNode.parentNode.getElementsByTagName(\'div\')[0].style.display=this.checked?\'block\':\'none\';this.parentNode.getElementsByTagName(\'span\')[0].innerText=this.checked?\'▼\':\'▶\';">' + Object.prototype.toString.call(args) + '
';

					for (var k in args)
					{
						if(recursion)
						{
							html += '
' + k + ': ' + generateHTML(args[k], true, !(args instanceof Element) && args.self!=args) + '
';
						}
						else
						{
							if((typeof args[k])=='object')
							{
								html += '
' + k + ': ' + (args[k]||'null').toString() + '
';
							}
							else
							{
								html += '
' + k + ': ' + generateHTML(args[k], true, false) + '
';
							}

						}
					}

					return html + '

';
				}
			}

		},

		logger = function (icon, args)
		{

			if ( icon == 'time' )
			{
				times[ args[0] + '' ]=new Date();
				args[0] += ': timer started';
			}
			else if ( icon == 'timeEnd' )
			{
				if( times[ args[0] + ''] )
				{
					args[0] += ': timer took '+ ( (new Date()) - times[ args[0] + '' ] ) +'ms';
					delete times[ args[0] + '' ];
				}
				else
				{
					icon = 'error';
					args[0] += ': unknown timer';
				}
			}

			//logs into the desired function or into console.log
			( old_console[icon] || old_console.log ).apply(window.console, window.Array.prototype.slice.call(args));

			if (window.console._RELAY_TO_DOC)
			{

				var div = window.document.createElement('div');

				messages[messages.length] = div;

				div.style.border = '1px solid #333';
				div.style.background = '#666';
				div.className = 'console-log';
				div.innerHTML = ''+icons[icon]+'Console message at ' + (new Date()) + '×';

				for (i = 0, l = args.length; i < l; i++)
				{
					div.innerHTML += '
' + (window.console._USE_JSON ? escapeHTML(JSON.stringify(args[i])) : generateHTML(args[i],false,true)) + '
';
				}

				if (window.console._RELAY_TO_DOC instanceof window.Element)
				{
					window.console._RELAY_TO_DOC.appendChild(div);
				}
				else
				{
					window.document.body.appendChild(div);
				}
			}

		};

	window.console.log = function(){
		logger('log',arguments);
	};
	window.console.error = function(){
		logger('error',arguments);
	};
	window.console.info = function(){
		logger('info',arguments);
	};
	window.console.warning = function(){
		logger('warning',arguments);
	};
	window.console.time = function(){
		logger('time',arguments);
	};
	window.console.timeEnd = function(){
		logger('timeEnd',arguments);
	};

	window.console.clear = function(){
		old_console.clear.apply(window.console);

		for(var k in messages)
		{
			if(messages[k] && messages[k].parentNode)
			{
				messages[k].parentNode.removeChild(messages[k]);
				messages[k] = null;
			}
		}

		messages = [];
	};

	window.addEventListener('error', function (e)
	{
		var x = new Error(e.message);

		x.message = e.message;
		x.filename = e.filename;
		x.lineno = e.lineno;
		x.colno = e.colno;

		logger('error',[e.message, x]);
	});

})(Function('return this')());
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');

require('../src/locale-compare');

describe('default', function() {
  it('should order b after a', function() {
    assert('b'.localeCompare('a') === 1);
  });
});

describe('da-DK', function() {
  it('should order ø after p', function() {
    assert('ø'.localeCompare('p', 'da-DK') === 1);
  });
  it('should order an array', function() {
    var unordered = ['ø', 'å', 'z', 'æ'];
    var ordered = ['z', 'æ', 'ø', 'å'];
    assert.deepStrictEqual(unordered.sort(function(a, b) {
      return a.localeCompare(b, 'da-DK');
    }), ordered);
  });
});
<commit_msg>deep string test<commit_after>'use strict';

var assert = require('assert');

require('../src/locale-compare');

describe('default', function() {
  it('should order b after a', function() {
    assert('b'.localeCompare('a') === 1);
  });
});

describe('da-DK', function() {
  it('should order ø after p', function() {
    assert('ø'.localeCompare('p', 'da-DK') === 1);
  });
  it('should order deep strings', function() {
    assert('bbbbc'.localeCompare('bbbba', 'da-DK') === 1);
  });
  it('should order an array', function() {
    var unordered = ['ø', 'å', 'z', 'æ'];
    var ordered = ['z', 'æ', 'ø', 'å'];
    assert.deepStrictEqual(unordered.sort(function(a, b) {
      return a.localeCompare(b, 'da-DK');
    }), ordered);
  });
});
<|endoftext|>


<commit_before>// es6 application code

import Human from './human.js'

let foo = new Human("Foo", "Bar");

document.querySelector("h1").innerHTML = `Hello ${foo.toString()}`;
<commit_msg>import github module and try to load a repo<commit_after>// es6 application code

import Human from './human.js'
import Github from './../client/github/github-client.js'
import lively4 from './../src/lively4-client.js'

let foo = new Human("Foo", "Bar");

Github.getRepo((result) => {
    "use strict";
    console.log('# # # # # # # # # # # # # # # # # # # # # ');
    console.log(result);
    console.log(Github);
});

document.querySelector("h1").innerHTML = `Hello ${foo.toString()}`;
<|endoftext|>


<commit_before>document.addEventListener("DOMContentLoaded", function() {
    initVariables();
    initObject();

    loadFromLocalStorage();
});

var audioplayer = {
    version: "0.0.2",
    name: "Audioplayer",

    newSong: function(aElement) {
        audioplayer.stop();

        try {
            document.querySelector("[data-type='audio'].active").className = document.querySelector("[data-type='audio'].active").className.replace("active", "");
        } catch (error) {
            // no element was active
        }
        aElement.className += "active";

        // get song info
        var path = aElement.getAttribute("data-path");
        var title = aElement.getElementsByClassName("title")[0];
        var artist = aElement.getElementsByClassName("artist")[0];
        var album = aElement.getElementsByClassName("album")[0];
        var duration = aElement.getElementsByClassName("duration")[0];
        var coverImage = aElement.getElementsByTagName("img")[0].getAttribute("src");

        // set new info
        audioplayer.elements.title.innerHTML = title.innerHTML;

        if (typeof artist != "undefined") {
            audioplayer.elements.artist.innerHTML = artist.innerHTML;
        } else {
            audioplayer.elements.artist.innerHTML = null;
        }

        if (typeof album != "undefined") {
            audioplayer.elements.album.innerHTML = album.innerHTML;
        } else {
            audioplayer.elements.album.innerHTML = null;
        }

        audioplayer.elements.cover.setAttribute("src", coverImage);
        audioplayer.elements.timeline.total.innerHTML = duration.innerHTML;

        // test if browser supports audio format
        var extSplit = path.split(".");
        var format = extSplit[extSplit.length - 1];

        if (!! audioplayer.audio.object.canPlayType("audio/" + format) === false) {

            swal("Formato no soportado", "No es posible reproducir la cancion, tu navegador no soporta el formato " + format.toUpperCase(), "error");

        } else {
            // start new object
            audioplayer.audio.object = new Audio(path);
            audioplayer.play();

            audioplayer.audio.object.addEventListener("timeupdate", audioplayer.timeUpdate, false);
        }

    },
    play: function() {
        audioplayer.audio.object.volume = audioplayer.audio.volume;
        audioplayer.audio.object.muted = audioplayer.audio.muted;

        audioplayer.audio.object.play();
        //audioplayer.audio.object.onended = audioplayer.onended();

        audioplayer.elements.timeline.total.innerHTML = audioplayer.audio.duration;

        // update document title
        // update doument icon

        // scroll to active song

        audioplayer.elements.buttons.play.style.display = "none";
        audioplayer.elements.buttons.pause.style.display = "inline-block";

    },
    pause: function() {
        audioplayer.audio.object.pause();

        // set default document title

        audioplayer.elements.buttons.pause.style.display = "none";
        audioplayer.elements.buttons.play.style.display = "inline-bloc";
    },
    stop: function() {
        audioplayer.audio.object.currentTime = 0;
        audioplayer.elements.timeline.input.style.marginLeft = "0px";
    },
    nextSong: function() {
        var active = parseInt(document.querySelector("#songs .active").getAttribute("data-num"));
        var totalSongs = parseInt(document.querySelectorAll("#songs [data-type='audio']").length);

        // $loadOn = $totalSongs - $loadAfter;

        if (active < totalSongs) {
            var next = document.querySelector("#songs [data-num='" + (active + 1) + "']");
            audioplayer.newSong(next);

            // load more songs via ajax

        } else {
            swal({
                title:'Siguiente canción no disponible',
                text:'No hay mas canciones que reproducir',
                type:'info',
                showConfirmButton: false,
                timer: audioplayer.config.swalTimer
            });
        }
    },
    previousSong: function() {
        var active = parseInt(document.querySelector("#songs .active").getAttribute("data-num"));

        if (active > 0) {
            var previous = document.querySelector("#songs [data-num='" + (active - 1)  + "']");

            audioplayer.newSong(previous);

        } else {
            swal({
                title: '¡Canción anterior no disponible!',
                text: 'No hay ninguna cancion anterior a la actual',
                type: 'error',
                showConfirmButton: false,
                timer: audioplayer.config.swalTimer
            });
        }
    },
    repeat: function(repeat) {
        var mode = repeat.attr("data-mode");
        var button;

        repeat.style.display = "none";

        switch (mode) {
            case "none":
                mode = "all";
                button = audioplayer.elements.buttons.repeatAll;
                break;
            case "all":
                mode = "one";
                button = audioplayer.elements.buttons.repeatOne;
                break;
            case "one":
                mode = "none";
                button = audioplayer.elements.buttons.repeatNone;
                break;
        }

        audioplayer.audio.repeat = mode;
        button.style.display = "inline-block";
    },
    volumeUp: function() {
        if (audioplayer.audio.volume < 1) {
            var newVolume = Math.round((audioplayer.audio.volume + 0.02) * 100) / 100;

            audioplayer.audio.object.volume = newVolume;
            audioplayer.audio.volume = newVolume;

            audioplayer.elements.buttons.volumeIndicator.setAttribute("data-volume", Math.ceil(audioplayer.audio.volume * 100));

            if (audioplayer.audio.volume >= audioplayer.audio.volumeUpValue && audioplayer.audio.muted == false) {
                audioplayer.elements.buttons.volumeUp.style.display = "inline-block";
                audioplayer.elements.buttons.volumeDown.style.display = "none";

            } else if (audioplayer.audio.volume < audioplayer.audio.volumeUpValue && audioplayer.audio.muted == false) {
                audioplayer.elements.buttons.volumeDown.style.display = "inline-block";
                audioplayer.elements.buttons.volumeUp.style.display = "none";
            }

            localStorage.audioVolume = audioplayer.audio.volume * 100;
        }
    },
    volumeDown: function() {
        if (audioplayer.audio.volume > 0) {
            var newVolume = Math.round((audioplayer.audio.volume - 0.02) * 100) / 100;

            audioplayer.audio.object.volume = newVolume;
            audioplayer.audio.volume = newVolume;

            audioplayer.elements.buttons.volumeIndicator.setAttribute("data-volume", Math.ceil(audioplayer.audio.volume * 100));

            if (audioplayer.audio.volume >= audioplayer.audio.volumeUpValue && audioplayer.audio.muted == false) {
                audioplayer.elements.buttons.volumeUp.style.display = "inline-block";
                audioplayer.elements.buttons.volumeDown.style.display = "none";

            } else if (audioplayer.audio.volume < audioplayer.audio.volumeUpValue && audioplayer.audio.muted == false) {
                audioplayer.elements.buttons.volumeDown.style.display = "inline-block";
                audioplayer.elements.buttons.volumeUp.style.display = "none";
            }

            localStorage.audioVolume = audioplayer.audio.volume * 100;
        }
    },
    volumeMute: function() {
        if (!audioplayer.audio.muted) {
            audioplayer.audio.object.muted = true;
            audioplayer.audio.muted = true;

            audioplayer.elements.buttons.volumeUp.style.display = "none";
            audioplayer.elements.buttons.volumeDown.style.display = "none";
            audioplayer.elements.buttons.volumeMute.style.display = "inline-block";

        } else {
            audioplayer.audio.object.muted = false;
            audioplayer.audio.muted = false;

            audioplayer.elements.buttons.volumeMute.style.display = "none";

            if (audioplayer.audio.volume > audioplayer.audio.volumeUpValue) {
                audioplayer.elements.buttons.volumeUp.style.display = "inline-block";
            } else {
                audioplayer.elements.buttons.volumeDown.style.display = "inline-block";
            }
        }
    },
    onended: function() {
        audioplayer.stop();

        switch (audioplayer.audio.repeat) {
            case "all":
                audioplayer.nextSong();
                break;
            case "one":

        }
    },
    timeUpdate: function() {
        var percent = (audioplayer.audio.object.currentTime / audioplayer.audio.object.duration) * 100;
        audioplayer.elements.timeline.input.style.left = "calc(" + percent + "% - 5px)";

        var curTime = Math.round(audioplayer.audio.object.currentTime);

        var curMin = 0;
        var curSec = 0;

        if (curTime < 60) {
            curSec = curTime;
        } else {
            curMin = Math.floor(curTime / 60);
            curSec = curTime - curMin * 60;
        }

        if (curMin < 10) {
            curMin = "0" + curMin;
        }
        if (curSec < 10) {
            curSec = "0" + curSec;
        }

        audioplayer.elements.timeline.played.innerHTML = curMin + ":" + curSec;

    },

    log: function(txt) {
        console.info(audioplayer.name + " v" + audioplayer.version + ": " + txt);
    }
};

// audioplayer HTML elements
function initVariables() {
    audioplayer.elements = {};

    audioplayer.elements.player = document.getElementById("audioplayer");
    audioplayer.elements.title = audioplayer.elements.player.getElementsByClassName("title")[0];
    audioplayer.elements.artist = audioplayer.elements.player.getElementsByClassName("artist")[0].getElementsByClassName("content")[0];
    audioplayer.elements.album = audioplayer.elements.player.getElementsByClassName("album")[0].getElementsByClassName("content")[0];
    audioplayer.elements.cover = audioplayer.elements.player.getElementsByTagName("img")[0];

    audioplayer.elements.buttons = {};

    audioplayer.elements.buttons.play = audioplayer.elements.player.querySelector("[name='play']");
    audioplayer.elements.buttons.pause = audioplayer.elements.player.querySelector("[name='pause']");

    audioplayer.elements.buttons.stop = audioplayer.elements.player.querySelector("[name='stop']");

    audioplayer.elements.buttons.previousSong = audioplayer.elements.player.querySelector("[name='before']");
    audioplayer.elements.buttons.nextSong = audioplayer.elements.player.querySelector("[name='after']");

    audioplayer.elements.buttons.repeat = audioplayer.elements.player.querySelector("[name='repeat']");
    audioplayer.elements.buttons.repeatNone = audioplayer.elements.player.querySelector("[name='repeat'][data-mode='none']");
    audioplayer.elements.buttons.repeatAll = audioplayer.elements.player.querySelector("[name='repeat'][data-mode='all']");
    audioplayer.elements.buttons.repeatOne = audioplayer.elements.player.querySelector("[name='repeat'][data-mode='one']");

    audioplayer.elements.buttons.volumeIndicator = audioplayer.elements.player.querySelector("[name='volume']");
    audioplayer.elements.buttons.volumeUp = audioplayer.elements.player.querySelector("[name='volume'][data-mode='up']");
    audioplayer.elements.buttons.volumeDown = audioplayer.elements.player.querySelector("[name='volume'][data-mode='down']");
    audioplayer.elements.buttons.volumeMute = audioplayer.elements.player.querySelector("[name='volume'][data-mode='mute']");

    audioplayer.elements.timeline = {};

    audioplayer.elements.timeline.timeline = audioplayer.elements.player.getElementsByClassName("range")[0];
    audioplayer.elements.timeline.input = audioplayer.elements.player.getElementsByClassName("input")[0];
    audioplayer.elements.timeline.played = audioplayer.elements.player.getElementsByClassName("begin")[0];
    audioplayer.elements.timeline.total = audioplayer.elements.player.getElementsByClassName("end")[0];

    audioplayer.log("Variabled loaded");
}

// audio objects & properties
function initObject() {
     audioplayer.audio = {};

     audioplayer.audio.object = new Audio();

     audioplayer.audio.currentTime = audioplayer.audio.object.currentTime;
     audioplayer.audio.volume = 1;
     audioplayer.audio.repeat = "none";
     audioplayer.audio.muted = false;
     audioplayer.audio.volumeUpValue = 0.5;

     audioplayer.config = {};

     audioplayer.config.moreSongs = true;
     audioplayer.config.folder = "/";
     audioplayer.config.loadAfter = 30;
     audioplayer.config.swalTimer = 1500;
     audioplayer.config.scrollAnimationDuration = 500;
     audioplayer.config.scrollEnabled = true;

     audioplayer.log("Object and Properties loaded");
}

// load data from localStorage
function loadFromLocalStorage() {
    var lsAudioVolume = localStorage.audioVolume;
    if (typeof lsAudioVolume == "undefined") {
        localStorage.audioVolume = audioplayer.audio.volume * 100;
    } else {
        audioplayer.audio.volume = parseInt(lsAudioVolume) / 100;
    }
    audioplayer.elements.buttons.volumeIndicator.setAttribute("data-volume", Math.floor(audioplayer.audio.volume * 100));

    var lsAudioRepeat = localStorage.audioRepeat;
    if (typeof lsAudioRepeat == "undefined") {
        localStorage.audioRepeat = audioplayer.audio.repeat;
    } else {
        audioplayer.audio.repeat = lsAudioRepeat;
    }

    audioplayer.elements.buttons.repeat.style.display = "none";

    switch(audioplayer.audio.repeat) {
        case "all":
            audioplayer.elements.buttons.repeatAll.style.display = "inline-block";
            break;
        case "one":
            audioplayer.elements.buttons.repeatOne.style.display = "inline-block";
            break;
        case "none":
            audioplayer.elements.buttons.repeaNone.style.display = "inline-block";
            break;
    }
}

var hotKeys;
require("electron").ipcRenderer.on("keyPress", (event, action) => {

    hotKeys(action);

});
<commit_msg>small bug fix<commit_after>document.addEventListener("DOMContentLoaded", function() {
    initVariables();
    initObject();

    loadFromLocalStorage();
});

var audioplayer = {
    version: "0.0.2",
    name: "Audioplayer",

    newSong: function(aElement) {
        audioplayer.stop();

        try {
            document.querySelector("[data-type='audio'].active").className = document.querySelector("[data-type='audio'].active").className.replace("active", "");
        } catch (error) {
            // no element was active
        }
        aElement.className += "active";

        // get song info
        var path = aElement.getAttribute("data-path");
        var title = aElement.getElementsByClassName("title")[0];
        var artist = aElement.getElementsByClassName("artist")[0];
        var album = aElement.getElementsByClassName("album")[0];
        var duration = aElement.getElementsByClassName("duration")[0];
        var coverImage = aElement.getElementsByTagName("img")[0].getAttribute("src");

        // set new info
        audioplayer.elements.title.innerHTML = title.innerHTML;

        if (typeof artist != "undefined") {
            audioplayer.elements.artist.innerHTML = artist.innerHTML;
        } else {
            audioplayer.elements.artist.innerHTML = null;
        }

        if (typeof album != "undefined") {
            audioplayer.elements.album.innerHTML = album.innerHTML;
        } else {
            audioplayer.elements.album.innerHTML = null;
        }

        audioplayer.elements.cover.setAttribute("src", coverImage);
        audioplayer.elements.timeline.total.innerHTML = duration.innerHTML;

        // test if browser supports audio format
        var extSplit = path.split(".");
        var format = extSplit[extSplit.length - 1];

        if (!! audioplayer.audio.object.canPlayType("audio/" + format) === false) {

            swal("Formato no soportado", "No es posible reproducir la cancion, tu navegador no soporta el formato " + format.toUpperCase(), "error");

        } else {
            // start new object
            audioplayer.audio.object = new Audio(path);
            audioplayer.play();

            audioplayer.audio.object.addEventListener("timeupdate", audioplayer.timeUpdate, false);
        }

    },
    play: function() {
        audioplayer.audio.object.volume = audioplayer.audio.volume;
        audioplayer.audio.object.muted = audioplayer.audio.muted;

        audioplayer.audio.object.play();
        //audioplayer.audio.object.onended = audioplayer.onended();

        // update document title
        // update doument icon

        // scroll to active song

        audioplayer.elements.buttons.play.style.display = "none";
        audioplayer.elements.buttons.pause.style.display = "inline-block";

    },
    pause: function() {
        audioplayer.audio.object.pause();

        // set default document title

        audioplayer.elements.buttons.pause.style.display = "none";
        audioplayer.elements.buttons.play.style.display = "inline-bloc";
    },
    stop: function() {
        audioplayer.pause();
        audioplayer.audio.object.currentTime = 0;
        audioplayer.elements.timeline.input.style.marginLeft = "0px";
    },
    nextSong: function() {
        var active = parseInt(document.querySelector("#songs .active").getAttribute("data-num"));
        var totalSongs = parseInt(document.querySelectorAll("#songs [data-type='audio']").length);

        // $loadOn = $totalSongs - $loadAfter;

        if (active < totalSongs) {
            var next = document.querySelector("#songs [data-num='" + (active + 1) + "']");
            audioplayer.newSong(next);

            // load more songs via ajax

        } else {
            swal({
                title:'Siguiente canción no disponible',
                text:'No hay mas canciones que reproducir',
                type:'info',
                showConfirmButton: false,
                timer: audioplayer.config.swalTimer
            });
        }
    },
    previousSong: function() {
        var active = parseInt(document.querySelector("#songs .active").getAttribute("data-num"));

        if (active > 0) {
            var previous = document.querySelector("#songs [data-num='" + (active - 1)  + "']");

            audioplayer.newSong(previous);

        } else {
            swal({
                title: '¡Canción anterior no disponible!',
                text: 'No hay ninguna cancion anterior a la actual',
                type: 'error',
                showConfirmButton: false,
                timer: audioplayer.config.swalTimer
            });
        }
    },
    repeat: function(repeat) {
        var mode = repeat.attr("data-mode");
        var button;

        repeat.style.display = "none";

        switch (mode) {
            case "none":
                mode = "all";
                button = audioplayer.elements.buttons.repeatAll;
                break;
            case "all":
                mode = "one";
                button = audioplayer.elements.buttons.repeatOne;
                break;
            case "one":
                mode = "none";
                button = audioplayer.elements.buttons.repeatNone;
                break;
        }

        audioplayer.audio.repeat = mode;
        button.style.display = "inline-block";
    },
    volumeUp: function() {
        if (audioplayer.audio.volume < 1) {
            var newVolume = Math.round((audioplayer.audio.volume + 0.02) * 100) / 100;

            audioplayer.audio.object.volume = newVolume;
            audioplayer.audio.volume = newVolume;

            audioplayer.elements.buttons.volumeIndicator.setAttribute("data-volume", Math.ceil(audioplayer.audio.volume * 100));

            if (audioplayer.audio.volume >= audioplayer.audio.volumeUpValue && audioplayer.audio.muted == false) {
                audioplayer.elements.buttons.volumeUp.style.display = "inline-block";
                audioplayer.elements.buttons.volumeDown.style.display = "none";

            } else if (audioplayer.audio.volume < audioplayer.audio.volumeUpValue && audioplayer.audio.muted == false) {
                audioplayer.elements.buttons.volumeDown.style.display = "inline-block";
                audioplayer.elements.buttons.volumeUp.style.display = "none";
            }

            localStorage.audioVolume = audioplayer.audio.volume * 100;
        }
    },
    volumeDown: function() {
        if (audioplayer.audio.volume > 0) {
            var newVolume = Math.round((audioplayer.audio.volume - 0.02) * 100) / 100;

            audioplayer.audio.object.volume = newVolume;
            audioplayer.audio.volume = newVolume;

            audioplayer.elements.buttons.volumeIndicator.setAttribute("data-volume", Math.ceil(audioplayer.audio.volume * 100));

            if (audioplayer.audio.volume >= audioplayer.audio.volumeUpValue && audioplayer.audio.muted == false) {
                audioplayer.elements.buttons.volumeUp.style.display = "inline-block";
                audioplayer.elements.buttons.volumeDown.style.display = "none";

            } else if (audioplayer.audio.volume < audioplayer.audio.volumeUpValue && audioplayer.audio.muted == false) {
                audioplayer.elements.buttons.volumeDown.style.display = "inline-block";
                audioplayer.elements.buttons.volumeUp.style.display = "none";
            }

            localStorage.audioVolume = audioplayer.audio.volume * 100;
        }
    },
    volumeMute: function() {
        if (!audioplayer.audio.muted) {
            audioplayer.audio.object.muted = true;
            audioplayer.audio.muted = true;

            audioplayer.elements.buttons.volumeUp.style.display = "none";
            audioplayer.elements.buttons.volumeDown.style.display = "none";
            audioplayer.elements.buttons.volumeMute.style.display = "inline-block";

        } else {
            audioplayer.audio.object.muted = false;
            audioplayer.audio.muted = false;

            audioplayer.elements.buttons.volumeMute.style.display = "none";

            if (audioplayer.audio.volume > audioplayer.audio.volumeUpValue) {
                audioplayer.elements.buttons.volumeUp.style.display = "inline-block";
            } else {
                audioplayer.elements.buttons.volumeDown.style.display = "inline-block";
            }
        }
    },
    onended: function() {
        audioplayer.stop();

        switch (audioplayer.audio.repeat) {
            case "all":
                audioplayer.nextSong();
                break;
            case "one":

        }
    },
    timeUpdate: function() {
        var percent = (audioplayer.audio.object.currentTime / audioplayer.audio.object.duration) * 100;
        audioplayer.elements.timeline.input.style.left = "calc(" + percent + "% - 5px)";

        var curTime = Math.round(audioplayer.audio.object.currentTime);

        var curMin = 0;
        var curSec = 0;

        if (curTime < 60) {
            curSec = curTime;
        } else {
            curMin = Math.floor(curTime / 60);
            curSec = curTime - curMin * 60;
        }

        if (curMin < 10) {
            curMin = "0" + curMin;
        }
        if (curSec < 10) {
            curSec = "0" + curSec;
        }

        audioplayer.elements.timeline.played.innerHTML = curMin + ":" + curSec;
    },

    log: function(txt) {
        console.info(audioplayer.name + " v" + audioplayer.version + ": " + txt);
    }
};

// audioplayer HTML elements
function initVariables() {
    audioplayer.elements = {};

    audioplayer.elements.player = document.getElementById("audioplayer");
    audioplayer.elements.title = audioplayer.elements.player.getElementsByClassName("title")[0];
    audioplayer.elements.artist = audioplayer.elements.player.getElementsByClassName("artist")[0].getElementsByClassName("content")[0];
    audioplayer.elements.album = audioplayer.elements.player.getElementsByClassName("album")[0].getElementsByClassName("content")[0];
    audioplayer.elements.cover = audioplayer.elements.player.getElementsByTagName("img")[0];

    audioplayer.elements.buttons = {};

    audioplayer.elements.buttons.play = audioplayer.elements.player.querySelector("[name='play']");
    audioplayer.elements.buttons.pause = audioplayer.elements.player.querySelector("[name='pause']");

    audioplayer.elements.buttons.stop = audioplayer.elements.player.querySelector("[name='stop']");

    audioplayer.elements.buttons.previousSong = audioplayer.elements.player.querySelector("[name='before']");
    audioplayer.elements.buttons.nextSong = audioplayer.elements.player.querySelector("[name='after']");

    audioplayer.elements.buttons.repeat = audioplayer.elements.player.querySelector("[name='repeat']");
    audioplayer.elements.buttons.repeatNone = audioplayer.elements.player.querySelector("[name='repeat'][data-mode='none']");
    audioplayer.elements.buttons.repeatAll = audioplayer.elements.player.querySelector("[name='repeat'][data-mode='all']");
    audioplayer.elements.buttons.repeatOne = audioplayer.elements.player.querySelector("[name='repeat'][data-mode='one']");

    audioplayer.elements.buttons.volumeIndicator = audioplayer.elements.player.querySelector("[name='volume']");
    audioplayer.elements.buttons.volumeUp = audioplayer.elements.player.querySelector("[name='volume'][data-mode='up']");
    audioplayer.elements.buttons.volumeDown = audioplayer.elements.player.querySelector("[name='volume'][data-mode='down']");
    audioplayer.elements.buttons.volumeMute = audioplayer.elements.player.querySelector("[name='volume'][data-mode='mute']");

    audioplayer.elements.timeline = {};

    audioplayer.elements.timeline.timeline = audioplayer.elements.player.getElementsByClassName("range")[0];
    audioplayer.elements.timeline.input = audioplayer.elements.player.getElementsByClassName("input")[0];
    audioplayer.elements.timeline.played = audioplayer.elements.player.getElementsByClassName("begin")[0];
    audioplayer.elements.timeline.total = audioplayer.elements.player.getElementsByClassName("end")[0];

    audioplayer.log("Variabled loaded");
}

// audio objects & properties
function initObject() {
     audioplayer.audio = {};

     audioplayer.audio.object = new Audio();

     audioplayer.audio.currentTime = audioplayer.audio.object.currentTime;
     audioplayer.audio.volume = 1;
     audioplayer.audio.repeat = "none";
     audioplayer.audio.muted = false;
     audioplayer.audio.volumeUpValue = 0.5;

     audioplayer.config = {};

     audioplayer.config.moreSongs = true;
     audioplayer.config.folder = "/";
     audioplayer.config.loadAfter = 30;
     audioplayer.config.swalTimer = 1500;
     audioplayer.config.scrollAnimationDuration = 500;
     audioplayer.config.scrollEnabled = true;

     audioplayer.log("Object and Properties loaded");
}

// load data from localStorage
function loadFromLocalStorage() {
    var lsAudioVolume = localStorage.audioVolume;
    if (typeof lsAudioVolume == "undefined") {
        localStorage.audioVolume = audioplayer.audio.volume * 100;
    } else {
        audioplayer.audio.volume = parseInt(lsAudioVolume) / 100;
    }
    audioplayer.elements.buttons.volumeIndicator.setAttribute("data-volume", Math.floor(audioplayer.audio.volume * 100));

    var lsAudioRepeat = localStorage.audioRepeat;
    if (typeof lsAudioRepeat == "undefined") {
        localStorage.audioRepeat = audioplayer.audio.repeat;
    } else {
        audioplayer.audio.repeat = lsAudioRepeat;
    }

    audioplayer.elements.buttons.repeat.style.display = "none";

    switch(audioplayer.audio.repeat) {
        case "all":
            audioplayer.elements.buttons.repeatAll.style.display = "inline-block";
            break;
        case "one":
            audioplayer.elements.buttons.repeatOne.style.display = "inline-block";
            break;
        case "none":
            audioplayer.elements.buttons.repeaNone.style.display = "inline-block";
            break;
    }
}

var hotKeys;
require("electron").ipcRenderer.on("keyPress", (event, action) => {

    hotKeys(action);

});
<|endoftext|>


<commit_before>"use strict";

let htmlparser = require("htmlparser2");
let mongoose = require("mongoose");
let net = require("../net");
let util = require("util");
let Command = require("./commands");

let DefaultPoints = [25, 18, 15, 12, 10, 8, 6, 4, 2, 1];

let SeasonSchema = new mongoose.Schema({
  _id: Number,

  /**
   * Drivers participating in this season.
   */
  drivers: [{
    _id: false,
    firstName: String,
    lastName: String,
    code: String,
    number: Number,
  }],

  teams: [{
    _id: false,
    name: String,
    code: String,
  }],

  /**
   * Points system used during the season.
   */
  points: {
    type: [Number],
    default: DefaultPoints
  }
});

SeasonSchema.virtual("year")
  .get(function() {
    return this._id;
  })
  .set(function(year) {
    this._id = year;
  });

SeasonSchema.statics.findCurrent = function() {
  return Promise.resolve(this.findOne({_id: (new Date).getFullYear()}));
};

SeasonSchema.statics.driversForNames = function(rawnames, year) {
  if (!year) {
    year = (new Date).getFullYear();
  }
  let names = rawnames.map(name => name.toLowerCase());
  return this.findOne({_id: year})
    .then(season => {
      return names.map(name => {
        for (let driver of season.drivers.values()) {
          if (driver.code.toLowerCase() == name) {
            return driver;
          }
          if (driver.lastName.substring(0, name.length).toLowerCase() == name) {
            return driver;
          }
        }
        throw new Error(util.format("No match found for '%s'", name));
      });
    });
};

class ErgastDriverParser {
  parse(json) {
    let data = JSON.parse(json).MRData.DriverTable;
    return {
      year: parseInt(data.season),
      drivers: data.Drivers.map(raw => ({
        number: parseInt(raw.permanentNumber),
        firstName: raw.givenName,
        lastName: raw.familyName,
        code: raw.code,
      })),
    };
  }
}

class ErgastTeamParser {
  parse(json) {
    let data = JSON.parse(json).MRData.ConstructorTable;
    return {
      year: parseInt(data.season),
      teams: data.Constructors.map(raw => ({
        name: raw.name,
        code: raw.constructorId,
      })),
    };
  }
}

class ErgastDownloader {
  constructor(config) {
    this.config = config;
  }

  download(year) {
    let p1 = net.download(this.url("drivers", year)).then(response => {
      return (new ErgastDriverParser).parse(response.data);
    });

    let p2 = net.download(this.url("constructors", year)).then(response => {
      return (new ErgastTeamParser).parse(response.data);
    });

    return Promise.all([p1, p2]).then(([doc1, doc2]) => {
      doc1.teams = doc2.teams;
      return doc1;
    });
  }

  url(resource, year) {
    if (!year) {
      year = (new Date).getFullYear();
    }
    return util.format("%s/%d/%s.json", this.config.get("modules.shared.ergast.url"), year, resource);
  }
}

exports.configure = services => {
  let database = services.get("database");
  let Season = database.model("season", SeasonSchema);

  services.registerFactory("seasondata.downloader", () => {
    return new ErgastDownloader(services.get("config"));
  });

  services.get("command.manager").add("rs", Command.ALLOW_WHITELIST, command => {
    let downloader = services.get("seasondata.downloader");
    return downloader.download(command.params[0]).then(data => {
      let season = new Season(data);
      return Season.update({_id: season.year}, season.toObject(), {upsert: true}).then(() => "OK");
    });
  });
};
<commit_msg>Error reporting on season reload<commit_after>"use strict";

let htmlparser = require("htmlparser2");
let mongoose = require("mongoose");
let net = require("../net");
let util = require("util");
let Command = require("./commands");

let DefaultPoints = [25, 18, 15, 12, 10, 8, 6, 4, 2, 1];

let SeasonSchema = new mongoose.Schema({
  _id: Number,

  /**
   * Drivers participating in this season.
   */
  drivers: [{
    _id: false,
    firstName: String,
    lastName: String,
    code: String,
    number: Number,
  }],

  teams: [{
    _id: false,
    name: String,
    code: String,
  }],

  /**
   * Points system used during the season.
   */
  points: {
    type: [Number],
    default: DefaultPoints
  }
});

SeasonSchema.virtual("year")
  .get(function() {
    return this._id;
  })
  .set(function(year) {
    this._id = year;
  });

SeasonSchema.statics.findCurrent = function() {
  return Promise.resolve(this.findOne({_id: (new Date).getFullYear()}));
};

SeasonSchema.statics.driversForNames = function(rawnames, year) {
  if (!year) {
    year = (new Date).getFullYear();
  }
  let names = rawnames.map(name => name.toLowerCase());
  return this.findOne({_id: year})
    .then(season => {
      return names.map(name => {
        for (let driver of season.drivers.values()) {
          if (driver.code.toLowerCase() == name) {
            return driver;
          }
          if (driver.lastName.substring(0, name.length).toLowerCase() == name) {
            return driver;
          }
        }
        throw new Error(util.format("No match found for '%s'", name));
      });
    });
};

class ErgastDriverParser {
  parse(json) {
    let data = JSON.parse(json).MRData.DriverTable;
    return {
      year: parseInt(data.season),
      drivers: data.Drivers.map(raw => ({
        number: parseInt(raw.permanentNumber),
        firstName: raw.givenName,
        lastName: raw.familyName,
        code: raw.code,
      })),
    };
  }
}

class ErgastTeamParser {
  parse(json) {
    let data = JSON.parse(json).MRData.ConstructorTable;
    return {
      year: parseInt(data.season),
      teams: data.Constructors.map(raw => ({
        name: raw.name,
        code: raw.constructorId,
      })),
    };
  }
}

class ErgastDownloader {
  constructor(config) {
    this.config = config;
  }

  download(year) {
    let p1 = net.download(this.url("drivers", year)).then(response => {
      return (new ErgastDriverParser).parse(response.data);
    });

    let p2 = net.download(this.url("constructors", year)).then(response => {
      return (new ErgastTeamParser).parse(response.data);
    });

    return Promise.all([p1, p2]).then(([doc1, doc2]) => {
      doc1.teams = doc2.teams;
      return doc1;
    });
  }

  url(resource, year) {
    if (!year) {
      year = (new Date).getFullYear();
    }
    return util.format("%s/%d/%s.json", this.config.get("modules.shared.ergast.url"), year, resource);
  }
}

exports.configure = services => {
  let database = services.get("database");
  let Season = database.model("season", SeasonSchema);

  services.registerFactory("seasondata.downloader", () => {
    return new ErgastDownloader(services.get("config"));
  });

  services.get("command.manager").add("rs", Command.ALLOW_WHITELIST, command => {
    let downloader = services.get("seasondata.downloader");
    return downloader.download(command.params[0]).then(data => {
      let season = new Season(data);
      return Season.update({_id: season.year}, season.toObject(), {upsert: true}).then(
        () => "OK",
        error => new Error("Failed to reload season")
      );
    });
  });
};
<|endoftext|>


<commit_before>// Copyright 2011 Marcel Laverdet (code partially borrowed from original streamline fibers runtime)
"use strict";

var Fiber = require('fibers');
var util = require('../util');
var frameModule = require('../frame');

var g = util.getGlobals('fibers');

var keys = [];

function applyFast(fn, that, args) {
	switch (args.length) {
		case 1: return fn.call(that, args[0]);
		case 2: return fn.call(that, args[0], args[1]);
		case 3: return fn.call(that, args[0], args[1], args[2]);
		case 4: return fn.call(that, args[0], args[1], args[2], args[3]);
		default: return fn.apply(that, args);
	}
}

exports.await = function (file, line, object, property, index1, index2, returnArray, args) {
	var bound = typeof property !== "function";
	var fn = bound ? object[property] : property;
	if (typeof fn !== "function") throw util.typeError("cannot call", "function", fn);
	var key = '', wrapper;
	if (index2 == null && !returnArray) {
		key = keys[index1] || (keys[index1] = 'fiberized-' + index1);
		wrapper = fn[key];
		if (!wrapper && bound) {
			// second chance for foo.call(bar, _, ...). Optimize if bar.foo['fiberized-0'] exists
			if ((property === 'call') && index1 > 0 && typeof object === 'function') {
				var key2 = keys[index1 - 1] || (keys[index1 - 1] = 'fiberized-' + (index1 - 1));
				var fn2 = object[key2];
				if (fn2 && fn2[property]) {
					object = fn2;
					wrapper = fn2[property];
				}
			}
		}
		if (wrapper) {
			if (g.emitter) wrapper = frameModule.wrap(file, line, wrapper);
			// streamline < 2.0 does not pass args - return wrapper in this case
			if (Array.isArray(args)) return applyFast(wrapper, object, args);
			else return bound ? wrapper.bind(object) : wrapper;
		}
	}
	return awaitSlow(file, line, object, property, index1, index2, returnArray, args, bound, fn, key);
};

function awaitSlow(file, line, object, property, index1, index2, returnArray, args, bound, fn, key) {
	var that = bound ? object : this;

	var wrapper = function () {
		var args = Array.prototype.slice.call(arguments),
			arg = args[index1];
		if (typeof arg !== 'boolean') throw util.argError(fn.name, index1, 'boolean', arg);

		var fiber = Fiber.current;
		var err, val, yielded = false;
		var callback = function (e, v) {
			if (returnArray && !e) {
				v = Array.prototype.slice.call(arguments, 1);
			}
			if (!yielded) {
				yielded = true;
				err = e;
				val = v;
			} else {
				var context = g.context;
				var frame = g.frame;
				try {
					if (e) {
						fiber.throwInto(e);
					} else {
						fiber.run(v);
					}
				} finally {
					g.context = context;
					g.frame = frame;
					// reset all local variables to avoid memory leak
					context = null;
					frame = null;
				}
			}
		};
		if (index2 != null) {
			args[index1] = function (r) {
				callback(null, r);
			}
			args[index2] = function (e) {
				callback(e);
			}
		} else {
			args[index1] = callback;
		}

		// Invoke the function and yield
		var frame = g.emitter && frameModule.pushFrame(file, line, fn.name);
		applyFast(fn, that, args);

		if (yielded) {
			if (frame) frame.pop();
			if (err) throw wrapError(err);
			return val;
		}
		yielded = true;

		var cx = g.context;
		try {
			if (frame) frame.yield();
			return Fiber.yield();
		} catch (e) {
			throw wrapError(e);
		} finally {
			g.context = cx;
			g.frame = frame;
			if (frame) {
				frame.resume();
				frame.pop();
			}
			cx = null;
			frame = null;
		}

	}

	if (!bound && key) {
		fn[key] = wrapper;
	}
	return Array.isArray(args) ? applyFast(wrapper, object, args) : wrapper;
};

function arityWrapper(template) {
	var body = template.toString();
	body = body.substring(body.indexOf('{'));
	var cache = [];
	function makeArgs(i) {
		if (i <= 0) return "";
		return i > 1 ? makeArgs(i - 1) + ', a' + i : "a1";
	}
	function makeTransform(i) {
		/* enable this when we switch to node 4.x
		return function(fn, index) {
			var f = template(fn, index);
			Object.defineProperty(f, "length", {
				value: i,
			});
			return f;
		}*/
		return eval("(function wrapper(fn, index)" + body.replace(/function\s*wrapper\(\)/, "function wrapper(" + makeArgs(i) + ")") + ")");
	}
	return function (i) {
		return cache[i] || (cache[i] = makeTransform(i));
	}
}

var asyncTemplate = arityWrapper(function (fn, index) {
	var wrapper = function wrapper() {
		var that = this;
		var args = Array.prototype.slice.call(arguments);
		var cb = args[index];
		if (typeof cb !== "function") {
			if (g.allowBooleanPlaceholders && typeof cb === 'boolean') {
				if (cb) cb = util.defaultCallback;
				else return exports.future("", 0, null, wrapper.bind(this), index)(args);
			}
			else throw util.argError(fn.name, index, "function", typeof cb);
		}
		// Start a new fiber
		var cx = g.context;
		var frame = g.frame;
		Fiber(function __streamline$run() {
			// copy variables from outer scope into locals and reset them
			// this avoids a serious memory leak.
			var largs = args;
			args = null;
			var lcb = cb;
			cb = null;
			var lthat = that;
			that = null;

			var val, err = null;
			g.context = cx;
			cx = null;
			try {
				val = applyFast(fn, lthat, largs);
			} catch (e) {
				err = e;
			} finally {
				lcb(err, val);
			}
		}).run();
		g.frame = frame;
	}
	wrapper['fiberized-' + index] = fn;
	return wrapper;
});

exports.async = function (fn, index, arity) {
	if (typeof fn !== "function") throw util.typeError("cannot wrap function", "function", fn);
	return asyncTemplate(arity)(fn, index);
}

exports.new = function (file, line, constructor, index) {
	if (typeof constructor !== "function") throw util.typeError("cannot instantiate", "function", constructor);
	return function () {
		var that = Object.create(constructor.prototype);
		arguments[index] = true;
		applyFast(exports.await(file, line, null, constructor, index, null, false), that, arguments);
		return that;
	};
}

function wrapError(e) {
	if (!(e instanceof Error)) return e;
	var extra = { message: "__streamline$extra" };
	Error.captureStackTrace(extra);
	var ne = Object.create(e);
	Object.defineProperty(ne, 'stack', {
		get: function () {
			return (e.stack + (extra ? extra.stack : "")).split('\n').filter(function (frame) {
				return !/\bstreamline-runtime.lib\b/.test(frame) &&
					frame.indexOf('__streamline$') < 0;
			}).join('\n');
		},
		enumerable: true,
	});
	return ne;
}

exports.future = require('../future');
require('./builtins');

Function.prototype.apply_['fiberized-0'] = function (dummy, thisObj, args, index) {
	if (this['fiberized-0']) {
		args = Array.prototype.slice.call(args, 0);
		args.splice(index != null && index >= 0 ? index : args.length, 0, dummy);
		return applyFast(this['fiberized-0'], thisObj, args);
	} else {
		return Function.prototype.apply_.call(this, dummy, thisObj, args, index);
	}
}<commit_msg>fixed Sage/f-promise#4 - context restore bug<commit_after>// Copyright 2011 Marcel Laverdet (code partially borrowed from original streamline fibers runtime)
"use strict";

var Fiber = require('fibers');
var util = require('../util');
var frameModule = require('../frame');

var g = util.getGlobals('fibers');

var keys = [];

function applyFast(fn, that, args) {
	switch (args.length) {
		case 1: return fn.call(that, args[0]);
		case 2: return fn.call(that, args[0], args[1]);
		case 3: return fn.call(that, args[0], args[1], args[2]);
		case 4: return fn.call(that, args[0], args[1], args[2], args[3]);
		default: return fn.apply(that, args);
	}
}

exports.await = function (file, line, object, property, index1, index2, returnArray, args) {
	var bound = typeof property !== "function";
	var fn = bound ? object[property] : property;
	if (typeof fn !== "function") throw util.typeError("cannot call", "function", fn);
	var key = '', wrapper;
	if (index2 == null && !returnArray) {
		key = keys[index1] || (keys[index1] = 'fiberized-' + index1);
		wrapper = fn[key];
		if (!wrapper && bound) {
			// second chance for foo.call(bar, _, ...). Optimize if bar.foo['fiberized-0'] exists
			if ((property === 'call') && index1 > 0 && typeof object === 'function') {
				var key2 = keys[index1 - 1] || (keys[index1 - 1] = 'fiberized-' + (index1 - 1));
				var fn2 = object[key2];
				if (fn2 && fn2[property]) {
					object = fn2;
					wrapper = fn2[property];
				}
			}
		}
		if (wrapper) {
			if (g.emitter) wrapper = frameModule.wrap(file, line, wrapper);
			// streamline < 2.0 does not pass args - return wrapper in this case
			if (Array.isArray(args)) return applyFast(wrapper, object, args);
			else return bound ? wrapper.bind(object) : wrapper;
		}
	}
	return awaitSlow(file, line, object, property, index1, index2, returnArray, args, bound, fn, key);
};

function awaitSlow(file, line, object, property, index1, index2, returnArray, args, bound, fn, key) {
	var that = bound ? object : this;

	var wrapper = function () {
		var args = Array.prototype.slice.call(arguments),
			arg = args[index1];
		if (typeof arg !== 'boolean') throw util.argError(fn.name, index1, 'boolean', arg);

		var fiber = Fiber.current;
		var err, val, yielded = false;
		var callback = function (e, v) {
			if (returnArray && !e) {
				v = Array.prototype.slice.call(arguments, 1);
			}
			if (!yielded) {
				yielded = true;
				err = e;
				val = v;
			} else {
				var context = g.context;
				var frame = g.frame;
				try {
					if (e) {
						fiber.throwInto(e);
					} else {
						fiber.run(v);
					}
				} finally {
					g.context = context;
					g.frame = frame;
					// reset all local variables to avoid memory leak
					context = null;
					frame = null;
				}
			}
		};
		if (index2 != null) {
			args[index1] = function (r) {
				callback(null, r);
			}
			args[index2] = function (e) {
				callback(e);
			}
		} else {
			args[index1] = callback;
		}

		// Invoke the function and yield
		var frame = g.emitter && frameModule.pushFrame(file, line, fn.name);
		applyFast(fn, that, args);

		if (yielded) {
			if (frame) frame.pop();
			if (err) throw wrapError(err);
			return val;
		}
		yielded = true;

		var cx = g.context;
		try {
			if (frame) frame.yield();
			return Fiber.yield();
		} catch (e) {
			throw wrapError(e);
		} finally {
			g.context = cx;
			g.frame = frame;
			if (frame) {
				frame.resume();
				frame.pop();
			}
			cx = null;
			frame = null;
		}

	}

	if (!bound && key) {
		fn[key] = wrapper;
	}
	return Array.isArray(args) ? applyFast(wrapper, object, args) : wrapper;
};

function arityWrapper(template) {
	var body = template.toString();
	body = body.substring(body.indexOf('{'));
	var cache = [];
	function makeArgs(i) {
		if (i <= 0) return "";
		return i > 1 ? makeArgs(i - 1) + ', a' + i : "a1";
	}
	function makeTransform(i) {
		/* enable this when we switch to node 4.x
		return function(fn, index) {
			var f = template(fn, index);
			Object.defineProperty(f, "length", {
				value: i,
			});
			return f;
		}*/
		return eval("(function wrapper(fn, index)" + body.replace(/function\s*wrapper\(\)/, "function wrapper(" + makeArgs(i) + ")") + ")");
	}
	return function (i) {
		return cache[i] || (cache[i] = makeTransform(i));
	}
}

var asyncTemplate = arityWrapper(function (fn, index) {
	var wrapper = function wrapper() {
		var that = this;
		var args = Array.prototype.slice.call(arguments);
		var cb = args[index];
		if (typeof cb !== "function") {
			if (g.allowBooleanPlaceholders && typeof cb === 'boolean') {
				if (cb) cb = util.defaultCallback;
				else return exports.future("", 0, null, wrapper.bind(this), index)(args);
			}
			else throw util.argError(fn.name, index, "function", typeof cb);
		}
		// Start a new fiber
		var cx = g.context;
		var frame = g.frame;
		Fiber(function __streamline$run() {
			// copy variables from outer scope into locals and reset them
			// this avoids a serious memory leak.
			var largs = args;
			args = null;
			var lcb = cb;
			cb = null;
			var lthat = that;
			that = null;

			var val, err = null;
			try {
				val = applyFast(fn, lthat, largs);
			} catch (e) {
				err = e;
			} finally {
				lcb(err, val);
			}
		}).run();
		g.context = cx;
		g.frame = frame;
	}
	wrapper['fiberized-' + index] = fn;
	return wrapper;
});

exports.async = function (fn, index, arity) {
	if (typeof fn !== "function") throw util.typeError("cannot wrap function", "function", fn);
	return asyncTemplate(arity)(fn, index);
}

exports.new = function (file, line, constructor, index) {
	if (typeof constructor !== "function") throw util.typeError("cannot instantiate", "function", constructor);
	return function () {
		var that = Object.create(constructor.prototype);
		arguments[index] = true;
		applyFast(exports.await(file, line, null, constructor, index, null, false), that, arguments);
		return that;
	};
}

function wrapError(e) {
	if (!(e instanceof Error)) return e;
	var extra = { message: "__streamline$extra" };
	Error.captureStackTrace(extra);
	var ne = Object.create(e);
	Object.defineProperty(ne, 'stack', {
		get: function () {
			return (e.stack + (extra ? extra.stack : "")).split('\n').filter(function (frame) {
				return !/\bstreamline-runtime.lib\b/.test(frame) &&
					frame.indexOf('__streamline$') < 0;
			}).join('\n');
		},
		enumerable: true,
	});
	return ne;
}

exports.future = require('../future');
require('./builtins');

Function.prototype.apply_['fiberized-0'] = function (dummy, thisObj, args, index) {
	if (this['fiberized-0']) {
		args = Array.prototype.slice.call(args, 0);
		args.splice(index != null && index >= 0 ? index : args.length, 0, dummy);
		return applyFast(this['fiberized-0'], thisObj, args);
	} else {
		return Function.prototype.apply_.call(this, dummy, thisObj, args, index);
	}
}<|endoftext|>


<commit_before>var tape = require("tape"),
    jsdom = require("./jsdom"),
    d3_graphviz = require("../");

tape("logEvents(true) enables event logging.", function(test) {
    var window = global.window = jsdom('

');
    var document = global.document = window.document;
    var graphviz = d3_graphviz.graphviz("#graph");

    graphviz
        .zoom(false)
        .logEvents(true)
        .dot('digraph {a -> b;}')
        .render();

    test.end();
});
<commit_msg>Added check that the events are registered in logEvents test<commit_after>var tape = require("tape"),
    jsdom = require("./jsdom"),
    d3_graphviz = require("../");

tape("logEvents(true) enables event logging.", function(test) {
    var window = global.window = jsdom('

');
    var document = global.document = window.document;
    var graphviz = d3_graphviz.graphviz("#graph");

    graphviz
        .zoom(false)
        .logEvents(true)
        .dot('digraph {a -> b;}')
        .render();

    var eventTypes = graphviz._eventTypes;
    n = 0;
    for (let i in eventTypes) {
        let eventType = eventTypes[i];
        test.equal(typeof graphviz._dispatch.on(eventType + ".log"), 'function', "An event named " + eventType + ".log is registered when event logging is enabled");
        n += 1;
    }
    test.ok(n > 10, "More than 10 events are registered when event logging is enabled");
    test.equal(n, eventTypes.length, "All " + eventTypes.length + " events are registered when event logging is enabled");
    test.end();
});
<|endoftext|>


<commit_before>var util = require('util');
var h2frame = require('../frame');
var Http2Frame = h2frame.Http2Frame;

var TYPE_CODE = 0x04;

/******************
 * SETTINGS FRAME
 ******************/
var Http2SettingsFrame = module.exports = function (buf) {
    if (!(this instanceof Http2SettingsFrame)) {
        return new Http2SettigsFrame(buf);
    }
    if (buf) {
        this.buf = buf;
    } else {
        this.buf = new Buffer([0x00, 0x00, TYPE_CODE, 0x00, 0x00, 0x00, 0x00, 0x00]);
    }
};
util.inherits(Http2SettingsFrame, Http2Frame);
Object.defineProperty(Http2SettingsFrame, 'TYPE_CODE', {
    get: function () { return 0x04; },
});
Object.defineProperty(Http2SettingsFrame, 'FLAG_ACK', {
    get: function () { return 1; },
});
Object.defineProperty(Http2SettingsFrame, 'PARAM_SETTINGS_HEADER_TABLE_SIZE', {
    get: function () { return 1; },
});
Object.defineProperty(Http2SettingsFrame, 'PARAM_SETTINGS_ENABLE_PUSH', {
    get: function () { return 2; },
});
Object.defineProperty(Http2SettingsFrame, 'PARAM_SETTINGS_MAX_CONCURRENT_STREAMS', {
    get: function () { return 3; },
});
Object.defineProperty(Http2SettingsFrame, 'PARAM_SETTINGS_INITIAL_WINDOW_SIZE', {
    get: function () { return 4; },
});
Http2SettingsFrame.prototype.toString = function () {
    var str = Http2Frame.prototype.toString.call(this);
    var flags = [];
    var params = [], param;
    if (this.flags) {
        str += "\n";
        str += ' Flags: ';
        if (this.flags & Http2SettingsFrame.FLAG_ACK) {
            flags.push('ACK');
        }
        str += flags.join(' | ');
    }
    if (this.getParamCount()) {
        str += "\n";
        str += ' Params:\n';
        for (var i = 0; i < this.getParamCount(); i++) {
            param = this.getParamByIndex(i);
            if (param.id === Http2SettingsFrame.PARAM_SETTINGS_HEADER_TABLE_SIZE) {
                params.push('  SETTINGS_HEADER_TABLE_SIZE: ' + param.value);
            } else if (param.id === Http2SettingsFrame.PARAM_SETTINGS_ENABLE_PUSH) {
                params.push('  SETTINGS_ENABLE_PUSH: ' + param.value);
            } else if (param.id === Http2SettingsFrame.PARAM_SETTINGS_MAX_CONCURRENT_STREAMS) {
                params.push('  SETTINGS_MAX_CONCURRENT_STREAMS: ' + param.value);
            } else if (param.id === Http2SettingsFrame.PARAM_SETTINGS_INITIAL_WINDOW_SIZE) {
                params.push('  SETTINGS_INITIAL_WINDOW_SIZE: ' + param.value);
            } else {
                params.push('  ' + param.id + ': ' + param.value);
            }
        }
        str += params.join('\n');
    }
    return str;
};
Http2SettingsFrame.prototype.getParamCount = function () {
    return this.length / 6;
};
Http2SettingsFrame.prototype.getParamByIndex = function (index) {
    if (index >= this.getParamCount()) {
        return void(0);
    }
    return {
        id: this.buf.readUInt16BE(Http2Frame.HEADER_SIZE + 6 * index),
        value: this.buf.readUInt32BE(Http2Frame.HEADER_SIZE + 6 * index + 2)
    };
};
Http2SettingsFrame.prototype.getParamById = function (id) {
    var param, i, n = this.getParamCount();
    for (i = 0; i < n; i++) {
        param = this.getParamByIndex(i)
        if (param.id === id) {
            return param;
        }
    }
    return void(0);
};
Http2SettingsFrame.prototype.getParamIndexOf = function (id) {
    var param, i, n = this.getParamCount();
    for (i = 0; i < n; i++) {
        param = this.getParamByIndex(i)
        if (param.id === id) {
            return i;
        }
    }
    return void(0);
};
Http2SettingsFrame.prototype.setParam = function (id, value) {
    var index;
    if (typeof (index = this.getParamIndexOf(id)) !== 'undefined') {
        this.buf.writeUInt32BE(value, Http2Frame.HEADER_SIZE + 6 * index + 2);
    } else {
        var newBuf = new Buffer(6);
        newBuf.writeUInt16BE(id, 0);
        newBuf.writeUInt32BE(value, 2);
        this.buf = Buffer.concat([this.buf, newBuf], this.buf.length + 6);
        this.length += 6;
    }
};
<commit_msg>fix typo<commit_after>var util = require('util');
var h2frame = require('../frame');
var Http2Frame = h2frame.Http2Frame;

var TYPE_CODE = 0x04;

/******************
 * SETTINGS FRAME
 ******************/
var Http2SettingsFrame = module.exports = function (buf) {
    if (!(this instanceof Http2SettingsFrame)) {
        return new Http2SettingsFrame(buf);
    }
    if (buf) {
        this.buf = buf;
    } else {
        this.buf = new Buffer([0x00, 0x00, TYPE_CODE, 0x00, 0x00, 0x00, 0x00, 0x00]);
    }
};
util.inherits(Http2SettingsFrame, Http2Frame);
Object.defineProperty(Http2SettingsFrame, 'TYPE_CODE', {
    get: function () { return 0x04; },
});
Object.defineProperty(Http2SettingsFrame, 'FLAG_ACK', {
    get: function () { return 1; },
});
Object.defineProperty(Http2SettingsFrame, 'PARAM_SETTINGS_HEADER_TABLE_SIZE', {
    get: function () { return 1; },
});
Object.defineProperty(Http2SettingsFrame, 'PARAM_SETTINGS_ENABLE_PUSH', {
    get: function () { return 2; },
});
Object.defineProperty(Http2SettingsFrame, 'PARAM_SETTINGS_MAX_CONCURRENT_STREAMS', {
    get: function () { return 3; },
});
Object.defineProperty(Http2SettingsFrame, 'PARAM_SETTINGS_INITIAL_WINDOW_SIZE', {
    get: function () { return 4; },
});
Http2SettingsFrame.prototype.toString = function () {
    var str = Http2Frame.prototype.toString.call(this);
    var flags = [];
    var params = [], param;
    if (this.flags) {
        str += "\n";
        str += ' Flags: ';
        if (this.flags & Http2SettingsFrame.FLAG_ACK) {
            flags.push('ACK');
        }
        str += flags.join(' | ');
    }
    if (this.getParamCount()) {
        str += "\n";
        str += ' Params:\n';
        for (var i = 0; i < this.getParamCount(); i++) {
            param = this.getParamByIndex(i);
            if (param.id === Http2SettingsFrame.PARAM_SETTINGS_HEADER_TABLE_SIZE) {
                params.push('  SETTINGS_HEADER_TABLE_SIZE: ' + param.value);
            } else if (param.id === Http2SettingsFrame.PARAM_SETTINGS_ENABLE_PUSH) {
                params.push('  SETTINGS_ENABLE_PUSH: ' + param.value);
            } else if (param.id === Http2SettingsFrame.PARAM_SETTINGS_MAX_CONCURRENT_STREAMS) {
                params.push('  SETTINGS_MAX_CONCURRENT_STREAMS: ' + param.value);
            } else if (param.id === Http2SettingsFrame.PARAM_SETTINGS_INITIAL_WINDOW_SIZE) {
                params.push('  SETTINGS_INITIAL_WINDOW_SIZE: ' + param.value);
            } else {
                params.push('  ' + param.id + ': ' + param.value);
            }
        }
        str += params.join('\n');
    }
    return str;
};
Http2SettingsFrame.prototype.getParamCount = function () {
    return this.length / 6;
};
Http2SettingsFrame.prototype.getParamByIndex = function (index) {
    if (index >= this.getParamCount()) {
        return void(0);
    }
    return {
        id: this.buf.readUInt16BE(Http2Frame.HEADER_SIZE + 6 * index),
        value: this.buf.readUInt32BE(Http2Frame.HEADER_SIZE + 6 * index + 2)
    };
};
Http2SettingsFrame.prototype.getParamById = function (id) {
    var param, i, n = this.getParamCount();
    for (i = 0; i < n; i++) {
        param = this.getParamByIndex(i)
        if (param.id === id) {
            return param;
        }
    }
    return void(0);
};
Http2SettingsFrame.prototype.getParamIndexOf = function (id) {
    var param, i, n = this.getParamCount();
    for (i = 0; i < n; i++) {
        param = this.getParamByIndex(i)
        if (param.id === id) {
            return i;
        }
    }
    return void(0);
};
Http2SettingsFrame.prototype.setParam = function (id, value) {
    var index;
    if (typeof (index = this.getParamIndexOf(id)) !== 'undefined') {
        this.buf.writeUInt32BE(value, Http2Frame.HEADER_SIZE + 6 * index + 2);
    } else {
        var newBuf = new Buffer(6);
        newBuf.writeUInt16BE(id, 0);
        newBuf.writeUInt32BE(value, 2);
        this.buf = Buffer.concat([this.buf, newBuf], this.buf.length + 6);
        this.length += 6;
    }
};
<|endoftext|>


<commit_before>$(document).ready(function() {
    $.ajax({
        url: cmsCloudFlareURL,
        type: "GET",
        dataType: "html",
        timeout: 5000,
        success: function(data, status, xhr) {
            $('#data').fadeOut(200, function() {
                this.addClass('well');
                this.html(data);
                this.fadeIn(200);
            });
        },
        error: function(xhr, status, error) {
            $('#data').fadeOut(200, function() {
                this.html('
There was an error getting the data
');
                this.fadeIn(200);
            });
        }
    });
});
<commit_msg>Fixes<commit_after>$(document).ready(function() {
    $.ajax({
        url: cmsCloudFlareURL,
        type: "GET",
        dataType: "html",
        timeout: 5000,
        success: function(data, status, xhr) {
            var data = $('#data');
            data.fadeOut(200, function() {
                data.addClass('well');
                data.html(data);
                data.fadeIn(200);
            });
        },
        error: function(xhr, status, error) {
            var data = $('#data');
            data.fadeOut(200, function() {
                data.html('
There was an error getting the data
');
                data.fadeIn(200);
            });
        }
    });
});
<|endoftext|>


<commit_before>var express = require('express');
var site = require('./site');
const nunjucks = require('nunjucks');
var app = express();

nunjucks.configure('views', {
    autoescape: true,
    express: app
});
app.use(express.static('static'));
app.get('/', site.home);
app.get('/q/:smb', site.quote);
app.get('/c/:smb/:expiry', site.chains);
app.get('/ts/:smb', site.timesales);
app.listen(3000);
<commit_msg>use absolute path to sandbox<commit_after>var express = require('express');
var site = require('./site');
const nunjucks = require('nunjucks');
var app = express();

nunjucks.configure('views', {
    autoescape: true,
    express: app
});
app.use(express.static(__dirname + 'static'));

app.get('/', site.home);
app.get('/q/:smb', site.quote);
app.get('/c/:smb/:expiry', site.chains);
app.get('/ts/:smb', site.timesales);
app.listen(3000);
<|endoftext|>