<commit_before>define([
	"dojo/_base/declare", "dijit/_WidgetBase", "dojo/on",
	"dojo/dom-class", "dijit/_Templated", "dojo/text!./templates/GenomeOverview.html",
	"dojo/request", "dojo/_base/lang", "dojox/charting/Chart2D", "dojox/charting/themes/ThreeD", "dojox/charting/action2d/MoveSlice",
	"dojox/charting/action2d/Tooltip", "dojo/dom-construct"

], function (declare, WidgetBase, on,
			 domClass, Templated, Template,
			 xhr, lang, Chart2D, Theme, MoveSlice,
			 ChartTooltip, domConstruct) {
	return declare([WidgetBase, Templated], {
		baseClass: "GenomeOverview",
		disabled: false,
		templateString: Template,
		apiServiceUrl: window.App.dataAPI,
		genome: null,
		genomeFeatureSummary: null,
		"_setGenomeAttr": function (genome) {
			this.genome = genome;
			console.log("Set Genome", genome);

			this.getSummaryData();

			if(this._started){
				this.refresh();
			}
		},
		"_setGenomeFeatureSummaryAttr": function (summary) {
			domConstruct.empty(this.gfDataNode);
			var table = domConstruct.create("table", {}, this.gfDataNode);
			var tbody = domConstruct.create("tbody", {}, table);

			var htr = domConstruct.create("tr", {}, tbody);
			domConstruct.create("td", {}, htr);
			domConstruct.create("td", {innerHTML: "PATRIC"}, htr);
			domConstruct.create("td", {innerHTML: "RefSeq"}, htr);

			Object.keys(summary).forEach(function (prop) {
				var tr = domConstruct.create('tr', {}, tbody);
				domConstruct.create("td", {innerHTML: prop}, tr);
				domConstruct.create("td", {innerHTML: summary[prop]}, tr);
				domConstruct.create("td", {innerHTML: 0}, tr);
			});

			/*
			 if (!this.gfPieChart) {
			 this.gfPieChart = new Chart2D(this.gfPieChartNode);
			 this.gfPieChart.setTheme(Theme);

			 this.gfPieChart.addPlot("default", {
			 type: "Columns",
			 radius: 75,
			 labels: true,
			 labelOffset: -30
			 });
			 this.gfPieChart.addSeries("default", gfData);
			 new MoveSlice(this.gfPieChart,"default");
			 new ChartTooltip(this.gfPieChart,"default");
			 }

			 this.gfPieChart.render();
			 */
		},

		"_setProteinFeatureSummaryAttr": function (summary) {
			var gfData = [];
			Object.keys(summary).forEach(function (prop) {
				gfData.push({text: prop, x: 0, y: summary[prop]});
			});
			console.log("GF DATA: ", gfData);

			if(!this.pfPieChart){
				this.pfPieChart = new Chart2D(this.pfPieChartNode);
				this.pfPieChart.setTheme(Theme);

				this.pfPieChart.addPlot("default", {
					type: "Pie",
					radius: 75,
					labels: true,
					labelOffset: -30
				});
				this.pfPieChart.addSeries("default", gfData);
				new MoveSlice(this.pfPieChart, "default");
				new ChartTooltip(this.pfPieChart, "default");
			}

			this.pfPieChart.render();
		},
		"_setSpecialtyGeneSummaryAttr": function (summary) {
			domConstruct.empty(this.sgDataNode);
			var table = domConstruct.create("table", {}, this.sgDataNode);
			var tbody = domConstruct.create("tbody", {}, table);

			var htr = domConstruct.create("tr", {}, tbody);
			domConstruct.create("td", {}, htr);
			domConstruct.create("td", {innerHTML: "Source"}, htr);
			domConstruct.create("td", {innerHTML: "Genes"}, htr);

			Object.keys(summary).forEach(function (prop) {
				var tr = domConstruct.create('tr', {}, tbody);
				var property_source = prop.split(':');
				domConstruct.create("td", {innerHTML: property_source[0]}, tr);
				domConstruct.create("td", {innerHTML: property_source[1]}, tr);
				domConstruct.create("td", {innerHTML: summary[prop]}, tr);
			});
		},

		getSummaryData: function () {
			// getting genome feature summary
			xhr.get(this.apiServiceUrl + "/genome_feature/?eq(genome_id," + this.genome.genome_id + ")&limit(1)&facet((field,feature_type),(mincount,1))&http_accept=application/solr+json", {
				handleAs: "json",
				headers: {"accept": "application/solr+json"}
			}).then(lang.hitch(this, function (data) {
				console.log("Data: ", data);
				var genomeSummary = {};
				var idx = 0;
				while(idx < data.facet_counts.facet_fields.feature_type.length - 1){
					genomeSummary[data.facet_counts.facet_fields.feature_type[idx]] = data.facet_counts.facet_fields.feature_type[idx + 1];
					idx += 2;
				}
				console.log("Genome Summary: ", genomeSummary);
				this.set("genomeFeatureSummary", genomeSummary);
			}));

			xhr.get(this.apiServiceUrl + "/sp_gene/?eq(genome_id," + this.genome.genome_id + ")&limit(1)&facet((field,property_source),(mincount,1),(sort,index))&http_accept=application/solr+json", {
				handleAs: "json",
				headers: {"accept": "application/solr+json"}
			})
				.then(lang.hitch(this, function (data) {
					console.log("Data: ", data);
					var spSummary = {};
					var idx = 0;
					while(idx < data.facet_counts.facet_fields.property_source.length - 1){
						spSummary[data.facet_counts.facet_fields.property_source[idx]] = data.facet_counts.facet_fields.property_source[idx + 1];
						idx += 2;
					}
					console.log("Specialty Gene Summary: ", spSummary);
					this.set("specialtyGeneSummary", spSummary);
				}));

		},
		refresh: function () {
			if(this.genome && this.genome.genome_id){
				Object.keys(this.genome).forEach(lang.hitch(this, function (prop) {
					if(this[prop + "Node"]){
						this[prop + "Node"].innerHTML = this.genome[prop];
					}
				}));

				this.genomeSummary.innerHTML = "Length: " + this.genome.genome_length + "bp, Chromosomes: " + this.genome.chromosomes + ", Plasmids: " + this.genome.plasmids + ", Contigs: " + this.genome.contigs;
			}else{
				console.log("Invalid Genome: ", this.genome);
			}
		},
		startup: function () {
			if(this._started){
				return;
			}
			this.inherited(arguments);
			this.refresh();
		}

	});
});
<commit_msg>format corrected<commit_after>define([
	"dojo/_base/declare", "dijit/_WidgetBase", "dojo/on",
	"dojo/dom-class", "dijit/_Templated", "dojo/text!./templates/GenomeOverview.html",
	"dojo/request", "dojo/_base/lang", "dojox/charting/Chart2D", "dojox/charting/themes/ThreeD", "dojox/charting/action2d/MoveSlice",
	"dojox/charting/action2d/Tooltip", "dojo/dom-construct"

], function(declare, WidgetBase, on,
			domClass, Templated, Template,
			xhr, lang, Chart2D, Theme, MoveSlice,
			ChartTooltip, domConstruct) {
	return declare([WidgetBase, Templated], {
		baseClass: "GenomeOverview",
		disabled: false,
		templateString: Template,
		apiServiceUrl: window.App.dataAPI,
		genome: null,
		genomeFeatureSummary: null,
		"_setGenomeAttr": function(genome) {
			this.genome = genome;
			console.log("Set Genome", genome);

			this.getSummaryData();

			if(this._started){
				this.refresh();
			}
		},
		"_setGenomeFeatureSummaryAttr": function(summary) {
			domConstruct.empty(this.gfDataNode);
			var table = domConstruct.create("table", {}, this.gfDataNode);
			var tbody = domConstruct.create("tbody", {}, table);

			var htr = domConstruct.create("tr", {}, tbody);
			domConstruct.create("td", {}, htr);
			domConstruct.create("td", {innerHTML: "PATRIC"}, htr);
			domConstruct.create("td", {innerHTML: "RefSeq"}, htr);

			Object.keys(summary).forEach(function(prop) {
				var tr = domConstruct.create('tr', {}, tbody);
				domConstruct.create("td", {innerHTML: prop}, tr);
				domConstruct.create("td", {innerHTML: summary[prop]}, tr);
				domConstruct.create("td", {innerHTML: 0}, tr);
			});

			/*
			 if (!this.gfPieChart) {
			 this.gfPieChart = new Chart2D(this.gfPieChartNode);
			 this.gfPieChart.setTheme(Theme);

			 this.gfPieChart.addPlot("default", {
			 type: "Columns",
			 radius: 75,
			 labels: true,
			 labelOffset: -30
			 });
			 this.gfPieChart.addSeries("default", gfData);
			 new MoveSlice(this.gfPieChart,"default");
			 new ChartTooltip(this.gfPieChart,"default");
			 }

			 this.gfPieChart.render();
			 */
		},

		"_setProteinFeatureSummaryAttr": function(summary) {
			var gfData = [];
			Object.keys(summary).forEach(function(prop) {
				gfData.push({text: prop, x: 0, y: summary[prop]});
			});
			console.log("GF DATA: ", gfData);

			if(!this.pfPieChart){
				this.pfPieChart = new Chart2D(this.pfPieChartNode);
				this.pfPieChart.setTheme(Theme);

				this.pfPieChart.addPlot("default", {
					type: "Pie",
					radius: 75,
					labels: true,
					labelOffset: -30
				});
				this.pfPieChart.addSeries("default", gfData);
				new MoveSlice(this.pfPieChart, "default");
				new ChartTooltip(this.pfPieChart, "default");
			}

			this.pfPieChart.render();
		},
		"_setSpecialtyGeneSummaryAttr": function(summary) {
			domConstruct.empty(this.sgDataNode);
			var table = domConstruct.create("table", {}, this.sgDataNode);
			var tbody = domConstruct.create("tbody", {}, table);

			var htr = domConstruct.create("tr", {}, tbody);
			domConstruct.create("td", {}, htr);
			domConstruct.create("td", {innerHTML: "Source"}, htr);
			domConstruct.create("td", {innerHTML: "Genes"}, htr);

			Object.keys(summary).forEach(function(prop) {
				var tr = domConstruct.create('tr', {}, tbody);
				var property_source = prop.split(':');
				domConstruct.create("td", {innerHTML: property_source[0]}, tr);
				domConstruct.create("td", {innerHTML: property_source[1]}, tr);
				domConstruct.create("td", {innerHTML: summary[prop]}, tr);
			});
		},

		getSummaryData: function() {
			// getting genome feature summary
			xhr.get(this.apiServiceUrl + "/genome_feature/?eq(genome_id," + this.genome.genome_id + ")&limit(1)&facet((field,feature_type),(mincount,1))&http_accept=application/solr+json", {
				handleAs: "json",
				headers: {"accept": "application/solr+json"}
			}).then(lang.hitch(this, function(data) {
				console.log("Data: ", data);
				var genomeSummary = {};
				var idx = 0;
				while(idx < data.facet_counts.facet_fields.feature_type.length - 1){
					genomeSummary[data.facet_counts.facet_fields.feature_type[idx]] = data.facet_counts.facet_fields.feature_type[idx + 1];
					idx += 2;
				}
				console.log("Genome Summary: ", genomeSummary);
				this.set("genomeFeatureSummary", genomeSummary);
			}));

			xhr.get(this.apiServiceUrl + "/sp_gene/?eq(genome_id," + this.genome.genome_id + ")&limit(1)&facet((field,property_source),(mincount,1),(sort,index))&http_accept=application/solr+json", {
				handleAs: "json",
				headers: {"accept": "application/solr+json"}
			})
				.then(lang.hitch(this, function(data) {
					console.log("Data: ", data);
					var spSummary = {};
					var idx = 0;
					while(idx < data.facet_counts.facet_fields.property_source.length - 1){
						spSummary[data.facet_counts.facet_fields.property_source[idx]] = data.facet_counts.facet_fields.property_source[idx + 1];
						idx += 2;
					}
					console.log("Specialty Gene Summary: ", spSummary);
					this.set("specialtyGeneSummary", spSummary);
				}));

		},
		refresh: function() {
			if(this.genome && this.genome.genome_id){
				Object.keys(this.genome).forEach(lang.hitch(this, function(prop) {
					if(this[prop + "Node"]){
						this[prop + "Node"].innerHTML = this.genome[prop];
					}
				}));

				this.genomeSummary.innerHTML = "Length: " + this.genome.genome_length + "bp, Chromosomes: " + this.genome.chromosomes + ", Plasmids: " + this.genome.plasmids + ", Contigs: " + this.genome.contigs;
			}else{
				console.log("Invalid Genome: ", this.genome);
			}
		},
		startup: function() {
			if(this._started){
				return;
			}
			this.inherited(arguments);
			this.refresh();
		}

	});
});
<|endoftext|>


<commit_before>define([
	"dojo/_base/declare","dijit/_WidgetBase","dojo/on",
	"dojo/dom-class","dijit/_TemplatedMixin","dijit/_WidgetsInTemplateMixin",
	"dojo/text!./templates/Expression.html","./AppBase","p3/widget/WorkspaceFilenameValidationTextBox"
], function(
	declare, WidgetBase, on,
	domClass,Templated,WidgetsInTemplate,
	Template,AppBase
){
	return declare([AppBase], {
		"baseClass": "Expression",
		templateString: Template,
		applicationName: "DifferentialExpression",
		constructor: function(){
			this._selfSet=true;
		},

		getValues: function(){
			var values = this.inherited(arguments);
			var exp_values={};
			var ustring_keys=["xformat","source_id_type","data_type", "experiment_title", "experiment_description","organism","metadata_format"];
			var ustring={};
			ustring_keys.forEach(function(k){
				ustring[k]=values[k];
			});
			//get xsetup from object type
			ustring["xsetup"]=this.xfile.searchBox.get("item").type; // should be this.xfile.get("selection").type but need to fix on quick drop
			ustring["organism"]=this.scientific_nameWidget.get('displayedValue');
			exp_values["ustring"]=ustring;
			exp_values["xfile"]=values["xfile"];
			exp_values["mfile"]=values["mfile"];

			return exp_values;
		}

	});
});

<commit_msg>expression: updated processing form submission<commit_after>define([
	"dojo/_base/declare","dijit/_WidgetBase","dojo/on",
	"dojo/dom-class","dijit/_TemplatedMixin","dijit/_WidgetsInTemplateMixin",
	"dojo/text!./templates/Expression.html","./AppBase","p3/widget/WorkspaceFilenameValidationTextBox"
], function(
	declare, WidgetBase, on,
	domClass,Templated,WidgetsInTemplate,
	Template,AppBase
){
	return declare([AppBase], {
		"baseClass": "Expression",
		templateString: Template,
		applicationName: "DifferentialExpression",
		constructor: function(){
			this._selfSet=true;
		},

		getValues: function(){
			var values = this.inherited(arguments);
			var exp_values={};
			var ustring_keys=["xformat","source_id_type","data_type", "experiment_title", "experiment_description","organism","metadata_format"];
			var ustring={};
			ustring_keys.forEach(function(k){
				ustring[k]=values[k];
			});
			//get xsetup from object type
			ustring["xsetup"]=this.xfile.searchBox.get("item").type; // should be this.xfile.get("selection").type but need to fix on quick drop
			ustring["organism"]=this.scientific_nameWidget.get('displayedValue');
			exp_values["ustring"]=JSON.stringify(ustring);
			exp_values["xfile"]=values["xfile"];
			exp_values["mfile"]=values["mfile"];
			exp_values["output_path"]=values["output_path"];

			return exp_values;
		}

	});
});

<|endoftext|>


<commit_before>function FirstPersonControls(world, camera, element) {
    var self = this;

    var target = new THREE.Vector3(0, 0, 0);

    var movementSpeed = 10;
    var lookSpeed = 0.1;

    var movementX = 0;
    var movementY = 0;

    var lat = -1/2 * Math.PI;
    var lon = -3/4 * Math.PI;

    var movingForward = false;
    var movingBack = false;
    var movingLeft = false;
    var movingRight = false;

    var jumping = { pressed : false, released : true };

    var viewHalfX = 0;
    var viewHalfY = 0;

    var selectedItem = 'gun';

    self.isJumping = function () {
        return jumping.pressed;
    };

    self.jumped = function () {
        jumping.pressed = false;
    };

    self.handleResize = function () {
        viewHalfX = element.offsetWidth / 2;
        viewHalfY = element.offsetHeight / 2;
    };

    var havePointerLock = 'pointerLockElement' in document ||
            'mozPointerLockElement' in document ||
            'webkitPointerLockElement' in document;

    if (havePointerLock) {
        element.requestPointerLock = element.requestPointerLock ||
                element.mozRequestPointerLock ||
                element.webkitRequestPointerLock;
    } else {
        alert("You should probably use the latest Chrome or Firefox. Pointer lock is required");
    }

    function mouseDown(event) {
        element.focus();

        event.preventDefault();
        event.stopPropagation();

        element.requestPointerLock();

        if (selectedItem == 'gun') {
            var point = world.findWorldIntersection(camera);
            if (point) world.addSmallCube(point);
        } else if (selectedItem == 'shovel') {
            world.removeLookedAtBlock(camera);
        } else {
            throw "Not sure what to do with the currently selected item: '" + selectedItem + "'";
        }
    };

    function mouseUp(event) {
        event.preventDefault();
        event.stopPropagation();
        // TODO: Add use for this?
    };

    function mouseMove(event) {
        movementX += event.movementX ||
                event.mozMovementX        ||
                event.webkitMovementX     ||
                0;
        movementY += event.movementY ||
                event.mozMovementY        ||
                event.webkitMovementY     ||
                0;
    };

    var selectElm = document.getElementById('selection');
    function select(item) {
        var html = ''
        if (item == 'gun') {
            html = '1: gun, 2: shovel';
        } else if (item == 'shovel') {
            html = '1: gun, 2: shovel';
        } else {
            html = '????? ' + item + ' ?????'
        }
        selectedItem = item;
        selectElm.innerHTML = html;
    }

    function pointerLockChange() {
        if (document.pointerLockElement === element ||
                document.mozPointerLockElement === element ||
                document.webkitPointerLockElement === element) {
            // Pointer was just locked, enable the mousemove listener
            element.addEventListener('mousemove', mouseMove, false);
        } else {
            // Pointer was just unlocked, disable the mousemove listener
            element.removeEventListener('mousemove', mouseMove, false);
        }
    };

    function keyDown(event) {
        switch (event.keyCode) {
            case 188: /*comma*/
            case 38: /*up*/
            case 87: /*W*/ movingForward = true; break;

            case 37: /*left*/
            case 65: /*A*/ movingLeft = true; break;

            case 79: /*O*/
            case 40: /*down*/
            case 83: /*S*/ movingBack = true; break;

            case 69: /*E*/
            case 39: /*right*/
            case 68: /*D*/ movingRight = true; break;

            case 32: /*space*/
                if (jumping.released) {
                    jumping.pressed = true;
                    jumping.released = false;
                }
                break;
            case 49: /*1*/
            case 55: // 1 on prgmr dvorak
                select('gun');
                break;
            case 50: /*2*/
            case 219: // 2 on prgmr dvorak
                select('shovel');
                break;

            default:
                console.log("Warning: Unrecognized keyCode: " + event.keyCode);
        }
    };

    function keyUp(event) {
        switch(event.keyCode) {
            case 188: /*comma*/
            case 38: /*up*/
            case 87: /*W*/ movingForward = false; break;

            case 37: /*left*/
            case 65: /*A*/ movingLeft = false; break;

            case 79: /*O*/
            case 40: /*down*/
            case 83: /*S*/ movingBack = false; break;

            case 69: /*E*/
            case 39: /*right*/
            case 68: /*D*/ movingRight = false; break;

            case 32: /*space*/ jumping.released = true; break;
        }
    };

    function clamp(n, a, b) {
        return Math.max(a, Math.min(b, n));
    }
    var info = document.getElementById('info');
    self.update = function(dt) {
        var ds = dt * movementSpeed;
        var p = camera.position;

        function dirt(p) {
            var block = world.blockAt(p.x, p.y, p.z);
            if (block) return block.isType(Block.DIRT);
            else return true;
        }
        if (movingForward) {
            camera.translateZ(-ds);
            if (dirt(p)) {
                camera.translateZ(ds);
            }
        }
        if (movingBack) {
            camera.translateZ(ds);
            if (dirt(p)) {
                camera.translateZ(-ds);
            }
        }

        if (movingLeft) {
            camera.translateX(-ds);
            if (dirt(p)) {
                camera.translateX(ds);
            }
        }
        if (movingRight) {
            camera.translateX(ds);
            if (dirt(p)) {
                camera.translateX(-ds);
            }
        }

        lon += movementX * dt * lookSpeed;
        lat -= movementY * dt * lookSpeed;
        lat = clamp(lat, -Math.PI + 0.01, -0.01);
        movementX = 0;
        movementY = 0;

        target.x = p.x + Math.sin(lat) * Math.cos(lon);
        target.y = p.y + Math.cos(lat);
        target.z = p.z + Math.sin(lat) * Math.sin(lon);
        camera.lookAt(target);

        info.innerHTML = JSON.stringify({
            x: round(p.x, 2),
            y: round(p.y, 2),
            z: round(p.z, 2)
        });
    };

    document.addEventListener('pointerlockchange', pointerLockChange, false);
    document.addEventListener('mozpointerlockchange', pointerLockChange, false);
    document.addEventListener('webkitpointerlockchange', pointerLockChange, false);

    element.tabIndex = "-1";
    element.addEventListener('contextmenu', function (event) {
        event.preventDefault();
    }, false);
    element.addEventListener('mousedown', mouseDown, false);
    element.addEventListener('mouseup', mouseUp, false);
    element.addEventListener('keydown', keyDown, false);
    element.addEventListener('keyup', keyUp, false);

    function round(n, digits) {
        var factor = Math.pow(10, digits);
        return Math.round(n * factor) / factor;
    }

    self.handleResize();
};
<commit_msg>look change shouldn't actually be times dt.<commit_after>function FirstPersonControls(world, camera, element) {
    var self = this;

    var target = new THREE.Vector3(0, 0, 0);

    var movementSpeed = 10;
    var lookSpeed = 0.005;

    var movementX = 0;
    var movementY = 0;

    var lat = -1/2 * Math.PI;
    var lon = -3/4 * Math.PI;

    var movingForward = false;
    var movingBack = false;
    var movingLeft = false;
    var movingRight = false;

    var jumping = { pressed : false, released : true };

    var viewHalfX = 0;
    var viewHalfY = 0;

    var selectedItem = 'gun';

    self.isJumping = function () {
        return jumping.pressed;
    };

    self.jumped = function () {
        jumping.pressed = false;
    };

    self.handleResize = function () {
        viewHalfX = element.offsetWidth / 2;
        viewHalfY = element.offsetHeight / 2;
    };

    var havePointerLock = 'pointerLockElement' in document ||
            'mozPointerLockElement' in document ||
            'webkitPointerLockElement' in document;

    if (havePointerLock) {
        element.requestPointerLock = element.requestPointerLock ||
                element.mozRequestPointerLock ||
                element.webkitRequestPointerLock;
    } else {
        alert("You should probably use the latest Chrome or Firefox. Pointer lock is required");
    }

    function mouseDown(event) {
        element.focus();

        event.preventDefault();
        event.stopPropagation();

        element.requestPointerLock();

        if (selectedItem == 'gun') {
            var point = world.findWorldIntersection(camera);
            if (point) world.addSmallCube(point);
        } else if (selectedItem == 'shovel') {
            world.removeLookedAtBlock(camera);
        } else {
            throw "Not sure what to do with the currently selected item: '" + selectedItem + "'";
        }
    };

    function mouseUp(event) {
        event.preventDefault();
        event.stopPropagation();
        // TODO: Add use for this?
    };

    function mouseMove(event) {
        movementX += event.movementX ||
                event.mozMovementX        ||
                event.webkitMovementX     ||
                0;
        movementY += event.movementY ||
                event.mozMovementY        ||
                event.webkitMovementY     ||
                0;
    };

    var selectElm = document.getElementById('selection');
    function select(item) {
        var html = ''
        if (item == 'gun') {
            html = '1: gun, 2: shovel';
        } else if (item == 'shovel') {
            html = '1: gun, 2: shovel';
        } else {
            html = '????? ' + item + ' ?????'
        }
        selectedItem = item;
        selectElm.innerHTML = html;
    }

    function pointerLockChange() {
        if (document.pointerLockElement === element ||
                document.mozPointerLockElement === element ||
                document.webkitPointerLockElement === element) {
            // Pointer was just locked, enable the mousemove listener
            element.addEventListener('mousemove', mouseMove, false);
        } else {
            // Pointer was just unlocked, disable the mousemove listener
            element.removeEventListener('mousemove', mouseMove, false);
        }
    };

    function keyDown(event) {
        switch (event.keyCode) {
            case 188: /*comma*/
            case 38: /*up*/
            case 87: /*W*/ movingForward = true; break;

            case 37: /*left*/
            case 65: /*A*/ movingLeft = true; break;

            case 79: /*O*/
            case 40: /*down*/
            case 83: /*S*/ movingBack = true; break;

            case 69: /*E*/
            case 39: /*right*/
            case 68: /*D*/ movingRight = true; break;

            case 32: /*space*/
                if (jumping.released) {
                    jumping.pressed = true;
                    jumping.released = false;
                }
                break;
            case 49: /*1*/
            case 55: // 1 on prgmr dvorak
                select('gun');
                break;
            case 50: /*2*/
            case 219: // 2 on prgmr dvorak
                select('shovel');
                break;

            default:
                console.log("Warning: Unrecognized keyCode: " + event.keyCode);
        }
    };

    function keyUp(event) {
        switch(event.keyCode) {
            case 188: /*comma*/
            case 38: /*up*/
            case 87: /*W*/ movingForward = false; break;

            case 37: /*left*/
            case 65: /*A*/ movingLeft = false; break;

            case 79: /*O*/
            case 40: /*down*/
            case 83: /*S*/ movingBack = false; break;

            case 69: /*E*/
            case 39: /*right*/
            case 68: /*D*/ movingRight = false; break;

            case 32: /*space*/ jumping.released = true; break;
        }
    };

    function clamp(n, a, b) {
        return Math.max(a, Math.min(b, n));
    }
    var info = document.getElementById('info');
    self.update = function(dt) {
        var ds = dt * movementSpeed;
        var p = camera.position;

        function dirt(p) {
            var block = world.blockAt(p.x, p.y, p.z);
            if (block) return block.isType(Block.DIRT);
            else return true;
        }
        if (movingForward) {
            camera.translateZ(-ds);
            if (dirt(p)) {
                camera.translateZ(ds);
            }
        }
        if (movingBack) {
            camera.translateZ(ds);
            if (dirt(p)) {
                camera.translateZ(-ds);
            }
        }

        if (movingLeft) {
            camera.translateX(-ds);
            if (dirt(p)) {
                camera.translateX(ds);
            }
        }
        if (movingRight) {
            camera.translateX(ds);
            if (dirt(p)) {
                camera.translateX(-ds);
            }
        }

        lon += movementX * lookSpeed;
        lat -= movementY * lookSpeed;
        lat = clamp(lat, -Math.PI + 0.01, -0.01);
        movementX = 0;
        movementY = 0;

        target.x = p.x + Math.sin(lat) * Math.cos(lon);
        target.y = p.y + Math.cos(lat);
        target.z = p.z + Math.sin(lat) * Math.sin(lon);
        camera.lookAt(target);

        info.innerHTML = JSON.stringify({
            x: round(p.x, 2),
            y: round(p.y, 2),
            z: round(p.z, 2)
        });
    };

    document.addEventListener('pointerlockchange', pointerLockChange, false);
    document.addEventListener('mozpointerlockchange', pointerLockChange, false);
    document.addEventListener('webkitpointerlockchange', pointerLockChange, false);

    element.tabIndex = "-1";
    element.addEventListener('contextmenu', function (event) {
        event.preventDefault();
    }, false);
    element.addEventListener('mousedown', mouseDown, false);
    element.addEventListener('mouseup', mouseUp, false);
    element.addEventListener('keydown', keyDown, false);
    element.addEventListener('keyup', keyUp, false);

    function round(n, digits) {
        var factor = Math.pow(10, digits);
        return Math.round(n * factor) / factor;
    }

    self.handleResize();
};
<|endoftext|>


<commit_before>'use strict';

var app = app || {};

(function(module){
  var challengePong = (callback) => {
    $('.leaderboard').on('click', function(){
      console.log(app.Player.localUser);
      $.get('/challenge', {challenger: app.Player.localUser, defender:}).then(callback);
    })
  }
  module.challengePong = challengePong;
})(app)
<commit_msg>added a listener to get the user and pick the available challenges, not done<commit_after>'use strict';

var app = app || {};

(function(module){
  var challengePong = (callback) => {
    $('.leaderboard').on('click', function(){
      console.log(app.Player.localUser);
      $.get('/challenge', {challenger: app.Player.localUser/*, defender:*/}).then(callback);
    })
  }
  module.challengePong = challengePong;
})(app)
<|endoftext|>


<commit_before>"use strict";
module.exports =
function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
var util = require("./util");
var ASSERT = require("./assert");
var tryCatch = util.tryCatch;

Promise.method = function (fn) {
    if (typeof fn !== "function") {
        throw new Promise.TypeError(FUNCTION_ERROR + util.classString(fn));
    }
    return function () {
        var ret = new Promise(INTERNAL);
        ret._captureStackTrace();
        ret._pushContext();
        var value = tryCatch(fn).apply(this, arguments);
        ret._popContext();
        ret._resolveFromSyncValue(value);
        return ret;
    };
};

Promise.attempt = Promise["try"] = function (fn) {
    if (typeof fn !== "function") {
        return apiRejection(FUNCTION_ERROR + util.classString(fn));
    }
    var ret = new Promise(INTERNAL);
    ret._captureStackTrace();
    ret._pushContext();
    var value;
    if (arguments.length > 1) {
        debug.deprecated("calling Promise.try with more than 1 argument");
        var arg = arguments[1];
        var ctx = arguments[2];
        value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
                                  : tryCatch(fn).call(ctx, arg);
    } else {
        value = tryCatch(fn)();
    }
    ret._popContext();
    ret._resolveFromSyncValue(value);
    return ret;
};

Promise.prototype._resolveFromSyncValue = function (value) {
    ASSERT(!this._isFollowing());
    if (value === util.errorObj) {
        this._rejectCallback(value.e, false);
    } else {
        this._resolveCallback(value, true);
    }
};
};
<commit_msg>Check for forgotten returns when using Promise.try or Promise.method<commit_after>"use strict";
module.exports =
function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
var util = require("./util");
var ASSERT = require("./assert");
var tryCatch = util.tryCatch;

Promise.method = function (fn) {
    if (typeof fn !== "function") {
        throw new Promise.TypeError(FUNCTION_ERROR + util.classString(fn));
    }
    return function () {
        var ret = new Promise(INTERNAL);
        ret._captureStackTrace();
        ret._pushContext();
        var value = tryCatch(fn).apply(this, arguments);
        var promiseCreated = ret._popContext();
        debug.checkForgottenReturns(
            value, promiseCreated, "Promise.method", ret);
        ret._resolveFromSyncValue(value);
        return ret;
    };
};

Promise.attempt = Promise["try"] = function (fn) {
    if (typeof fn !== "function") {
        return apiRejection(FUNCTION_ERROR + util.classString(fn));
    }
    var ret = new Promise(INTERNAL);
    ret._captureStackTrace();
    ret._pushContext();
    var value;
    if (arguments.length > 1) {
        debug.deprecated("calling Promise.try with more than 1 argument");
        var arg = arguments[1];
        var ctx = arguments[2];
        value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
                                  : tryCatch(fn).call(ctx, arg);
    } else {
        value = tryCatch(fn)();
    }
    var promiseCreated = ret._popContext();
    debug.checkForgottenReturns(
        value, promiseCreated, "Promise.try", ret);
    ret._resolveFromSyncValue(value);
    return ret;
};

Promise.prototype._resolveFromSyncValue = function (value) {
    ASSERT(!this._isFollowing());
    if (value === util.errorObj) {
        this._rejectCallback(value.e, false);
    } else {
        this._resolveCallback(value, true);
    }
};
};
<|endoftext|>


<commit_before>/* global app:true, io:false */

var socket;
var myname;
var block_id;
var pattern_array = [];
var pattern_string;

(function() {
  'use strict';

  /*socket = io.connect();
  socket.on('connect', function(){
  	socket.emit('/replay/#join');
  });

  socket.on('message', function (message) {
      console.log(message);
  });

  socket.on('disconnect', function() {
      console.log('>>> DB disconnected');
  });*/

  app = app || {};

  app.Reset = Backbone.Model.extend({
    defaults: {
      success: false,
      errors: [],
      errfor: {},
      blockid: undefined,
      confitm: ''
    },
    url: function(){
      return '/account/pattern/' + this.get('block_id') +'/';
    }
  });

  app.PatternView = Backbone.View.extend({
    el: '#pattern_menu',
    template: _.template( $('#tmpl-pattern_menu').html() ),
    events: {
      'click .btn-check': 'reqCheck',
      'click .btn-edit': 'reqEdit',
      'click .btn-submit': 'reqSubmit'
    },
    initialize: function() {
      //this.model = new app.Blocks();
      //this.listenTo(this.model, 'sync', this.render);
      this.render();
    },
    render: function() {
      this.$el.html(this.template);
    },
    reqCheck: function() {
      document.getElementById("btn_check").disabled = true;
      document.getElementById("btn_submit").disabled = false;
      document.getElementById("btn_edit").disabled = false;
      var input = document.getElementById("pattern_input").value.split(/\n/);
      input = cleanArray(input);

      input.forEach(function(line){
	    var res = line.split(",");
	    pattern_array.push(res);
      });
      console.log(pattern_array);

      pattern_string = input.join("&&");
      console.log(pattern_string);
    },
    reqEdit: function() {
      document.getElementById("btn_check").disabled = false;
      document.getElementById("btn_submit").disabled = true;
      document.getElementById("btn_edit").disabled = true;
    },
    reqSubmit: function() {
      document.getElementById("btn_check").disabled = true;
      document.getElementById("btn_submit").disabled = true;
      document.getElementById("btn_edit").disabled = true;
      console.log("Submit");
    }
  });

  app.Router = Backbone.Router.extend({
    routes: {
      'account/pattern/': 'default',
      'account/pattern/load/:block/': 'load'
    },
    default: function(){
      console.log(" >>default view, nothing loaded");
    },
    load: function(block) {
      console.log(">> loading block "+block);
      block_id = block;
      var info_div = document.getElementById("info_box");
      var info_text = document.createElement("h6");
      var block_node = document.createTextNode("Pattern for [ block # "+block_id+" ]");
      var pattern_node = document.createTextNode(" -  [ pattern # "+" ]");
	info_text.appendChild(block_node);
	info_text.appendChild(pattern_node);
	info_div.appendChild(info_text);
      document.getElementById("btn_submit").disabled = true;
      document.getElementById("btn_edit").disabled = true;
      //socket.emit('/replay/#callblock', { targetBlock: block});
      setupVis();
    }
  });

  $(document).ready(function() {
    app.patternView = new app.PatternView();
    app.router = new app.Router();
    Backbone.history.start({ pushState: true });
  });
}());

function cleanArray(actual){
  var newArray = new Array();
  for(var i = 0; i<actual.length; i++){
      if (actual[i].length > 0){
        newArray.push(actual[i]);
    }
  }
  return newArray;
}

/////////////////////////////
// Canvas setup functions
/////////////////////////////

var 	svg_led;

function setupVis(){
    d3.select("#pattern_vis").selectAll("svg")
	.remove();

    svg_vis = d3.select("#pattern_vis").append("svg")
	.attr("width", 300)
	.attr("height", 900)
	.append("g");
	//.attr("transform", "translate(4, 4)");
}

 /*   var frame = svg_data_vis.selectAll(".frame")
	    .data(d3data)
    .enter().append("g")
	    .attr("class", "block")
	    .attr("transform", function (d,i)
	    {
		    var dx = (i+1)%100*datavis_x_gap;
		    var dy = 20 + Math.floor((i+1)/100)*datavis_y_gap;
		    return "translate(" + dx + ","+ dy + ")";
	    });
	    //.on('mouseover', tip.show)
	    //.on('mouseout', tip.hide);

    frame.append("rect")
	    .attr("class", function (d,i)
	    {
		    var class_name;
		    if(i==current_frame){
		      class_name="current-frame";
		    }
		    else{
		      if (d.ledarray.length>0){
			    class_name="frame-with-led";
		      }else{
			    class_name="frame-no-led";
		      }

		    }
		    return class_name;
	    })
	    .attr("width", 8)
	    .attr("height", 8);*/
	    /*.attr("led", function (d){
		    if (d.ledarray.length>0){
			    return true;
		    }else{
			    return false
		    }
	    });*/
	    //.on('mouseover', tip.show)
	    //.on('mouseout', tip.hide)
	    //.on('click', mouseclick);
    /*frame.append("line")
	    .attr("class", function (d,i)
	    {
		    var class_name = "stroke-led";
		    return class_name;
	    })
	    .attr("x1", 4)
	    .attr("y1", 4)
	    .attr("x2", function (d){
	      if (d.ledarray.length>0) {
		var x2=0;

		d.ledarray.forEach(function(ele){
		  x2 = x2 + parseFloat(ele.arrow[1])*8 - parseFloat(ele.arrow[3])*8;
		});

		return 4 + x2/(d.ledarray.length)
	      }else{
		return 4
	      }
	    })
	    .attr("y2",function (d){
	      if (d.ledarray.length>0) {
		var y2=0;

		d.ledarray.forEach(function(ele){
		  y2 = y2 + parseFloat(ele.arrow[0])*8 - parseFloat(ele.arrow[2])*8;
		});

		return 4 + y2/(d.ledarray.length)
	      }else{
		return 4
	      }

	      return 4
	    });
	    */<commit_msg>pattern vis<commit_after>/* global app:true, io:false */

var socket;
var myname;
var block_id;
var pattern_array = [];
var pattern_string;

(function() {
  'use strict';

  /*socket = io.connect();
  socket.on('connect', function(){
  	socket.emit('/replay/#join');
  });

  socket.on('message', function (message) {
      console.log(message);
  });

  socket.on('disconnect', function() {
      console.log('>>> DB disconnected');
  });*/

  app = app || {};

  app.Reset = Backbone.Model.extend({
    defaults: {
      success: false,
      errors: [],
      errfor: {},
      blockid: undefined,
      confitm: ''
    },
    url: function(){
      return '/account/pattern/' + this.get('block_id') +'/';
    }
  });

  app.PatternView = Backbone.View.extend({
    el: '#pattern_menu',
    template: _.template( $('#tmpl-pattern_menu').html() ),
    events: {
      'click .btn-check': 'reqCheck',
      'click .btn-edit': 'reqEdit',
      'click .btn-submit': 'reqSubmit'
    },
    initialize: function() {
      //this.model = new app.Blocks();
      //this.listenTo(this.model, 'sync', this.render);
      this.render();
    },
    render: function() {
      this.$el.html(this.template);
    },
    reqCheck: function() {
      document.getElementById("btn_check").disabled = true;
      document.getElementById("btn_submit").disabled = false;
      document.getElementById("btn_edit").disabled = false;
      document.getElementById("pattern_input").disabled = false;
      var input = document.getElementById("pattern_input").value.split(/\n/);
      input = cleanArray(input);

      input.forEach(function(line){
	    var res = line.split(",");
	    pattern_array.push(res);
      });
      console.log(pattern_array);

      pattern_string = input.join("&&");
      console.log(pattern_string);
    },
    reqEdit: function() {
      document.getElementById("btn_check").disabled = false;
      document.getElementById("btn_submit").disabled = true;
      document.getElementById("btn_edit").disabled = true;
      document.getElementById("pattern_input").disabled = true;
    },
    reqSubmit: function() {
      document.getElementById("btn_check").disabled = true;
      document.getElementById("btn_submit").disabled = true;
      document.getElementById("btn_edit").disabled = true;
      console.log("Submit");
    }
  });

  app.Router = Backbone.Router.extend({
    routes: {
      'account/pattern/': 'default',
      'account/pattern/load/:block/': 'load'
    },
    default: function(){
      console.log(" >>default view, nothing loaded");
    },
    load: function(block) {
      console.log(">> loading block "+block);
      block_id = block;
      var info_div = document.getElementById("info_box");
      var info_text = document.createElement("h6");
      var block_node = document.createTextNode("Pattern for [ block # "+block_id+" ]");
      var pattern_node = document.createTextNode(" -  [ pattern # "+" ]");
	info_text.appendChild(block_node);
	info_text.appendChild(pattern_node);
	info_div.appendChild(info_text);
      document.getElementById("btn_submit").disabled = true;
      document.getElementById("btn_edit").disabled = true;
      //socket.emit('/replay/#callblock', { targetBlock: block});
      setupVis();
    }
  });

  $(document).ready(function() {
    app.patternView = new app.PatternView();
    app.router = new app.Router();
    Backbone.history.start({ pushState: true });
  });
}());

function cleanArray(actual){
  var newArray = new Array();
  for(var i = 0; i<actual.length; i++){
      if (actual[i].length > 0){
        newArray.push(actual[i]);
    }
  }
  return newArray;
}

/////////////////////////////
// Canvas setup functions
/////////////////////////////

var 	svg_led;

function setupVis(){
    d3.select("#pattern_vis").selectAll("svg")
	.remove();

    svg_vis = d3.select("#pattern_vis").append("svg")
	.attr("width", 300)
	.attr("height", 900)
	.append("g");
	//.attr("transform", "translate(4, 4)");
}

 /*   var frame = svg_data_vis.selectAll(".frame")
	    .data(d3data)
    .enter().append("g")
	    .attr("class", "block")
	    .attr("transform", function (d,i)
	    {
		    var dx = (i+1)%100*datavis_x_gap;
		    var dy = 20 + Math.floor((i+1)/100)*datavis_y_gap;
		    return "translate(" + dx + ","+ dy + ")";
	    });
	    //.on('mouseover', tip.show)
	    //.on('mouseout', tip.hide);

    frame.append("rect")
	    .attr("class", function (d,i)
	    {
		    var class_name;
		    if(i==current_frame){
		      class_name="current-frame";
		    }
		    else{
		      if (d.ledarray.length>0){
			    class_name="frame-with-led";
		      }else{
			    class_name="frame-no-led";
		      }

		    }
		    return class_name;
	    })
	    .attr("width", 8)
	    .attr("height", 8);*/
	    /*.attr("led", function (d){
		    if (d.ledarray.length>0){
			    return true;
		    }else{
			    return false
		    }
	    });*/
	    //.on('mouseover', tip.show)
	    //.on('mouseout', tip.hide)
	    //.on('click', mouseclick);
    /*frame.append("line")
	    .attr("class", function (d,i)
	    {
		    var class_name = "stroke-led";
		    return class_name;
	    })
	    .attr("x1", 4)
	    .attr("y1", 4)
	    .attr("x2", function (d){
	      if (d.ledarray.length>0) {
		var x2=0;

		d.ledarray.forEach(function(ele){
		  x2 = x2 + parseFloat(ele.arrow[1])*8 - parseFloat(ele.arrow[3])*8;
		});

		return 4 + x2/(d.ledarray.length)
	      }else{
		return 4
	      }
	    })
	    .attr("y2",function (d){
	      if (d.ledarray.length>0) {
		var y2=0;

		d.ledarray.forEach(function(ele){
		  y2 = y2 + parseFloat(ele.arrow[0])*8 - parseFloat(ele.arrow[2])*8;
		});

		return 4 + y2/(d.ledarray.length)
	      }else{
		return 4
	      }

	      return 4
	    });
	    */<|endoftext|>


<commit_before>// ==UserScript==
// @name         hide ads and premium
// @description  kleinanzeigen.ebay.de
// @version      1.0.2
// @grant        none
// @icon         http://www.google.com/s2/favicons?domain=kleinanzeigen.ebay.de
// @namespace    https://github.com/solygen/userscripts
// @repository   https://github.com/solygen/userscripts.git
// @license      MIT
//
// @include      http://kleinanzeigen.ebay.de/*

// @require      https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js
//
// @updateURL    https://rawgithub.com/solygen/userscripts/master/scripts/kleinanzeigen.ebay.de/hide-ads.user.js
// @downloadURL  https://rawgithub.com/solygen/userscripts/master/scripts/kleinanzeigen.ebay.de/hide-ads.user.js
// @homepage     https://github.com/solygen/userscripts

// ==/UserScript==

(function () {

    'use strict';

    function rearrange () {
        var itemnodes = $('.managead-listitem-features');

        $.each(itemnodes, function (i, node) {
            node = $(node);

            // remove premium options and move statistics node
            node.empty()
                .append(
                    node.parent().find('.horizontal-list').last()
                ).css({
                    'font-size': '30px',
                    'padding-left': '350px'
                });

            // auto extend
            $('.my-manageads-adlist .managead-listitem-action-extend').trigger('click');

            // stats
            $.each(node.find('li'), function (i, node) {
                node = $(node);

                var img = node.find('i'),
                    label = $('<strong>').text(
                                            node.text()
                                                .replace('Besucher', '')
                                                .replace('mal gemerkt', '')
                                                .trim()
                                        )
                                        .css('padding-left', '6px');

                node.empty()
                    .css('display', 'block');

                // do not show '0' values
                if (label.text() === '0' || label.text() === '')
                    return;
                node.append(img, label);
            });
        });
    }

    // hide adds
    setTimeout(function () {
        // simply remove premium stuff
        $('#srp_adsense-top, #srp_adsense-middle, #srp_adsense-bottom, #srchrslt-adtable-topads, .headerbox.t-border-yellow, #home-gallery').remove();

        // re-arrange 'meine kleinanzeigen'
        if (!$('.managead-listitem-features').length) return;
        rearrange();

    }, 400);

    // clear title
    document.title = (document.title.split('|')[0]).trim();

})();
<commit_msg>fix auto extend<commit_after>// ==UserScript==
// @name         hide ads and premium
// @description  kleinanzeigen.ebay.de
// @version      1.0.3
// @grant        none
// @icon         http://www.google.com/s2/favicons?domain=kleinanzeigen.ebay.de
// @namespace    https://github.com/solygen/userscripts
// @repository   https://github.com/solygen/userscripts.git
// @license      MIT
//
// @include      http://kleinanzeigen.ebay.de/*

// @require      https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js
//
// @updateURL    https://rawgithub.com/solygen/userscripts/master/scripts/kleinanzeigen.ebay.de/hide-ads.user.js
// @downloadURL  https://rawgithub.com/solygen/userscripts/master/scripts/kleinanzeigen.ebay.de/hide-ads.user.js
// @homepage     https://github.com/solygen/userscripts

// ==/UserScript==

(function () {

    'use strict';

    function rearrange () {
        var itemnodes = $('.managead-listitem-features');

        $.each(itemnodes, function (i, node) {
            node = $(node);

            // remove premium options and move statistics node
            node.empty()
                .append(
                    node.parent().find('.horizontal-list').last()
                ).css({
                    'font-size': '30px',
                    'padding-left': '350px'
                });

            // auto extend
            $('.managead-listitem-action-extend').trigger('click');

            // stats
            $.each(node.find('li'), function (i, node) {
                node = $(node);

                var img = node.find('i'),
                    label = $('<strong>').text(
                                            node.text()
                                                .replace('Besucher', '')
                                                .replace('mal gemerkt', '')
                                                .trim()
                                        )
                                        .css('padding-left', '6px');

                node.empty()
                    .css('display', 'block');

                // do not show '0' values
                if (label.text() === '0' || label.text() === '')
                    return;
                node.append(img, label);
            });
        });
    }

    // hide adds
    setTimeout(function () {
        // simply remove premium stuff
        $('#srp_adsense-top, #srp_adsense-middle, #srp_adsense-bottom, #srchrslt-adtable-topads, .headerbox.t-border-yellow, #home-gallery').remove();

        // re-arrange 'meine kleinanzeigen'
        if (!$('.managead-listitem-features').length) return;
        rearrange();

    }, 400);

    // clear title
    document.title = (document.title.split('|')[0]).trim();

})();
<|endoftext|>


<commit_before>const chartMixin = {
  props: {
    data: { type: [Object, Array], default: null },
    settings: { type: Object, default () { return {} } },
    width: { type: String, default: 'auto' },
    height: { type: String, default: '400px' },
    beforeConfig: { type: Function },
    afterConfig: { type: Function },
    events: { type: Object },
    grid: { type: Object },
    colors: { type: Array },
    tooltipVisible: { type: Boolean, default: true },
    legendVisible: { type: Boolean, default: true },
    legendPosition: { type: String },
    markLine: { type: Object },
    markArea: { type: Object },
    markPoint: { type: Object },
    visualMap: { type: [Object, Array] },
    dataZoom: { type: [Object, Array] },
    toolbox: { type: Object },
    initOptions: { type: Object, default () { return {} } },
    title: Object,
    legend: Object,
    xAxis: Object,
    yAxis: Object,
    radar: Object,
    tooltip: Object,
    axisPointer: Object,
    brush: Object,
    geo: Object,
    timeline: Object,
    graphic: Object,
    series: Object,
    backgroundColor: [Object, String],
    textStyle: Object,
    animation: Object
  },

  watch: {
    data: {
      deep: true,
      handler (v) {
        if (v) { this.dataHandler(v) }
      }
    },

    settings: {
      deep: true,
      handler (v) {
        if (v.type && this.chartLib) this.chartHandler = this.chartLib[v.type]
        this.dataHandler(this.data)
      }
    }
  },

  computed: {
    canvasStyle () {
      return {
        width: this.width,
        height: this.height,
        position: 'relative'
      }
    }
  },

  methods: {
    dataHandler (data) {
      if (!this.chartHandler) return
      if (!data ||
        !Array.isArray(data.columns) ||
        !Array.isArray(data.rows)) return false
      const { columns, rows } = data
      const extra = {
        tooltipVisible: this.tooltipVisible,
        legendVisible: this.legendVisible
      }
      if (this.beforeConfig) data = this.beforeConfig(data)

      let options = this.chartHandler(columns, rows, this.settings, extra)

      if (options) {
        if (this.legendPosition && options.legend) {
          options.legend[this.legendPosition] = 10
          if (~['left', 'right'].indexOf(this.legendPosition)) {
            options.legend.top = 'middle'
            options.legend.orient = 'vertical'
          }
        }
        if (this.colors) options.color = this.colors
        if (this.grid) options.grid = this.grid
        if (this.dataZoom) options.dataZoom = this.dataZoom
        if (this.visualMap) options.visualMap = this.visualMap
        if (this.toolbox) options.toolbox = this.toolbox
        if (this.title) options.title = this.title
        if (this.legend) options.legend = this.legend
        if (this.xAxis) options.xAxis = this.xAxis
        if (this.yAxis) options.yAxis = this.yAxis
        if (this.radar) options.radar = this.radar
        if (this.tooltip) options.tooltip = this.tooltip
        if (this.axisPointer) options.axisPointer = this.axisPointer
        if (this.brush) options.brush = this.brush
        if (this.geo) options.geo = this.geo
        if (this.timeline) options.timeline = this.timeline
        if (this.graphic) options.graphic = this.graphic
        if (this.series) options.series = this.series
        if (this.backgroundColor) options.backgroundColor = this.backgroundColor
        if (this.textStyle) options.textStyle = this.textStyle
        if (this.animation) {
          Object.keys(this.animation).forEach(key => {
            options[key] = this.animation[key]
          })
        }
        if (this.markArea || this.markLine || this.markPoint) {
          const marks = {
            markArea: this.markArea,
            markLine: this.markLine,
            markPoint: this.markPoint
          }
          const series = options.series
          if (this.getType(series) === '[object Array]') {
            series.forEach(item => {
              this.addMark(item, marks)
            })
          } else if (this.getType(series) === '[object Object]') {
            this.addMark(series, marks)
          }
        }
        if (this.afterConfig) options = this.afterConfig(options)
        this.echarts.setOption(options, true)
      }
    },

    addMark (seriesItem, marks) {
      Object.keys(marks).forEach(key => {
        if (marks[key]) {
          seriesItem[key] = marks[key]
        }
      })
    },

    getType (v) {
      return Object.prototype.toString.call(v)
    },

    init () {
      if (this.echarts) return
      this.echarts = this.echartsLib.init(this.$refs.canvas, 've-chart', this.initOptions)
      if (this.data) this.dataHandler(this.data)
      if (this.events) this.bindEvents()
    },

    bindEvents () {
      Object.keys(this.events).forEach(event => {
        this.echarts.on(event, this.events[event])
      })
    }
  },

  mounted () {
    this.init()
    window.addEventListener('resize', this.echarts.resize)
  },

  beforeDestory () {
    window.removeEventListener('resize', this.echarts.resize)
    this.echarts.dispose()
  }
}

export default chartMixin
<commit_msg>新增：增加watcher到所有的props上<commit_after>const chartMixin = {
  props: {
    data: { type: [Object, Array], default: null },
    settings: { type: Object, default () { return {} } },
    width: { type: String, default: 'auto' },
    height: { type: String, default: '400px' },
    beforeConfig: { type: Function },
    afterConfig: { type: Function },
    events: { type: Object },
    grid: { type: Object },
    colors: { type: Array },
    tooltipVisible: { type: Boolean, default: true },
    legendVisible: { type: Boolean, default: true },
    legendPosition: { type: String },
    markLine: { type: Object },
    markArea: { type: Object },
    markPoint: { type: Object },
    visualMap: { type: [Object, Array] },
    dataZoom: { type: [Object, Array] },
    toolbox: { type: Object },
    initOptions: { type: Object, default () { return {} } },
    title: Object,
    legend: Object,
    xAxis: Object,
    yAxis: Object,
    radar: Object,
    tooltip: Object,
    axisPointer: Object,
    brush: Object,
    geo: Object,
    timeline: Object,
    graphic: Object,
    series: Object,
    backgroundColor: [Object, String],
    textStyle: Object,
    animation: Object
  },

  watch: {
    data: {
      deep: true,
      handler (v) {
        if (v) { this.dataHandler(v) }
      }
    },

    settings: {
      deep: true,
      handler (v) {
        if (v.type && this.chartLib) this.chartHandler = this.chartLib[v.type]
        this.dataHandler(this.data)
      }
    }
  },

  computed: {
    canvasStyle () {
      return {
        width: this.width,
        height: this.height,
        position: 'relative'
      }
    }
  },

  methods: {
    dataHandler (data) {
      if (!this.chartHandler) return
      if (!data ||
        !Array.isArray(data.columns) ||
        !Array.isArray(data.rows)) return false
      const { columns, rows } = data
      const extra = {
        tooltipVisible: this.tooltipVisible,
        legendVisible: this.legendVisible
      }
      if (this.beforeConfig) data = this.beforeConfig(data)

      let options = this.chartHandler(columns, rows, this.settings, extra)

      if (options) {
        if (this.legendPosition && options.legend) {
          options.legend[this.legendPosition] = 10
          if (~['left', 'right'].indexOf(this.legendPosition)) {
            options.legend.top = 'middle'
            options.legend.orient = 'vertical'
          }
        }
        if (this.colors) options.color = this.colors
        if (this.grid) options.grid = this.grid
        if (this.dataZoom) options.dataZoom = this.dataZoom
        if (this.visualMap) options.visualMap = this.visualMap
        if (this.toolbox) options.toolbox = this.toolbox
        if (this.title) options.title = this.title
        if (this.legend) options.legend = this.legend
        if (this.xAxis) options.xAxis = this.xAxis
        if (this.yAxis) options.yAxis = this.yAxis
        if (this.radar) options.radar = this.radar
        if (this.tooltip) options.tooltip = this.tooltip
        if (this.axisPointer) options.axisPointer = this.axisPointer
        if (this.brush) options.brush = this.brush
        if (this.geo) options.geo = this.geo
        if (this.timeline) options.timeline = this.timeline
        if (this.graphic) options.graphic = this.graphic
        if (this.series) options.series = this.series
        if (this.backgroundColor) options.backgroundColor = this.backgroundColor
        if (this.textStyle) options.textStyle = this.textStyle
        if (this.animation) {
          Object.keys(this.animation).forEach(key => {
            options[key] = this.animation[key]
          })
        }
        if (this.markArea || this.markLine || this.markPoint) {
          const marks = {
            markArea: this.markArea,
            markLine: this.markLine,
            markPoint: this.markPoint
          }
          const series = options.series
          if (this.getType(series) === '[object Array]') {
            series.forEach(item => {
              this.addMark(item, marks)
            })
          } else if (this.getType(series) === '[object Object]') {
            this.addMark(series, marks)
          }
        }
        if (this.afterConfig) options = this.afterConfig(options)
        this.echarts.setOption(options, true)
      }
    },

    addMark (seriesItem, marks) {
      Object.keys(marks).forEach(key => {
        if (marks[key]) {
          seriesItem[key] = marks[key]
        }
      })
    },

    getType (v) {
      return Object.prototype.toString.call(v)
    },

    init () {
      if (this.echarts) return
      this.echarts = this.echartsLib.init(this.$refs.canvas, 've-chart', this.initOptions)
      if (this.data) this.dataHandler(this.data)
      if (this.events) this.bindEvents()
    },

    bindEvents () {
      Object.keys(this.events).forEach(event => {
        this.echarts.on(event, this.events[event])
      })
    },

    addWatchToProps () {
      const watchedVariable = this._watchers.map(watcher => watcher.expression)
      Object.keys(this.$props).forEach(prop => {
        if (!~watchedVariable.indexOf(prop)) {
          const opts = {}
          if (Object.prototype.toString.call(prop) === '[object Object]') {
            opts.deep = true
          }
          this.$watch(prop, () => {
            this.dataHandler(this.data)
          }, opts)
        }
      })
    }
  },

  created () {
    this.addWatchToProps()
  },

  mounted () {
    this.init()
    window.addEventListener('resize', this.echarts.resize)
  },

  beforeDestory () {
    window.removeEventListener('resize', this.echarts.resize)
    this.echarts.dispose()
  }
}

export default chartMixin
<|endoftext|>


<commit_before>var projects = {

	"smart facebook birthday assistant": {
		"image":"https://avatars3.githubusercontent.com/u/22071699?v=3&s=200",
		"team":"lannisters sucks",
		"link":"https://github.com/sameer2800/IIITA_HACKS"

	},

	"<project-name>":{
                      "image":"https://avatars3.githubusercontent.com/u/22071699?v=3&s=200",
                      "team":"IIIT-A Hacks",
                      "link":"https://github.com/iiitahacks"
                  },
         "Gather":{
                      "image":"https://avatars3.githubusercontent.com/u/22071699?v=3&s=200",
                      "team":"checkmate",
                      "link":"https://github.com/magician03/gather"
                  },
          "KrayZ":{
                      "image":"https://openclipart.org/image/800px/svg_to_png/227918/Video-Game-Controller-Icon.png"",
                      "team":"Krayz",
                      "link":"https://github.com/indreshattri/KrayZ"
                  },

}
<commit_msg>Team HopeLess Project updated<commit_after>var projects = {

	"smart facebook birthday assistant": {
		"image":"https://avatars3.githubusercontent.com/u/22071699?v=3&s=200",
		"team":"lannisters sucks",
		"link":"https://github.com/sameer2800/IIITA_HACKS"

	},

	"<project-name>":{
                      "image":"https://avatars3.githubusercontent.com/u/22071699?v=3&s=200",
                      "team":"IIIT-A Hacks",
                      "link":"https://github.com/iiitahacks"
                  },
         "Gather":{
                      "image":"https://avatars3.githubusercontent.com/u/22071699?v=3&s=200",
                      "team":"checkmate",
                      "link":"https://github.com/magician03/gather"
                  },
          "KrayZ":{
                      "image":"https://openclipart.org/image/800px/svg_to_png/227918/Video-Game-Controller-Icon.png"",
                      "team":"Krayz",
                      "link":"https://github.com/indreshattri/KrayZ"
                  },
	"voix": {
			"image":"http://images.clipartpanda.com/simple-microphone-vector-microphone-voice_318-26622.jpg",
			"team":"HopeLess",
			"link":"https://github.com/SaptakS/voix.git"

}
<|endoftext|>


<commit_before>/**
 * Created by dim on 7.5.17.
 */

var props = {
    fnc: 'function',
    obj: 'object',
    str: 'string',
    nbr: 'number',
    bln: 'boolean',
    arr: 'array'
};

var schema = {
    type: props.obj,
    props: {
        ss: {
            isRequired: true, // optional
            type: props.str // required
        },
        nn: {
            isRequired: false,
            type: props.nbr
        },
        bb: {
            type: props.bln
        },
        fn: {
            type: props.fnc
        },
        aa: {
            type: props.arr,
            isRequired: true,

            item: {
                type: props.obj,
                props: {
                    gg: {
                        type: props.nbr,
                        isRequired: true
                    }
                }
            }
        },
        cc: {
            type: function (value) {
                return value > 3;
            }
        }
    }
};

var obj = {
    ss: 'ee',
    nn: 11,
    bb: true,
    aa: [{gg: 1}, {gg: 2}],
    fn: function () {

    },
    cc: 4
};

function checkType(schema, obj, error) {

    if (!error) {
        error = {
            message: '',
            path: '/'
        }
    }

    if (typeof schema.type === props.fnc) {
        return schema.type(obj);
    }

    switch (schema.type) {
        case props.fnc:
        case props.obj:
        case props.str:
        case props.nbr:
        case props.bln:

            if (typeof obj !== schema.type) {
                return false;
            }

            if (schema.props) {

                return Object.keys(schema.props).every(function (key) {

                    if (obj.hasOwnProperty(key)) {
                        return checkType(schema.props[key], obj[key], error);
                    }

                    return !schema.props[key].isRequired;

                });

            }

            return true;

            break;

        case props.arr:

            if (!Array.isArray(obj)) {
                return false;
            }

            return obj.every(function (item) {
                return checkType(schema.item, item, error);
            });

            break;

        default:
            new Error('Can not resolve type: ' + schema.type);

    }

}

console.log(checkType(schema, obj));

<commit_msg>in progress...<commit_after>/**
 * Created by dim on 7.5.17.
 */

var props = {
    fnc: 'function',
    obj: 'object',
    str: 'string',
    nbr: 'number',
    bln: 'boolean',
    arr: 'array'
};

var schema = {
    type: props.obj,
    props: {
        ss: {
            isRequired: true, // optional
            type: props.str // required
        },
        nn: {
            isRequired: false,
            type: props.nbr
        },
        bb: {
            type: props.bln
        },
        fn: {
            type: props.fnc
        },
        aa: {
            type: props.arr,
            isRequired: true,

            item: {
                type: props.obj,
                props: {
                    gg: {
                        type: props.nbr,
                        isRequired: true
                    }
                }
            }
        },
        cc: {
            type: function (value) {
                return value > 3;
            }
        }
    }
};

var obj = {
    ss: 'ee',
    nn: 11,
    bb: true,
    aa: [{gg: 1}, {gg: 2}],
    fn: function () {

    },
    cc: 4
};

function checkType(schema, obj) {

    if (typeof schema.type === props.fnc) {
        return schema.type(obj);
    }

    switch (schema.type) {
        case props.fnc:
        case props.obj:
        case props.str:
        case props.nbr:
        case props.bln:

            if (typeof obj !== schema.type) {
                return false;
            }

            if (schema.props) {

                return Object.keys(schema.props).every(function (key) {

                    if (obj.hasOwnProperty(key)) {
                        return checkType(schema.props[key], obj[key]);
                    }

                    return !schema.props[key].isRequired;

                });

            }

            return true;

            break;

        case props.arr:

            if (!Array.isArray(obj)) {
                return false;
            }

            return obj.every(function (item) {
                return checkType(schema.item, item);
            });

            break;

        default:
            new Error('Can not resolve type: ' + schema.type);

    }

}

console.log(checkType(schema, obj));

<|endoftext|>


<commit_before>var path = require('path');
var express = require('express');
var Sequelize = require('sequelize');
var bodyParser = require('body-parser');
var auth = require('http-auth');

var app = express();
app.use(bodyParser.json());

var basic = auth.basic({
  realm: 'Flags',
  file: __dirname + '/.htpasswd',
});

var sequelize = new Sequelize('sqlite://database', {
  logging: false,
  storage: path.join(__dirname, 'database.sqlite'),
});

var Flag = sequelize.define('flag', {
  type: { type: Sequelize.STRING, allowNull: false },
  value: { type: Sequelize.STRING, allowNull: false },
});

var Concept = sequelize.define('concept', {
  id: { type: Sequelize.STRING, primaryKey: true },
  type: { type: Sequelize.STRING },
  name: { type: Sequelize.STRING },
  datasets: { type: Sequelize.STRING },
}, {
  setterMethods: {
    datasets: function (value) {
      this.setDataValue('datasets', value.join(','));
    },
  },
  getterMethods: {
    datasets: function () {
      return (this.getDataValue('datasets') || '').split(',');
    },
  },
});

var Origin = Flag.belongsTo(Concept, { as: 'origin' });
var Target = Flag.belongsTo(Concept, { as: 'target' });

sequelize.sync({ force: false }).then(function () {});

app.get('/flags', auth.connect(basic), function (req, res) {
  var query = req.query;
  var params = {};

  if (query.concept) {
    params.$or = [
      { originId: decodeURIComponent(query.concept) },
      { targetId: decodeURIComponent(query.concept) },
    ];
  }

  Flag.findAll({
    where: params,
    include: [Origin, Target],
    order: [['createdAt', 'DESC']],
  }).then(function (rows) {
    res.json(rows);
  });
});

app.get('/flags/relations.ndjson', auth.connect(basic), function (req, res) {
  Flag.findAll({
    where: {
      $or: [{ type: 'duplicate' }, { type: 'missing-relation' }],
    },
    include: [Origin, Target],
  }).then(function (rows) {
    res.send(rows.map(function (row) {
      return JSON.stringify({
        from: row.originId,
        type: row.value,
        to: row.targetId,
      });
    }).join('\n'));
  });
});

app.get('/flags/pits.ndjson', auth.connect(basic), function (req, res) {
  Flag.findAll({
    where: {
      $or: [{ type: 'wrong-type' }],
    },
    include: [Origin, Target],
  }).then(function (rows) {
    res.send(rows.map(function (row) {
      return JSON.stringify({
        id: row.origin.id,
        type: row.value,
        name: row.origin.name,
        dataset: row.origin.datasets.shift(),
      });
    }).join('\n'));
  });
});

app.post('/flags', auth.connect(basic), function (req, res) {
  var data = req.body;

  Concept
    .findOrCreate({
      where: { id: data.origin.id },
      defaults: data.origin,
    })
    .then(function () {
      return Concept.findOrCreate({
        where: { id: data.target.id },
        defaults: data.target,
      });
    })
    .then(function () {
      return Flag.create({
        type: data.type,
        value: data.value,
        originId: data.origin.id,
        targetId: data.target.id,
      });
    })
    .then(function (flag) {
      return res.status(201).json(flag);
    });
});

module.exports = app;
<commit_msg>Remove auth from GET request<commit_after>var path = require('path');
var express = require('express');
var Sequelize = require('sequelize');
var bodyParser = require('body-parser');
var auth = require('http-auth');

var app = express();
app.use(bodyParser.json());

var basic = auth.basic({
  realm: 'Flags',
  file: __dirname + '/.htpasswd',
});

var sequelize = new Sequelize('sqlite://database', {
  logging: false,
  storage: path.join(__dirname, 'database.sqlite'),
});

var Flag = sequelize.define('flag', {
  type: { type: Sequelize.STRING, allowNull: false },
  value: { type: Sequelize.STRING, allowNull: false },
});

var Concept = sequelize.define('concept', {
  id: { type: Sequelize.STRING, primaryKey: true },
  type: { type: Sequelize.STRING },
  name: { type: Sequelize.STRING },
  datasets: { type: Sequelize.STRING },
}, {
  setterMethods: {
    datasets: function (value) {
      this.setDataValue('datasets', value.join(','));
    },
  },
  getterMethods: {
    datasets: function () {
      return (this.getDataValue('datasets') || '').split(',');
    },
  },
});

var Origin = Flag.belongsTo(Concept, { as: 'origin' });
var Target = Flag.belongsTo(Concept, { as: 'target' });

sequelize.sync({ force: false }).then(function () {});

app.get('/flags', function (req, res) {
  var query = req.query;
  var params = {};

  if (query.concept) {
    params.$or = [
      { originId: decodeURIComponent(query.concept) },
      { targetId: decodeURIComponent(query.concept) },
    ];
  }

  Flag.findAll({
    where: params,
    include: [Origin, Target],
    order: [['createdAt', 'DESC']],
  }).then(function (rows) {
    res.json(rows);
  });
});

app.get('/flags/relations.ndjson', auth.connect(basic), function (req, res) {
  Flag.findAll({
    where: {
      $or: [{ type: 'duplicate' }, { type: 'missing-relation' }],
    },
    include: [Origin, Target],
  }).then(function (rows) {
    res.send(rows.map(function (row) {
      return JSON.stringify({
        from: row.originId,
        type: row.value,
        to: row.targetId,
      });
    }).join('\n'));
  });
});

app.get('/flags/pits.ndjson', auth.connect(basic), function (req, res) {
  Flag.findAll({
    where: {
      $or: [{ type: 'wrong-type' }],
    },
    include: [Origin, Target],
  }).then(function (rows) {
    res.send(rows.map(function (row) {
      return JSON.stringify({
        id: row.origin.id,
        type: row.value,
        name: row.origin.name,
        dataset: row.origin.datasets.shift(),
      });
    }).join('\n'));
  });
});

app.post('/flags', auth.connect(basic), function (req, res) {
  var data = req.body;

  Concept
    .findOrCreate({
      where: { id: data.origin.id },
      defaults: data.origin,
    })
    .then(function () {
      return Concept.findOrCreate({
        where: { id: data.target.id },
        defaults: data.target,
      });
    })
    .then(function () {
      return Flag.create({
        type: data.type,
        value: data.value,
        originId: data.origin.id,
        targetId: data.target.id,
      });
    })
    .then(function (flag) {
      return res.status(201).json(flag);
    });
});

module.exports = app;
<|endoftext|>


<commit_before>var redis = require("redis");
var client = redis.createClient();

// read all tasks from redis and return
function readAllTasks(callback) {
  var taskArray = [];

  // fetches set of tasks ids
  client.smembers("idSet", function(err, reply) {
    reply.forEach(function(key) {

      // for each id return all hash info
      client.hgetall(key, function(err, reply) {
        console.log("reply: ", reply);
        taskArray.push(reply);
      });
    });
  });

  // Remove setTimeout when we have the time
  setTimeout(function() {
    callback(null, taskArray);
  }, 500);
};

function storeTask(task, callback) {

  client.select(0, function() {

    // Random id for each task
    var id = Math.floor(Math.random() * 1000);
    client.hmset(id, {
      "id": id,
      "taskName": task,
      "done": "not-done",
      "category": "red"
    }, callback);
    client.sadd("idSet", id, function(err, reply) {

      if (err) {
        console.log("id sadd err: ", err);
      } else {
        console.log("id sadd successful");

        // once new task is added, return all data
        readAllTasks(callback);
      }
    });
  });
}

function updateStatus(taskId, taskStatus, callback) {
  console.log("updateStatus: ", taskId, taskStatus);

  client.select(0, function() {

    var update;
    if (taskStatus == "not-done") {
      update = "done"
    } else {
        update = "not-done"
      }

    client.hset(taskId, "done", update, function(err, reply) {

      if (err) {
        console.log("status update err:", err);
      } else {
        console.log("status update successful");

        readAllTasks(callback);
      }
    })
  });
}

module.exports = {
  readAllTasks: readAllTasks,
  storeTask: storeTask,
  updateStatus: updateStatus
};
<commit_msg>50ms for speed! setTimeout still not fixed<commit_after>var redis = require("redis");
var client = redis.createClient();

// read all tasks from redis and return
function readAllTasks(callback) {
  var taskArray = [];

  // fetches set of tasks ids
  client.smembers("idSet", function(err, reply) {
    reply.forEach(function(key) {

      // for each id return all hash info
      client.hgetall(key, function(err, reply) {
        console.log("reply: ", reply);
        taskArray.push(reply);
      });
    });
  });

  // Remove setTimeout when we have the time
  setTimeout(function() {
    callback(null, taskArray);
  }, 50);
}

function storeTask(task, callback) {

  client.select(0, function() {

    // Random id for each task
    var id = Math.floor(Math.random() * 1000);
    client.hmset(id, {
      "id": id,
      "taskName": task,
      "done": "not-done",
      "category": "red"
    }, callback);
    client.sadd("idSet", id, function(err, reply) {

      if (err) {
        console.log("id sadd err: ", err);
      } else {
        console.log("id sadd successful");

        // once new task is added, return all data
        readAllTasks(callback);
      }
    });
  });
}

function updateStatus(taskId, taskStatus, callback) {
  console.log("updateStatus: ", taskId, taskStatus);

  client.select(0, function() {

    var update;
    if (taskStatus == "not-done") {
      update = "done"
    } else {
        update = "not-done"
      }

    client.hset(taskId, "done", update, function(err, reply) {

      if (err) {
        console.log("status update err:", err);
      } else {
        console.log("status update successful");

        readAllTasks(callback);
      }
    })
  });
}

module.exports = {
  readAllTasks: readAllTasks,
  storeTask: storeTask,
  updateStatus: updateStatus
};
<|endoftext|>


<commit_before>import isFunction from 'lodash/lang/isFunction'
import isObject from 'lodash/lang/isObject'
import forEach from 'lodash/collection/forEach'
import Promise from 'bluebird'

export default function({plugins = {}} = {}) {
  const stack = []

  function dispatch(req, res) {
    return stack.reduce((p, call) => {
      return p.then(() => {
        return call(req, res)
      })
    }, Promise.resolve())
  }

  const dispatcher = (req, res) => {
    return dispatch(req, res)
      .catch(err => {
        if (err.nonce) {
          return
        }

        res
          .status(err.status)
          .json({
            type: err.type,
            message: err.message,
            errors: isObject(err.data) ? err.data : undefined
          })
      })
  }

  function registerPlugin(plugin) {
    if (isFunction(plugin)) {
      return (...spec) => {
        stack.push(plugin(...spec))
        return dispatcher
      }
    }

    if (isObject(plugin)) {
      const container = {}
      forEach(plugin, (name, key) => {
        container[key] = (...spec) => {
          stack.push(name(...spec))
          return dispatcher
        }
      })

      return container
    }

    throw new Error(`The provided plugin has invalid type "${typeof plugin}"`)
  }

  // plugins
  function plugin(name, plugin) {
    if (dispatcher.hasOwnProperty(name)) {
      throw new Error(`The plugin with name ${name} is already registered or would overwrite a builtin method.`)
    }
    Object.defineProperty(dispatcher, name, {
      value: registerPlugin(plugin)
    })

    return dispatcher
  }

  Object.defineProperty(dispatcher, 'plugin', {
    value: plugin
  })

  forEach(plugins, (fn, name) => plugin(name, fn))

  return dispatcher
}
<commit_msg>refactor: use builtin `Promise.each` method<commit_after>import isFunction from 'lodash/lang/isFunction'
import isObject from 'lodash/lang/isObject'
import forEach from 'lodash/collection/forEach'
import Promise from 'bluebird'

export default function({plugins = {}} = {}) {

  const stack = []

  const dispatcher = (req, res) => {
    return Promise
      .each(stack, call => call(req, res))
      .catch(err => {
        if (err.nonce) {
          return
        }

        res
          .status(err.status)
          .json({
            type: err.type,
            message: err.message,
            errors: isObject(err.data) ? err.data : undefined
          })
      })
  }

  function registerPlugin(plugin) {
    if (isFunction(plugin)) {
      return (...spec) => {
        stack.push(plugin(...spec))
        return dispatcher
      }
    }

    if (isObject(plugin)) {
      const container = {}
      forEach(plugin, (name, key) => {
        container[key] = (...spec) => {
          stack.push(name(...spec))
          return dispatcher
        }
      })

      return container
    }

    throw new Error(`The provided plugin has invalid type "${typeof plugin}"`)
  }

  // plugins
  function plugin(name, plugin) {
    if (dispatcher.hasOwnProperty(name)) {
      throw new Error(`The plugin with name ${name} is already registered or would overwrite a builtin method.`)
    }
    Object.defineProperty(dispatcher, name, {
      value: registerPlugin(plugin)
    })

    return dispatcher
  }

  Object.defineProperty(dispatcher, 'plugin', {
    value: plugin
  })

  forEach(plugins, (fn, name) => plugin(name, fn))

  return dispatcher
}
<|endoftext|>