<commit_before>function Graph() {
    this.nodes = {};
    this.selcategory = null;
    this.voxdir = null;
    this.subject = null;
    this.catmapdir = null;
    this.lastdataname = "";
    this.showinglabels = true;
}
Graph.prototype.setrgbdata = function(data) {
    // Changes what is shown on the graph to the given [data].
    // [data] should be an associative array of either
    // 1. Hex color string and float size pairs
    // 2. Floating point values
    this.hideselcategory();

    // Right now let's just assume the former
    for (var name in data) {
        // console.log(name);
        var ndata = data[name];

        if (name in this.nodes) {
            // console.log("Animating "+name)
            // $(this.nodes[name].obj.nodemarker).attr("fill", ndata[0]);
            // $(this.nodes[name].obj.nodemarker).animate({svgFill: ndata[0], svgR: Math.sqrt(ndata[1]*60)}, 2000, "linear");
            $(this.nodes[name]).attr("fill", ndata[0]).attr("r", Math.sqrt(ndata[1]*60));
        }
    }
}
Graph.prototype.setlindata = function(data) {
    // Changes what is shown on the graph to the given [data].
    // [data] should be an associative array of values

    // Right now let's just assume the former
    for (var name in data) {
        // console.log(name);
        var ndata = data[name];
        if (name in this.nodes) {
            // console.log("Animating "+name)
            var nodecolor = ndata>0 ? "red" : "blue";
            // $(this.nodes[name].obj.nodemarker).animate({svgFill: nodecolor, svgR: Math.sqrt(Math.abs(ndata))}, 2000, "linear");
            $(this.nodes[name]).attr("fill", nodecolor).attr("r", 2*Math.sqrt(Math.abs(ndata)));
            // $(this.nodes[name].obj.nodemarker).attr("fill", ndata[0]);
            // $(this.nodes[name]).animate({svgR: Math.sqrt(ndata[1]*60)}, 5000, "linear");
        }
    }
}
Graph.prototype.showvoxel = function(voxind, vertind) {
    // Shows the data for voxel [voxind] on the graph.
    // Automatically loads from a set directory..
    var gr = this;
    var voxcorr = this.viewer.datasets.ModelPerformance.array.data[voxind].toFixed(3);
    // console.log("Showing STRF for voxel "+voxind);
    $("#wngraph-title").html("Voxel "+this.subject+"-"+voxind+", r = "+voxcorr+"");
    var data = NParray.fromURL(this.voxdir+this.subject+"-"+voxind+".bin",
        function (npa) {
            for (var i=0; i<nodenames.length; i++) {
                var val = npa.data[i];
                var nodecolor = val>0 ? "red" : "blue";
                $(gr.nodes[nodenames[i]]).attr("fill", nodecolor).attr("r", 2*Math.sqrt(Math.abs(val)));
            }
    });
    // Setup link
    var voxurl = window.location.href.split("?")[0]+"?vox="+voxind+"&vert="+vertind;
    $("#linkurl").val(voxurl);
    $("#linkurl").hide();
    $("#viewlink").show();
}
Graph.prototype.showcategory = function(catname) {
    // If there was a previously selected node, un-select it
    this.hideselcategory();
    this.selcategory = catname;
    var node = this.nodes[catname];

    // Expand the marker of the selected node, add to its edge
    $(node).attr("stroke", "#fff");
    //node.origsw = $(node).attr("stroke-width");
    //node.origr = $(node).attr("r");
    $(node).animate({svgStrokeWidth: "+=4", svgR: "+=20"}, 500, "swing");
    $(node).mouseout();

    for (var i=0; i<nodenames.length; i++) {
        if (nodenames[i]==catname) {
            // console.log("Showing map for category "+nodenames[i]+", from url "+this.catmapdir+this.subject+"-"+i+".bin");
            if (this.lastdataname != "") {
                this.viewer.rmData(this.lastdataname);
            }
            this.lastdataname = 'Category: '+catname.split(".")[0].replace(/_/g, " ");
            NParray.fromURL(this.catmapdir+this.subject+"-"+i+".bin",
                function (data) {
                    var catdata = Object();
                    var dset = new Dataset(data);
                    dset.cmap = "RdBu_r";
                    dset.min = -3;
                    dset.max = 3;
                    catdata['Category: '+catname.split(".")[0].replace(/_/g, " ")] = dset;
                    this.viewer.addData(catdata);
                });
        }
    }
}
Graph.prototype.hideselcategory = function() {
    if (this.selcategory != null) {
	var oldsel = this.nodes[this.selcategory];
	$(oldsel).animate({svgStrokeWidth:oldsel.origsw, svgR:oldsel.origr}, 100, "swing");
    }
}
Graph.prototype.togglelabels = function() {
    if (this.showinglabels) {
        // Hide them!
        $("#wngraph > g#biglabels").animate({svgOpacity: 0.0}, 500, "swing");
        $("#wnlabelbutton").text("Show Labels");
        this.showinglabels = false;
    }
    else {
        // Show them!
        $("#wngraph > g#biglabels").animate({svgOpacity: 1.0}, 500, "swing");
        $("#wnlabelbutton").text("Hide Labels");
        this.showinglabels = true;
    }
}
Graph.prototype.showrgb = function() {
    this.setrgbdata(colordata);
    $("#wngraph-title").html("Semantic Space");
    $("#viewlink").hide();
    $("#linkurl").hide();
    this.viewer.picker.axes[0].obj.parent.remove(this.viewer.picker.axes[0].obj);
    this.viewer.picker.axes = [];
    this.viewer.controls.dispatchEvent({type:"change"});
}

function setupGraph() {
    var svgnode = $("#wngraph")[0];
    var graph = new Graph();
    $("#wngraph circle").each(function() {
        graph.nodes[this.id] = this;
        $(this).attr("stroke-width", "0");
        /// Add mouse events
        $(this).click(function(e){
	    graph.showcategory(this.id);
	});
        $(this).hoverIntent({
            over: function(e){
		var exp = 10;
		if (graph.selcategory != this.id) {
		    exp = 10;
		}
		else {
		    exp = 0;
		}
                var lbgpad = 3;
		var lbgoffset = 10;
		var labeloffsetsign = 1;
		var lbgoffx = -lbgoffset - lbgpad;
		var lbgoffw = 2*lbgpad + lbgoffset;

                // Move this node in front
                $("#svgnodes")[0].removeChild(this);
                $("#svglabels")[0].appendChild(this);

                var svglabel = document.createElementNS("http://www.w3.org/2000/svg", "text");
		if ($(this).attr("cx")>400) {
		    // The label will go on the left
		    svglabel.setAttribute("text-anchor", "end");
		    labeloffsetsign = -1;
		    lbgoffx = -lbgpad;
		    lbgoffw = 2*lbgpad + lbgoffset;
		}

                svglabel.setAttribute("x", $(this).attr("cx"));
                svglabel.setAttribute("y", Math.round($(this).attr("cy")));
                svglabel.setAttribute("fill", "#fff");
                svglabel.setAttribute("font-weight", "bold");
                svglabel.setAttribute("font-family", "arial");
                svglabel.setAttribute("font-size", "24px");
                svglabel.setAttribute("visibility", "hidden");
                svglabel.setAttribute("alignment-baseline", "middle");
                svglabel.textContent = this.id.split(".")[0].replace(/_/g, " ");
                $("#svglabels")[0].appendChild(svglabel);

                var label = $(svglabel);
                this.label = label;
                // Make the label visible, position it correctly
                label.attr("visibility", "visible");
                label.fadeIn(100);
                label.attr("x", parseFloat($(this).attr("cx")) + labeloffsetsign*(parseFloat($(this).attr("r")) + parseFloat($(this).attr("stroke-width")) + exp + lbgpad));

                // Create background for label
                var labelbg = document.createElementNS("http://www.w3.org/2000/svg", "rect");
                var lbb = label[0].getBBox();
                labelbg.setAttribute("x", Math.round(lbb.x+lbgoffx));
                labelbg.setAttribute("y", Math.round(lbb.y-lbgpad+2));
                labelbg.setAttribute("width", Math.round(lbb.width+lbgoffw));
                labelbg.setAttribute("height", Math.round(lbb.height+2*lbgpad-4));
                labelbg.setAttribute("fill", "#000");
                labelbg.setAttribute("fill-opacity", 0.8);
                labelbg.setAttribute("stroke", "#fff");
                labelbg.setAttribute("stroke-width", 2);
                labelbg.setAttribute("stroke-opacity", 1.0);
                labelbg.setAttribute("rx", 5);
                labelbg.setAttribute("ry", 5);
                $("#svgnodes")[0].appendChild(labelbg);
                this.labelbg = labelbg;

                // Expand the marker, add to its edge
		if (graph.selcategory != this.id) {
                    $(this).attr("stroke", "#fff");
                    this.origsw = $(this).attr("stroke-width");
                    this.origr = $(this).attr("r");
                    $(this).animate({svgStrokeWidth: "+=2", svgR: "+="+exp}, 100, "swing");
		}

                // Show the node definition
                $("#wngraph-definition").html(""+this.id + ": " + wndefs[this.id]);

            },
            timeout: 300,
            sensitivity: 100,
            interval: 20,
            out: function(e){
                this.label.fadeOut(100);
                $(this.labelbg).fadeOut(100);
                //$(this).animate({svgStrokeWidth: "-=2", svgR: "-="+exp}, 100, "swing");
		if (graph.selcategory != this.id) {
                    $(this).animate({svgStrokeWidth: "-=2", svgR: this.origr}, 100, "swing");
		    if (this.origsw==0) {
			$(this).attr("stroke", "none");
                    }
		}
                $("#svgnodes")[0].removeChild(this.labelbg);
                $("#svglabels")[0].removeChild(this);
                $("#svgnodes").append(this);
            }
        });
    });
    return graph;
}

var dtypeNames = {
    "uint32":Uint32Array,
    "uint16":Uint16Array,
    "uint8":Uint8Array,
    "int32":Int32Array,
    "int16":Int16Array,
    "int8":Int8Array,
    "float32":Float32Array,
}
var dtypeMap = [Uint32Array, Uint16Array, Uint8Array, Int32Array, Int16Array, Int8Array, Float32Array]
var loadCount = 0;
function NParray(data, dtype, shape) {
    this.data = data;
    this.shape = shape;
    this.dtype = dtype;
    this.size = this.data.length;
}
NParray.fromJSON = function(json) {
    var size = json.shape.length ? json.shape[0] : 0;
    for (var i = 1, il = json.shape.length; i < il; i++) {
        size *= json.shape[i];
    }
    var pad = 0;
    if (json.pad) {
        size += json.pad;
        pad = json.pad;
    }

    var data = new (dtypeNames[json.dtype])(size);
    var charview = new Uint8Array(data.buffer);
    var bytes = charview.length / data.length;

    var str = atob(json.data.slice(0,-1));
    var start = pad*bytes, stop  = size*bytes - start;
    for ( var i = start, il = Math.min(stop, str.length); i < il; i++ ) {
        charview[i] = str.charCodeAt(i - start);
    }

    return new NParray(data, json.dtype, json.shape);
}
NParray.fromURL = function(url, callback) {
    loadCount++;
    $("#dataload").show();
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'arraybuffer';
    xhr.onload = function(e) {
        if (this.readyState == 4 && this.status == 200) {
            loadCount--;
            var data = new Uint32Array(this.response, 0, 2);
            var dtype = dtypeMap[data[0]];
            var ndim = data[1];
            var shape = new Uint32Array(this.response, 8, ndim);
            var array = new dtype(this.response, (ndim+2)*4);
            callback(new NParray(array, dtype, shape));
            if (loadCount == 0)
                $("#dataload").hide();
        }
    };
    xhr.send()
}
NParray.prototype.view = function() {
    if (arguments.length == 1 && this.shape.length > 1) {
        var shape;
        var slice = arguments[0];
        if (this.shape.slice)
            shape = this.shape.slice(1);
        else
            shape = this.shape.subarray(1);
        var size = shape[0];
        for (var i = 1, il = shape.length; i < il; i++) {
            size *= shape[i];
        }
        return new NParray(this.data.subarray(slice*size, (slice+1)*size), this.dtype, shape);
    } else {
        throw "Can only slice in first dimension for now"
    }
}
NParray.prototype.minmax = function() {
    var min = Math.pow(2, 32);
    var max = -min;

    for (var i = 0, il = this.data.length; i < il; i++) {
        if (this.data[i] < min) {
            min = this.data[i];
        }
        if (this.data[i] > max) {
            max = this.data[i];
        }
    }

    return [min, max];
}
<commit_msg>Fix remapped vertex bug<commit_after>function Graph() {
    this.nodes = {};
    this.selcategory = null;
    this.voxdir = null;
    this.subject = null;
    this.catmapdir = null;
    this.lastdataname = "";
    this.showinglabels = true;
}
Graph.prototype.setrgbdata = function(data) {
    // Changes what is shown on the graph to the given [data].
    // [data] should be an associative array of either
    // 1. Hex color string and float size pairs
    // 2. Floating point values
    this.hideselcategory();

    // Right now let's just assume the former
    for (var name in data) {
        // console.log(name);
        var ndata = data[name];

        if (name in this.nodes) {
            // console.log("Animating "+name)
            // $(this.nodes[name].obj.nodemarker).attr("fill", ndata[0]);
            // $(this.nodes[name].obj.nodemarker).animate({svgFill: ndata[0], svgR: Math.sqrt(ndata[1]*60)}, 2000, "linear");
            $(this.nodes[name]).attr("fill", ndata[0]).attr("r", Math.sqrt(ndata[1]*60));
        }
    }
}
Graph.prototype.setlindata = function(data) {
    // Changes what is shown on the graph to the given [data].
    // [data] should be an associative array of values

    // Right now let's just assume the former
    for (var name in data) {
        // console.log(name);
        var ndata = data[name];
        if (name in this.nodes) {
            // console.log("Animating "+name)
            var nodecolor = ndata>0 ? "red" : "blue";
            // $(this.nodes[name].obj.nodemarker).animate({svgFill: nodecolor, svgR: Math.sqrt(Math.abs(ndata))}, 2000, "linear");
            $(this.nodes[name]).attr("fill", nodecolor).attr("r", 2*Math.sqrt(Math.abs(ndata)));
            // $(this.nodes[name].obj.nodemarker).attr("fill", ndata[0]);
            // $(this.nodes[name]).animate({svgR: Math.sqrt(ndata[1]*60)}, 5000, "linear");
        }
    }
}
Graph.prototype.showvoxel = function(voxind, vertind) {
    // Shows the data for voxel [voxind] on the graph.
    // Automatically loads from a set directory..
    var gr = this;
    var voxcorr = this.viewer.datasets.ModelPerformance.textures[0][vertind].toFixed(3); //Get the reordered index value
    // console.log("Showing STRF for voxel "+voxind);
    $("#wngraph-title").html("Voxel "+this.subject+"-"+voxind+", r = "+voxcorr+"");
    var data = NParray.fromURL(this.voxdir+this.subject+"-"+voxind+".bin",
        function (npa) {
            for (var i=0; i<nodenames.length; i++) {
                var val = npa.data[i];
                var nodecolor = val>0 ? "red" : "blue";
                $(gr.nodes[nodenames[i]]).attr("fill", nodecolor).attr("r", 2*Math.sqrt(Math.abs(val)));
            }
    });
    // Setup link
    var voxurl = window.location.href.split("?")[0]+"?vox="+voxind+"&vert="+vertind;
    $("#linkurl").val(voxurl);
    $("#linkurl").hide();
    $("#viewlink").show();
}
Graph.prototype.showcategory = function(catname) {
    // If there was a previously selected node, un-select it
    this.hideselcategory();
    this.selcategory = catname;
    var node = this.nodes[catname];

    // Expand the marker of the selected node, add to its edge
    $(node).attr("stroke", "#fff");
    //node.origsw = $(node).attr("stroke-width");
    //node.origr = $(node).attr("r");
    $(node).animate({svgStrokeWidth: "+=4", svgR: "+=20"}, 500, "swing");
    $(node).mouseout();

    for (var i=0; i<nodenames.length; i++) {
        if (nodenames[i]==catname) {
            // console.log("Showing map for category "+nodenames[i]+", from url "+this.catmapdir+this.subject+"-"+i+".bin");
            if (this.lastdataname != "") {
                this.viewer.rmData(this.lastdataname);
            }
            this.lastdataname = 'Category: '+catname.split(".")[0].replace(/_/g, " ");
            NParray.fromURL(this.catmapdir+this.subject+"-"+i+".bin",
                function (data) {
                    var catdata = Object();
                    var dset = new Dataset(data);
                    dset.cmap = "RdBu_r";
                    dset.min = -3;
                    dset.max = 3;
                    catdata['Category: '+catname.split(".")[0].replace(/_/g, " ")] = dset;
                    this.viewer.addData(catdata);
                });
        }
    }
}
Graph.prototype.hideselcategory = function() {
    if (this.selcategory != null) {
	var oldsel = this.nodes[this.selcategory];
	$(oldsel).animate({svgStrokeWidth:oldsel.origsw, svgR:oldsel.origr}, 100, "swing");
    }
}
Graph.prototype.togglelabels = function() {
    if (this.showinglabels) {
        // Hide them!
        $("#wngraph > g#biglabels").animate({svgOpacity: 0.0}, 500, "swing");
        $("#wnlabelbutton").text("Show Labels");
        this.showinglabels = false;
    }
    else {
        // Show them!
        $("#wngraph > g#biglabels").animate({svgOpacity: 1.0}, 500, "swing");
        $("#wnlabelbutton").text("Hide Labels");
        this.showinglabels = true;
    }
}
Graph.prototype.showrgb = function() {
    this.setrgbdata(colordata);
    $("#wngraph-title").html("Semantic Space");
    $("#viewlink").hide();
    $("#linkurl").hide();
    this.viewer.picker.axes[0].obj.parent.remove(this.viewer.picker.axes[0].obj);
    this.viewer.picker.axes = [];
    this.viewer.controls.dispatchEvent({type:"change"});
}

function setupGraph() {
    var svgnode = $("#wngraph")[0];
    var graph = new Graph();
    $("#wngraph circle").each(function() {
        graph.nodes[this.id] = this;
        $(this).attr("stroke-width", "0");
        /// Add mouse events
        $(this).click(function(e){
	    graph.showcategory(this.id);
	});
        $(this).hoverIntent({
            over: function(e){
		var exp = 10;
		if (graph.selcategory != this.id) {
		    exp = 10;
		}
		else {
		    exp = 0;
		}
                var lbgpad = 3;
		var lbgoffset = 10;
		var labeloffsetsign = 1;
		var lbgoffx = -lbgoffset - lbgpad;
		var lbgoffw = 2*lbgpad + lbgoffset;

                // Move this node in front
                $("#svgnodes")[0].removeChild(this);
                $("#svglabels")[0].appendChild(this);

                var svglabel = document.createElementNS("http://www.w3.org/2000/svg", "text");
		if ($(this).attr("cx")>400) {
		    // The label will go on the left
		    svglabel.setAttribute("text-anchor", "end");
		    labeloffsetsign = -1;
		    lbgoffx = -lbgpad;
		    lbgoffw = 2*lbgpad + lbgoffset;
		}

                svglabel.setAttribute("x", $(this).attr("cx"));
                svglabel.setAttribute("y", Math.round($(this).attr("cy")));
                svglabel.setAttribute("fill", "#fff");
                svglabel.setAttribute("font-weight", "bold");
                svglabel.setAttribute("font-family", "arial");
                svglabel.setAttribute("font-size", "24px");
                svglabel.setAttribute("visibility", "hidden");
                svglabel.setAttribute("alignment-baseline", "middle");
                svglabel.textContent = this.id.split(".")[0].replace(/_/g, " ");
                $("#svglabels")[0].appendChild(svglabel);

                var label = $(svglabel);
                this.label = label;
                // Make the label visible, position it correctly
                label.attr("visibility", "visible");
                label.fadeIn(100);
                label.attr("x", parseFloat($(this).attr("cx")) + labeloffsetsign*(parseFloat($(this).attr("r")) + parseFloat($(this).attr("stroke-width")) + exp + lbgpad));

                // Create background for label
                var labelbg = document.createElementNS("http://www.w3.org/2000/svg", "rect");
                var lbb = label[0].getBBox();
                labelbg.setAttribute("x", Math.round(lbb.x+lbgoffx));
                labelbg.setAttribute("y", Math.round(lbb.y-lbgpad+2));
                labelbg.setAttribute("width", Math.round(lbb.width+lbgoffw));
                labelbg.setAttribute("height", Math.round(lbb.height+2*lbgpad-4));
                labelbg.setAttribute("fill", "#000");
                labelbg.setAttribute("fill-opacity", 0.8);
                labelbg.setAttribute("stroke", "#fff");
                labelbg.setAttribute("stroke-width", 2);
                labelbg.setAttribute("stroke-opacity", 1.0);
                labelbg.setAttribute("rx", 5);
                labelbg.setAttribute("ry", 5);
                $("#svgnodes")[0].appendChild(labelbg);
                this.labelbg = labelbg;

                // Expand the marker, add to its edge
		if (graph.selcategory != this.id) {
                    $(this).attr("stroke", "#fff");
                    this.origsw = $(this).attr("stroke-width");
                    this.origr = $(this).attr("r");
                    $(this).animate({svgStrokeWidth: "+=2", svgR: "+="+exp}, 100, "swing");
		}

                // Show the node definition
                $("#wngraph-definition").html(""+this.id + ": " + wndefs[this.id]);

            },
            timeout: 300,
            sensitivity: 100,
            interval: 20,
            out: function(e){
                this.label.fadeOut(100);
                $(this.labelbg).fadeOut(100);
                //$(this).animate({svgStrokeWidth: "-=2", svgR: "-="+exp}, 100, "swing");
		if (graph.selcategory != this.id) {
                    $(this).animate({svgStrokeWidth: "-=2", svgR: this.origr}, 100, "swing");
		    if (this.origsw==0) {
			$(this).attr("stroke", "none");
                    }
		}
                $("#svgnodes")[0].removeChild(this.labelbg);
                $("#svglabels")[0].removeChild(this);
                $("#svgnodes").append(this);
            }
        });
    });
    return graph;
}

var dtypeNames = {
    "uint32":Uint32Array,
    "uint16":Uint16Array,
    "uint8":Uint8Array,
    "int32":Int32Array,
    "int16":Int16Array,
    "int8":Int8Array,
    "float32":Float32Array,
}
var dtypeMap = [Uint32Array, Uint16Array, Uint8Array, Int32Array, Int16Array, Int8Array, Float32Array]
var loadCount = 0;
function NParray(data, dtype, shape) {
    this.data = data;
    this.shape = shape;
    this.dtype = dtype;
    this.size = this.data.length;
}
NParray.fromJSON = function(json) {
    var size = json.shape.length ? json.shape[0] : 0;
    for (var i = 1, il = json.shape.length; i < il; i++) {
        size *= json.shape[i];
    }
    var pad = 0;
    if (json.pad) {
        size += json.pad;
        pad = json.pad;
    }

    var data = new (dtypeNames[json.dtype])(size);
    var charview = new Uint8Array(data.buffer);
    var bytes = charview.length / data.length;

    var str = atob(json.data.slice(0,-1));
    var start = pad*bytes, stop  = size*bytes - start;
    for ( var i = start, il = Math.min(stop, str.length); i < il; i++ ) {
        charview[i] = str.charCodeAt(i - start);
    }

    return new NParray(data, json.dtype, json.shape);
}
NParray.fromURL = function(url, callback) {
    loadCount++;
    $("#dataload").show();
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'arraybuffer';
    xhr.onload = function(e) {
        if (this.readyState == 4 && this.status == 200) {
            loadCount--;
            var data = new Uint32Array(this.response, 0, 2);
            var dtype = dtypeMap[data[0]];
            var ndim = data[1];
            var shape = new Uint32Array(this.response, 8, ndim);
            var array = new dtype(this.response, (ndim+2)*4);
            callback(new NParray(array, dtype, shape));
            if (loadCount == 0)
                $("#dataload").hide();
        }
    };
    xhr.send()
}
NParray.prototype.view = function() {
    if (arguments.length == 1 && this.shape.length > 1) {
        var shape;
        var slice = arguments[0];
        if (this.shape.slice)
            shape = this.shape.slice(1);
        else
            shape = this.shape.subarray(1);
        var size = shape[0];
        for (var i = 1, il = shape.length; i < il; i++) {
            size *= shape[i];
        }
        return new NParray(this.data.subarray(slice*size, (slice+1)*size), this.dtype, shape);
    } else {
        throw "Can only slice in first dimension for now"
    }
}
NParray.prototype.minmax = function() {
    var min = Math.pow(2, 32);
    var max = -min;

    for (var i = 0, il = this.data.length; i < il; i++) {
        if (this.data[i] < min) {
            min = this.data[i];
        }
        if (this.data[i] > max) {
            max = this.data[i];
        }
    }

    return [min, max];
}
<|endoftext|>


<commit_before>var tooltipMessage = "";
var flavorText = "";
var letterColours = ["#000000", "#FF0000", "#0000FF", "#00FF00", "#FFFF00", "#FF5500", "#8000FF", "#FF00FF", "#863200"];
var upgradeMessages = ['Increases multi-click by 1 for every two generators',
						'Increases multi-click by 1 for every two generators',
						'Increases multi-click by 5 for every two generators',
						'Increases multi-click by 5 for every two generators',
						'Increases generator '+changeColor(1)+' by 69 times',
						'Increases generator '+changeColor(2)+' by 69 times',
						'Increases generator '+changeColor(3)+' by 69 times',
						'Increases generator '+changeColor(4)+' by 69 times',
						'Increases autoclicker speed by 2 times',
						'Increases autoclicker speed by 2 times',
						'Increases autoclicker speed by 2 times',
						'Increases autoclicker speed by 2 times',
						'Unlock generator autoclick speed',
						'Reduce cost of '+changeColor(5)+'\'s to 1',
						'Every '+changeColor(2)+' generator after 30 will reduce the cost of '+changeColor(4)+'\'s by 15 (up to 66 times)',
						'Every '+changeColor(1)+' generator reduces the cost of '+changeColor(3)+' and '+changeColor(1)+' generators by 1.2 times',
						'Unlocks \'research\' feature (not at all suspicious)',
						'Reduce the cost of '+changeColor(2)+' generators by 1000',
						'Increase generator '+changeColor(5)+' by 69 times',
						'Reduce the cost of '+changeColor(2)+' generators by 1000',
						'Unlock Button',
						'If the number of '+changeColor(4)+'generators is a multiple of 10, increase the multiplier of '+changeColor(4)+' generators by 10 times',
						'Every three '+changeColor(2)+' generators will add one to the multiplier for '+changeColor(2)+' generators (before any other bonuses)',
						'Increases '+changeColor(5)+' generator multiplier by 5 times',
						'Increases '+changeColor(5)+' generator multiplier by 5 times',
						'Increases '+changeColor(5)+' generator multiplier by 5 times',
						'Increases '+changeColor(5)+' generator multiplier by 5 times',
						'Increases '+changeColor(5)+' generator multiplier by 5 times'];
var flavorTextMessages = ['big click',
'bigger click',
'even bigger click',
'yet even bigger click',
						'gotta go fast',
						'gotta go fast',
						'gotta go fast',
						'gotta go fast',
						'meme number',
						'meme number',
						'meme number',
						'meme number',
						'dank discounts',
						'gotta go faster',
						'42',
						'13',
						'spoopy',
						'discounted',
						'gotta go fast',
						'discounted',
						'!!!omg!!!]',
						'\'four\' has four letters',
						'you need to do to twos too',
						'very spoopy',
						'very spoopy',
						'very spoopy',
						'very spoopy',
						'very spoopy'];
var researchMessages = ['Increase rate of decrease of cost of '+changeColor(7)+'\'s by 5',
						'Increase rate of decrease of cost of '+changeColor(7)+'\'s by 100',
						'Increase rate of decrease of cost of '+changeColor(7)+'\'s by 100',
						'Increase rate of decrease of cost of '+changeColor(7)+'\'s by 25',
						'Increase rate of decrease of cost of '+changeColor(7)+'\'s by 25',
						'Increase rate of decrease of cost of '+changeColor(7)+'\'s by 25'
						];
var researchFlavorTextMessages = ['lucky number',
						'lucky number',
						'lucky number',
						'lucky number',
						'lucky number',
						'lucky number',
						];
function renderTooltip() {
	document.getElementById("tooltipMessage").innerHTML = tooltipMessage+"

";
	document.getElementById("flavorText").innerHTML = flavorText;
	if (!flavorText)
		document.getElementById("tooltipMessage").innerHTML = tooltipMessage;
}
function changeColor(num) {
	return "" + num + "";
}
function setResearchTooltip(num) {
	tooltipMessage = researchMessages[num-1];
	if (!researchMessages[num-1])
		tooltipMessage = "";
	flavorText = researchFlavorTextMessages[num-1];
	if (!researchFlavorTextMessages[num-1])
		flavorText = "";
	document.getElementById("tooltip").className = "footer text";
	renderTooltip();
}
function setUpgradeTooltip(num) {
	tooltipMessage = upgradeMessages[num-1];
	if (!upgradeMessages[num-1])
		tooltipMessage = "";
	flavorText = flavorTextMessages[num-1];
	if (!flavorTextMessages[num-1])
		flavorText = "";
	document.getElementById("tooltip").className = "footer text";
	renderTooltip();
}
function setMultiplierTooltip(num) {
	tooltipMessage = "Increases multiplier of " + changeColor(num) + " generators";
	flavorText = "";
	document.getElementById("tooltip").className = "footer text";
	renderTooltip();
}
function setTooltip(num) {
	if (num<8)
		tooltipMessage = "Generates 1 " + changeColor(num) + " per second, multiplied by (1+each amount of higher generators)";
	else
		tooltipMessage = "Generates 1 " + changeColor(num) + " per second";
		flavorText = "";
	document.getElementById("tooltip").className = "footer text";
	renderTooltip();
}
function cancelTooltip() {
	tooltipMessage = "";
	flavorText = "";
	document.getElementById("tooltip").className = "text";
	renderTooltip();
}<commit_msg>fixed flavour text<commit_after>var tooltipMessage = "";
var flavorText = "";
var letterColours = ["#000000", "#FF0000", "#0000FF", "#00FF00", "#FFFF00", "#FF5500", "#8000FF", "#FF00FF", "#863200"];
var upgradeMessages = ['Increases multi-click by 1 for every two generators',
						'Increases multi-click by 1 for every two generators',
						'Increases multi-click by 5 for every two generators',
						'Increases multi-click by 5 for every two generators',
						'Increases generator '+changeColor(1)+' by 69 times',
						'Increases generator '+changeColor(2)+' by 69 times',
						'Increases generator '+changeColor(3)+' by 69 times',
						'Increases generator '+changeColor(4)+' by 69 times',
						'Increases autoclicker speed by 2 times',
						'Increases autoclicker speed by 2 times',
						'Increases autoclicker speed by 2 times',
						'Increases autoclicker speed by 2 times',
						'Unlock generator autoclick speed',
						'Reduce cost of '+changeColor(5)+'\'s to 1',
						'Every '+changeColor(2)+' generator after 30 will reduce the cost of '+changeColor(4)+'\'s by 15 (up to 66 times)',
						'Every '+changeColor(1)+' generator reduces the cost of '+changeColor(3)+' and '+changeColor(1)+' generators by 1.2 times',
						'Unlocks \'research\' feature (not at all suspicious)',
						'Reduce the cost of '+changeColor(2)+' generators by 1000',
						'Increase generator '+changeColor(5)+' by 69 times',
						'Reduce the cost of '+changeColor(2)+' generators by 1000',
						'Unlock Button',
						'If the number of '+changeColor(4)+'generators is a multiple of 10, increase the multiplier of '+changeColor(4)+' generators by 10 times',
						'Every three '+changeColor(2)+' generators will add one to the multiplier for '+changeColor(2)+' generators (before any other bonuses)',
						'Increases '+changeColor(5)+' generator multiplier by 5 times',
						'Increases '+changeColor(5)+' generator multiplier by 5 times',
						'Increases '+changeColor(5)+' generator multiplier by 5 times',
						'Increases '+changeColor(5)+' generator multiplier by 5 times',
						'Increases '+changeColor(5)+' generator multiplier by 5 times'];
var flavorTextMessages = ['big click',
'bigger click',
'even bigger click',
'yet even bigger click',
						'meme number',
						'meme number',
						'meme number',
						'meme number',
						'gotta go fast',
						'gotta go fast',
						'gotta go fast',
						'gotta go fast',
						'dank discounts',
						'gotta go faster',
						'42',
						'13',
						'spoopy',
						'discounted',
						'gotta go fast',
						'discounted',
						'!!!omg!!!]',
						'\'four\' has four letters',
						'you need to do to twos too',
						'very spoopy',
						'very spoopy',
						'very spoopy',
						'very spoopy',
						'very spoopy'];
var researchMessages = ['Increase rate of decrease of cost of '+changeColor(7)+'\'s by 5',
						'Increase rate of decrease of cost of '+changeColor(7)+'\'s by 100',
						'Increase rate of decrease of cost of '+changeColor(7)+'\'s by 100',
						'Increase rate of decrease of cost of '+changeColor(7)+'\'s by 25',
						'Increase rate of decrease of cost of '+changeColor(7)+'\'s by 25',
						'Increase rate of decrease of cost of '+changeColor(7)+'\'s by 25'
						];
var researchFlavorTextMessages = ['lucky number',
						'lucky number',
						'lucky number',
						'lucky number',
						'lucky number',
						'lucky number',
						];
function renderTooltip() {
	document.getElementById("tooltipMessage").innerHTML = tooltipMessage+"

";
	document.getElementById("flavorText").innerHTML = flavorText;
	if (!flavorText)
		document.getElementById("tooltipMessage").innerHTML = tooltipMessage;
}
function changeColor(num) {
	return "" + num + "";
}
function setResearchTooltip(num) {
	tooltipMessage = researchMessages[num-1];
	if (!researchMessages[num-1])
		tooltipMessage = "";
	flavorText = researchFlavorTextMessages[num-1];
	if (!researchFlavorTextMessages[num-1])
		flavorText = "";
	document.getElementById("tooltip").className = "footer text";
	renderTooltip();
}
function setUpgradeTooltip(num) {
	tooltipMessage = upgradeMessages[num-1];
	if (!upgradeMessages[num-1])
		tooltipMessage = "";
	flavorText = flavorTextMessages[num-1];
	if (!flavorTextMessages[num-1])
		flavorText = "";
	document.getElementById("tooltip").className = "footer text";
	renderTooltip();
}
function setMultiplierTooltip(num) {
	tooltipMessage = "Increases multiplier of " + changeColor(num) + " generators";
	flavorText = "";
	document.getElementById("tooltip").className = "footer text";
	renderTooltip();
}
function setTooltip(num) {
	if (num<8)
		tooltipMessage = "Generates 1 " + changeColor(num) + " per second, multiplied by (1+each amount of higher generators)";
	else
		tooltipMessage = "Generates 1 " + changeColor(num) + " per second";
		flavorText = "";
	document.getElementById("tooltip").className = "footer text";
	renderTooltip();
}
function cancelTooltip() {
	tooltipMessage = "";
	flavorText = "";
	document.getElementById("tooltip").className = "text";
	renderTooltip();
}
<|endoftext|>


<commit_before>class Navigation {

    get KEY_DOWN() {
      return 40;
    }

    get KEY_UP() {
      return 38;
    }

    get KEY_LEFT() {
      return 37;
    }

    get KEY_RIGHT() {
      return  39;
    }

    get KEY_TAB() {
       return 9;
    }

    get KEY_RETURN() {
        return 13;
    }

    get KEY_ESCAPE() {
        return 27;
    }

    /**
     * @param {HTMLElement} root
     */
    constructor(root) {
        this.document    = $(document);
        this.rootElement = $(root);
        this.menuBtn     = $('.sc-btn-mobile-menu', this.rootElement);
        this.activeItem  = null;
        this.activeMenu  = null;
        this.menuIsOpen  = false;
        this.menus       = $('nav > ul > li', this.rootElement);
        this.items       = [];
        this.initEvents();
    }

    /**
     * @event Navigation#toggleMenu
     * @event Navigation#escapeMenu
     * @event Navigation#onKeyDown
     * @event Navigation#onKeyUp
     */
    initEvents() {
        this.rootElement.on('click', 'ul>li', $.proxy(this.toggleMenu, this));
        this.menuBtn.on('click', $.proxy(this.toggleMenu, this));
        this.document.on('click', $.proxy(this.escapeMenu, this));
        this.document.on('keydown', $.proxy(this.onKeyDown, this));
        this.document.on('keyup', $.proxy(this.onKeyUp, this));
    }

    /**
     * @param {Object} event
     */
    toggleMenu(event) {
        event.stopPropagation();
        let clickedMenu = $(event.target).closest('li');

        if ($(event.target).closest('li').length === 0) {
            clickedMenu = this.rootElement;
        }

        if (this.activeMenu && this.menuIsOpen) {

            if (this.activeMenu[0] == clickedMenu[0]) {
                this.closeMenu();
                return;
            } else if (this.rootElement[0] == clickedMenu[0]) {
                this.closeMenu(this.rootElement.find('.open').add(this.rootElement));
                return;
            } else if (this.activeMenu[0] != this.rootElement[0]) {
                this.closeMenu();
            }
        }

        this.setActiveMenu(clickedMenu);
        this.openMenu();
    }

    /**
     * @param {HTMLElement} element
     */
    setActiveMenu(element) {
        this.activeMenu = $(element);
    }

    /**
     * @param {HTMLElement} element
     */
    closeMenu(menu) {
        let closeTarget = menu || this.activeMenu;
        closeTarget.removeClass('open');
        this.unsetInactiveMenuItems();
        this.items = [];
        this.menuIsOpen = false;
    }

    openMenu() {
        if (!this.activeMenu) {
            // quick fix when active menu doesn't exists because of any unknown reason
            // TODO: fix it properly
            return;
        }

        this.activeMenu.addClass('open');
        this.items = this.activeMenu.find('ul:not(.submenu) > li:not(.subheadline)');
        this.menuIsOpen = true;
    }

    /**
     * @param {Object} event
     */
    escapeMenu(event) {
        this.activeMenu && this.menuIsOpen && this.closeMenu();
    }

    /**
     * @param {Number} keyCode
     * @returns {boolean}
     */
    isNavigationKey(keyCode) {
        return [
            this.KEY_DOWN,
            this.KEY_LEFT,
            this.KEY_RIGHT,
            this.KEY_UP,
            this.KEY_TAB
        ].indexOf(keyCode) > -1;
    }

    /**
     * Prevent scrolling
     *
     * @param {Object} event
     * @returns {boolean}
     */
    onKeyDown(event) {
        let keyCode = event.which;

        if (this.menuIsOpen && this.isNavigationKey(keyCode)) {
            event.preventDefault();
            return false;
        }

        return true;
    }

    /**
     * @param {Object} event
     * @returns {boolean}
     */
    onKeyUp(event) {
        let keyCode = event.which;

        switch (keyCode) {
            case this.KEY_ESCAPE:
                this.escapeMenu();
                break;
            case this.KEY_DOWN:
                this.handleJumpDown();
                break;
            case this.KEY_UP:
                this.handleJumpUp();
                break;
            case this.KEY_TAB:
                !!event.shiftKey ? this.handleJumpLeft() : this.handleJumpRight();
                break;
            case this.KEY_RIGHT:
                this.handleJumpRight();
                break;
            case this.KEY_LEFT:
                this.handleJumpLeft();
                break;
        }

        event.preventDefault();
        return false;
    }

    handleJumpDown() {
        // Expand the menu if closed
        if (false === this.menuIsOpen) {
            this.openMenu();
            this.selectFirstItem();
            return;
        }
        let position = this.items.indexOf(this.activeItem);
        this.items.length - 1 > position && position++;
        this.setActiveMenuItem(this.items[position]);
    }

    handleJumpUp() {
        if (false === this.menuIsOpen) {
            return;
        }
        let position = this.items.indexOf(this.activeItem);
        0 === position && this.closeMenu();
        0 < position && position--;
        this.setActiveMenuItem(this.items[position]);
    }

    handleJumpRight() {
        if (!this.activeMenu) {
            // quick fix when active menu doesn't exists because of any unknown reason
            // TODO: fix it properly
            return;
        }

        let current = this.menus.indexOf(this.activeMenu[0]);
        let newMenuIdx = this.menus.length - 1 > current ? newMenuIdx = current + 1 : 0;
        this.selectMenu(this.menus[newMenuIdx]);
    }

    handleJumpLeft() {
        if (!this.activeMenu) {
            // quick fix when active menu doesn't exists because of any unknown reason
            // TODO: fix it properly
            return;
        }

        let current = this.menus.indexOf(this.activeMenu[0]);
        let newMenuIdx = (0 < current) ? current - 1 : this.menus.length - 1;
        this.selectMenu(this.menus[newMenuIdx]);
    }

    /**
     * @param {HTMLElement} element
     */
    setActiveMenuItem(element) {
        this.unsetInactiveMenuItems();
        element = $(element);
        !element.hasClass('active-item') && element.addClass('active-item');
        this.activeItem = element[0];
        $('a', element).focus();
    }

    unsetInactiveMenuItems() {
        this.rootElement.find('.active-item').removeClass('active-item');
        this.activeItem = null;
    }

    selectFirstItem() {
        this.setActiveMenuItem(this.items[0]);
    }

    selectMenu(element) {
        if ('object' !== typeof element) {
            return;
        }
        this.menuIsOpen && this.closeMenu();
        this.setActiveMenu(element);
        this.openMenu();
        this.selectFirstItem();
    }
}

export default function () {
    let navigationElement = document.querySelector('.sc-navigation'),
        navigation        = null;
    if (navigationElement) {
        navigation = new Navigation(navigationElement);
    }
    return navigation;
}
<commit_msg>added console.log for navigation debugging<commit_after>class Navigation {

    get KEY_DOWN() {
      return 40;
    }

    get KEY_UP() {
      return 38;
    }

    get KEY_LEFT() {
      return 37;
    }

    get KEY_RIGHT() {
      return  39;
    }

    get KEY_TAB() {
       return 9;
    }

    get KEY_RETURN() {
        return 13;
    }

    get KEY_ESCAPE() {
        return 27;
    }

    /**
     * @param {HTMLElement} root
     */
    constructor(root) {
        this.document    = $(document);
        this.rootElement = $(root);
        this.menuBtn     = $('.sc-btn-mobile-menu', this.rootElement);
        this.activeItem  = null;
        this.activeMenu  = null;
        this.menuIsOpen  = false;
        this.menus       = $('nav > ul > li', this.rootElement);
        this.items       = [];
        this.initEvents();
    }

    /**
     * @event Navigation#toggleMenu
     * @event Navigation#escapeMenu
     * @event Navigation#onKeyDown
     * @event Navigation#onKeyUp
     */
    initEvents() {
        this.rootElement.on('click', 'ul>li', $.proxy(this.toggleMenu, this));
        this.menuBtn.on('click', $.proxy(this.toggleMenu, this));
        this.document.on('click', $.proxy(this.escapeMenu, this));
        this.document.on('keydown', $.proxy(this.onKeyDown, this));
        this.document.on('keyup', $.proxy(this.onKeyUp, this));
    }

    /**
     * @param {Object} event
     */
    toggleMenu(event) {
        event.stopPropagation();
        let clickedMenu = $(event.target).closest('li');

        if ($(event.target).closest('li').length === 0) {
            clickedMenu = this.rootElement;
        }

        if (this.activeMenu && this.menuIsOpen) {

            if (this.activeMenu[0] == clickedMenu[0]) {
                this.closeMenu();
                return;
            } else if (this.rootElement[0] == clickedMenu[0]) {
                this.closeMenu(this.rootElement.find('.open').add(this.rootElement));
                return;
            } else if (this.activeMenu[0] != this.rootElement[0]) {
                this.closeMenu();
            }
        }

        this.setActiveMenu(clickedMenu);
        this.openMenu();
    }

    /**
     * @param {HTMLElement} element
     */
    setActiveMenu(element) {
        this.activeMenu = $(element);
    }

    /**
     * @param {HTMLElement} element
     */
    closeMenu(menu) {
        let closeTarget = menu || this.activeMenu;
        closeTarget.removeClass('open');
        this.unsetInactiveMenuItems();
        this.items = [];
        this.menuIsOpen = false;
    }

    openMenu() {
        if (!this.activeMenu) {
            // quick fix when active menu doesn't exists because of any unknown reason
            // TODO: fix it properly
            return;
        }

        this.activeMenu.addClass('open');
        this.items = this.activeMenu.find('ul:not(.submenu) > li:not(.subheadline)');
        this.menuIsOpen = true;
    }

    /**
     * @param {Object} event
     */
    escapeMenu(event) {
        this.activeMenu && this.menuIsOpen && this.closeMenu();
    }

    /**
     * @param {Number} keyCode
     * @returns {boolean}
     */
    isNavigationKey(keyCode) {
        return [
            this.KEY_DOWN,
            this.KEY_LEFT,
            this.KEY_RIGHT,
            this.KEY_UP,
            this.KEY_TAB
        ].indexOf(keyCode) > -1;
    }

    /**
     * Prevent scrolling
     *
     * @param {Object} event
     * @returns {boolean}
     */
    onKeyDown(event) {
        let keyCode = event.which;

        if (this.menuIsOpen && this.isNavigationKey(keyCode)) {
            event.preventDefault();
            return false;
        }

        return true;
    }

    /**
     * @param {Object} event
     * @returns {boolean}
     */
    onKeyUp(event) {
        let keyCode = event.which;

        switch (keyCode) {
            case this.KEY_ESCAPE:
                this.escapeMenu();
                break;
            case this.KEY_DOWN:
                this.handleJumpDown();
                break;
            case this.KEY_UP:
                this.handleJumpUp();
                break;
            case this.KEY_TAB:
                !!event.shiftKey ? this.handleJumpLeft() : this.handleJumpRight();
                break;
            case this.KEY_RIGHT:
                this.handleJumpRight();
                break;
            case this.KEY_LEFT:
                this.handleJumpLeft();
                break;
        }

        event.preventDefault();
        return false;
    }

    handleJumpDown() {
        // Expand the menu if closed
        if (false === this.menuIsOpen) {
            this.openMenu();
            this.selectFirstItem();
            return;
        }
        let position = this.items.indexOf(this.activeItem);
        this.items.length - 1 > position && position++;
        this.setActiveMenuItem(this.items[position]);
    }

    handleJumpUp() {
        if (false === this.menuIsOpen) {
            return;
        }
        let position = this.items.indexOf(this.activeItem);
        0 === position && this.closeMenu();
        0 < position && position--;
        this.setActiveMenuItem(this.items[position]);
    }

    handleJumpRight() {
        if (!this.activeMenu) {
            // quick fix when active menu doesn't exists because of any unknown reason
            // TODO: fix it properly
            return;
        }

        let current = this.menus.indexOf(this.activeMenu[0]);
        let newMenuIdx = this.menus.length - 1 > current ? newMenuIdx = current + 1 : 0;
        this.selectMenu(this.menus[newMenuIdx]);
    }

    handleJumpLeft() {
        if (!this.activeMenu) {
            // quick fix when active menu doesn't exists because of any unknown reason
            // TODO: fix it properly
            return;
        }

        let current = this.menus.indexOf(this.activeMenu[0]);
        let newMenuIdx = (0 < current) ? current - 1 : this.menus.length - 1;
        this.selectMenu(this.menus[newMenuIdx]);
    }

    /**
     * @param {HTMLElement} element
     */
    setActiveMenuItem(element) {
        this.unsetInactiveMenuItems();
        element = $(element);
        !element.hasClass('active-item') && element.addClass('active-item');
        this.activeItem = element[0];
        $('a', element).focus();
    }

    unsetInactiveMenuItems() {
        this.rootElement.find('.active-item').removeClass('active-item');
        this.activeItem = null;
    }

    selectFirstItem() {
        this.setActiveMenuItem(this.items[0]);
    }

    selectMenu(element) {
        if ('object' !== typeof element) {
            return;
        }
        this.menuIsOpen && this.closeMenu();
        this.setActiveMenu(element);
        this.openMenu();
        this.selectFirstItem();
    }
}

export default function() {
    let navigationElement = document.querySelector('.sc-navigation'),
        navigation        = null;
    if (navigationElement) {
        navigation = new Navigation(navigationElement);
    }

    console.log('navigation: ', navigation);
    return navigation;
}
<|endoftext|>


<commit_before>var _ = require('lodash')
var overrides = {}
try { overrides = require('./truffle-overrides') } catch(e) {}

const defaults = {
  networks: {
    'production': {
      network_id: 1, // Ethereum public network
      host: 'localhost',
      port: 9999,
      'ethercamp-subdomain': 'live'
    },
    'morden': {
      network_id: 2, // morden
      host: 'localhost',
      port: 8888,
      'ethercamp-subdomain': 'morden-state'
    },
    'test': {
      network_id: 'default',
      host: 'localhost',
      port: 7777,
      from: '0x7e5f4552091a69125d5dfcb7b8c2659029395bdf',
      'ethercamp-subdomain': 'not-really'
    },
    'development': {
      network_id: 'default',
      host: 'localhost',
      port: 7777,
      from: '0x7e5f4552091a69125d5dfcb7b8c2659029395bdf'
    }
    // optional config values:
    // - gas
    // - gasPrice
  },
  mocha: {
    'useColors': true
  }
}

var config = _.defaultsDeep(overrides, defaults)
module.exports = config
<commit_msg>allow es5 in truffle.js<commit_after>/* eslint-disable no-var */

var _ = require('lodash')
var overrides = {}
try { overrides = require('./truffle-overrides') } catch (e) {}

const defaults = {
  networks: {
    'production': {
      network_id: 1, // Ethereum public network
      host: 'localhost',
      port: 9999,
      'ethercamp-subdomain': 'live'
    },
    'morden': {
      network_id: 2, // morden
      host: 'localhost',
      port: 8888,
      'ethercamp-subdomain': 'morden-state'
    },
    'test': {
      network_id: 'default',
      host: 'localhost',
      port: 7777,
      from: '0x7e5f4552091a69125d5dfcb7b8c2659029395bdf',
      'ethercamp-subdomain': 'not-really'
    },
    'development': {
      network_id: 'default',
      host: 'localhost',
      port: 7777,
      from: '0x7e5f4552091a69125d5dfcb7b8c2659029395bdf'
    }
    // optional config values:
    // - gas
    // - gasPrice
  },
  mocha: {
    'useColors': true
  }
}

var config = _.defaultsDeep(overrides, defaults)
module.exports = config
<|endoftext|>


<commit_before>'use strict';

import DeepFramework from 'deep-framework';
import Handler from './Handler';

export default {
  handler: (event, context) => {
    DeepFramework.KernelFromLambdaContext(context).bootstrap((deepKernel) => {
        new Handler(deepKernel).run(event, context);
    });
  },
};
<commit_msg>Update bootstrap.es6<commit_after>'use strict';

import DeepFramework from 'deep-framework';
import Handler from './Handler';

export default DeepFramework.LambdaHandler(Handler);
<|endoftext|>


<commit_before>import { combineReducers } from 'redux'

import cardsReducer from './cards'
import locationReducer from './location'
import shuttleReducer from './shuttle'
import mapReducer from './map'
import userReducer from './user'
import weatherReducer from './weather'
import surfReducer from './surf'
import diningReducer from './dining'
import eventsReducer from './events'
import newsReducer from './news'
import linksReducer from './links'
import routesReducer from './routes'
import scheduleReducer from './schedule'
import specialEventsReducer from './specialEvents'
import feedbackReducer from './feedback'
import requestStatusesReducer from './requestStatuses'
import requestErrorsReducer from './requestErrors'
import homeReducer from './home'
import messagesReducer from './messages'
import notificationsReducer from './notifications'

module.exports = combineReducers({
	cards: cardsReducer,
	location: locationReducer,
	shuttle: shuttleReducer,
	map: mapReducer,
	user: userReducer,
	weather: weatherReducer,
	surf: surfReducer,
	dining: diningReducer,
	events: eventsReducer,
	news: newsReducer,
	links: linksReducer,
	routes: routesReducer,
	specialEvents: specialEventsReducer,
	schedule: scheduleReducer,
	feedback: feedbackReducer,
	requestStatuses: requestStatusesReducer,
	requestErrors: requestErrorsReducer,
	home: homeReducer,
	messages: messagesReducer,
	notifications: notificationsReducer
})
<commit_msg>Remove notifications reducer from index reducer<commit_after>import { combineReducers } from 'redux'

import cardsReducer from './cards'
import locationReducer from './location'
import shuttleReducer from './shuttle'
import mapReducer from './map'
import userReducer from './user'
import weatherReducer from './weather'
import surfReducer from './surf'
import diningReducer from './dining'
import eventsReducer from './events'
import newsReducer from './news'
import linksReducer from './links'
import routesReducer from './routes'
import scheduleReducer from './schedule'
import specialEventsReducer from './specialEvents'
import feedbackReducer from './feedback'
import requestStatusesReducer from './requestStatuses'
import requestErrorsReducer from './requestErrors'
import homeReducer from './home'
import messagesReducer from './messages'

module.exports = combineReducers({
	cards: cardsReducer,
	location: locationReducer,
	shuttle: shuttleReducer,
	map: mapReducer,
	user: userReducer,
	weather: weatherReducer,
	surf: surfReducer,
	dining: diningReducer,
	events: eventsReducer,
	news: newsReducer,
	links: linksReducer,
	routes: routesReducer,
	specialEvents: specialEventsReducer,
	schedule: scheduleReducer,
	feedback: feedbackReducer,
	requestStatuses: requestStatusesReducer,
	requestErrors: requestErrorsReducer,
	home: homeReducer,
	messages: messagesReducer,
})
<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var Batter  = require('../models/batter');
var router  = express.Router();
var _       = require('lodash');
var chalk   = require('chalk');

// CONFIGURE BATTERS API ROUTES
// =============================================================================

// Configure all `batters`
// includes routes (GET, POST)
router.route('/')

  // create a batter (accessed at POST http://localhost:3000/batters)
  .post(function(req, res) {
    var batter = new Batter();    // create a new instance of the Batter model
    batter.set(req.body);
    batter.save(function(err, batter) {
      if (err) {
        console.log(err);
        res.status(400).json( {status: 'Fail', 'message': err.message, 'errors': err.errors } );
      }
      res.json({ id: batter._id, status: 'OK', message: 'Batter created' });
    });
  })

  // get all the batters (accessed at GET http://localhost:3000/api/v1/batters)
  .get(function(req, res) {
    // remove apikey from queryString
    var limit = req.query.limit;
    console.log(limit);
    var q = _.remove(req.query, function(key) {
      return key !== 'apikey';
    });

    var q = Batter.find(q).limit(limit);
    q.execFind(function(err, batters) {
      if (err) {res.send(err); }

      res.json(batters);
    });

  });

// on routes that end in /batters/:batter_id
// includes GET, PUT, PATCH, DELETE
// ----------------------------------------------------
router.route('/:batter_id')

  // get the better with that id
  .get(function(req, res) {
    Batter.findById(req.params.batter_id, function(err, batter) {
      // reconstruct error response to send same format as api-lumne
      if ((err) || (! batter)) {
        res.status(404).json({status: 'Fail', message: 'Batter Not Found'});
      }

      res.json(batter);
    });
  })

  // update the batter with this id
  .put(function(req, res) {
    Batter.findById(req.params.batter_id, function(err, batter) {
      if (err) {res.send(err); }

      batter.set(req.body);
      batter.save(function(err) {
        if (err) {res.send(err); }

        res.json({status: 'OK', message: batter.first_name +' '+ batter.last_name + ' Updated Successfully'});
      });
    });
  })

  // update the batter with this id
  .patch(function(req, res) {
    Batter.findById(req.params.batter_id, function(err, batter) {
      if (err) {res.send(err); }

      batter.set(req.body);
      batter.save(function(err) {
        if (err) {res.send(err); }

        res.json({status: 'OK', message: batter.first_name +' '+ batter.last_name + ' Updated Successfully'});
      });
    });
  })

  // delete the batter with this id
  .delete(function(req, res) {

    Batter.findById(req.params.batter_id, function(err, batter) {
      // reconstruct error response to send same format as api-lumne
      if ((err) || (! batter)) {
        res.status(404).send({status: 'Fail', message: 'Batter Not Found'});
      } else {
        Batter.remove({
          _id: req.params.batter_id
        }, function(err) {
          if (err) {
            res.status(404).send({status: 'Fail', message: 'Batter Not Found'});
          }
          res.status(200).send({status: 'OK', message: 'Batter Deleted Successfully'});
        });
      }

    });

});

module.exports = router;<commit_msg>removed some rogue console messages<commit_after>'use strict';

var express = require('express');
var Batter  = require('../models/batter');
var router  = express.Router();
var _       = require('lodash');
var chalk   = require('chalk');

// CONFIGURE BATTERS API ROUTES
// =============================================================================

// Configure all `batters`
// includes routes (GET, POST)
router.route('/')

  // create a batter (accessed at POST http://localhost:3000/batters)
  .post(function(req, res) {
    var batter = new Batter();    // create a new instance of the Batter model
    batter.set(req.body);
    batter.save(function(err, batter) {
      if (err) {
        res.status(400).json( {status: 'Fail', 'message': err.message, 'errors': err.errors } );
      }
      res.json({ id: batter._id, status: 'OK', message: 'Batter created' });
    });
  })

  // get all the batters (accessed at GET http://localhost:3000/api/v1/batters)
  .get(function(req, res) {
    // remove apikey from queryString
    var limit = req.query.limit;
    var q = _.remove(req.query, function(key) {
      return key !== 'apikey';
    });

    var q = Batter.find(q).limit(limit);
    q.execFind(function(err, batters) {
      if (err) {res.send(err); }

      res.json(batters);
    });

  });

// on routes that end in /batters/:batter_id
// includes GET, PUT, PATCH, DELETE
// ----------------------------------------------------
router.route('/:batter_id')

  // get the better with that id
  .get(function(req, res) {
    Batter.findById(req.params.batter_id, function(err, batter) {
      // reconstruct error response to send same format as api-lumne
      if ((err) || (! batter)) {
        res.status(404).json({status: 'Fail', message: 'Batter Not Found'});
      }

      res.json(batter);
    });
  })

  // update the batter with this id
  .put(function(req, res) {
    Batter.findById(req.params.batter_id, function(err, batter) {
      if (err) {res.send(err); }

      batter.set(req.body);
      batter.save(function(err) {
        if (err) {res.send(err); }

        res.json({status: 'OK', message: batter.first_name +' '+ batter.last_name + ' Updated Successfully'});
      });
    });
  })

  // update the batter with this id
  .patch(function(req, res) {
    Batter.findById(req.params.batter_id, function(err, batter) {
      if (err) {res.send(err); }

      batter.set(req.body);
      batter.save(function(err) {
        if (err) {res.send(err); }

        res.json({status: 'OK', message: batter.first_name +' '+ batter.last_name + ' Updated Successfully'});
      });
    });
  })

  // delete the batter with this id
  .delete(function(req, res) {

    Batter.findById(req.params.batter_id, function(err, batter) {
      // reconstruct error response to send same format as api-lumne
      if ((err) || (! batter)) {
        res.status(404).send({status: 'Fail', message: 'Batter Not Found'});
      } else {
        Batter.remove({
          _id: req.params.batter_id
        }, function(err) {
          if (err) {
            res.status(404).send({status: 'Fail', message: 'Batter Not Found'});
          }
          res.status(200).send({status: 'OK', message: 'Batter Deleted Successfully'});
        });
      }

    });

});

module.exports = router;<|endoftext|>


<commit_before>import Ember from 'ember';
import ResetScrollMixin from '../mixins/reset-scroll';
import SetupSubmitControllerMixin from '../mixins/setup-submit-controller';
import Analytics from '../mixins/analytics';
import config from 'ember-get-config';
import loadAll from 'ember-osf/utils/load-relationship';
import permissions from 'ember-osf/const/permissions';

export default Ember.Route.extend(Analytics, ResetScrollMixin, SetupSubmitControllerMixin, {
    theme: Ember.inject.service(),
    headTagsService: Ember.inject.service('head-tags'),
    currentUser: Ember.inject.service('currentUser'),
    queryParams: {
        edit: {
            refreshModel: true // if queryParam, do a full transition
        }
    },
    setup() {
        // Overrides setup method.  If query param /?edit is present, uses 'submit' controller instead.
        this.set('controllerName', this.get('editMode') ? 'submit' : 'content');
        return this._super(...arguments);
    },
    renderTemplate() {
        // Overrides renderTemplate method.  If query param /?edit is present, uses 'submit' template instead.
        this.render(this.get('editMode') ? 'submit' : 'content');
    },
    model(params) {
        if (params.edit)
            this.set('editMode', true);

        return this
            .store
            .findRecord('preprint', params.preprint_id);
    },
    setupController(controller, model) {
        if (this.get('editMode')) {
            // Runs setupController for 'submit'
            this.setupSubmitController(controller, model);
        } else {
            // Runs setupController for 'content'
            controller.set('activeFile', model.get('primaryFile'));
            controller.set('node', this.get('node'));
            Ember.run.scheduleOnce('afterRender', this, function() {
                MathJax.Hub.Queue(['Typeset', MathJax.Hub, [Ember.$('.abstract')[0], Ember.$('#preprintTitle')[0]]]);  // jshint ignore:line
            });
        }

        return this._super(...arguments);
    },
    afterModel(preprint) {
        // Redirect if necessary
        preprint.get('provider')
            .then(provider => {
                const providerId = provider.get('id');
                const themeId = this.get('theme.id');
                const isOSF = providerId === 'osf';

                // If we're on the proper branded site, stay there.
                if ((!themeId && isOSF) || themeId === providerId)
                    return;

                // Otherwise, redirect to the branded page
                // Hard redirect instead of transition, in anticipation of Phase 2 where providers will have their own domains.
                const {origin, search} = window.location;

                const urlParts = [
                    origin
                ];

                if (!isOSF)
                    urlParts.push('preprints', providerId);

                urlParts.push(preprint.get('id'), search);

                const url = urlParts.join('/');

                window.history.replaceState({}, document.title, url);
                window.location.replace(url);
            });

        return preprint.get('node').then(node => {
            this.set('node', node);

            if (this.get('editMode')) {
                let userPermissions = this.get('node.currentUserPermissions') || [];
                if (userPermissions.indexOf(permissions.ADMIN) === -1) {
                    this.replaceWith('forbidden'); // Non-admin trying to access edit form.
                }
            }

            const {origin} = window.location;
            const image = this.get('theme.logoSharing');
            const imageUrl = `${origin.replace(/^https/, 'http')}${image.path}`;
            const dateCreated = new Date(preprint.get('dateCreated'));
            const ogp = [
                ['fb:app_id', config.FB_APP_ID],
                ['og:title', node.get('title')],
                ['og:image', imageUrl],
                ['og:image:secure_url', `${origin}${image.path}`], // We should always be on https in staging/prod
                ['og:image:width', image.width.toString()],
                ['og:image:height', image.height.toString()],
                ['og:image:type', image.type],
                ['og:url', preprint.get('links.html')],
                ['og:description', node.get('description')],
                ['og:site_name', this.get('theme.provider.name')],
                ['og:type', 'article'],
                ['article:published_time', new Date(preprint.get('dateCreated') || null).toISOString()],
                ['article:modified_time', new Date(preprint.get('dateModified') || preprint.get('dateCreated') || null).toISOString()],
                ['citation_title', node.get('title')],
                ['citation_description', node.get('description')],
                ['citation_public_url', preprint.get('links.html')],
                ['citation_publication_date', `${dateCreated.getFullYear()}/${dateCreated.getMonth() + 1}/${dateCreated.getDate()}`],
                ['citation_doi', preprint.get('doi')],
                ['dc.title', node.get('title')],
                ['dc.abstract', node.get('description')],
                ['dc.identifier', preprint.get('links.html')],
                ['dc.identifier', preprint.get('doi')]
            ];

            const modified = preprint.get('dateModified') || preprint.get('dateCreated');

            if (modified)
                ogp.push(['article:modified_time', new Date(modified).toISOString()]);

            const tags = [
                ...preprint.get('subjects').map(subjectBlock => subjectBlock.map(subject => subject.text)),
                ...node.get('tags')
            ];

            for (const tag of tags)
                ogp.push(
                    ['article:tag', tag],
                    ['citation_keywords', tag],
                    ['dc.subject', tag]
                );

            let contributors = Ember.A();

            loadAll(node, 'contributors', contributors).then(() => {
                contributors.forEach(contributor => {
                    ogp.push(
                        ['og:type', 'article:author'],
                        ['profile:first_name', contributor.get('users.givenName')],
                        ['profile:last_name', contributor.get('users.familyName')],
                        ['citation_author', `${contributor.get('users.givenName')} ${contributor.get('users.familyName')}`],
                        ['dc.creator', `${contributor.get('users.givenName')} ${contributor.get('users.familyName')}`]
                    );
                });

                this.set('headTags', ogp.map(item => (
                    {
                        type: 'meta',
                        attrs: {
                            property: item[0],
                            content: item[1]
                        }
                    }
                )));

                this.get('headTagsService').collectHeadTags();

                preprint.get('provider').then(provider => {
                    ogp.push(
                        ['citation_publisher', provider.get('name')],
                        ['dc.publisher', provider.get('name')]
                    );
                    preprint.get('license').then(license => {
                        ogp.push(
                            ['dc.license', license.get('name')]
                        );
                        preprint.get('primaryFile').then(file => {
                            if (file.get('name').split('.').pop() === 'pdf') {
                                ogp.push(
                                    ['citation_pdf_url', file.get('links').download]
                                );
                            }
                            this.set('headTags', ogp.map(item => (
                                {
                                    type: 'meta',
                                    attrs: {
                                        property: item[0],
                                        content: item[1]
                                    }
                                }
                            )));
                            this.get('headTagsService').collectHeadTags();
                        });
                    });
                });
            });
        });
    },
    actions: {
        error(error) {
            if (error && error.errors && Ember.isArray(error.errors) && error.errors[0].detail === 'The requested node is no longer available.') {
                this.intermediateTransitionTo('resource-deleted'); // Node containing preprint has been deleted. 410 Gone.
            }
        }
    }
});
<commit_msg>Fix ordering of tags, de-nest promises<commit_after>import Ember from 'ember';
import ResetScrollMixin from '../mixins/reset-scroll';
import SetupSubmitControllerMixin from '../mixins/setup-submit-controller';
import Analytics from '../mixins/analytics';
import config from 'ember-get-config';
import loadAll from 'ember-osf/utils/load-relationship';
import permissions from 'ember-osf/const/permissions';

export default Ember.Route.extend(Analytics, ResetScrollMixin, SetupSubmitControllerMixin, {
    theme: Ember.inject.service(),
    headTagsService: Ember.inject.service('head-tags'),
    currentUser: Ember.inject.service('currentUser'),
    queryParams: {
        edit: {
            refreshModel: true // if queryParam, do a full transition
        }
    },
    setup() {
        // Overrides setup method.  If query param /?edit is present, uses 'submit' controller instead.
        this.set('controllerName', this.get('editMode') ? 'submit' : 'content');
        return this._super(...arguments);
    },
    renderTemplate() {
        // Overrides renderTemplate method.  If query param /?edit is present, uses 'submit' template instead.
        this.render(this.get('editMode') ? 'submit' : 'content');
    },
    model(params) {
        if (params.edit)
            this.set('editMode', true);

        return this
            .store
            .findRecord('preprint', params.preprint_id);
    },
    setupController(controller, model) {
        if (this.get('editMode')) {
            // Runs setupController for 'submit'
            this.setupSubmitController(controller, model);
        } else {
            // Runs setupController for 'content'
            controller.set('activeFile', model.get('primaryFile'));
            controller.set('node', this.get('node'));
            Ember.run.scheduleOnce('afterRender', this, function() {
                MathJax.Hub.Queue(['Typeset', MathJax.Hub, [Ember.$('.abstract')[0], Ember.$('#preprintTitle')[0]]]);  // jshint ignore:line
            });
        }

        return this._super(...arguments);
    },
    afterModel(preprint) {
        const {origin, search} = window.location;
        let contributors = Ember.A();

        return preprint.get('provider')
            .then(provider => {
                const providerId = provider.get('id');
                const themeId = this.get('theme.id');
                const isOSF = providerId === 'osf';

                // If we're on the proper branded site, stay here.
                if ((!themeId && isOSF) || themeId === providerId)
                    return Promise.all([
                        provider,
                        preprint.get('node')
                    ]);

                // Otherwise, redirect to the proper branded site.
                // Hard redirect instead of transition, in anticipation of Phase 2 where providers will have their own domains.
                const urlParts = [
                    origin
                ];

                if (!isOSF)
                    urlParts.push('preprints', providerId);

                urlParts.push(preprint.get('id'), search);

                const url = urlParts.join('/');

                window.history.replaceState({}, document.title, url);
                window.location.replace(url);

                return Promise.reject();
            })
            .then(([provider, node]) => {
                this.set('node', node);

                if (this.get('editMode')) {
                    const userPermissions = this.get('node.currentUserPermissions') || [];

                    if (!userPermissions.includes(permissions.ADMIN)) {
                        this.replaceWith('forbidden'); // Non-admin trying to access edit form.
                    }
                }

                return Promise.all([
                    provider,
                    node,
                    preprint.get('license'),
                    preprint.get('primaryFile'),
                    loadAll(node, 'contributors', contributors)
                ]);
            })
            .then(([provider, node, license, primaryFile]) => {
                const title = node.get('title');
                const description = node.get('description');
                const doi = preprint.get('doi');
                const image = this.get('theme.logoSharing');
                const imageUrl = `${origin.replace(/^https/, 'http')}${image.path}`;
                const dateCreated = new Date(preprint.get('dateCreated') || null);
                const dateModified = new Date(preprint.get('dateModified') || dateCreated);
                const providerName = provider.get('name');
                const canonicalUrl = preprint.get('links.html');

                // NOTE: Ordering of meta tags matters for scrapers (Facebook, LinkedIn, Google, etc)

                // Open Graph Protocol
                const openGraph = [
                    ['fb:app_id', config.FB_APP_ID],
                    ['og:title', title],
                    ['og:image', imageUrl],
                    ['og:image:secure_url', `${origin}${image.path}`], // We should always be on https in staging/prod
                    ['og:image:width', image.width.toString()],
                    ['og:image:height', image.height.toString()],
                    ['og:image:type', image.type],
                    ['og:url', canonicalUrl],
                    ['og:description', description],
                    ['og:site_name', providerName],
                    ['og:type', 'article'],
                    ['article:published_time', dateCreated.toISOString()],
                    ['article:modified_time', dateModified.toISOString()]
                ];

                // Highwire Press
                const highwirePress = [
                    ['citation_title', title],
                    ['citation_description', description],
                    ['citation_public_url', canonicalUrl],
                    ['citation_publication_date', `${dateCreated.getFullYear()}/${dateCreated.getMonth() + 1}/${dateCreated.getDate()}`],
                    ['citation_doi', doi]
                ];

                // TODO map Eprints fields
                // Eprints
                const eprints = [];

                // TODO map BE Press fields
                // BE Press
                const bePress = [];

                // TODO map PRISM fields
                // PRISM
                const prism = [];

                // Dublin Core
                const dublinCore = [
                    ['dc.title', title],
                    ['dc.abstract', description],
                    ['dc.identifier', canonicalUrl],
                    ['dc.identifier', doi]
                ];

                const tags = [
                    ...preprint.get('subjects').map(subjectBlock => subjectBlock.map(subject => subject.text)),
                    ...node.get('tags')
                ];

                for (const tag of tags) {
                    openGraph.push(['article:tag', tag]);
                    highwirePress.push(['citation_keywords', tag]);
                    dublinCore.push(['dc.subject', tag]);
                }

                for (const contributor of contributors) {
                    const givenName = contributor.get('users.givenName');
                    const familyName = contributor.get('users.familyName');
                    const fullName = contributor.get('users.fullName');

                    openGraph.push(
                        ['og:type', 'article:author'],
                        ['profile:first_name', givenName],
                        ['profile:last_name', familyName]
                    );
                    highwirePress.push(['citation_author', fullName]);
                    dublinCore.push(['dc.creator', fullName]);
                }

                highwirePress.push(['citation_publisher', providerName]);
                dublinCore.push(
                    ['dc.publisher', providerName],
                    ['dc.license', license.get('name')]
                );

                if (/\.pdf$/.test(primaryFile.get('name'))) {
                    highwirePress.push(['citation_pdf_url', primaryFile.get('links').download]);
                }

                const headTags = [
                    openGraph,
                    highwirePress,
                    eprints,
                    bePress,
                    prism,
                    dublinCore
                ]
                    .reduce((a, b) => a.concat(b), [])
                    .filter(item => item[1]) // Don't show tags with no content
                    .map(item => ({
                        type: 'meta',
                        attrs: {
                            property: item[0],
                            content: item[1]
                        }
                    }));

                this.set('headTags', headTags);
                this.get('headTagsService').collectHeadTags();
            });
    },
    actions: {
        error(error) {
            if (error && error.errors && Ember.isArray(error.errors) && error.errors[0].detail === 'The requested node is no longer available.') {
                this.intermediateTransitionTo('resource-deleted'); // Node containing preprint has been deleted. 410 Gone.
            }
        }
    }
});
<|endoftext|>


<commit_before>import NavigationBar from 'react-native-navbar';
import React, { Component, PropTypes } from 'react';
import {
  View,
  ScrollView,
} from 'react-native';

import {default as AddTodo} from '../components/add-todo';

class NewTodo extends Component {
  constructor(props) {
    super(props);
    this.cancel = this.backToList.bind(this);
    this.done = this.backToList.bind(this);
  }

  backToList() {
    this.props.navigator.pop();
  }

  render() {
    const {theme} = this.props;
    const {styles, variables} = theme;
    return (
      <View style={styles.container}>
        <NavigationBar
          title={{ title: 'New Task', tintColor: variables.colorTint }}
          leftButton={{ title: 'Cancel', handler: this.cancel, tintColor: variables.colorNavbarText }}
          style={styles.navbar}
        />
        <ScrollView horizontal={false}>
          <AddTodo onFinish={this.done} theme={theme} />
        </ScrollView>
      </View>
    );
  }
}

NewTodo.propTypes = {
  theme: PropTypes.object
};

export default NewTodo;
<commit_msg>Change New Todo to Modal.<commit_after>import NavigationBar from 'react-native-navbar';
import React, { Component, PropTypes } from 'react';
import {
  View,
  ScrollView,
  Modal,
} from 'react-native';

import {default as AddTodo} from '../components/add-todo';

class NewTodo extends Component {
  constructor(props) {
    super(props);
    this.cancel = this.backToList.bind(this);
    this.done = this.backToList.bind(this);
  }

  backToList() {
    this.props.navigator.pop();
  }

  render() {
    const {theme} = this.props;
    const {styles, variables} = theme;
    return (
      <Modal animationType={'slide'} >
          <View style={styles.container}>
            <NavigationBar
              title={{ title: 'New Task', tintColor: variables.colorTint }}
              leftButton={{ title: 'Cancel', handler: this.cancel, tintColor: variables.colorNavbarText }}
              style={styles.navbar}
            />
            <ScrollView horizontal={false}>
              <AddTodo onFinish={this.done} theme={theme} />
            </ScrollView>
          </View>
      </Modal>
    );
  }
}

NewTodo.propTypes = {
  theme: PropTypes.object
};

export default NewTodo;
<|endoftext|>