<commit_before>var numberOfItemsToAdd = 100;
var Suites = [];

Suites.push({
    name: 'Vue',
    url: 'vue/index.html',
    version: '0.8.5',
    prepare: function (runner, contentWindow, contentDocument) {
        return runner.waitForElement('#new-todo').then(function (element) {
            element.focus();
            return element;
        });
    },
    tests: [
        new BenchmarkTestStep('Adding' + numberOfItemsToAdd + 'Items', function (newTodo, contentWindow, contentDocument) {
            var app = contentWindow.app;
            for (var i = 0; i < numberOfItemsToAdd; i++) {
                app.newTodo = 'Something to do ' + i;
                app.addTodo()
            }
        }),
        new BenchmarkTestStep('CompletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var checkboxes = contentDocument.querySelectorAll('.toggle');
            for (var i = 0; i < checkboxes.length; i++)
                checkboxes[i].click();
        }),
        new BenchmarkTestStep('DeletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var deleteButtons = contentDocument.querySelectorAll('.destroy');
            for (var i = 0; i < deleteButtons.length; i++)
                deleteButtons[i].click();
        })
    ]
});

Suites.push({
    name: 'Backbone',
    url: 'todomvc/architecture-examples/backbone/index.html',
    version: '1.1.0',
    prepare: function (runner, contentWindow, contentDocument) {
    contentWindow.Backbone.sync = function () {}
        return runner.waitForElement('#new-todo').then(function (element) {
            element.focus();
            return element;
        });
    },
    tests: [
        new BenchmarkTestStep('Adding' + numberOfItemsToAdd + 'Items', function (newTodo, contentWindow, contentDocument) {
            var appView = contentWindow.appView;
            var fakeEvent = {which: contentWindow.ENTER_KEY};
            for (var i = 0; i < numberOfItemsToAdd; i++) {
                newTodo.value = 'Something to do ' + i;
                appView.createOnEnter(fakeEvent);
            }
        }),
        new BenchmarkTestStep('CompletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var checkboxes = contentDocument.querySelectorAll('.toggle');
            for (var i = 0; i < checkboxes.length; i++)
                checkboxes[i].click();
        }),
        new BenchmarkTestStep('DeletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var deleteButtons = contentDocument.querySelectorAll('.destroy');
            for (var i = 0; i < deleteButtons.length; i++)
                deleteButtons[i].click();
        }),
    ]
});

Suites.push({
    name: 'Knockout',
    url: 'todomvc/architecture-examples/knockoutjs/index.html',
    version: '3.0.0',
    prepare: function (runner, contentWindow, contentDocument) {
        return runner.waitForElement('#new-todo').then(function (element) {
            element.focus();
            return element;
        });
    },
    tests: [
        new BenchmarkTestStep('Adding' + numberOfItemsToAdd + 'Items', function (newTodo, contentWindow, contentDocument) {
            var viewModel = contentWindow.viewModel;
            for (var i = 0; i < numberOfItemsToAdd; i++) {
                viewModel.current('Something to do ' + i);
                viewModel.add()
            }
        }),
        new BenchmarkTestStep('CompletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var checkboxes = contentDocument.querySelectorAll('.toggle');
            for (var i = 0; i < checkboxes.length; i++)
                checkboxes[i].click();
        }),
        new BenchmarkTestStep('DeletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var deleteButtons = contentDocument.querySelectorAll('.destroy');
            for (var i = 0; i < deleteButtons.length; i++)
                deleteButtons[i].click();
        }),
    ]
});

Suites.push({
    name: 'Ember',
    url: 'todomvc/architecture-examples/emberjs/index.html',
    version: '1.3.1 + Handlebars 1.3.0',
    prepare: function (runner, contentWindow, contentDocument) {
        contentWindow.Todos.Store = contentWindow.DS.Store.extend({
            revision: 12,
            adapter: 'Todos.LSAdapter',
            commit: function () { }
        });

        return runner.waitForElement('#new-todo').then(function (element) {
            element.focus();
            return {
                views: contentWindow.Ember.View.views,
                emberRun: contentWindow.Ember.run,
            }
        });
    },
    tests: [
        new BenchmarkTestStep('Adding' + numberOfItemsToAdd + 'Items', function (params) {
            for (var i = 0; i < numberOfItemsToAdd; i++) {
                params.emberRun(function () { params.views["new-todo"].set('value', 'Something to do' + i); });
                params.emberRun(function () { params.views["new-todo"].insertNewline(document.createEvent('Event')); });
            }
        }),
        new BenchmarkTestStep('CompletingAllItems', function (params, contentWindow, contentDocument) {
            var checkboxes = contentDocument.querySelectorAll('.ember-checkbox');
            for (var i = 0; i < checkboxes.length; i++) {
                var view = params.views[checkboxes[i].id];
                params.emberRun(function () { view.set('checked', true); });
            }
        }),
        new BenchmarkTestStep('DeletingItems', function (params, contentWindow, contentDocument) {
            var deleteButtons = contentDocument.querySelectorAll('.destroy');
            for (var i = 0; i < deleteButtons.length; i++)
                params.emberRun(function () { deleteButtons[i].click(); });
        }),
    ]
});

Suites.push({
    name: 'Angular',
    url: 'todomvc/architecture-examples/angularjs-perf/index.html',
    version: '1.2.9',
    prepare: function (runner, contentWindow, contentDocument) {
        return runner.waitForElement('#new-todo').then(function (element) {
            element.focus();
            return element;
        });
    },
    tests: [
        new BenchmarkTestStep('Adding' + numberOfItemsToAdd + 'Items', function (newTodo, contentWindow, contentDocument) {
            var todomvc = contentWindow.todomvc;
            var submitEvent = document.createEvent('Event');
            submitEvent.initEvent('submit', true, true);
            var inputEvent = document.createEvent('Event');
            inputEvent.initEvent('input', true, true);
            for (var i = 0; i < numberOfItemsToAdd; i++) {
                newTodo.value = 'Something to do ' + i;
                newTodo.dispatchEvent(inputEvent);
                newTodo.form.dispatchEvent(submitEvent);
            }
        }),
        new BenchmarkTestStep('CompletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var checkboxes = contentDocument.querySelectorAll('.toggle');
            for (var i = 0; i < checkboxes.length; i++)
                checkboxes[i].click();
        }),
        new BenchmarkTestStep('DeletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var deleteButtons = contentDocument.querySelectorAll('.destroy');
            for (var i = 0; i < deleteButtons.length; i++)
                deleteButtons[i].click();
        }),
    ]
});

Suites.push({
    name: 'React',
    url: 'todomvc/labs/architecture-examples/react/index.html',
    version: '0.8.0',
    prepare: function (runner, contentWindow, contentDocument) {
        contentWindow.Utils.store = function () {}
        return runner.waitForElement('#new-todo').then(function (element) {
            element.focus();
            return element;
        });
    },
    tests: [
        new BenchmarkTestStep('Adding' + numberOfItemsToAdd + 'Items', function (newTodo, contentWindow, contentDocument) {
            var todomvc = contentWindow.todomvc;
            for (var i = 0; i < numberOfItemsToAdd; i++) {
                newTodo.value = 'Something to do ' + i;

                var keydownEvent = document.createEvent('Event');
                keydownEvent.initEvent('keydown', true, true);
                keydownEvent.which = 13; // VK_ENTER
                newTodo.dispatchEvent(keydownEvent);
            }
        }),
        new BenchmarkTestStep('CompletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var checkboxes = contentDocument.querySelectorAll('.toggle');
            for (var i = 0; i < checkboxes.length; i++)
                checkboxes[i].click();
        }),
        new BenchmarkTestStep('DeletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var deleteButtons = contentDocument.querySelectorAll('.destroy');
            for (var i = 0; i < deleteButtons.length; i++)
                deleteButtons[i].click();
        }),
    ]
});

Suites.push({
    name: 'Om',
    url: 'todomvc/labs/architecture-examples/om/index.html',
    version: '? + React 0.8.0',
    prepare: function (runner, contentWindow, contentDocument) {
        return runner.waitForElement('#new-todo').then(function (element) {
            element.focus();
            return element;
        });
    },
    tests: [
        new BenchmarkTestStep('Adding' + numberOfItemsToAdd + 'Items', function (newTodo, contentWindow, contentDocument) {
            var todomvc = contentWindow.todomvc;
            for (var i = 0; i < numberOfItemsToAdd; i++) {
                newTodo.value = 'Something to do ' + i;

                var keydownEvent = document.createEvent('Event');
                keydownEvent.initEvent('keydown', true, true);
                keydownEvent.which = 13; // VK_ENTER
                newTodo.dispatchEvent(keydownEvent);
            }
        }),
        new BenchmarkTestStep('CompletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var checkboxes = contentDocument.querySelectorAll('.toggle');
            for (var i = 0; i < checkboxes.length; i++)
                checkboxes[i].click();
        }),
        new BenchmarkTestStep('DeletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var deleteButtons = contentDocument.querySelectorAll('.destroy');
            for (var i = 0; i < deleteButtons.length; i++)
                deleteButtons[i].click();
        }),
    ]
});

Suites.push({
    name: 'Ractive',
    url: 'todomvc/labs/architecture-examples/ractive/index.html',
    version: '0.3.8',
    prepare: function (runner, contentWindow, contentDocument) {
        return runner.waitForElement('#new-todo').then(function (element) {
            element.focus();
            return element;
        });
    },
    tests: [
        new BenchmarkTestStep('Adding' + numberOfItemsToAdd + 'Items', function (newTodo, contentWindow, contentDocument) {
            for (var i = 0; i < numberOfItemsToAdd; i++) {
                newTodo.value = 'Something to do ' + i;

                var keydownEvent = document.createEvent('Event');
                keydownEvent.initEvent('keydown', true, true);
                keydownEvent.which = 13; // VK_ENTER
                newTodo.dispatchEvent(keydownEvent);
            }
        }),
        new BenchmarkTestStep('CompletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var checkboxes = contentDocument.querySelectorAll('.toggle');
            for (var i = 0; i < checkboxes.length; i++)
                checkboxes[i].click();
        }),
        new BenchmarkTestStep('DeletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var deleteButtons = contentDocument.querySelectorAll('.destroy');
            for (var i = 0; i < deleteButtons.length; i++)
                deleteButtons[i].click();
        }),
    ]
});
<commit_msg>0.8.6<commit_after>var numberOfItemsToAdd = 100;
var Suites = [];

Suites.push({
    name: 'Vue',
    url: 'vue/index.html',
    version: '0.8.6',
    prepare: function (runner, contentWindow, contentDocument) {
        return runner.waitForElement('#new-todo').then(function (element) {
            element.focus();
            return element;
        });
    },
    tests: [
        new BenchmarkTestStep('Adding' + numberOfItemsToAdd + 'Items', function (newTodo, contentWindow, contentDocument) {
            var app = contentWindow.app;
            for (var i = 0; i < numberOfItemsToAdd; i++) {
                app.newTodo = 'Something to do ' + i;
                app.addTodo()
            }
        }),
        new BenchmarkTestStep('CompletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var checkboxes = contentDocument.querySelectorAll('.toggle');
            for (var i = 0; i < checkboxes.length; i++)
                checkboxes[i].click();
        }),
        new BenchmarkTestStep('DeletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var deleteButtons = contentDocument.querySelectorAll('.destroy');
            for (var i = 0; i < deleteButtons.length; i++)
                deleteButtons[i].click();
        })
    ]
});

Suites.push({
    name: 'Backbone',
    url: 'todomvc/architecture-examples/backbone/index.html',
    version: '1.1.0',
    prepare: function (runner, contentWindow, contentDocument) {
    contentWindow.Backbone.sync = function () {}
        return runner.waitForElement('#new-todo').then(function (element) {
            element.focus();
            return element;
        });
    },
    tests: [
        new BenchmarkTestStep('Adding' + numberOfItemsToAdd + 'Items', function (newTodo, contentWindow, contentDocument) {
            var appView = contentWindow.appView;
            var fakeEvent = {which: contentWindow.ENTER_KEY};
            for (var i = 0; i < numberOfItemsToAdd; i++) {
                newTodo.value = 'Something to do ' + i;
                appView.createOnEnter(fakeEvent);
            }
        }),
        new BenchmarkTestStep('CompletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var checkboxes = contentDocument.querySelectorAll('.toggle');
            for (var i = 0; i < checkboxes.length; i++)
                checkboxes[i].click();
        }),
        new BenchmarkTestStep('DeletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var deleteButtons = contentDocument.querySelectorAll('.destroy');
            for (var i = 0; i < deleteButtons.length; i++)
                deleteButtons[i].click();
        }),
    ]
});

Suites.push({
    name: 'Knockout',
    url: 'todomvc/architecture-examples/knockoutjs/index.html',
    version: '3.0.0',
    prepare: function (runner, contentWindow, contentDocument) {
        return runner.waitForElement('#new-todo').then(function (element) {
            element.focus();
            return element;
        });
    },
    tests: [
        new BenchmarkTestStep('Adding' + numberOfItemsToAdd + 'Items', function (newTodo, contentWindow, contentDocument) {
            var viewModel = contentWindow.viewModel;
            for (var i = 0; i < numberOfItemsToAdd; i++) {
                viewModel.current('Something to do ' + i);
                viewModel.add()
            }
        }),
        new BenchmarkTestStep('CompletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var checkboxes = contentDocument.querySelectorAll('.toggle');
            for (var i = 0; i < checkboxes.length; i++)
                checkboxes[i].click();
        }),
        new BenchmarkTestStep('DeletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var deleteButtons = contentDocument.querySelectorAll('.destroy');
            for (var i = 0; i < deleteButtons.length; i++)
                deleteButtons[i].click();
        }),
    ]
});

Suites.push({
    name: 'Ember',
    url: 'todomvc/architecture-examples/emberjs/index.html',
    version: '1.3.1 + Handlebars 1.3.0',
    prepare: function (runner, contentWindow, contentDocument) {
        contentWindow.Todos.Store = contentWindow.DS.Store.extend({
            revision: 12,
            adapter: 'Todos.LSAdapter',
            commit: function () { }
        });

        return runner.waitForElement('#new-todo').then(function (element) {
            element.focus();
            return {
                views: contentWindow.Ember.View.views,
                emberRun: contentWindow.Ember.run,
            }
        });
    },
    tests: [
        new BenchmarkTestStep('Adding' + numberOfItemsToAdd + 'Items', function (params) {
            for (var i = 0; i < numberOfItemsToAdd; i++) {
                params.emberRun(function () { params.views["new-todo"].set('value', 'Something to do' + i); });
                params.emberRun(function () { params.views["new-todo"].insertNewline(document.createEvent('Event')); });
            }
        }),
        new BenchmarkTestStep('CompletingAllItems', function (params, contentWindow, contentDocument) {
            var checkboxes = contentDocument.querySelectorAll('.ember-checkbox');
            for (var i = 0; i < checkboxes.length; i++) {
                var view = params.views[checkboxes[i].id];
                params.emberRun(function () { view.set('checked', true); });
            }
        }),
        new BenchmarkTestStep('DeletingItems', function (params, contentWindow, contentDocument) {
            var deleteButtons = contentDocument.querySelectorAll('.destroy');
            for (var i = 0; i < deleteButtons.length; i++)
                params.emberRun(function () { deleteButtons[i].click(); });
        }),
    ]
});

Suites.push({
    name: 'Angular',
    url: 'todomvc/architecture-examples/angularjs-perf/index.html',
    version: '1.2.9',
    prepare: function (runner, contentWindow, contentDocument) {
        return runner.waitForElement('#new-todo').then(function (element) {
            element.focus();
            return element;
        });
    },
    tests: [
        new BenchmarkTestStep('Adding' + numberOfItemsToAdd + 'Items', function (newTodo, contentWindow, contentDocument) {
            var todomvc = contentWindow.todomvc;
            var submitEvent = document.createEvent('Event');
            submitEvent.initEvent('submit', true, true);
            var inputEvent = document.createEvent('Event');
            inputEvent.initEvent('input', true, true);
            for (var i = 0; i < numberOfItemsToAdd; i++) {
                newTodo.value = 'Something to do ' + i;
                newTodo.dispatchEvent(inputEvent);
                newTodo.form.dispatchEvent(submitEvent);
            }
        }),
        new BenchmarkTestStep('CompletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var checkboxes = contentDocument.querySelectorAll('.toggle');
            for (var i = 0; i < checkboxes.length; i++)
                checkboxes[i].click();
        }),
        new BenchmarkTestStep('DeletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var deleteButtons = contentDocument.querySelectorAll('.destroy');
            for (var i = 0; i < deleteButtons.length; i++)
                deleteButtons[i].click();
        }),
    ]
});

Suites.push({
    name: 'React',
    url: 'todomvc/labs/architecture-examples/react/index.html',
    version: '0.8.0',
    prepare: function (runner, contentWindow, contentDocument) {
        contentWindow.Utils.store = function () {}
        return runner.waitForElement('#new-todo').then(function (element) {
            element.focus();
            return element;
        });
    },
    tests: [
        new BenchmarkTestStep('Adding' + numberOfItemsToAdd + 'Items', function (newTodo, contentWindow, contentDocument) {
            var todomvc = contentWindow.todomvc;
            for (var i = 0; i < numberOfItemsToAdd; i++) {
                newTodo.value = 'Something to do ' + i;

                var keydownEvent = document.createEvent('Event');
                keydownEvent.initEvent('keydown', true, true);
                keydownEvent.which = 13; // VK_ENTER
                newTodo.dispatchEvent(keydownEvent);
            }
        }),
        new BenchmarkTestStep('CompletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var checkboxes = contentDocument.querySelectorAll('.toggle');
            for (var i = 0; i < checkboxes.length; i++)
                checkboxes[i].click();
        }),
        new BenchmarkTestStep('DeletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var deleteButtons = contentDocument.querySelectorAll('.destroy');
            for (var i = 0; i < deleteButtons.length; i++)
                deleteButtons[i].click();
        }),
    ]
});

Suites.push({
    name: 'Om',
    url: 'todomvc/labs/architecture-examples/om/index.html',
    version: '? + React 0.8.0',
    prepare: function (runner, contentWindow, contentDocument) {
        return runner.waitForElement('#new-todo').then(function (element) {
            element.focus();
            return element;
        });
    },
    tests: [
        new BenchmarkTestStep('Adding' + numberOfItemsToAdd + 'Items', function (newTodo, contentWindow, contentDocument) {
            var todomvc = contentWindow.todomvc;
            for (var i = 0; i < numberOfItemsToAdd; i++) {
                newTodo.value = 'Something to do ' + i;

                var keydownEvent = document.createEvent('Event');
                keydownEvent.initEvent('keydown', true, true);
                keydownEvent.which = 13; // VK_ENTER
                newTodo.dispatchEvent(keydownEvent);
            }
        }),
        new BenchmarkTestStep('CompletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var checkboxes = contentDocument.querySelectorAll('.toggle');
            for (var i = 0; i < checkboxes.length; i++)
                checkboxes[i].click();
        }),
        new BenchmarkTestStep('DeletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var deleteButtons = contentDocument.querySelectorAll('.destroy');
            for (var i = 0; i < deleteButtons.length; i++)
                deleteButtons[i].click();
        }),
    ]
});

Suites.push({
    name: 'Ractive',
    url: 'todomvc/labs/architecture-examples/ractive/index.html',
    version: '0.3.8',
    prepare: function (runner, contentWindow, contentDocument) {
        return runner.waitForElement('#new-todo').then(function (element) {
            element.focus();
            return element;
        });
    },
    tests: [
        new BenchmarkTestStep('Adding' + numberOfItemsToAdd + 'Items', function (newTodo, contentWindow, contentDocument) {
            for (var i = 0; i < numberOfItemsToAdd; i++) {
                newTodo.value = 'Something to do ' + i;

                var keydownEvent = document.createEvent('Event');
                keydownEvent.initEvent('keydown', true, true);
                keydownEvent.which = 13; // VK_ENTER
                newTodo.dispatchEvent(keydownEvent);
            }
        }),
        new BenchmarkTestStep('CompletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var checkboxes = contentDocument.querySelectorAll('.toggle');
            for (var i = 0; i < checkboxes.length; i++)
                checkboxes[i].click();
        }),
        new BenchmarkTestStep('DeletingAllItems', function (newTodo, contentWindow, contentDocument) {
            var deleteButtons = contentDocument.querySelectorAll('.destroy');
            for (var i = 0; i < deleteButtons.length; i++)
                deleteButtons[i].click();
        }),
    ]
});
<|endoftext|>


<commit_before>// based on http://kx.com/q/c/c.js
// uses Node.js Buffer instead of ArrayBuffer [michaelwittig]
// added support for decompression [GMelika]
var J2P32 = Math.pow(2, 32);

function decompress(compressedSize, b) {
	"use strict";
	var n = 0,
		r = 0,
		f = 0,
		s = 8,
		p = s,
		i = 0;
	var dst = new Buffer(compressedSize);
	var d = 12;
	var aa = new Int32Array(256);
	while (s < dst.length) {
		if (!i) {
			f = b[d++];
			i = 1;
		}
		if (f & i) {
			r = aa[b[d++]];
			dst[s++] = dst[r++];
			dst[s++] = dst[r++];
			n = 0xff & b[d++];
			for (var m = 0; m < n; m++) {
				dst[s + m] = dst[r + m];
			}
		} else {
			dst[s++] = b[d++];
		}
		while (p < (s - 1)) {
			aa[dst[p] ^ dst[p + 1]] = p++;
		}
		if (f & i) {
			p = (s += n);
		}
		i *= 2;
		if (i === 256) {
			i = 0;
		}
	}
	return dst;
}

function deserialize(b, nanos2date, flipTables) {
	"use strict";
	var pos = 8;

	var isCompressed = b[2] === 1;
	if (isCompressed) {
		var compressedSize = rInt32();
		b = decompress(compressedSize, b);
		pos = 8;
	}

	function rBool() {
		return rInt8() === 1;
	}
	function rChar() {
		var val = rInt8();
		if (val === 32) {
			return null;
		} else {
			return String.fromCharCode(val);
		}
	}
	function rInt8() {
		var val = b.readInt8(pos);
		pos += 1;
		return val;
	}
	function rInt(n) {
		var val;
		if (n === 1) {
			val = b.readInt8(pos);
		} else if (n === 2) {
			val = b.readInt16LE(pos);
		} else if (n === 4) {
			val = b.readInt32LE(pos);
		} else {
			throw new Error("only n = 1, 2 or 4 is supported");
		}
		pos += n;
		return val;
	}
	function rUInt8() {
		var val = b.readUInt8(pos);
		pos += 1;
		return val;
	}
	function rGuid() {
		var x = "0123456789abcdef", s = "";
		for (var i = 0; i < 16; i++) {
			var c = rUInt8();
			s += i == 4 || i === 6 || i === 8 || i === 10 ? "-" : "";
			s += x[c >> 4];
			s += x[c & 15];
		}
		if (s === "00000000-0000-0000-0000-000000000000") {
			return null;
		} else {
			return s;
		}
	}
	function rInt16() {
		var h = rInt(2);
		if (h === -32768) {
			return null;
		} else if (h === 32767) {
			return Infinity;
		} else if (h === -32767) {
			return -Infinity;
		} else {
			return h;
		}
	}
	function rInt32() {
		var i = rInt(4);
		if (i === -2147483648) {
			return null;
		} else if (i === 2147483647) {
			return Infinity;
		} else if (i === -2147483647) {
			return -Infinity;
		} else {
			return i;
		}
	}
	function rInt64() { // closest number to 64 bit int...
		var y = rInt(4);
		var x = rInt(4);
		if (x === -2147483648 && y === 0) {
			return null;
		} else if (x === 2147483647 && y === -1) {
			return Infinity;
		} else if (x === -2147483648 && y === 1) {
			return -Infinity;
		} else {
			return x * J2P32 + (y >= 0 ? y : J2P32 + y);
		}
	}
	function rFloat32() {
		var val = b.readFloatLE(pos);
		pos += 4;
		if (Number.isNaN(val)) {
			return null;
		} else {
			return val;
		}
	}
	function rFloat64() {
		var val = b.readDoubleLE(pos);
		pos += 8;
		if (Number.isNaN(val)) {
			return null;
		} else {
			return val;
		}
	}
	function rSymbol() {
		var i = pos, c, s = "";
		while ((c = rInt8()) !== 0) {
			s += String.fromCharCode(c);
		}
		if (s === "") {
			return null;
		} else {
			return s;
		}
	}
	function rTimestamp() {
		var val = rInt64();
		if (val === null) {
			return null;
		}
		if (nanos2date === false) {
			return 86400000000000 * (10957 + (val / 86400000000000));
		} else {
			return date(val / 86400000000000);
		}
	}
	function rMonth() {
		var y = rInt32();
		if (y === null) {
			return null;
		}
		var m = y % 12;
		y = 2000 + y / 12;
		return new Date(Date.UTC(y, m, 1));
	}
	function date(n) {
		return new Date(86400000 * (10957 + n));
	}
	function rDate() {
		var val = rInt32();
		return (val === null) ? null : date(val);
	}
	function rDateTime() {
		var val = rFloat64();
		return (val === null) ? null : date(val);
	}
	function rTimespan() {
		var val = rInt64();
		if (val === null) {
			return null;
		}
		if (nanos2date === false) {
			return val;
		}
		return date(val / 86400000000000);
	}
	function rSecond() {
		var val = rInt32();
		if (val === null) {
			return null;
		}
		return date(val / 86400);
	}
	function rMinute() {
		var val = rInt32();
		if (val === null) {
			return null;
		}
		return date(val / 1440);
	}
	function rTime() {
		var val = rInt32();
		if (val === null) {
			return null;
		}
		return date(val / 86400000);
	}

	function r() {
		var fns = [r, rBool, rGuid, null, rUInt8, rInt16, rInt32, rInt64, rFloat32, rFloat64, rChar, rSymbol, rTimestamp, rMonth, rDate, rDateTime, rTimespan, rMinute, rSecond, rTime];
		var i = 0, n, t = rInt8();
		if (t < 0 && t > -20) {
			return fns[-t]();
		}
		if (t > 99) {
			if (t === 100) {
				rSymbol();
				return r();
			}
			if (t < 104) {
				return rInt8() === 0 && t === 101 ? null : "func";
			}
			if (t > 105) {
				r();
			} else {
				for (n = rInt32(); i < n; i++) {
					r();
				}
			}
			return "func";
		}
		if (99 === t) {
			var flip = 98 === rUInt8();
			pos -= 1;
			var	x = r(),
				y = r(),
				o;
			if (!flip) {
				o = {};
				for (i = 0; i < x.length; i++) {
					o[x[i]] = y[i];
				}
			} else {
				o = new Array(2);
			}
			return o;
		}
		pos++;
		if (98 === t) {
			if (flipTables === false) {
				return r(); // better as array of dicts?
			} else {
				rInt8(); // check type is 99 here
				// read the arrays and then flip them into an array of dicts
				var x = r();
				var y = r();
				var A = new Array(y[0].length);
				for (var j = 0; j < y[0].length; j++) {
					var o = {};
					for (var i = 0; i < x.length; i++) {
						o[x[i]] = y[i][j];
					}
					A[j] = o;
				}
				return A;
			}
		}
		n = rInt32();
		if (10 === t) {
			var s = "";
			n += pos;
			for (; pos < n; s += rChar());
			return s;
		}
		var A = new Array(n);
		var f = fns[t];
		for (i = 0; i < n; i++) {
			A[i] = f();
		}
		return A;
	}
	return r();
}

function serialize(x) {
	"use strict";
	var pos = 0,
		b;

	function toType(obj) {
		return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
	}

	function getKeys(x) {
		var v = [], o;
		for (o in x) {
			v.push(o);
		}
		return v;
	}
	function getVals(x) {
		var v = [], o;
		for (o in x) {
			v.push(x[o]);
		}
		return v;
	}

	function calcN(x, dt) {
		var t = dt ? dt : toType(x);
		switch (t) {
			case 'null':
				return 2;
			case 'object':
				return 1 + calcN(getKeys(x), 'symbols') + calcN(getVals(x), null);
			case 'boolean':
				return 2;
			case 'number':
				return 9;
			case 'array':
				{
					var n = 6;
					for (var i = 0; i < x.length; i++) {
						n += calcN(x[i], null);
					}
					return n;
				}
			case 'symbols':
				{
					var n = 6;
					for (var i = 0; i < x.length; i++) {
						n += calcN(x[i], 'symbol');
					}
					return n;
				}
			case 'string':
				return x.length + (x[0] === '`' ? 1 : 6);
			case 'date':
				return 9;
			case 'symbol':
				return 2 + x.length;
		}
		throw "bad type " + t;
	}

	function wb(i) {
		b.writeInt8(i, pos);
		pos += 1;
	}
	function wf(i) {
		b.writeDoubleLE(i, pos);
		pos += 8;
	}
	function wn(n, i) {
		if (n === 1) {
			b.writeInt8(i, pos);
		} else if (n === 2) {
			b.writeInt16LE(i, pos);
		} else if (n === 4) {
			b.writeInt32LE(i, pos);
		} else {
			throw new Error("only n = 1, 2 or 4 is supported");
		}
		pos += n;
	}
	function w(x, dt) {
		var t = dt ? dt : toType(x);
		switch (t) {
			case 'null':
				{
					wb(101);
					wb(0);
				}
				break;
			case 'boolean':
				{
					wb(-1);
					wb(x ? 1 : 0);
				}
				break;
			case 'number':
				{
					wb(-9);
					wf(x);
				}
				break;
			case 'date':
				{
					wb(-15);
					wf(((x.getTime() - (new Date(x)).getTimezoneOffset() * 60000) / 86400000) - 10957);
				}
				break;
			case 'symbol':
				{
					wb(-11);
					for (var i = 0; i < x.length; i++) {
						wb(x[i].charCodeAt());
					}
					wb(0);
				}
				break;
			case 'string':
				if (x[0] === '`') {
					w(x.substr(1), 'symbol');
				} else {
					wb(10);
					wb(0);
					wn(4, x.length);
					for (var i = 0; i < x.length; i++) {
						wb(x[i].charCodeAt());
					}
				}
				break;
			case 'object':
				{
					wb(99);
					w(getKeys(x), 'symbols');
					w(getVals(x), null);
				}
				break;
			case 'array':
				{
					wb(0);
					wb(0);
					wn(4, x.length);
					for (var i = 0; i < x.length; i++) {
						w(x[i], null);
					}
				}
				break;
			case 'symbols':
				{
					wb(0);
					wb(0);
					wn(4, x.length);
					for (var i = 0; i < x.length; i++) {
						w(x[i], 'symbol');
					}
				}
				break;
		}
	}
	var n = calcN(x, null);
	b = new Buffer(8 + n);
	wb(1);
	wb(0);
	wb(0);
	wb(0);
	wn(4, b.length);
	w(x, null);
	return b;
}

exports.deserialize = deserialize;
exports.serialize = serialize;
<commit_msg>cleanup<commit_after>// based on http://kx.com/q/c/c.js
// uses Node.js Buffer instead of ArrayBuffer [michaelwittig]
// added support for decompression [GMelika]
var J2P32 = Math.pow(2, 32);

function decompress(compressedSize, b) {
	"use strict";
	var n = 0,
		r = 0,
		f = 0,
		s = 8,
		p = s,
		i = 0;
	var dst = new Buffer(compressedSize);
	var d = 12;
	var aa = new Int32Array(256);
	while (s < dst.length) {
		if (!i) {
			f = b[d++];
			i = 1;
		}
		if (f & i) {
			r = aa[b[d++]];
			dst[s++] = dst[r++];
			dst[s++] = dst[r++];
			n = 0xff & b[d++];
			for (var m = 0; m < n; m++) {
				dst[s + m] = dst[r + m];
			}
		} else {
			dst[s++] = b[d++];
		}
		while (p < (s - 1)) {
			aa[dst[p] ^ dst[p + 1]] = p++;
		}
		if (f & i) {
			p = (s += n);
		}
		i *= 2;
		if (i === 256) {
			i = 0;
		}
	}
	return dst;
}

function deserialize(b, nanos2date, flipTables) {
	"use strict";
	var pos = 8, isCompressed = (b[2] === 1);
	function rBool() {
		return rInt8() === 1;
	}
	function rChar() {
		var val = rInt8();
		if (val === 32) {
			return null;
		} else {
			return String.fromCharCode(val);
		}
	}
	function rInt8() {
		var val = b.readInt8(pos);
		pos += 1;
		return val;
	}
	function rInt(n) {
		var val;
		if (n === 1) {
			val = b.readInt8(pos);
		} else if (n === 2) {
			val = b.readInt16LE(pos);
		} else if (n === 4) {
			val = b.readInt32LE(pos);
		} else {
			throw new Error("only n = 1, 2 or 4 is supported");
		}
		pos += n;
		return val;
	}
	function rUInt8() {
		var val = b.readUInt8(pos);
		pos += 1;
		return val;
	}
	function rGuid() {
		var x = "0123456789abcdef", s = "";
		for (var i = 0; i < 16; i++) {
			var c = rUInt8();
			s += i === 4 || i === 6 || i === 8 || i === 10 ? "-" : "";
			s += x[c >> 4];
			s += x[c & 15];
		}
		if (s === "00000000-0000-0000-0000-000000000000") {
			return null;
		} else {
			return s;
		}
	}
	function rInt16() {
		var h = rInt(2);
		if (h === -32768) {
			return null;
		} else if (h === 32767) {
			return Infinity;
		} else if (h === -32767) {
			return -Infinity;
		} else {
			return h;
		}
	}
	function rInt32() {
		var i = rInt(4);
		if (i === -2147483648) {
			return null;
		} else if (i === 2147483647) {
			return Infinity;
		} else if (i === -2147483647) {
			return -Infinity;
		} else {
			return i;
		}
	}
	function rInt64() { // closest number to 64 bit int...
		var y = rInt(4);
		var x = rInt(4);
		if (x === -2147483648 && y === 0) {
			return null;
		} else if (x === 2147483647 && y === -1) {
			return Infinity;
		} else if (x === -2147483648 && y === 1) {
			return -Infinity;
		} else {
			return x * J2P32 + (y >= 0 ? y : J2P32 + y);
		}
	}
	function rFloat32() {
		var val = b.readFloatLE(pos);
		pos += 4;
		if (Number.isNaN(val)) {
			return null;
		} else {
			return val;
		}
	}
	function rFloat64() {
		var val = b.readDoubleLE(pos);
		pos += 8;
		if (Number.isNaN(val)) {
			return null;
		} else {
			return val;
		}
	}
	function rSymbol() {
		var i = pos, c, s = "";
		while ((c = rInt8()) !== 0) {
			s += String.fromCharCode(c);
		}
		if (s === "") {
			return null;
		} else {
			return s;
		}
	}
	function rTimestamp() {
		var val = rInt64();
		if (val === null) {
			return null;
		}
		if (nanos2date === false) {
			return 86400000000000 * (10957 + (val / 86400000000000));
		} else {
			return date(val / 86400000000000);
		}
	}
	function rMonth() {
		var y = rInt32();
		if (y === null) {
			return null;
		}
		var m = y % 12;
		y = 2000 + y / 12;
		return new Date(Date.UTC(y, m, 1));
	}
	function date(n) {
		return new Date(86400000 * (10957 + n));
	}
	function rDate() {
		var val = rInt32();
		return (val === null) ? null : date(val);
	}
	function rDateTime() {
		var val = rFloat64();
		return (val === null) ? null : date(val);
	}
	function rTimespan() {
		var val = rInt64();
		if (val === null) {
			return null;
		}
		if (nanos2date === false) {
			return val;
		}
		return date(val / 86400000000000);
	}
	function rSecond() {
		var val = rInt32();
		if (val === null) {
			return null;
		}
		return date(val / 86400);
	}
	function rMinute() {
		var val = rInt32();
		if (val === null) {
			return null;
		}
		return date(val / 1440);
	}
	function rTime() {
		var val = rInt32();
		if (val === null) {
			return null;
		}
		return date(val / 86400000);
	}
	function r() {
		var fns = [r, rBool, rGuid, null, rUInt8, rInt16, rInt32, rInt64, rFloat32, rFloat64, rChar, rSymbol, rTimestamp, rMonth, rDate, rDateTime, rTimespan, rMinute, rSecond, rTime];
		var i = 0, n, t = rInt8();
		if (t < 0 && t > -20) {
			return fns[-t]();
		}
		if (t > 99) {
			if (t === 100) {
				rSymbol();
				return r();
			}
			if (t < 104) {
				return rInt8() === 0 && t === 101 ? null : "func";
			}
			if (t > 105) {
				r();
			} else {
				for (n = rInt32(); i < n; i++) {
					r();
				}
			}
			return "func";
		}
		if (99 === t) {
			var flip = 98 === rUInt8();
			pos -= 1;
			var	x = r(),
				y = r(),
				o;
			if (!flip) {
				o = {};
				for (i = 0; i < x.length; i++) {
					o[x[i]] = y[i];
				}
			} else {
				o = new Array(2);
			}
			return o;
		}
		pos++;
		if (98 === t) {
			if (flipTables === false) {
				return r();
			} else {
				rInt8();
				var x = r();
				var y = r();
				var A = new Array(y[0].length);
				for (var j = 0; j < y[0].length; j++) {
					var o = {};
					for (var i = 0; i < x.length; i++) {
						o[x[i]] = y[i][j];
					}
					A[j] = o;
				}
				return A;
			}
		}
		n = rInt32();
		if (10 === t) {
			var s = "";
			n += pos;
			while (pos < n) {
				s += rChar();
			}
			return s;
		}
		var A = new Array(n);
		var f = fns[t];
		for (i = 0; i < n; i++) {
			A[i] = f();
		}
		return A;
	}
	if (isCompressed) {
		var compressedSize = rInt32();
		b = decompress(compressedSize, b);
		pos = 8;
	}
	return r();
}

function serialize(x) {
	"use strict";
	var pos = 0, b;
	function toType(obj) {
		return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
	}
	function getKeys(x) {
		var v = [], o;
		for (o in x) {
			if (x.hasOwnProperty(o)) {
				v.push(o);
			}
		}
		return v;
	}
	function getVals(x) {
		var v = [], o;
		for (o in x) {
			if (x.hasOwnProperty(o)) {
				v.push(x[o]);
			}
		}
		return v;
	}
	function calcN(x, dt) {
		var t = dt ? dt : toType(x);
		switch (t) {
			case 'null':
				return 2;
			case 'object':
				return 1 + calcN(getKeys(x), 'symbols') + calcN(getVals(x), null);
			case 'boolean':
				return 2;
			case 'number':
				return 9;
			case 'array':
				{
					var n = 6;
					for (var i = 0; i < x.length; i++) {
						n += calcN(x[i], null);
					}
					return n;
				}
			case 'symbols':
				{
					var n = 6;
					for (var i = 0; i < x.length; i++) {
						n += calcN(x[i], 'symbol');
					}
					return n;
				}
			case 'string':
				return x.length + (x[0] === '`' ? 1 : 6);
			case 'date':
				return 9;
			case 'symbol':
				return 2 + x.length;
		}
		throw "bad type " + t;
	}
	function wb(i) {
		b.writeInt8(i, pos);
		pos += 1;
	}
	function wf(i) {
		b.writeDoubleLE(i, pos);
		pos += 8;
	}
	function wn(n, i) {
		if (n === 1) {
			b.writeInt8(i, pos);
		} else if (n === 2) {
			b.writeInt16LE(i, pos);
		} else if (n === 4) {
			b.writeInt32LE(i, pos);
		} else {
			throw new Error("only n = 1, 2 or 4 is supported");
		}
		pos += n;
	}
	function w(x, dt) {
		var t = dt ? dt : toType(x);
		switch (t) {
			case 'null':
				{
					wb(101);
					wb(0);
				}
				break;
			case 'boolean':
				{
					wb(-1);
					wb(x ? 1 : 0);
				}
				break;
			case 'number':
				{
					wb(-9);
					wf(x);
				}
				break;
			case 'date':
				{
					wb(-15);
					wf(((x.getTime() - (new Date(x)).getTimezoneOffset() * 60000) / 86400000) - 10957);
				}
				break;
			case 'symbol':
				{
					wb(-11);
					for (var i = 0; i < x.length; i++) {
						wb(x[i].charCodeAt());
					}
					wb(0);
				}
				break;
			case 'string':
				if (x[0] === '`') {
					w(x.substr(1), 'symbol');
				} else {
					wb(10);
					wb(0);
					wn(4, x.length);
					for (var i = 0; i < x.length; i++) {
						wb(x[i].charCodeAt());
					}
				}
				break;
			case 'object':
				{
					wb(99);
					w(getKeys(x), 'symbols');
					w(getVals(x), null);
				}
				break;
			case 'array':
				{
					wb(0);
					wb(0);
					wn(4, x.length);
					for (var i = 0; i < x.length; i++) {
						w(x[i], null);
					}
				}
				break;
			case 'symbols':
				{
					wb(0);
					wb(0);
					wn(4, x.length);
					for (var i = 0; i < x.length; i++) {
						w(x[i], 'symbol');
					}
				}
				break;
		}
	}
	var n = calcN(x, null);
	b = new Buffer(8 + n);
	wb(1);
	wb(0);
	wb(0);
	wb(0);
	wn(4, b.length);
	w(x, null);
	return b;
}

exports.deserialize = deserialize;
exports.serialize = serialize;
<|endoftext|>


<commit_before>/*
	usage:
	======
	var layout = Backbone.View.extend({
		view: {
			type: MyNiceItemView,

		},

		initialize: function() {

		}
	});
*/
(function(){

	// check for Backbone
	// check for Underscore
	var _ = this._;
	var Backbone = this.Backbone;

	// if Underscore or Backbone have not been loaded
	// exit to prevent js errors
	if (!_ || !Backbone || !JSON) {
		return;
	}

	// defintion of Extension
	function CollectionView(view) {
		this.cv_views = [];
		// initialize collection if given
		if (view.view && view.view.collection) {
			this.collection = new view.view.collection();
		} else {
			this.collection = new Backbone.Collection();
		}

		// bind to events of views if given

		// view.listenTo(this.collection, 'reset update', this.render);
	}

	CollectionView.prototype = {
		render: function() {
			// this.trigger('before:render');
			this.resetViews();
			this.collection.each(this.renderItem, this);
			// this.trigger('after:render');
		},

		renderItem: function(model) {
			var index = this.cv_views.length,
				view = this.view.type;
			this.cv_views.push(new view({ model: model }));
			if (this.view.events) {
				_.each(this.view.events, function(method, _event){
					this.listenTo(this.cv_views[index], _event, this[method]);
				}, this);
			}
			this.$el.append( this.cv_views[index].render().el );
		},

		resetViews: function() {
			_.invoke(this.cv_views, 'remove');
			this.cv_views.length = 0;
		},

		_hide: function() {
			this.$el.removeClass(this.transition.css);
		},

		_show: function () {
			this.$el.addClass(this.transition.css);
		}
	};

	var init = function() {
		Backbone.trigger('extend:View', {
			key: 'view',
			extension: CollectionView,
			initialize: function () {
				this.listenTo(this.collection, 'reset destroy add remove sort', function(){
					this.render();
				});
			}
		});
	};

	init();

	// if using AMD and xManager is loaded after the extension
	Backbone.on('xManager:ready', init);
}());<commit_msg>refactored listenning to events, docs<commit_after>/*
	usage:
	======
	var layout = Backbone.View.extend({
		view: {
			type: MyNiceItemView,

			// optional - a reference to a collection object to create an instance from
			collection: MusicLibrary,

			// custom events of the collection views that this view listens to
			// the config follows Backbone.View events configuration
			events: {
				'play-media': 'onMediaPlayed'
			}

		},

		initialize: function() {

		}
	});
*/
(function(){

	// check for Backbone
	// check for Underscore
	var _ = this._;
	var Backbone = this.Backbone;

	// if Underscore or Backbone have not been loaded
	// exit to prevent js errors
	if (!_ || !Backbone || !JSON) {
		return;
	}

	// defintion of Extension
	function CollectionView(view) {
		this.cv_views = [];
		// if view already has a collection
		// don't create a new one
		if (view.collection) return;

		// initialize collection if given
		if (view.view && view.view.collection) {
			this.collection = new view.view.collection();
		} else {
			this.collection = new Backbone.Collection();
		}

		// bind to events of views if given

		// view.listenTo(this.collection, 'reset update', this.render);
	}

	CollectionView.prototype = {
		render: function() {
			// this.trigger('before:render');
			this.resetViews();
			this.collection.each(this.renderItem, this);
			// this.trigger('after:render');
		},

		renderItem: function(model) {
			var index = this.cv_views.length,
				view = this.view.type;
			this.cv_views.push(new view({ model: model }));
			_.each(this.view.events, this._listenToView, this);
			this.$el.append( this.cv_views[index].render().el );
		},

		_listenToView: function (method, _event) {
			this.listenTo(this.cv_views[this.cv_views.length], _event, this[method]);
		},

		resetViews: function() {
			_.invoke(this.cv_views, 'remove');
			this.cv_views.length = 0;
		},

		_hide: function() {
			this.$el.removeClass(this.transition.css);
		},

		_show: function () {
			this.$el.addClass(this.transition.css);
		}
	};

	var init = function() {
		Backbone.trigger('extend:View', {
			key: 'view',
			extension: CollectionView,
			initialize: function () {
				this.listenTo(this.collection, 'reset destroy add remove sort', function(){
					this.render();
				});
			}
		});
	};

	init();

	// if using AMD and xManager is loaded after the extension
	Backbone.on('xManager:ready', init);
}());<|endoftext|>


<commit_before>'use strict';

// Module dependencies.
const cleverCore = require('clever-core');
const storage = cleverCore.loadStorage();
const mongoose = require('mongoose');
const Schema  = mongoose.Schema;
const _ = require('lodash');
const Q = require('q');
const async = require('async');
const bubblesort = require('bubble-sort-js');

// Mongoose Error Handling
function hasErrors(err) {
  if (err) {
    console.log(err);
    let modelErrors = [];
    switch (err.code) {
      case 11000: {}
      case 11001: {
        modelErrors.push({
          msg: 'Slug already used',
          param: 'slug'
        });
        break;
      }
      default: {
        if (err.errors) {
          for (var x in err.errors) {
            modelErrors.push({
              param: x,
              msg: err.errors[x].message,
              value: err.errors[x].value
            });
          }
        }
      }
    }
    return modelErrors;
  }

  return null;
}

// Validations
function validateUniqueSlug(value, callback) {
  const Gallery = mongoose.model('Gallery');
  Gallery.find({
    $and: [{
      slug: value
    }, {
      _id: {
        $ne: this._id
      }
    }]
  }, function(err, gallery) {
    callback(err || gallery.length === 0);
  });
};

// Getter
function escapeProperty(value) {
  return _.escape(value);
};

// ImageSchema
const ImageSchema = new Schema({
  ref: {
    type: String,
    required: true
  },
  order: {
    type: Number,
    required: true,
  }
});

// GallerySchema
const GallerySchema = new Schema({
  slug: {
    type: String,
    required: true,
    unique: true,
    // TODO: match valid slug chars
    validate: [validateUniqueSlug, 'Slug is already in-use']
  },
  title: {
    type: String,
    required: true,
    get: escapeProperty
  },
  comment: {
    type: String,
    default: '',
    get: escapeProperty
  },
  _images: {
    type: [ImageSchema],
    default: []
  }
});

// Virtuals
GallerySchema.virtual('image_preview').set(function(url) {
  throw new Error('Gallery::image_preview cannot be set.');
}).get(function() {
  if(this._images.length === 0) return false;
  return this._image_preview || false;
});

GallerySchema.virtual('n_images').set(function(url) {
  throw new Error('Gallery::n_images cannot be set.');
}).get(function() {
  return this.images ? this.images.length : 0;
});

// Static Methods
GallerySchema.statics = {
  /**
   * CountGalleries - return the number of galleries
   *
   * @return {Object}
   * @api public
   */
  countGalleries: function() {
    const Gallery = mongoose.model('Gallery');
    const defer = Q.defer();
    Gallery.count({}, function(err, nGalleries) {
      if (err) return defer.reject(err);
      return defer.resolve(nGalleries);
    });
    return defer.promise;
  },

  /**
   * GetGalleries - return the list of galleries
   *
   * @param {Number} skip
   * @param {Number} limit
   * @return {Object}
   * @api public
   */
  getGalleries: function(skip, limit) {
    const Gallery = mongoose.model('Gallery');
    const options = skip && limit ? {skip: skip, limit: limit} : {};
    const defer = Q.defer();
    Gallery.find({}, {}, options, function(err, galleries) {
      if (err) return defer.reject(err);
      return defer.resolve(galleries);
    });
    return defer.promise;
  },

  /**
   * GetGalleryList - return the list of galleries
   *
   * @return {Object}
   * @api public
   */
  getGalleryList: function() {
    const Gallery = mongoose.model('Gallery');
    const defer = Q.defer();
    Gallery.find({}, {}, {}, function(err, galleries) {
      if (err) return defer.reject(err);
      async.map(galleries, function(gallery, cb) {
        const listElement = {};
        listElement._id = gallery._id;
        listElement.title = gallery.title;
        cb(null, listElement);
      }, function(errors, galleryList) {
        if(errors) return defer.reject(errors);
        defer.resolve(galleryList);
      });

    }).sort({ title: -1 });
    return defer.promise;
  },

  /**
   * GetGalleryById - return the gallery matching the id
   *
   * @param {String} id
   * @return {Object}
   * @api public
   */
  getGalleryById: function(id) {
    if(!id) throw new Error('Gallery.getGalleryById: id parameter is mandatory');
    const Gallery = mongoose.model('Gallery');
    const defer = Q.defer();
    Gallery.findOne({_id: id}, function(err, gallery) {
      if (err) return defer.reject(err);
      defer.resolve(gallery);
    });
    return defer.promise;
  },

  /**
   * EditGalleryById - edit the gallery matching the id
   *
   * @param {String} id
   * @return {Object}
   * @api public
   */
  editGalleryById: function(id, galleryParams) {

    if(!id) throw new Error('Gallery.editGalleryById: id parameter is mandatory');
    const Gallery = mongoose.model('Gallery');
    const defer = Q.defer();

    function save(gallery) {

      Object.keys(galleryParams).forEach(function (key, index) {
        gallery[key] = galleryParams[key];
      });

      gallery.save(function(err) {
        const errors = hasErrors(err);
        if(errors) return defer.reject(errors);
        defer.resolve(gallery);
      });
    }

    Gallery.getGalleryById(id)
      .then(save)
      .catch(defer.reject);

    return defer.promise;
  },

  /**
   * AddGalleryImagesByGalleryId
   *
   * @param {String} id
   * @return {Array}
   * @api public
   */
  addGalleryImagesByGalleryId: function(id, images) {

    if(!id) throw new Error('Gallery.addGalleryImagesByGalleryId: id parameter is mandatory');
    if(!images) throw new Error('Gallery.addGalleryImagesByGalleryId: images parameter is mandatory');
    const Gallery = mongoose.model('Gallery');
    const defer = Q.defer();

    function save(gallery) {

      const starterOrder = gallery._images.length;

      images.forEach(function(image, index) {
        if(!image._id) defer.reject(new Error('Gallery.addGalleryImagesByGalleryId: image._id doesn\'t exist'));
        gallery._images.push({
          ref: image._id,
          order: starterOrder + index
        });
      });

      gallery.save(function(err) {
        const errors = hasErrors(err);
        if(errors) return defer.reject(errors);
        defer.resolve(gallery);
      });
    }

    Gallery.getGalleryById(id)
      .then(save)
      .catch(defer.reject);

    return defer.promise;
  },

  /**
   * DeleteGalleryById - delete the gallery matching the id
   *
   * @param {String} id
   * @return {Object}
   * @api public
   */
  deleteGalleryById: function(id) {
    if(!id) throw new Error('Gallery.deleteGalleryById: id parameter is mandatory');
    const Gallery = mongoose.model('Gallery');
    const defer = Q.defer();

    Gallery.getGalleryById(id)
      .then(function(gallery) {
        gallery.deleteImages()
          .then(function (){
            Gallery.remove({_id: gallery._id}, function(err, result) {
              if (err) return defer.reject(err);
              return defer.resolve(result);
            });
          });
      });

    return defer.promise;
  },

  createGallery: function(galleryParams) {
    const Gallery = mongoose.model('Gallery');
    const gallery = new Gallery(galleryParams);

    const defer = Q.defer();
    gallery.save(function(err) {
      const errors = hasErrors(err);
      if(errors) return defer.reject(errors);
      defer.resolve(gallery);
    });

    return defer.promise;
  }
}

// Instance Methods
GallerySchema.methods = {

  /**
   * LoadImages - loadImages from _images
   *
   * @return {Array}
   * @api public
   */
  loadImages: function() {
    const File = mongoose.model('File');
    const defer = Q.defer();
    const thisGallery = this;

    // Order images
    bubblesort(this._images, function(a, b) { return a.order - b.order; });

    async.map(this._images, function(_image, cb) {
      File.getFileById(_image.ref)
        .then(function(image) {
          cb(null, image);
        })
        .catch(cb); // cb(err)
    }, function(err, images) {
      if(err) return defer.reject(err);

      const loadedImages = [];
      const loadedImageRefs = [];

      images.forEach(function(image, index) {
        if(image) {
          loadedImages.push(image);
          loadedImageRefs.push({ref: image._id, order: index})
        }
      });

      thisGallery.images = loadedImages;

      if(thisGallery.images.length > 0) {
        thisGallery._image_preview = thisGallery.images[0].url;
      }

      if(loadedImageRefs.length === thisGallery._images.length) {
        return defer.resolve(thisGallery.images);
      }

      thisGallery._images = loadedImageRefs;
      thisGallery.save(function(err) {
        if(err) return defer.reject(err);
        defer.resolve(thisGallery.images);
      });

    });

    return defer.promise;
  },

  /**
   * DeleteImages - deleteImages from files collection
   *
   * @return void
   * @api public
   */
  deleteImages: function() {
    const File = mongoose.model('File');
    const defer = Q.defer();

    async.each(this._images, function(_image, cb) {
      File.deleteFileById(_image.ref)
        .then(cb.bind(null, null))
        .catch(cb); // cb(err)
    }, function(err) {
      if(err) return defer.reject(err);
      defer.resolve()
    });
    return defer.promise;
  },

  /**
   * Hide security sensitive fields
   *
   * @returns {*|Array|Binary|Object}
   */
  toJSON: function() {
    return this.toObject();;
  }
};

mongoose.model('Gallery', GallerySchema);
<commit_msg>pagination fixed<commit_after>'use strict';

// Module dependencies.
const cleverCore = require('clever-core');
const storage = cleverCore.loadStorage();
const mongoose = require('mongoose');
const Schema  = mongoose.Schema;
const _ = require('lodash');
const Q = require('q');
const async = require('async');
const bubblesort = require('bubble-sort-js');

// Mongoose Error Handling
function hasErrors(err) {
  if (err) {
    console.log(err);
    let modelErrors = [];
    switch (err.code) {
      case 11000: {}
      case 11001: {
        modelErrors.push({
          msg: 'Slug already used',
          param: 'slug'
        });
        break;
      }
      default: {
        if (err.errors) {
          for (var x in err.errors) {
            modelErrors.push({
              param: x,
              msg: err.errors[x].message,
              value: err.errors[x].value
            });
          }
        }
      }
    }
    return modelErrors;
  }

  return null;
}

// Validations
function validateUniqueSlug(value, callback) {
  const Gallery = mongoose.model('Gallery');
  Gallery.find({
    $and: [{
      slug: value
    }, {
      _id: {
        $ne: this._id
      }
    }]
  }, function(err, gallery) {
    callback(err || gallery.length === 0);
  });
};

// Getter
function escapeProperty(value) {
  return _.escape(value);
};

// ImageSchema
const ImageSchema = new Schema({
  ref: {
    type: String,
    required: true
  },
  order: {
    type: Number,
    required: true,
  }
});

// GallerySchema
const GallerySchema = new Schema({
  slug: {
    type: String,
    required: true,
    unique: true,
    // TODO: match valid slug chars
    validate: [validateUniqueSlug, 'Slug is already in-use']
  },
  title: {
    type: String,
    required: true,
    get: escapeProperty
  },
  comment: {
    type: String,
    default: '',
    get: escapeProperty
  },
  _images: {
    type: [ImageSchema],
    default: []
  }
});

// Virtuals
GallerySchema.virtual('image_preview').set(function(url) {
  throw new Error('Gallery::image_preview cannot be set.');
}).get(function() {
  if(this._images.length === 0) return false;
  return this._image_preview || false;
});

GallerySchema.virtual('n_images').set(function(url) {
  throw new Error('Gallery::n_images cannot be set.');
}).get(function() {
  return this.images ? this.images.length : 0;
});

// Static Methods
GallerySchema.statics = {
  /**
   * CountGalleries - return the number of galleries
   *
   * @return {Object}
   * @api public
   */
  countGalleries: function() {
    const Gallery = mongoose.model('Gallery');
    const defer = Q.defer();
    Gallery.count({}, function(err, nGalleries) {
      if (err) return defer.reject(err);
      return defer.resolve(nGalleries);
    });
    return defer.promise;
  },

  /**
   * GetGalleries - return the list of galleries
   *
   * @param {Number} skip
   * @param {Number} limit
   * @return {Object}
   * @api public
   */
  getGalleries: function(skip, limit) {
    const Gallery = mongoose.model('Gallery');
    const options = skip && limit ? {skip: skip, limit: limit} : {skip: 0, limit: 10};
    const defer = Q.defer();
    Gallery.find({}, {}, options, function(err, galleries) {
      if (err) return defer.reject(err);
      return defer.resolve(galleries);
    });
    return defer.promise;
  },

  /**
   * GetGalleryList - return the list of galleries
   *
   * @return {Object}
   * @api public
   */
  getGalleryList: function() {
    const Gallery = mongoose.model('Gallery');
    const defer = Q.defer();
    Gallery.find({}, {}, {}, function(err, galleries) {
      if (err) return defer.reject(err);
      async.map(galleries, function(gallery, cb) {
        const listElement = {};
        listElement._id = gallery._id;
        listElement.title = gallery.title;
        cb(null, listElement);
      }, function(errors, galleryList) {
        if(errors) return defer.reject(errors);
        defer.resolve(galleryList);
      });

    }).sort({ title: -1 });
    return defer.promise;
  },

  /**
   * GetGalleryById - return the gallery matching the id
   *
   * @param {String} id
   * @return {Object}
   * @api public
   */
  getGalleryById: function(id) {
    if(!id) throw new Error('Gallery.getGalleryById: id parameter is mandatory');
    const Gallery = mongoose.model('Gallery');
    const defer = Q.defer();
    Gallery.findOne({_id: id}, function(err, gallery) {
      if (err) return defer.reject(err);
      defer.resolve(gallery);
    });
    return defer.promise;
  },

  /**
   * EditGalleryById - edit the gallery matching the id
   *
   * @param {String} id
   * @return {Object}
   * @api public
   */
  editGalleryById: function(id, galleryParams) {

    if(!id) throw new Error('Gallery.editGalleryById: id parameter is mandatory');
    const Gallery = mongoose.model('Gallery');
    const defer = Q.defer();

    function save(gallery) {

      Object.keys(galleryParams).forEach(function (key, index) {
        gallery[key] = galleryParams[key];
      });

      gallery.save(function(err) {
        const errors = hasErrors(err);
        if(errors) return defer.reject(errors);
        defer.resolve(gallery);
      });
    }

    Gallery.getGalleryById(id)
      .then(save)
      .catch(defer.reject);

    return defer.promise;
  },

  /**
   * AddGalleryImagesByGalleryId
   *
   * @param {String} id
   * @return {Array}
   * @api public
   */
  addGalleryImagesByGalleryId: function(id, images) {

    if(!id) throw new Error('Gallery.addGalleryImagesByGalleryId: id parameter is mandatory');
    if(!images) throw new Error('Gallery.addGalleryImagesByGalleryId: images parameter is mandatory');
    const Gallery = mongoose.model('Gallery');
    const defer = Q.defer();

    function save(gallery) {

      const starterOrder = gallery._images.length;

      images.forEach(function(image, index) {
        if(!image._id) defer.reject(new Error('Gallery.addGalleryImagesByGalleryId: image._id doesn\'t exist'));
        gallery._images.push({
          ref: image._id,
          order: starterOrder + index
        });
      });

      gallery.save(function(err) {
        const errors = hasErrors(err);
        if(errors) return defer.reject(errors);
        defer.resolve(gallery);
      });
    }

    Gallery.getGalleryById(id)
      .then(save)
      .catch(defer.reject);

    return defer.promise;
  },

  /**
   * DeleteGalleryById - delete the gallery matching the id
   *
   * @param {String} id
   * @return {Object}
   * @api public
   */
  deleteGalleryById: function(id) {
    if(!id) throw new Error('Gallery.deleteGalleryById: id parameter is mandatory');
    const Gallery = mongoose.model('Gallery');
    const defer = Q.defer();

    Gallery.getGalleryById(id)
      .then(function(gallery) {
        gallery.deleteImages()
          .then(function (){
            Gallery.remove({_id: gallery._id}, function(err, result) {
              if (err) return defer.reject(err);
              return defer.resolve(result);
            });
          });
      });

    return defer.promise;
  },

  createGallery: function(galleryParams) {
    const Gallery = mongoose.model('Gallery');
    const gallery = new Gallery(galleryParams);

    const defer = Q.defer();
    gallery.save(function(err) {
      const errors = hasErrors(err);
      if(errors) return defer.reject(errors);
      defer.resolve(gallery);
    });

    return defer.promise;
  }
}

// Instance Methods
GallerySchema.methods = {

  /**
   * LoadImages - loadImages from _images
   *
   * @return {Array}
   * @api public
   */
  loadImages: function() {
    const File = mongoose.model('File');
    const defer = Q.defer();
    const thisGallery = this;

    // Order images
    bubblesort(this._images, function(a, b) { return a.order - b.order; });

    async.map(this._images, function(_image, cb) {
      File.getFileById(_image.ref)
        .then(function(image) {
          cb(null, image);
        })
        .catch(cb); // cb(err)
    }, function(err, images) {
      if(err) return defer.reject(err);

      const loadedImages = [];
      const loadedImageRefs = [];

      images.forEach(function(image, index) {
        if(image) {
          loadedImages.push(image);
          loadedImageRefs.push({ref: image._id, order: index})
        }
      });

      thisGallery.images = loadedImages;

      if(thisGallery.images.length > 0) {
        thisGallery._image_preview = thisGallery.images[0].url;
      }

      if(loadedImageRefs.length === thisGallery._images.length) {
        return defer.resolve(thisGallery.images);
      }

      thisGallery._images = loadedImageRefs;
      thisGallery.save(function(err) {
        if(err) return defer.reject(err);
        defer.resolve(thisGallery.images);
      });

    });

    return defer.promise;
  },

  /**
   * DeleteImages - deleteImages from files collection
   *
   * @return void
   * @api public
   */
  deleteImages: function() {
    const File = mongoose.model('File');
    const defer = Q.defer();

    async.each(this._images, function(_image, cb) {
      File.deleteFileById(_image.ref)
        .then(cb.bind(null, null))
        .catch(cb); // cb(err)
    }, function(err) {
      if(err) return defer.reject(err);
      defer.resolve()
    });
    return defer.promise;
  },

  /**
   * Hide security sensitive fields
   *
   * @returns {*|Array|Binary|Object}
   */
  toJSON: function() {
    return this.toObject();;
  }
};

mongoose.model('Gallery', GallerySchema);
<|endoftext|>


<commit_before>const base = require( './base.js' );

module.exports = Object.assign( {}, base, {
    list: [
        'class-mod',
        'flair-contentcreator',
        'flair-css',
        'flair-emissary',
        'flair-forummod',
        'flair-map',
        'flair-mod',
        'flair-rainbow',
        'flair-twitch',
        'flair-youtube',
    ],
    type: 'author_flair_css_class',
} );
<commit_msg>Update more flairs<commit_after>const base = require( './base.js' );

module.exports = Object.assign( {}, base, {
    list: [
        'class-mod',
        'flair-contentcreator',
        'flair-css',
        'flair-emissary',
        'flair-forummod',
        'flair-map',
        'flair-mod',
        'flair-rainbow',
        'flair-tlead',
        'flair-twitch',
        'flair-youtube',
    ],
    type: 'author_flair_css_class',
} );
<|endoftext|>


<commit_before>"use strict";

/*global module, require*/

var d3 = require("d3"),
    _ = require("lodash"),
    leaflet = require("leaflet"),

    legendFactory = require("../../legend/legend-data.js"),

    legendsByName = {
	"total-heat-density": require("./Total Heat Density.json"),
	"public-buildings-heat-density": require("./Public Buildings Heat Density.json"),
	"commercial-heat-density": require("./Commercial Heat Density.json"),
	"industrial-heat-density": require("./Industrial Heat Density.json"),
	"residential-heat-density": require("./Residential Heat Density.json")
    },

    urlsByLayerName = {
	"total-heat-density": "Total Heat Density",
	"public-buildings-heat-density": "Public Buildings Heat Density",
	"commercial-heat-density": "Commercial Heat Density",
	"industrial-heat-density": "Industrial Heat Density",
	"residential-heat-density": "Residential Heat Density"
    },

    maxZoom = 17;

module.exports = {
    layerNames: Object.keys(legendsByName),

    leafletLayers: function(getZoom) {
	var bins = d3.map(),

	    makeLegend = function(layerName, baseUrl) {
		var f = function() {
		    var z = getZoom();

		    if (z > maxZoom) {
			z = maxZoom;
		    }

		    return bins.get(layerName)[z - 1];
		};

		f.header = function() {
		    return layerName + ' kWh/m2/year';
		};

		return f;
	    };

	Object.keys(legendsByName)
	    .forEach(function(layerName) {
		bins.set(
		    layerName,
		    legendsByName[layerName]
			.map(legendFactory.bins)
		);
	    });

	return function(layerName) {
	    var baseUrl = "http://test-tiles.0d9303a4.cdn.memsites.com/" + urlsByLayerName[layerName],

		layer = leaflet.tileLayer(baseUrl + '/Z{z}/{y}/{x}.png', {
		    attribution: 'English National Heat Map,',
		    minZoom: 2,
		    maxZoom: 17,
		    bounds: leaflet.latLngBounds(
			leaflet.latLng(50, -7),
			leaflet.latLng(56, 2)
		    )
		});

	    layer.options.zIndex = 1;
	    layer.legend = makeLegend(layerName, baseUrl);

	    return layer;
	};
    }
};
<commit_msg>Heat map legend no longer errors if you zoom all the way out.<commit_after>"use strict";

/*global module, require*/

var d3 = require("d3"),
    _ = require("lodash"),
    leaflet = require("leaflet"),

    legendFactory = require("../../legend/legend-data.js"),

    legendsByName = {
	"total-heat-density": require("./Total Heat Density.json"),
	"public-buildings-heat-density": require("./Public Buildings Heat Density.json"),
	"commercial-heat-density": require("./Commercial Heat Density.json"),
	"industrial-heat-density": require("./Industrial Heat Density.json"),
	"residential-heat-density": require("./Residential Heat Density.json")
    },

    urlsByLayerName = {
	"total-heat-density": "Total Heat Density",
	"public-buildings-heat-density": "Public Buildings Heat Density",
	"commercial-heat-density": "Commercial Heat Density",
	"industrial-heat-density": "Industrial Heat Density",
	"residential-heat-density": "Residential Heat Density"
    },

    maxZoom = 17;

module.exports = {
    layerNames: Object.keys(legendsByName),

    leafletLayers: function(getZoom) {
	var bins = d3.map(),

	    makeLegend = function(layerName, baseUrl) {
		var f = function() {
		    var z = getZoom();

		    z = Math.min(z, maxZoom);
		    z = Math.max(z, 1);

		    return bins.get(layerName)[z - 1];
		};

		f.header = function() {
		    return layerName + ' kWh/m2/year';
		};

		return f;
	    };

	Object.keys(legendsByName)
	    .forEach(function(layerName) {
		bins.set(
		    layerName,
		    legendsByName[layerName]
			.map(legendFactory.bins)
		);
	    });

	return function(layerName) {
	    var baseUrl = "http://test-tiles.0d9303a4.cdn.memsites.com/" + urlsByLayerName[layerName],

		layer = leaflet.tileLayer(baseUrl + '/Z{z}/{y}/{x}.png', {
		    attribution: 'English National Heat Map,',
		    minZoom: 2,
		    maxZoom: 17,
		    bounds: leaflet.latLngBounds(
			leaflet.latLng(50, -7),
			leaflet.latLng(56, 2)
		    )
		});

	    layer.options.zIndex = 1;
	    layer.legend = makeLegend(layerName, baseUrl);

	    return layer;
	};
    }
};
<|endoftext|>


<commit_before>const PlexRepository = require('src/plex/plexRepository');
const configuration = require('src/config/configuration').getInstance();
const establishedDatabase = require('src/database/database');

const plexRepository = new PlexRepository();

class UpdateRequestsInPlex {
   constructor() {
      this.database = establishedDatabase;
      this.queries = {
         getRequests: `SELECT * FROM requests WHERE status IS 'requested' OR 'downloaded'`,
         saveNewStatus: `UPDATE requests SET status = ? WHERE id IS ? and type IS ?`,
      }
   }

   getRequests() {
      return this.database.all(this.queries.getRequests);
   }

   scrub() {
      return this.getRequests()
         .then((requests) => Promise.all(requests.map(async (movie) => {
            return plexRepository.inPlex(movie)
         })))
         .then((requests_checkInPlex) => requests_checkInPlex.filter((movie) => movie.matchedInPlex))
   }

   updateStatus(status) {
     this.scrub().then((newInPlex) =>
         newInPlex.map((movie) => {
            console.log('updated', movie.title, 'to', status)
            // this.database.run(this.queries.saveNewStatus, [status, movie.id, movie.type])
         })
      )
   }
}

var requestsUpdater = new UpdateRequestsInPlex();
requestsUpdater.updateStatus('downloaded')

module.exports = UpdateRequestsInPlex<commit_msg>Script for updating all requested and downloading request status to downloaded if exist in plex<commit_after>const Plex = require('src/plex/plex')
const configuration = require('src/config/configuration').getInstance();
const plex = new Plex(configuration.get('plex', 'ip'))
const establishedDatabase = require('src/database/database');

class UpdateRequestsInPlex {
  constructor() {
     this.database = establishedDatabase;
     this.queries = {
        getMovies: `SELECT * FROM requests WHERE status = 'requested' OR status = 'downloading'`,
//         getMovies: "select * from requests where status is 'reset'",
        saveNewStatus: `UPDATE requests SET status = ? WHERE id IS ? and type IS ?`,
     }
  }
  getByStatus() {
     return this.database.all(this.queries.getMovies);
  }
  scrub() {
     return this.getByStatus()
        .then((requests) => Promise.all(requests.map(movie => plex.existsInPlex(movie))))
  }

  commitNewStatus(status, id, type, title) {
    console.log(type, title, 'updated to:', status)
    this.database.run(this.queries.saveNewStatus, [status, id, type])
  }

  updateStatus(status) {
    this.getByStatus()
      .then(requests => Promise.all(requests.map(request => plex.existsInPlex(request))))
      .then(matchedRequests => matchedRequests.filter(request => request.existsInPlex))
      .then(newMatches => newMatches.map(match => this.commitNewStatus(status, match.id, match.type, match.title)))
  }
}
var requestsUpdater = new UpdateRequestsInPlex();
requestsUpdater.updateStatus('downloaded')

module.exports = UpdateRequestsInPlex
<|endoftext|>


<commit_before>function openLink(link) {
	window.open(encodeURI(link));
}

function doCustomActions() {
	// no custom actions needed in hosted webapp
}

function trackPage() {
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-46128370-1', 'd26tzgk0gx1hwh.cloudfront.net');
  ga('send', 'pageview');
}

<commit_msg>commenting out unused openLink function<commit_after>//function openLink(link) {
//	window.open(encodeURI(link));
//}

function doCustomActions() {
	// no custom actions needed in hosted webapp
}

function trackPage() {
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-46128370-1', 'd26tzgk0gx1hwh.cloudfront.net');
  ga('send', 'pageview');
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2016 Glyptodon Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * @file Responds to messages received from the clipboard broker, which MUST
 * only send such messages if clipboard access is granted. Requests will take
 * the form of messages having a "type" property which may be "get-data" for
 * requests to read clipboard data and "set-data" for requests to set the
 * current clipboard data. If the type is "get-data", the response callback
 * given to chrome.runtime.sendMessage() will be invoked with the current
 * clipboard data if and when it is successfully read. If the type is
 * "set-data", an additional "data" property must be present which contains
 * the string data to set.
 *
 * @author Michael Jumper
 */

// Wait for and handle any clipboard request messages from the content page
chrome.runtime.onMessage.addListener(function handleMessage(message, sender,
            sendResponse) {

    // Handle message appropriately depending on message type
    switch (message.type) {

        // STUB: Pull clipboard data if requested
        case 'get-data':
            sendResponse('TEST: ' + new Date().toString());
            break;

        // STUB: Set clipboard data if requested
        case 'set-data':
            console.log('SET', message.data);
            break;

    }

});

<commit_msg>GUAC-1480: Implement read/write to clipboard.<commit_after>/*
 * Copyright (C) 2016 Glyptodon Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * @file Responds to messages received from the clipboard broker, which MUST
 * only send such messages if clipboard access is granted. Requests will take
 * the form of messages having a "type" property which may be "get-data" for
 * requests to read clipboard data and "set-data" for requests to set the
 * current clipboard data. If the type is "get-data", the response callback
 * given to chrome.runtime.sendMessage() will be invoked with the current
 * clipboard data if and when it is successfully read. If the type is
 * "set-data", an additional "data" property must be present which contains
 * the string data to set.
 *
 * @author Michael Jumper
 */

(function() {

    /**
     * A textarea which will function as the intermediary between JavaScript
     * and the local clipboard contents.
     *
     * @type {Element}
     */
    var clipboardContents = document.createElement('textarea');
    document.body.appendChild(clipboardContents);

    // Wait for and handle any clipboard request messages from the content page
    chrome.runtime.onMessage.addListener(function handleMessage(message,
                sender, sendResponse) {

        // Handle message appropriately depending on message type
        switch (message.type) {

            // Pull clipboard data if requested
            case 'get-data':

                // Prepare textarea to receive paste
                clipboardContents.value = '';
                clipboardContents.select();

                // Attempt paste of current clipboard, forwarding the
                // resulting data if successful
                if (document.execCommand('paste'))
                    sendResponse(clipboardContents.value);

                break;

            // Set clipboard data if requested
            case 'set-data':

                // Assign and select desired value within textarea
                clipboardContents.value = message.data;
                clipboardContents.select();

                // Attempt copy, failing silently if unsuccessful
                document.execCommand('copy');
                break;

        }

    }); // end message handler

})();

<|endoftext|>