<commit_before>function HL7Message() {};

HL7Message.prototype.getSegmentByType = function(type) {
    let seg = {};

    for (let i in this.segments) {
        if (this.segments[i].segmentType === type) {
            seg = this.segments[i];
            return seg;
        }
    }

    return seg;
}

HL7Message.prototype.getSegmentsByType = function(type) {
    let segs = [];

    for (let i in this.msg.segments) {
        if (this.msg.segments[i].segmentType === type) {
            segs.push(this.msg.segments[i]);
        }
    }

    return segs;
};

var HL7Parser = {
    // adding in output types to flex how info is displayed/sent once parsed
    OUTPUT_TYPES : {
        PAGE: 'PAGE',
        JSON: 'JSON'
    },
    STATUSES     : {
        SUCCESS: 'SUCCESS',
        ERROR: 'ERROR'
    },
    message     : {},
    fieldSep    : '|',
    compSep     : '^',
    subCompSep  : '&',
    repeatSep   : '~',
    escapeChar  : '\\',

    // parse message into object
    parseMessage    : function(inboundMessage) {
        let msg = inboundMessage.trim();

        if (msg === '' || msg.substring(0,3) != 'MSH') {
            this.message.resultStatus = this.STATUSES.ERROR
            this.message.resultReason = 'Not a valid HL7 message';

            return null;
        } else {
            this.originalMsg = msg;
            this.setSeparators();
            this.separateSegs();
            this.parseSegs();

            return this.message//new HL7Message(this.message);
        }
    },

    // replace separates with actual separators from message
    setSeparators : function() {
        this.fieldSep   = this.originalMsg.substring(3,4);
        this.compSep    = this.originalMsg.substring(4,5);
        this.repeatSep  = this.originalMsg.substring(5,6);
        this.subCompSep = this.originalMsg.substring(7,8);
        this.escapeChar = this.originalMsg.substring(6,7);
    },
    // separate message segments into a list
    separateSegs : function() {
        this.segments = this.originalMsg.split("\n");
        // remove any whitespace around segments, just in case
        for (let i = 0; i < this.segments.length; i++) {
            this.segments[i] = this.segments[i].trim();
        }
    },
    // parse out segments
    // places results in message object
    parseSegs : function() {
        let myMsg = new HL7Message();
        myMsg.segments = [];

        myMsg.originalMsg = this.originalMsg;

        for (let i = 0; i < this.segments.length; i++) {
            let currSeg         = this.segments[i];
            let currSegFields   = currSeg.split(this.fieldSep);

            console.log(currSeg);

            //cleanup list and remove last item if empty
            // this will always happen if the segment ends with the field sep
            if (currSegFields[(currSegFields.length - 1)] == '') currSegFields.splice(-1,1);

            // If we're at the MSH, correct segment numbering and add the field separator as the first value
            if (currSegFields[0] === 'MSH') {
                currSegFields[0] = this.fieldSep; //Replace the array's first value "MSH" with the Field Separator
                currSegFields.unshift("MSH"); // Add back "MSH" as the array's first value
            }

            let segObj = {};

            segObj.segmentType = currSegFields[0];
            segObj.fieldCount = (currSegFields.length-1);
            segObj.segmentText = currSeg;
            //segObj.segmentFullText = (currSeg);
            // segObj.fields = {};

            segObj.fields = [];

            for (let j = 0; j < currSegFields.length; j++) {
                let currField = currSegFields[j];

                segObj.fields[j] = {};
                segObj.fields[j].value = currField;

                segObj.fields[j].instances = [];

                let repSet = currField.split(this.repeatSep);
                for (let k = 0; k < repSet.length; k++) {
                    let repField = repSet[k];

                    segObj.fields[j].instances[k] = {};
                    segObj.fields[j].instances[k].value = repField;

                    segObj.fields[j].instances[k].components = [];

                    let compSet = repField.split(this.compSep);
                    for (let l = 0; l < compSet.length; l++) {
                        let compField = compSet[l];

                        segObj.fields[j].instances[k].components[l] = {};
                        segObj.fields[j].instances[k].components[l].value = compField;

                        segObj.fields[j].instances[k].components[l].subcomps = [];

                        let subCompSet = compField.split(this.subCompSep);
                        for (let y = 0; y < subCompSet.length; y++) {
                            let subComp = subCompSet[y];

                            segObj.fields[j].instances[k].components[l].subcomps[y] = {};
                            segObj.fields[j].instances[k].components[l].subcomps[y].value = subComp;
                        }
                    }
                }
            }

            //console.log(JSON.stringify(segObj));

            myMsg.segments.push(segObj);

            //myMsg.segments[i] = (segObj);

            //console.log(myMsg.segments);
        }

        // set MSH segment
        myMsg.MSH = myMsg.getSegmentByType('MSH');

        // add message type, control id, and hl7 version
        myMsg.messageType = myMsg.MSH.fields[9].value;
        myMsg.controlID = myMsg.MSH.fields[10].value;
        myMsg.version = myMsg.MSH.fields[12].value;

        this.message = myMsg;
        this.resultStatus = this.STATUSES.SUCCESS;

    },

    getHTMLOutput   : function(msgObject) {
        console.log('testing forever');
        console.log(msgObject);

        let outputDiv = document.createElement('div');

        // create header element
        let headerElem = document.createElement('h3');
        headerElem.append(document.createTextNode(
            msgObject.messageType +
            ' - Control ID: ' + msgObject.controlID +
            ' - Version: ' + msgObject.version
        ));
        outputDiv.appendChild(headerElem);

        for (let segment of msgObject.segments) {
            // create main detail section for segment
            let segDetElem = document.createElement('details');
            let segSumElem = document.createElement('summary');
            let fieldDivElem = document.createElement('div');
            segSumElem.append(document.createTextNode(segment.segmentText));
            segDetElem.appendChild(segSumElem);
            segDetElem.appendChild(fieldDivElem);

            for (let j = 1; j < segment.fields.length; j++) {
                let field = segment.fields[j];

                let fieldDetElem = document.createElement('details');
                let fieldSumElem = document.createElement('summary');
                fieldSumElem.append(document.createTextNode('['+j+'] '+field.value));
                fieldDetElem.appendChild(fieldSumElem);
                fieldDivElem.appendChild(fieldDetElem);

                let repDiv = document.createElement('div');
                fieldDetElem.appendChild(repDiv);

                for (let k = 0; k < field.instances.length; k++) {
                    let instance = field.instances[k];

                    let instanceDet = document.createElement('details');
                    repDiv.appendChild(instanceDet);

                    let instanceSum = document.createElement('summary');
                    instanceSum.append(document.createTextNode('('+k+') '+instance.value));
                    instanceDet.appendChild(instanceSum);

                    let compDiv = document.createElement('div');
                    instanceDet.appendChild(compDiv);

                    for (let l = 0; l < instance.components.length; l++) {
                        let component = instance.components[l];

                        let componentDet = document.createElement('details');
                        compDiv.appendChild(componentDet);

                        let compSum = document.createElement('summary');
                        compSum.append(document.createTextNode('['+l+'] '+component.value));
                        componentDet.appendChild(compSum);

                        let subCompDiv = document.createElement('div');
                        componentDet.appendChild(subCompDiv);

                        for (let y = 0; y < component.subcomps.length; y++) {
                            let subcomp = component.subcomps[y];

                            let subDet = document.createElement('details');
                            subCompDiv.appendChild(subDet);

                            let subSum = document.createElement('summary');
                            subSum.append(document.createTextNode('['+y+'] '+subcomp.value));
                            subDet.appendChild(subSum);
                        }
                    }
                }
            }

            outputDiv.appendChild(segDetElem);
        }

        return outputDiv;
    }
};<commit_msg>Update hl7parser.js<commit_after>function HL7Message() {};

HL7Message.prototype.getSegmentByType = function(type) {
    let seg = {};

    for (let i in this.segments) {
        if (this.segments[i].segmentType === type) {
            seg = this.segments[i];
            return seg;
        }
    }

    return seg;
}

HL7Message.prototype.getSegmentsByType = function(type) {
    let segs = [];

    for (let i in this.msg.segments) {
        if (this.msg.segments[i].segmentType === type) {
            segs.push(this.msg.segments[i]);
        }
    }

    return segs;
};

var HL7Parser = {
    // adding in output types to flex how info is displayed/sent once parsed
    OUTPUT_TYPES : {
        PAGE: 'PAGE',
        JSON: 'JSON'
    },
    STATUSES     : {
        SUCCESS: 'SUCCESS',
        ERROR: 'ERROR'
    },
    message     : {},
    fieldSep    : '|',
    compSep     : '^',
    subCompSep  : '&',
    repeatSep   : '~',
    escapeChar  : '\\',

    // parse message into object
    parseMessage    : function(inboundMessage) {
        let msg = inboundMessage.trim();

        if (msg === '' || msg.substring(0,3) != 'MSH') {
            this.message.resultStatus = this.STATUSES.ERROR
            this.message.resultReason = 'Not a valid HL7 message';

            return null;
        } else {
            this.originalMsg = msg;
            this.setSeparators();
            this.separateSegs();
            this.parseSegs();

            return this.message//new HL7Message(this.message);
        }
    },

    // replace separates with actual separators from message
    setSeparators : function() {
        this.fieldSep   = this.originalMsg.substring(3,4);
        this.compSep    = this.originalMsg.substring(4,5);
        this.repeatSep  = this.originalMsg.substring(5,6);
        this.subCompSep = this.originalMsg.substring(7,8);
        this.escapeChar = this.originalMsg.substring(6,7);
    },
    // separate message segments into a list
    separateSegs : function() {
        this.segments = this.originalMsg.split("\n");
        // remove any whitespace around segments, just in case
        for (let i = 0; i < this.segments.length; i++) {
            this.segments[i] = this.segments[i].trim();
        }
    },
    // parse out segments
    // places results in message object
    parseSegs : function() {
        let myMsg = new HL7Message();
        myMsg.segments = [];

        myMsg.originalMsg = this.originalMsg;

        for (let i = 0; i < this.segments.length; i++) {
            let currSeg         = this.segments[i];
            let currSegFields   = currSeg.split(this.fieldSep);

            console.log(currSeg);

            //cleanup list and remove last item if empty
            // this will always happen if the segment ends with the field sep
            if (currSegFields[(currSegFields.length - 1)] == '') currSegFields.splice(-1,1);

            // If we're at the MSH, correct segment numbering and add the field separator as the first value
            if (currSegFields[0] === 'MSH') {
                currSegFields[0] = this.fieldSep; //Replace the array's first value "MSH" with the Field Separator
                currSegFields.unshift("MSH"); // Add back "MSH" as the array's first value
            }

            let segObj = {};

            segObj.segmentType = currSegFields[0];
            segObj.fieldCount = (currSegFields.length-1);
            segObj.segmentText = currSeg;
            //segObj.segmentFullText = (currSeg);
            // segObj.fields = {};

            segObj.fields = [];

            for (let j = 0; j < currSegFields.length; j++) {
                let currField = currSegFields[j];

                segObj.fields[j] = {};
                segObj.fields[j].value = currField;

                segObj.fields[j].instances = [];

                let repSet = currField.split(this.repeatSep);
                for (let k = 0; k < repSet.length; k++) {
                    let repField = repSet[k];

                    segObj.fields[j].instances[k] = {};
                    segObj.fields[j].instances[k].value = repField;

                    segObj.fields[j].instances[k].components = [];

                    let compSet = repField.split(this.compSep);
                    for (let l = 0; l < compSet.length; l++) {
                        let compField = compSet[l];

                        segObj.fields[j].instances[k].components[l] = {};
                        segObj.fields[j].instances[k].components[l].value = compField;

                        segObj.fields[j].instances[k].components[l].subcomps = [];

                        let subCompSet = compField.split(this.subCompSep);
                        for (let y = 0; y < subCompSet.length; y++) {
                            let subComp = subCompSet[y];

                            segObj.fields[j].instances[k].components[l].subcomps[y] = {};
                            segObj.fields[j].instances[k].components[l].subcomps[y].value = subComp;
                        }
                    }
                }
            }

            //console.log(JSON.stringify(segObj));

            myMsg.segments.push(segObj);

            //myMsg.segments[i] = (segObj);

            //console.log(myMsg.segments);
        }

        // set MSH segment
        myMsg.MSH = myMsg.getSegmentByType('MSH');

        // add message type, control id, and hl7 version
        myMsg.messageType = myMsg.MSH.fields[9].value;
        myMsg.controlID = myMsg.MSH.fields[10].value;
        myMsg.version = myMsg.MSH.fields[12].value;

        this.message = myMsg;
        this.resultStatus = this.STATUSES.SUCCESS;

    },

    getHTMLOutput   : function(msgObject) {
        console.log('testing forever');
        console.log(msgObject);

        let outputDiv = document.createElement('div');

        // create header element
        let headerElem = document.createElement('h3');
        headerElem.append(document.createTextNode(
            msgObject.messageType +
            ' - Control ID: ' + msgObject.controlID +
            ' - Version: ' + msgObject.version
        ));
        outputDiv.appendChild(headerElem);

        for (let segment of msgObject.segments) {
            // create main detail section for segment
            let segDetElem = document.createElement('details');
            let segSumElem = document.createElement('summary');
            let fieldDivElem = document.createElement('div');
            segSumElem.append(document.createTextNode(segment.segmentText));
            segDetElem.appendChild(segSumElem);
            segDetElem.appendChild(fieldDivElem);

            for (let j = 1; j < segment.fields.length; j++) {
                let field = segment.fields[j];

                let fieldDetElem = document.createElement('details');
                let fieldSumElem = document.createElement('summary');
                fieldSumElem.append(document.createTextNode('['+j+'] '+field.value));
                fieldDetElem.appendChild(fieldSumElem);
                fieldDivElem.appendChild(fieldDetElem);

                let repDiv = document.createElement('div');
                fieldDetElem.appendChild(repDiv);

                for (let k = 0; k < field.instances.length; k++) {
                    let instance = field.instances[k];

                    let instanceDet = document.createElement('details');
                    repDiv.appendChild(instanceDet);

                    let instanceSum = document.createElement('summary');
                    instanceSum.append(document.createTextNode('('+(k+1)+') '+instance.value));
                    instanceDet.appendChild(instanceSum);

                    let compDiv = document.createElement('div');
                    instanceDet.appendChild(compDiv);

                    for (let l = 0; l < instance.components.length; l++) {
                        let component = instance.components[l];

                        let componentDet = document.createElement('details');
                        compDiv.appendChild(componentDet);

                        let compSum = document.createElement('summary');
                        compSum.append(document.createTextNode('['+(l+1)+'] '+component.value));
                        componentDet.appendChild(compSum);

                        let subCompDiv = document.createElement('div');
                        componentDet.appendChild(subCompDiv);

                        for (let y = 0; y < component.subcomps.length; y++) {
                            let subcomp = component.subcomps[y];

                            let subDet = document.createElement('details');
                            subCompDiv.appendChild(subDet);

                            let subSum = document.createElement('summary');
                            subSum.append(document.createTextNode('['+(y+1)+'] '+subcomp.value));
                            subDet.appendChild(subSum);
                        }
                    }
                }
            }

            outputDiv.appendChild(segDetElem);
        }

        return outputDiv;
    }
};<|endoftext|>


<commit_before>import Component from 'framework/component';

Component.addHelpers({
  unreadIcon(unread) {
    const icon = 'glyphicon-ok-';
    unread = unread === null || typeof(unread) === 'undefined' ? true : unread;
    return icon + (unread ? 'circle' : 'sign');
  },
  unreadLabel(unread) {
    unread = unread === null || typeof(unread) === 'undefined' ? true : unread;
    return unread ? 'read' : 'unread';
  }
});

<commit_msg>Refactor helpers/feeds to use agave kind<commit_after>import Component from 'framework/component';

Component.addHelpers({
  unreadIcon(unread) {
    const icon = 'glyphicon-ok-';
    unread = unread === null || kind(unread) === 'undefined' ? true : unread;
    return icon + (unread ? 'circle' : 'sign');
  },
  unreadLabel(unread) {
    unread = unread === null || kind(unread) === 'undefined' ? true : unread;
    return unread ? 'read' : 'unread';
  }
});

<|endoftext|>


<commit_before>var NRS = (function(NRS, $, undefined) {
	NRS.fetchingModalData = false;

	// save the original function object
	var _superModal = $.fn.modal;

	// add locked as a new option
	$.extend(_superModal.Constructor.DEFAULTS, {
		locked: false
	});

	// capture the original hide
	var _hide = _superModal.Constructor.prototype.hide;

	// add the lock, unlock and override the hide of modal
	$.extend(_superModal.Constructor.prototype, {
		// locks the dialog so that it cannot be hidden
		lock: function() {
			this.options.locked = true;
		}
		// unlocks the dialog so that it can be hidden by 'esc' or clicking on the backdrop (if not static)
		,
		unlock: function() {
			this.options.locked = false;
		}
		// override the original hide so that the original is only called if the modal is unlocked
		,
		hide: function() {
			if (this.options.locked) return;

			_hide.apply(this, arguments);
		}
	});

	//Reset scroll position of tab when shown.
	$('a[data-toggle="tab"]').on("shown.bs.tab", function(e) {
		var target = $(e.target).attr("href");
		$(target).scrollTop(0);
	})

	//hide modal when another one is activated.
	$(".modal").on("show.bs.modal", function(e) {
		var $visible_modal = $(".modal.in");

		if ($visible_modal.length) {
			$visible_modal.modal("hide");
		}
	});

	$(".modal").on("shown.bs.modal", function() {
		$(this).find("input[type=text]:first, input[type=password]:first").first().focus();
		$(this).find("input[name=converted_account_id]").val("");
		NRS.showedFormWarning = false; //maybe not the best place... we assume forms are only in modals?
	});

	//Reset form to initial state when modal is closed
	$(".modal").on("hidden.bs.modal", function(e) {
		$(this).find(":input:not([type=hidden],button)").each(function(index) {
			var default_value = $(this).data("default");
			var type = $(this).attr("type");

			if (type == "checkbox") {
				if (default_value == "checked") {
					$(this).prop("checked", true);
				} else {
					$(this).prop("checked", false);
				}
			} else {
				if (default_value) {
					$(this).val(default_value);
				} else {
					$(this).val("");
				}
			}
		});

		//Hidden form field
		$(this).find("input[name=converted_account_id]").val("");

		//Hide/Reset any possible error messages
		$(this).find(".callout-danger:not(.never_hide), .error_message, .account_info").html("").hide();

		NRS.showedFormWarning = false;
	});

	return NRS;
}(NRS || {}, jQuery));<commit_msg>Modal helper functions.<commit_after>var NRS = (function(NRS, $, undefined) {
	NRS.fetchingModalData = false;

	// save the original function object
	var _superModal = $.fn.modal;

	// add locked as a new option
	$.extend(_superModal.Constructor.DEFAULTS, {
		locked: false
	});

	// capture the original hide
	var _hide = _superModal.Constructor.prototype.hide;

	// add the lock, unlock and override the hide of modal
	$.extend(_superModal.Constructor.prototype, {
		// locks the dialog so that it cannot be hidden
		lock: function() {
			this.options.locked = true;
		}
		// unlocks the dialog so that it can be hidden by 'esc' or clicking on the backdrop (if not static)
		,
		unlock: function() {
			this.options.locked = false;
		}
		// override the original hide so that the original is only called if the modal is unlocked
		,
		hide: function() {
			if (this.options.locked) return;

			_hide.apply(this, arguments);
		}
	});

	//Reset scroll position of tab when shown.
	$('a[data-toggle="tab"]').on("shown.bs.tab", function(e) {
		var target = $(e.target).attr("href");
		$(target).scrollTop(0);
	})

	//hide modal when another one is activated.
	$(".modal").on("show.bs.modal", function(e) {
		var $visible_modal = $(".modal.in");

		if ($visible_modal.length) {
			$visible_modal.modal("hide");
		}
	});

	$(".modal").on("shown.bs.modal", function() {
		$(this).find("input[type=text]:first, input[type=password]:first").first().focus();
		$(this).find("input[name=converted_account_id]").val("");
		NRS.showedFormWarning = false; //maybe not the best place... we assume forms are only in modals?
	});

	//Reset form to initial state when modal is closed
	$(".modal").on("hidden.bs.modal", function(e) {
		$(this).find(":input:not([type=hidden],button)").each(function(index) {
			var default_value = $(this).data("default");
			var type = $(this).attr("type");

			if (type == "checkbox") {
				if (default_value == "checked") {
					$(this).prop("checked", true);
				} else {
					$(this).prop("checked", false);
				}
			} else {
				if (default_value) {
					$(this).val(default_value);
				} else {
					$(this).val("");
				}
			}
		});

		//Hidden form field
		$(this).find("input[name=converted_account_id]").val("");

		//Hide/Reset any possible error messages
		$(this).find(".callout-danger:not(.never_hide), .error_message, .account_info").html("").hide();

		NRS.showedFormWarning = false;
	});

	NRS.showModalError = function(errorMessage, $modal) {
		var $btn = $modal.find("button.btn-primary:not([data-dismiss=modal], .ignore)");

		$modal.find(".error_message").html(String(errorMessage).escapeHTML()).show();
		$btn.button("reset");
		$modal.modal("unlock");
	}

	NRS.closeModal = function($modal) {
		if (!$modal) {
			$modal = $("div.modal.in:first");
		}

		var $btn = $modal.find("button.btn-primary:not([data-dismiss=modal], .ignore)");

		$btn.button("reset");
		$modal.modal("unlock");
		$modal.modal("hide");

	}

	return NRS;
}(NRS || {}, jQuery));<|endoftext|>


<commit_before>
function Menu(canvas, isAnimated) {
	this.buttons = new Array(),
	this.canvas = canvas,
	this.isAnimated = isAnimated,
	this.ctx = canvas.getContext('2d');

	this.listener_mousedown = function (event) {
		console.info('listener_mousedown!', event);
	}

	this.listener_mousemove = function (event) {
		/*var i, x = 0, y = 0;
		console.info(this.buttons);
		for (i = 0; i < this.buttons.length; i += 1) {
			if (this.buttons[i].inRange(x, y)) {
				this.redrawMenu();
				break;
			}
		}*/
	}

	this.redrawMenu = function () {
		var i;
		this.ctx.clearRect(0, 0, canvas.width, canvas.height);
		for (i = 0; i < this.buttons.length; i += 1) {
			this.ctx.drawImage(this.buttons[i].getCanvas(), this.buttons[i].getX(), this.buttons[i].getY());
		}
	}

	this.listener_mouseup = function (event) {
		console.info('listener_mouseup!', event);
		console.info(this);
		this.redrawMenu();
	}
}

Menu.prototype.init = function () {
	console.info(this.buttons);
	this.canvas.addEventListener('mouseup', this.listener_mouseup);
	this.canvas.addEventListener('mousedown', this.listener_mousedown);
	this.canvas.addEventListener('mousemove', this.listener_mousemove);

	this.redrawMenu();
	console.info(this.buttons);
}

Menu.prototype.appendButton = function (button) {
	this.buttons.push(button);
}

var BUTTON_ENUM = {
	"inactive": 0,
	"focused": 1,
	"down": 2,
	"up": 3
}

function Button(x, y, width, height) {
	this.x = x;
	this.y = y;
	this.width = width;
	this.height = height;
	this.x_limit = this.x + this.width;
	this.y_limit = this.y + this.height;
	this.status = BUTTON_ENUM.inactive;
	this.canvas = document.createElement('canvas');
	this.canvas.width = width;
	this.canvas.height = height;
	this.ctx = this.canvas.getContext('2d');
}

Button.prototype.inRange = function (x, y) {
	if (x >= this.x && x <= this.x_limit && y >= this.y && y <= this.y_limit) {
		return true;
	}
	return false;
}

Button.prototype.getCanvas = function () {
	this.ctx.clearRect(0, 0, this.width, this.height);
	this.ctx.fillStyle = "green";
	this.ctx.fillRect(0, 0, this.width, this.height);

	return this.canvas;
}

Button.prototype.getX = function () {
	return this.x;
}

Button.prototype.getY = function () {
	return this.y;
}<commit_msg>Added self notation<commit_after>
function Menu(canvas, isAnimated) {
	var self = this;
	this.buttons = new Array(),
	this.canvas = canvas,
	this.isAnimated = isAnimated,
	this.ctx = canvas.getContext('2d');

	this.listener_mousedown = function (event) {
		console.info('listener_mousedown!', event);
	}

	this.listener_mousemove = function (event) {
		var i, x = 0, y = 0;
		for (i = 0; i < self.buttons.length; i += 1) {
			if (self.buttons[i].inRange(x, y)) {
				self.redrawMenu();
				break;
			}
		}
	}

	this.redrawMenu = function () {
		var i;
		this.ctx.clearRect(0, 0, canvas.width, canvas.height);
		for (i = 0; i < this.buttons.length; i += 1) {
			this.ctx.drawImage(this.buttons[i].getCanvas(), this.buttons[i].getX(), this.buttons[i].getY());
		}
	}

	this.listener_mouseup = function (event) {
		console.info('listener_mouseup!', event);
		self.redrawMenu();
	}
}

Menu.prototype.init = function () {
	console.info(this.buttons);
	this.canvas.addEventListener('mouseup', this.listener_mouseup);
	this.canvas.addEventListener('mousedown', this.listener_mousedown);
	this.canvas.addEventListener('mousemove', this.listener_mousemove);

	this.redrawMenu();
	console.info(this.buttons);
}

Menu.prototype.appendButton = function (button) {
	this.buttons.push(button);
}

var BUTTON_ENUM = {
	"inactive": 0,
	"focused": 1,
	"down": 2,
	"up": 3
}

function Button(x, y, width, height) {
	this.x = x;
	this.y = y;
	this.width = width;
	this.height = height;
	this.x_limit = this.x + this.width;
	this.y_limit = this.y + this.height;
	this.status = BUTTON_ENUM.inactive;
	this.canvas = document.createElement('canvas');
	this.canvas.width = width;
	this.canvas.height = height;
	this.ctx = this.canvas.getContext('2d');
}

Button.prototype.inRange = function (x, y) {
	if (x >= this.x && x <= this.x_limit && y >= this.y && y <= this.y_limit) {
		return true;
	}
	return false;
}

Button.prototype.getCanvas = function () {
	this.ctx.clearRect(0, 0, this.width, this.height);
	this.ctx.fillStyle = "green";
	this.ctx.fillRect(0, 0, this.width, this.height);

	return this.canvas;
}

Button.prototype.getX = function () {
	return this.x;
}

Button.prototype.getY = function () {
	return this.y;
}<|endoftext|>


<commit_before>$.extend({
  keys: function(obj){
    var a = [];
    $.each(obj, function(k){ a.push(k) });
    return a;
  }
});

if (!Array.indexOf) Array.prototype.indexOf = function(obj) {
  for(var i = 0; i < this.length; i++){
    if(this[i] == obj) {
      return i;
    }
  }
  return -1;
}

if (!Array.find_matches) Array.find_matches = function(a) {
  var i, m = [];
  a = a.sort();
  i = a.length
  while(i--) {
    if (a[i - 1] == a[i]) {
      m.push(a[i]);
    }
  }
  if (m.length == 0) {
    return false;
  }
  return m;
}

function VariantOptions(options, allow_backorders) {

  var options = options;
  var allow_backorders = allow_backorders;
  var variant, divs, parent, index = 0;
  var selection = [];

  function init() {
    divs = $('#product-variants .variant-options');
    disable(divs.find('a.option-value').addClass('locked'));
    update();
    enable(parent.find('a.option-value'));
    toggle();
    $('.clear-option a.clear-button').hide().click(handle_clear);
  }

  function get_index(parent) {
    return parseInt($(parent).attr('class').replace(/[^\d]/g, ''));
  }

  function update(i) {
    index = isNaN(i) ? index : i;
    parent = $(divs.get(index));
    buttons = parent.find('a.option-value');
    parent.find('a.clear-button').hide();
  }

  function disable(btns) {
    return btns.removeClass('selected');
  }

  function enable(btns) {
    return btns.not('.unavailable').removeClass('locked').unbind('click').filter('.in-stock').click(handle_click).filter('.auto-click').removeClass('auto-click').click();
  }

  function advance() {
    index++
    update();
    inventory(buttons.removeClass('locked'));
    enable(buttons.filter('.in-stock'));
  }

  function inventory(btns) {
    var keys, variants, count = 0, selected = {};
    var sels = $.map(divs.find('a.selected'), function(i) { return i.rel });
    $.each(sels, function(key, value) {
      key = value.split('-');
      var v = options[key[0]][key[1]];
      keys = $.keys(v);
      var m = Array.find_matches(selection.concat(keys));
      if (selection.length == 0) {
        selection = keys;
      } else if (m) {
        selection = m;
      }
    });
    btns.removeClass('in-stock out-of-stock unavailable').each(function(i, element) {
      variants = get_variant_objects(element.rel);
      keys = $.keys(variants);
      if (keys.length == 0) {
        disable($(element).addClass('unavailable locked').unbind('click'));
      } else if (keys.length == 1) {
        _var = variants[keys[0]];
        $(element).addClass((allow_backorders || _var.count) ? selection.length == 1 ? 'in-stock auto-click' : 'in-stock' : 'out-of-stock');
      } else if (allow_backorders) {
        $(element).addClass('in-stock');
      } else {
        $.each(variants, function(key, value) { count += value.count });
        $(element).addClass(count ? 'in-stock' : 'out-of-stock');
      }
    });
  }

  function get_variant_objects(rels) {
    var i, ids, obj, variants = {};
    if (typeof(rels) == 'string') { rels = [rels]; }
    var otid, ovid, opt, opv;
    i = rels.length;
    try {
      while (i--) {
        ids = rels[i].split('-');
        otid = ids[0];
        ovid = ids[1];
        opt = options[otid];
        if (opt) {
          opv = opt[ovid];
          ids = $.keys(opv);
          if (opv && ids.length) {
            var j = ids.length;
            while (j--) {
              obj = opv[ids[j]];
              if (obj && $.keys(obj).length && 0 <= selection.indexOf(obj.id.toString())) {
                variants[obj.id] = obj;
              }
            }
          }
        }
      }
    } catch(error) {
      //console.log(error);
    }
    return variants;
  }

  function to_f(string) {
    return parseFloat(string.replace(/[^\d\.]/g, ''));
  }

  function find_variant() {
    var selected = divs.find('a.selected');
    var variants = get_variant_objects(selected.get(0).rel);
    if (selected.length == divs.length) {
      return variant = variants[selection[0]];
    } else {
      var prices = [];
      $.each(variants, function(key, value) { prices.push(value.price) });
      prices = $.unique(prices).sort(function(a, b) {
        return to_f(a) < to_f(b) ? -1 : 1;
      });
      if (prices.length == 1) {
        $('#product-price .price').html('' + prices[0] + '');
      } else {
        $('#product-price .price').html('' + prices[0] + ' - ' + prices[prices.length - 1] + '');
      }
      return false;
    }
  }

  function toggle() {
    if (variant) {
      $('#variant_id').val(variant.id);
      $('#product-price .price').removeClass('unselected').text(variant.price);
      $('#cart-form button[type=submit]').attr('disabled', false).fadeTo(100, 1);
      try {
        show_variant_images(variant.id);
      } catch(error) {
        // depends on modified version of product.js
      }
    } else {
      $('#variant_id').val('');
      $('#cart-form button[type=submit]').attr('disabled', true).fadeTo(0, 0.5);
      price = $('#product-price .price').addClass('unselected')
      // Replace product price by "(select)" only when there are at least 1 variant not out-of-stock
      variants = $("div.variant-options.index-0")
      if (variants.find("a.option-value.out-of-stock").length != variants.find("a.option-value").length)
        price.text('(select)');
    }
  }

  function clear(i) {
    variant = null;
    update(i);
    enable(buttons.removeClass('selected'));
    toggle();
    parent.nextAll().each(function(index, element) {
      disable($(element).find('a.option-value').show().removeClass('in-stock out-of-stock').addClass('locked').unbind('click'));
      $(element).find('a.clear-button').hide();
    });
    show_all_variant_images();
  }

  function handle_clear(evt) {
    evt.preventDefault();
    clear(get_index(this));
  }

  function handle_click(evt) {
    evt.preventDefault();
    variant = null;
    selection = [];
    var a = $(this);
    if (!parent.has(a).length) {
      clear(divs.index(a.parents('.variant-options:first')));
    }
    disable(buttons);
    var a = enable(a.addClass('selected'));
    parent.find('a.clear-button').css('display', 'block');
    advance();
    if (find_variant()) {
      toggle();
    }
  }

  $(document).ready(init);

};
<commit_msg>setting buttons inside of the scope<commit_after>$.extend({
  keys: function(obj){
    var a = [];
    $.each(obj, function(k){ a.push(k) });
    return a;
  }
});

if (!Array.indexOf) Array.prototype.indexOf = function(obj) {
  for(var i = 0; i < this.length; i++){
    if(this[i] == obj) {
      return i;
    }
  }
  return -1;
}

if (!Array.find_matches) Array.find_matches = function(a) {
  var i, m = [];
  a = a.sort();
  i = a.length
  while(i--) {
    if (a[i - 1] == a[i]) {
      m.push(a[i]);
    }
  }
  if (m.length == 0) {
    return false;
  }
  return m;
}

function VariantOptions(options, allow_backorders) {

  var options = options;
  var allow_backorders = allow_backorders;
  var variant, divs, parent, index = 0;
  var selection = [];
  var buttons;

  function init() {
    divs = $('#product-variants .variant-options');
    disable(divs.find('a.option-value').addClass('locked'));
    update();
    enable(parent.find('a.option-value'));
    toggle();
    $('.clear-option a.clear-button').hide().click(handle_clear);
  }

  function get_index(parent) {
    return parseInt($(parent).attr('class').replace(/[^\d]/g, ''));
  }

  function update(i) {
    index = isNaN(i) ? index : i;
    parent = $(divs.get(index));
    buttons = parent.find('a.option-value');
    parent.find('a.clear-button').hide();
  }

  function disable(btns) {
    return btns.removeClass('selected');
  }

  function enable(btns) {
    return btns.not('.unavailable').removeClass('locked').unbind('click').filter('.in-stock').click(handle_click).filter('.auto-click').removeClass('auto-click').click();
  }

  function advance() {
    index++
    update();
    inventory(buttons.removeClass('locked'));
    enable(buttons.filter('.in-stock'));
  }

  function inventory(btns) {
    var keys, variants, count = 0, selected = {};
    var sels = $.map(divs.find('a.selected'), function(i) { return i.rel });
    $.each(sels, function(key, value) {
      key = value.split('-');
      var v = options[key[0]][key[1]];
      keys = $.keys(v);
      var m = Array.find_matches(selection.concat(keys));
      if (selection.length == 0) {
        selection = keys;
      } else if (m) {
        selection = m;
      }
    });
    btns.removeClass('in-stock out-of-stock unavailable').each(function(i, element) {
      variants = get_variant_objects(element.rel);
      keys = $.keys(variants);
      if (keys.length == 0) {
        disable($(element).addClass('unavailable locked').unbind('click'));
      } else if (keys.length == 1) {
        _var = variants[keys[0]];
        $(element).addClass((allow_backorders || _var.count) ? selection.length == 1 ? 'in-stock auto-click' : 'in-stock' : 'out-of-stock');
      } else if (allow_backorders) {
        $(element).addClass('in-stock');
      } else {
        $.each(variants, function(key, value) { count += value.count });
        $(element).addClass(count ? 'in-stock' : 'out-of-stock');
      }
    });
  }

  function get_variant_objects(rels) {
    var i, ids, obj, variants = {};
    if (typeof(rels) == 'string') { rels = [rels]; }
    var otid, ovid, opt, opv;
    i = rels.length;
    try {
      while (i--) {
        ids = rels[i].split('-');
        otid = ids[0];
        ovid = ids[1];
        opt = options[otid];
        if (opt) {
          opv = opt[ovid];
          ids = $.keys(opv);
          if (opv && ids.length) {
            var j = ids.length;
            while (j--) {
              obj = opv[ids[j]];
              if (obj && $.keys(obj).length && 0 <= selection.indexOf(obj.id.toString())) {
                variants[obj.id] = obj;
              }
            }
          }
        }
      }
    } catch(error) {
      //console.log(error);
    }
    return variants;
  }

  function to_f(string) {
    return parseFloat(string.replace(/[^\d\.]/g, ''));
  }

  function find_variant() {
    var selected = divs.find('a.selected');
    var variants = get_variant_objects(selected.get(0).rel);
    if (selected.length == divs.length) {
      return variant = variants[selection[0]];
    } else {
      var prices = [];
      $.each(variants, function(key, value) { prices.push(value.price) });
      prices = $.unique(prices).sort(function(a, b) {
        return to_f(a) < to_f(b) ? -1 : 1;
      });
      if (prices.length == 1) {
        $('#product-price .price').html('' + prices[0] + '');
      } else {
        $('#product-price .price').html('' + prices[0] + ' - ' + prices[prices.length - 1] + '');
      }
      return false;
    }
  }

  function toggle() {
    if (variant) {
      $('#variant_id').val(variant.id);
      $('#product-price .price').removeClass('unselected').text(variant.price);
      $('#cart-form button[type=submit]').attr('disabled', false).fadeTo(100, 1);
      try {
        show_variant_images(variant.id);
      } catch(error) {
        // depends on modified version of product.js
      }
    } else {
      $('#variant_id').val('');
      $('#cart-form button[type=submit]').attr('disabled', true).fadeTo(0, 0.5);
      price = $('#product-price .price').addClass('unselected')
      // Replace product price by "(select)" only when there are at least 1 variant not out-of-stock
      variants = $("div.variant-options.index-0")
      if (variants.find("a.option-value.out-of-stock").length != variants.find("a.option-value").length)
        price.text('(select)');
    }
  }

  function clear(i) {
    variant = null;
    update(i);
    enable(buttons.removeClass('selected'));
    toggle();
    parent.nextAll().each(function(index, element) {
      disable($(element).find('a.option-value').show().removeClass('in-stock out-of-stock').addClass('locked').unbind('click'));
      $(element).find('a.clear-button').hide();
    });
    show_all_variant_images();
  }

  function handle_clear(evt) {
    evt.preventDefault();
    clear(get_index(this));
  }

  function handle_click(evt) {
    evt.preventDefault();
    variant = null;
    selection = [];
    var a = $(this);
    if (!parent.has(a).length) {
      clear(divs.index(a.parents('.variant-options:first')));
    }
    disable(buttons);
    var a = enable(a.addClass('selected'));
    parent.find('a.clear-button').css('display', 'block');
    advance();
    if (find_variant()) {
      toggle();
    }
  }

  $(document).ready(init);

};
<|endoftext|>


<commit_before>import React, { useContext } from 'react';
import { Route, Redirect } from 'react-router-dom';
import { AuthContext } from '../Auth';

import { SIGN_IN } from '../../constants/routes.js';

/**
 * PrivateRoute component that takes the authentication status of the current
 * user from AuthContext. If they are authenticated, they will be allowed to
 * view the contents of the Route component. If they are not authenticated, they
 * will be redirected to the SIGN_IN page.
 */
const PrivateRoute = ({ component: RouteComponent, ...rest }) => {
  const currentUser = useContext(AuthContext);

  return (
    <Route
      {...rest}
      render={routeProps =>
        currentUser ? <RouteComponent {...routeProps} />
                    : <Redirect to={SIGN_IN} />
      }
    />
  );
}

export default PrivateRoute;
<commit_msg>Add comments<commit_after>import React, { useContext } from 'react';
import { Route, Redirect } from 'react-router-dom';
import { AuthContext } from '../Auth';

import { SIGN_IN } from '../../constants/routes.js';

/**
 * PrivateRoute component that functions similarly to the `Route` component,
 * with the added check that determines if the user is currently signed in.
 *
 * This component takes the authentication status of the current user from
 * AuthContext. If they are authenticated, they will be allowed to view the
 * contents of the Route component. If they are not authenticated, they will be
 * redirected to the SIGN_IN page.
 *
 * @param {Object} props The following props are expected:
 * - component {React.Component} The component that `PrivateRoute` should render
 * if the user is currently authenticated.
 */
const PrivateRoute = ({ component: RouteComponent, ...rest }) => {
  const currentUser = useContext(AuthContext);

  // The rest of the props passed into `PrivateRoute` are given as props to the
  // `Route` component as normal. The render prop is used to specify that, if
  // the user is signed in, the given component to render should be rendered
  // along with all the standard Route paths (URL path, etc.), and if the user
  // is not signed in, a `Redirect` prop should be rendered instead.
  return (
    <Route
      {...rest}
      render={routeProps =>
        currentUser ? <RouteComponent {...routeProps} />
                    : <Redirect to={SIGN_IN} />
      }
    />
  );
}

export default PrivateRoute;
<|endoftext|>


<commit_before>function huckleberryFinnText() {
	var s = "You don't know about me, without you have read a book by the name of The Adventures of Tom Sawyer, but that ain't no matter. That book was made by Mr. Mark Twain, and he told the truth, mainly. There was things which he stretched, but mainly he told the truth. That is nothing. I never seen anybody but lied, one time or another, without it was Aunt Polly, or the widow, or maybe Mary. Aunt Polly- Tom's Aunt Polly, she is- and Mary, and the Widow Douglas, is all told about in that book- which is mostly a true book; with some stretchers, as I said before. Now the way that the book winds up, is this: Tom and me found the money that the robbers hid in the cave, and it made us rich. We got six thousand dollars apiece- all gold. It was an awful sight ofmoney when it was piled up. Well, Judge Thatcher, he took it and put it out at interest, and it fetched us a dollar a day apiece, all the year round- more than a body could tell what to do with. The Widow Douglas, she took me for her son, and allowed she would sivilize me; but it was rough living in the house all the time, considering how dismal regular and decent the widow was in all her ways; and so when I couldn't stand it no longer, I lit out. I got into my old rags, and my sugar-hogshead again, and was free and satisfied. But Tom Sawyer, he hunted me up and said he was going to start a band of robbers and I might join if I would go back to the widow and be respectable."

	var textArr = s.split(" ");
	return textArr;
}

function settingUp(text){
	var nBucks = 157;
	var table = new newHtable(nBucks);
	table = insertFile(text, table);
	return table;
}

function goBabble(){
	var msg1 = "Parsing the text..."
	document.getElementById("toBabble").innerHTML = msg1;
	var huck = huckleberryFinnText();
	var t = settingUp(huck);
	document.getElementById("toBabble").innerHTML = "Babbling...";
	var bab = babble(5, 5, t);
	var text = bab.join("\n");
	document.getElementById("toBabble").innerHTML = text;
	return;
}<commit_msg>Lets take it from step 1 forwards. Dont put the cart infront of the horse<commit_after>function huckleberryFinnText() {
	var s = "You don't know about me, without you have read a book by the name of The Adventures of Tom Sawyer, but that ain't no matter. That book was made by Mr. Mark Twain, and he told the truth, mainly. There was things which he stretched, but mainly he told the truth. That is nothing. I never seen anybody but lied, one time or another, without it was Aunt Polly, or the widow, or maybe Mary. Aunt Polly- Tom's Aunt Polly, she is- and Mary, and the Widow Douglas, is all told about in that book- which is mostly a true book; with some stretchers, as I said before. Now the way that the book winds up, is this: Tom and me found the money that the robbers hid in the cave, and it made us rich. We got six thousand dollars apiece- all gold. It was an awful sight ofmoney when it was piled up. Well, Judge Thatcher, he took it and put it out at interest, and it fetched us a dollar a day apiece, all the year round- more than a body could tell what to do with. The Widow Douglas, she took me for her son, and allowed she would sivilize me; but it was rough living in the house all the time, considering how dismal regular and decent the widow was in all her ways; and so when I couldn't stand it no longer, I lit out. I got into my old rags, and my sugar-hogshead again, and was free and satisfied. But Tom Sawyer, he hunted me up and said he was going to start a band of robbers and I might join if I would go back to the widow and be respectable."

	var textArr = s.split(" ");
	return textArr;
}

function settingUp(text){
	var nBucks = 157;
	var table = new newHtable(nBucks);
	table = insertFile(text, table);
	return table;
}

function goBabble(){
	var msg1 = "Parsing the text..."
	document.getElementById("toBabble").innerHTML = msg1;
	/*var huck = huckleberryFinnText();
	var t = settingUp(huck);
	document.getElementById("toBabble").innerHTML = "Babbling...";
	var bab = babble(5, 5, t);
	var text = bab.join("\n");
	document.getElementById("toBabble").innerHTML = text;
	return;*/
}<|endoftext|>


<commit_before>/*
#
# i2mx_base.js - v0.1-Alpha
# Apache v2 License
#
*/

// Create img2musicXML (abbreviated as i2mx) namespace
var i2mx = {}

// Create i2mx "Data" class
i2mx.Data = new (function() {
    this.version_major = 0
    this.version_minor = 0
    this.version_patch = 0

    this.lastModification = "2018-01-16" // YYYY-MM-DD
})

// @TODO: Cache system?
// Create the i2mx "Elements" class
i2mx.Elements = new (function() {
    // "About"
    this.lastModification = function() {
        var id = "i2mx-ver_info-last-modification"
        return document.getElementById(id)
    }

    // "Page Manager"
    this.pageList = function() {
        var id = "i2mx-page_mngr-page-list"
        return document.getElementById(id)
    }

    this.pageCount = function() {
        var id = "i2mx-page_mngr-page-count"
        return document.getElementById(id)
    }

    this.addNewPageBtn = function() {
        var id = "i2mx-page_mngr-add-new-page-btn"
        return document.getElementById(id)
    }

    this.imgInput = function() {
        var id = "i2mx-page_mngr-assign-image-to-item-input"
        return document.getElementById(id)
    }

    // "Canvas"
    this.drawingCanvas = function() {
        var id = "i2mx-canvas"
        return document.getElementById(id)
    }

    this.closeCurrentPageBtn = function() {
        var id = "i2mx-canvas-close-current-page-btn"
        return document.getElementById(id)
    }

    this.canvasImageSettings = function() {
      var id = "i2mx-canvas-image-settings"
      return document.getElementById(id)
    }
})

// https://stackoverflow.com/a/5306832/3109177
Array.prototype.move = function (old_index, new_index) {
    while (old_index < 0) {
        old_index += this.length;
    }
    while (new_index < 0) {
        new_index += this.length;
    }
    if (new_index >= this.length) {
        var k = new_index - this.length;
        while ((k--) + 1) {
            this.push(undefined);
        }
    }
    this.splice(new_index, 0, this.splice(old_index, 1)[0]);
    //return this; // for testing purposes
};
<commit_msg>Bump last modification date to 2018-01-22<commit_after>/*
#
# i2mx_base.js - v0.1-Alpha
# Apache v2 License
#
*/

// Create img2musicXML (abbreviated as i2mx) namespace
var i2mx = {}

// Create i2mx "Data" class
i2mx.Data = new (function() {
    this.version_major = 0
    this.version_minor = 0
    this.version_patch = 0

    this.lastModification = "2018-01-22" // YYYY-MM-DD
})

// @TODO: Cache system?
// Create the i2mx "Elements" class
i2mx.Elements = new (function() {
    // "About"
    this.lastModification = function() {
        var id = "i2mx-ver_info-last-modification"
        return document.getElementById(id)
    }

    // "Page Manager"
    this.pageList = function() {
        var id = "i2mx-page_mngr-page-list"
        return document.getElementById(id)
    }

    this.pageCount = function() {
        var id = "i2mx-page_mngr-page-count"
        return document.getElementById(id)
    }

    this.addNewPageBtn = function() {
        var id = "i2mx-page_mngr-add-new-page-btn"
        return document.getElementById(id)
    }

    this.imgInput = function() {
        var id = "i2mx-page_mngr-assign-image-to-item-input"
        return document.getElementById(id)
    }

    // "Canvas"
    this.drawingCanvas = function() {
        var id = "i2mx-canvas"
        return document.getElementById(id)
    }

    this.closeCurrentPageBtn = function() {
        var id = "i2mx-canvas-close-current-page-btn"
        return document.getElementById(id)
    }

    this.canvasImageSettings = function() {
      var id = "i2mx-canvas-image-settings"
      return document.getElementById(id)
    }
})

// https://stackoverflow.com/a/5306832/3109177
Array.prototype.move = function (old_index, new_index) {
    while (old_index < 0) {
        old_index += this.length;
    }
    while (new_index < 0) {
        new_index += this.length;
    }
    if (new_index >= this.length) {
        var k = new_index - this.length;
        while ((k--) + 1) {
            this.push(undefined);
        }
    }
    this.splice(new_index, 0, this.splice(old_index, 1)[0]);
    //return this; // for testing purposes
};
<|endoftext|>


<commit_before>var currentQNum = 0;
var bp = 0, pps = 0, dms = 0, pg = 0, crp_or_esr = "crp", measurement = "";

$("#next-q-button").click(function(){
	currentQNum++;
	changeQuestion();
});

$("#prev-q-button").click(function(){
	currentQNum--;
	changeQuestion();
});

$("#to-result-button").click(function() {
	onAsdasFormSubmit();
});

function changeQuestion() {
	$(".asdas-question").hide();
	$(".asdas-question").eq(currentQNum).show();
	if (currentQNum <= 0) {
		$("#prev-q-button").hide();
	} else {
		$("#prev-q-button").show();
	}
	if (currentQNum >= $(".asdas-question").length - 1) {
		$("#control-panel-0").hide();
		$("#control-panel-1").show();
		$("#display-1-content").text(measurement);
	} else {
		$("#control-panel-0").show();
		$("#control-panel-1").hide();
		switch(currentQNum) {
			case 0:
				$("#display-0-content").text(bp);
				break;
			case 1:
				$("#display-0-content").text(pps);
				break;
			case 2:
				$("#display-0-content").text(dms);
				break;
			case 3:
				$("#display-0-content").text(pg);
				break;
			default:
				alert("currentQNum = " + currentQNum);
		}
	}
}

$("#control-panel-0 .key").click(function(){
	var keyVal = $(this).text();
	$("#display-0-content").text(keyVal);
	switch(currentQNum) {
		case 0:
			bp = keyVal;
			break;
		case 1:
			pps = keyVal;
			break;
		case 2:
			dms = keyVal;
			break;
		case 3:
			pg = keyVal;
			break;
		default:
			alert("currentQNum = " + currentQNum);
	}
});

$("#control-panel-1 .key").click(function(){
	var keyVal = $(this).text();
	var oldContent = $("#display-1-content").text();
	var newContent = oldContent + keyVal;
	measurement = newContent;
	$("#display-1-content").text(measurement);
});

$("#clear-button").click(function() {
	measurement = measurement.substr(0, measurement.length-1);
	$("#display-1-content").text(measurement);
});

function calcASDASCRP() {
	var result =
        0.12 * bp +
        0.06 * dms +
        0.11 * pg +
        0.07 * pps +
        0.58 * Math.log(1 + 1.0 * measurement); // multiply by 1.0 to prevent string concatenation
	return result;
}

function calcASDASESR() {
	var result =
        0.08 * bp +
        0.07 * dms +
        0.11 * pg +
        0.09 * pps +
        0.29 * Math.sqrt(measurement);
	return result;
}

function calcASDAS() {
	var result;
	var calc_mode = $('#crp-or-esr').val();
	if (calc_mode == 'crp') {
		result = calcASDASCRP();
	} else if (calc_mode == 'crp-dl') {
		measurement = measurement * 10;
		result = calcASDASCRP();
	} else if (calc_mode == 'esr') {
		result = calcASDASESR();
	} else {
		result = "ERROR";
	}
	return result
}

function onAsdasFormSubmit() {
	$('#asdas-form').hide();
	$('#asdas-result-panel').show();
	$('#answer-bp').text(bp);
	$('#answer-pps').text(pps);
	$('#answer-dms').text(dms);
	$('#answer-pg').text(pg);
	$('#answer-measurement').text(measurement);
	var ASDAS = calcASDAS();
	$('#asdas-result').text(ASDAS.toFixed(1));
	var backdrop_color;
	if (ASDAS < 1.3) {
		backdrop_color = '#ffff33';
	} else if (ASDAS < 2.1) {
		backdrop_color = '#ffaa33';
	} else if (ASDAS < 3.5) {
		backdrop_color = '#ff5533';
	} else {
		backdrop_color = '#ff0033';
	}
	$('#result-backdrop').css("background-color", backdrop_color);
}

function onAsdasResultPanelSubmit() {
	currentQNum = 0;
	changeQuestion();
	$('#asdas-form').show();
	$('#asdas-result-panel').hide();
}
<commit_msg>Update index-new.js<commit_after>var currentQNum = 0;
var bp = 0, pps = 0, dms = 0, pg = 0, calc_mode = "crp", measurement = "0";

$("#next-q-button").click(function(){
	currentQNum++;
	changeQuestion();
});

$("#prev-q-button").click(function(){
	currentQNum--;
	changeQuestion();
});

$("#to-result-button").click(function() {
	onAsdasFormSubmit();
});

function changeQuestion() {
	$(".asdas-question").hide();
	$(".asdas-question").eq(currentQNum).show();
	if (currentQNum <= 0) {
		$("#prev-q-button").hide();
	} else {
		$("#prev-q-button").show();
	}
	if (currentQNum >= $(".asdas-question").length - 1) {
		$("#control-panel-0").hide();
		$("#control-panel-1").show();
		$("#display-1-content").text(measurement);
	} else {
		$("#control-panel-0").show();
		$("#control-panel-1").hide();
		switch(currentQNum) {
			case 0:
				$("#display-0-content").text(bp);
				break;
			case 1:
				$("#display-0-content").text(pps);
				break;
			case 2:
				$("#display-0-content").text(dms);
				break;
			case 3:
				$("#display-0-content").text(pg);
				break;
			default:
				alert("currentQNum = " + currentQNum);
		}
	}
}

$("#control-panel-0 .key").click(function(){
	var keyVal = $(this).text();
	$("#display-0-content").text(keyVal);
	switch(currentQNum) {
		case 0:
			bp = keyVal;
			break;
		case 1:
			pps = keyVal;
			break;
		case 2:
			dms = keyVal;
			break;
		case 3:
			pg = keyVal;
			break;
		default:
			alert("currentQNum = " + currentQNum);
	}
});

$("#control-panel-1 .key").click(function(){
	var keyVal = $(this).text();
	var oldContent = measurement;
	if(oldContent == "0" && keyVal != ".") {
		oldContent = "";
	}
	var newContent = oldContent + keyVal;
	measurement = newContent;
	$("#display-1-content").text(measurement);
});

$("#clear-button").click(function() {
	measurement = measurement.substr(0, measurement.length-1);
	if(measurement == "") {
		measurement = "0";
	}
	$("#display-1-content").text(measurement);
});

$("#crp-esr-buttons").click(function() {
	calc_mode = $('input[name="crp-or-esr"]:checked').val();
});

function calcASDASCRP(crp) {
	var result =
        0.12 * bp +
        0.06 * dms +
        0.11 * pg +
        0.07 * pps +
        0.58 * Math.log(1 + 1.0 * crp); // multiply by 1.0 to prevent string concatenation
	return result;
}

function calcASDASESR() {
	var result =
        0.08 * bp +
        0.07 * dms +
        0.11 * pg +
        0.09 * pps +
        0.29 * Math.sqrt(measurement);
	return result;
}

function calcASDAS() {
	var result;
	if (calc_mode == 'crp') {
		result = calcASDASCRP(measurement);
	} else if (calc_mode == 'crp-dl') {
		result = calcASDASCRP(measurement * 10);
	} else if (calc_mode == 'esr') {
		result = calcASDASESR();
	} else {
		result = "ERROR";
	}
	return result
}

function onAsdasFormSubmit() {
	$('#asdas-form').hide();
	$('#asdas-result-panel').show();
	$('#answer-bp').text(bp);
	$('#answer-pps').text(pps);
	$('#answer-dms').text(dms);
	$('#answer-pg').text(pg);
	$('#answer-crp-or-esr').text($('label[for="crp-esr-' + calc_mode + '"]').text());
	$('#answer-measurement').text(measurement);
	var ASDAS = calcASDAS();
	$('#asdas-result').text(ASDAS.toFixed(1));
	var backdrop_color;
	if (ASDAS < 1.3) {
		backdrop_color = $('#asdas-activity-0').css("background-color");
	} else if (ASDAS < 2.1) {
		backdrop_color = $('#asdas-activity-1').css("background-color");
	} else if (ASDAS < 3.5) {
		backdrop_color = $('#asdas-activity-2').css("background-color");
	} else {
		backdrop_color = $('#asdas-activity-3').css("background-color");
	}
	$('#result-backdrop').css("background-color", backdrop_color);
}

function onAsdasResultPanelSubmit() {
	currentQNum = 0;
	changeQuestion();
	$('#asdas-form').show();
	$('#asdas-result-panel').hide();
}
<|endoftext|>


<commit_before>/* WebSockets */
function sendJSON(socket, obj) {
  socket.send(JSON.stringify(obj));
}

function make_connection (name) {
  var socket = new WebSocket('ws://' + location.hostname + ':8080/ws');
  socket.onopen = function() {
    socket.send(name)
  }

  socket.onclose = function() {
    alert("Server closed connection")
  }

  socket.onmessage = function(evt) {
    var message = JSON.parse(evt.data)
    socket.dispatchEvent(new CustomEvent(message.type, {'detail': message}))
  }
  return socket;
}

function define_components(connection) {
  /* Vue filters */
  Vue.filter('round', function(value) {
    value = parseFloat(value);
    value = Math.round((value + 0.0001) * 100) / 100;
    value = value.toString()
    x = value.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
      x1 = x1.replace(rgx, '$1' + ' ' + '$2');
    }
    return x1 + x2;
  })

  /* Vue components */
  Vue.component('etg-monitor', {
    template: '

<slot>{{ monitor }}</slot>
{{ value | round }}
',
    props: {
      monitor: {
        type: String,
        required: true
      }
    },
    data: function() {
      return {
        value: 0
      }
    },
    created: function() {
      var mon = this
      connection.addEventListener('change', function(e) {
        data = e.detail.packet;
        if (data[mon.monitor]) {
          mon.value = data[mon.monitor]
        }
      })
    }
  })

  Vue.component('etg-slider', {
    template: `

<slot>{{ ident }}</slot>

    <input v-model.number="value" type="range"
    :min="min" :max="max" :step="step"
    v-on:input="update($event.target.value)">
    </input>
    {{ value | round }} {{ unit }}

`,
    props: {
      ident: {
        type: String,
        required: true
      },
      init: {
        type: Number,
        required: false,
        default: 0
      },
      unit: {
        type: String,
        default: '%'
      },
      min: {
        type: Number,
        default: 0
      },
      max: {
        type: Number,
        default: 100
      },
      step: {
        type: Number,
        default: 1
      },
    },
    data: function() {
      return {
        value: this.init
      }
    },
    methods: {
      update: function(value) {
        this.value = parseFloat(value);
        sendJSON(socket, {'type': 'change',
                           'packet': {[this.ident]: this.value}});
      },
    },
    created: function() {
      var mon = this
      connection.addEventListener('change', function(e) {
        data = e.detail.packet;
        if (data[mon.ident]) {
          mon.value = data[mon.ident]
        }
      })
    }
  })

  Vue.component('plot', {
    template: '

',
  })
}

/* Tab functionality */
function openTab(event, name) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }

  // Show the current tab, and add an "active" class to the link that opened the tab
  document.getElementById(name).style.display = "block";
  event.currentTarget.className += " active";
}

function setup_vue(data, socket) {
  window.vm = new Vue({
    el: "#content",
    delimiters: ['[[', ']]'],
    data: data,
    methods: {
      changeTax: function(energy_type, amount) {
        var data = this.taxes;
        data[energy_type] += amount;
        sendJSON(socket, {'type': 'change', 'packet': {'taxes': data}})
      },
      updateMarket: function(name, value) {
        if (value < 0) {
          value = 0;
          vm.market[name] = 0;
        }
        socket.send(JSON.stringify({'type': 'change', 'packet':
          {'market': {name: value}}}))
      }
    },
    filters: {
      capitalize: function (value) {
        if (!value) return ''
        value = value.toString()
        return value.charAt(0).toUpperCase() + value.slice(1)
      },
    }
  })
  socket.dispatchEvent(new CustomEvent('change', {'detail': {'packet': data}}))
}
<commit_msg>Moved over to using strict javascript<commit_after>"use strict";
/* WebSockets */
function sendJSON(socket, obj) {
  socket.send(JSON.stringify(obj));
}

function make_connection (name) {
  var socket = new WebSocket('ws://' + location.hostname + ':8080/ws');
  socket.onopen = function() {
    socket.send(name)
  }

  socket.onclose = function() {
    alert("Server closed connection")
  }

  socket.onmessage = function(evt) {
    var message = JSON.parse(evt.data)
    socket.dispatchEvent(new CustomEvent(message.type, {'detail': message}))
  }
  return socket;
}

function define_components(connection) {
  /* Vue filters */
  Vue.filter('round', function(value) {
    value = parseFloat(value);
    value = Math.round((value + 0.0001) * 100) / 100;
    value = value.toString()
    var x = value.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
      x1 = x1.replace(rgx, '$1' + ' ' + '$2');
    }
    return x1 + x2;
  })

  /* Vue components */
  Vue.component('etg-monitor', {
    template: '

<slot>{{ monitor }}</slot>
{{ value | round }}
',
    props: {
      monitor: {
        type: String,
        required: true
      }
    },
    data: function() {
      return {
        value: 0
      }
    },
    created: function() {
      var mon = this
      connection.addEventListener('change', function(e) {
        var data = e.detail.packet;
        if (data[mon.monitor]) {
          mon.value = data[mon.monitor]
        }
      })
    }
  })

  Vue.component('etg-slider', {
    template: `

<slot>{{ ident }}</slot>

    <input v-model.number="value" type="range"
    :min="min" :max="max" :step="step"
    v-on:input="update($event.target.value)">
    </input>
    {{ value | round }} {{ unit }}

`,
    props: {
      ident: {
        type: String,
        required: true
      },
      init: {
        type: Number,
        required: false,
        default: 0
      },
      unit: {
        type: String,
        default: '%'
      },
      min: {
        type: Number,
        default: 0
      },
      max: {
        type: Number,
        default: 100
      },
      step: {
        type: Number,
        default: 1
      },
    },
    data: function() {
      return {
        value: this.init
      }
    },
    methods: {
      update: function(value) {
        this.value = parseFloat(value);
        sendJSON(socket, {'type': 'change',
                           'packet': {[this.ident]: this.value}});
      },
    },
    created: function() {
      var mon = this
      connection.addEventListener('change', function(e) {
        data = e.detail.packet;
        if (data[mon.ident]) {
          mon.value = data[mon.ident]
        }
      })
    }
  })

  Vue.component('plot', {
    template: '

',
  })
}

/* Tab functionality */
function openTab(event, name) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }

  // Show the current tab, and add an "active" class to the link that opened the tab
  document.getElementById(name).style.display = "block";
  event.currentTarget.className += " active";
}

function setup_vue(data, socket) {
  window.vm = new Vue({
    el: "#content",
    delimiters: ['[[', ']]'],
    data: data,
    methods: {
      changeTax: function(energy_type, amount) {
        var data = this.taxes;
        data[energy_type] += amount;
        sendJSON(socket, {'type': 'change', 'packet': {'taxes': data}})
      },
      updateMarket: function(name, value) {
        if (value < 0) {
          value = 0;
          vm.market[name] = 0;
        }
        socket.send(JSON.stringify({'type': 'change', 'packet':
          {'market': {name: value}}}))
      }
    },
    filters: {
      capitalize: function (value) {
        if (!value) return ''
        value = value.toString()
        return value.charAt(0).toUpperCase() + value.slice(1)
      },
    }
  })
  socket.dispatchEvent(new CustomEvent('change', {'detail': {'packet': data}}))
}
<|endoftext|>


<commit_before>/** Copyright 2014-2019 Stewart Allen -- All Rights Reserved */

"use strict";

var gs_kiri_fill = exports;

(function() {

    if (!self.kiri) self.kiri = {};
    if (self.kiri.fill) return;

    var KIRI = self.kiri,
        BASE = self.base,
        UTIL = BASE.util,
        ROUND = UTIL.round,
        DEG2RAD = Math.PI / 180,
        FILL = self.kiri.fill = {
            hex: fillHexFull,
            grid: fillGrid,
            gyroid: fillGyroid,
            triangle: fillTriangle
        };

    function fillHexFull(target) {
        fillHex(target, true);
    }

    /**
     * emitter creates a hex infill pattern and sends to target
     *
     * @param {Object} target
     * @param {boolean} full continuous walls
     */
    function fillHex(target, full) {
        // compute segment lengths (vert/horiz and 45)
        let spacing = target.offset() / 2,
            vhlen = (1 - target.density()) * 4 + spacing,
            anxlen = ROUND(Math.cos(30 * DEG2RAD) * vhlen, 7),
            anylen = ROUND(Math.sin(30 * DEG2RAD) * vhlen, 7),
            bounds = target.bounds(),
            even = true,
            evenZ = target.zIndex() % 2 === 0,
            maxy = bounds.max.y + (vhlen + anylen * 2),
            x, y;

        if (full || evenZ) {
            x = bounds.min.x;
            for (;;) {
                if (even && x > bounds.max.x) break;
                if (!even && x > bounds.max.x + anxlen + spacing) break;
                y = bounds.min.y;
                target.newline();
                while (y <= maxy) {
                    target.emit(x,y);
                    y += vhlen;
                    target.emit(x,y);
                    if (even) x += anxlen; else x -= anxlen;
                    y += anylen;
                    target.emit(x,y);
                    y += vhlen;
                    target.emit(x,y);
                    if (even) x -= anxlen; else x += anxlen;
                    y += anylen;
                }
                x += spacing;
                if (even) x += (anxlen * 2);
                even = !even;
                target.newline();
            }
        } else {
            y = bounds.min.y + vhlen;
            for (;;) {
                if (even && y > bounds.max.y) break;
                if (!even && y > bounds.max.y + anylen) break;
                x = bounds.min.x;
                target.newline();
                while (x < bounds.max.x) {
                    target.emit(x,y);
                    if (even) y += anylen; else y -= anylen;
                    x += anxlen;
                    target.emit(x,y);
                    x += spacing;
                    target.emit(x,y);
                    if (even) y -= anylen; else y += anylen;
                    x += anxlen;
                    target.emit(x,y);
                    x += spacing;
                }
                y += vhlen;
                if (even) y += (anylen * 2);
                even = !even;
                target.newline();
            }
        }
    }

    function fillGyroid(target) {
        let bounds = target.bounds();
        let height = target.zHeight();
        let span_x = bounds.max.x - bounds.min.x;
        let span_y = bounds.max.y - bounds.min.y;
        let density = target.density();
        let tile = 1 + (1 - density) * 15;
        let tile_x = span_x / tile;
        let tile_y = span_y / tile;
        let tile_z = 1 / tile;
        let gyroid = BASE.gyroid.slice(target.zValue() * tile_z, (1 - density) * 500);

        gyroid.polys.forEach(poly => {
            for (let tx=0; tx<=tile_x; tx++) {
                for (let ty=0; ty<=tile_y; ty++) {
                    target.newline();
                    let bx = tx * tile + bounds.min.x;
                    let by = ty * tile + bounds.min.y;
                    poly.forEach(point => {
                        target.emit(bx + point.x * tile, by + point.y * tile);
                    });
                }
            }
        });
    }

    function fillGrid(target) {
        let bounds = target.bounds();
        let height = target.zHeight();
        let span_x = bounds.max.x - bounds.min.x;
        let span_y = bounds.max.y - bounds.min.y;
        let density = target.density();
        let tile = 1 + (1 - density) * 5;
        let tile_x = span_x / tile;
        let tile_y = span_y / tile;
        let tile_z = 1 / tile;
        let offset = target.offset() / 2;

        for (let tx=0; tx<=tile_x; tx++) {
            target.newline();
            for (let ty=0; ty<=tile_y; ty++) {
                let bx = tx * tile + bounds.min.x;
                let by = ty * tile + bounds.min.y;
                if ((tx + ty) % 2) {
                    target.emit(bx + offset, by);
                    target.emit(bx + tile - offset, by + tile);
                } else {
                    target.emit(bx + tile - offset, by);
                    target.emit(bx + offset, by + tile);
                }
            }
        }
    }

    function fillTriangle(target) {
        let bounds = target.bounds();
        let height = target.zHeight();
        let span_x = bounds.max.x - bounds.min.x;
        let span_y = bounds.max.y - bounds.min.y;
        let density = target.density();
        let tile = 1 + (1 - density) * 5;
        let tile_x = span_x / tile;
        let tile_y = span_y / tile;
        let tile_z = 1 / tile;
        let line_w = target.lineWidth() / 2;
        let offset = target.offset();

        for (let tx=0; tx<=tile_x; tx++) {
            target.newline();
            for (let ty=0; ty<=tile_y; ty++) {
                let bx = tx * tile + bounds.min.x;
                let by = ty * tile + bounds.min.y;
                if ((tx + ty) % 2) {
                    target.emit(bx, by);
                    target.emit(bx + tile - offset - line_w, by + tile);
                } else {
                    target.emit(bx + tile - offset - line_w, by);
                    target.emit(bx, by + tile);
                }
            }
        }

        for (let tx=0; tx<=tile_x; tx++) {
            target.newline();
            for (let ty=0; ty<=tile_y; ty++) {
                let bx = tx * tile + bounds.min.x;
                let by = ty * tile + bounds.min.y;
                target.emit(bx + tile - line_w, by);
                target.emit(bx + tile - line_w, by + tile);
            }
        }
    }

})();
<commit_msg>make grid/triangle tiles square with padding<commit_after>/** Copyright 2014-2019 Stewart Allen -- All Rights Reserved */

"use strict";

var gs_kiri_fill = exports;

(function() {

    if (!self.kiri) self.kiri = {};
    if (self.kiri.fill) return;

    let KIRI = self.kiri,
        BASE = self.base,
        UTIL = BASE.util,
        ROUND = UTIL.round,
        DEG2RAD = Math.PI / 180,
        FILL = self.kiri.fill = {
            hex: fillHexFull,
            grid: fillGrid,
            gyroid: fillGyroid,
            triangle: fillTriangle
        };

    function fillHexFull(target) {
        fillHex(target, true);
    }

    /**
     * emitter creates a hex infill pattern and sends to target
     *
     * @param {Object} target
     * @param {boolean} full continuous walls
     */
    function fillHex(target, full) {
        // compute segment lengths (vert/horiz and 45)
        let spacing = target.offset() / 2;
        let vhlen = (1 - target.density()) * 4 + spacing;
        let anxlen = ROUND(Math.cos(30 * DEG2RAD) * vhlen, 7);
        let anylen = ROUND(Math.sin(30 * DEG2RAD) * vhlen, 7);
        let bounds = target.bounds();
        let even = true;
        let evenZ = target.zIndex() % 2 === 0;
        let maxy = bounds.max.y + (vhlen + anylen * 2);
        let x, y;

        if (full || evenZ) {
            x = bounds.min.x;
            for (;;) {
                if (even && x > bounds.max.x) break;
                if (!even && x > bounds.max.x + anxlen + spacing) break;
                y = bounds.min.y;
                target.newline();
                while (y <= maxy) {
                    target.emit(x,y);
                    y += vhlen;
                    target.emit(x,y);
                    if (even) x += anxlen; else x -= anxlen;
                    y += anylen;
                    target.emit(x,y);
                    y += vhlen;
                    target.emit(x,y);
                    if (even) x -= anxlen; else x += anxlen;
                    y += anylen;
                }
                x += spacing;
                if (even) x += (anxlen * 2);
                even = !even;
                target.newline();
            }
        } else {
            y = bounds.min.y + vhlen;
            for (;;) {
                if (even && y > bounds.max.y) break;
                if (!even && y > bounds.max.y + anylen) break;
                x = bounds.min.x;
                target.newline();
                while (x < bounds.max.x) {
                    target.emit(x,y);
                    if (even) y += anylen; else y -= anylen;
                    x += anxlen;
                    target.emit(x,y);
                    x += spacing;
                    target.emit(x,y);
                    if (even) y -= anylen; else y += anylen;
                    x += anxlen;
                    target.emit(x,y);
                    x += spacing;
                }
                y += vhlen;
                if (even) y += (anylen * 2);
                even = !even;
                target.newline();
            }
        }
    }

    function fillGyroid(target) {
        let bounds = target.bounds();
        let height = target.zHeight();
        let span_x = bounds.max.x - bounds.min.x;
        let span_y = bounds.max.y - bounds.min.y;
        let density = target.density();
        let tile = 1 + (1 - density) * 15;
        let tile_x = span_x / tile;
        let tile_y = span_y / tile;
        let tile_z = 1 / tile;
        let gyroid = BASE.gyroid.slice(target.zValue() * tile_z, (1 - density) * 500);

        gyroid.polys.forEach(poly => {
            for (let tx=0; tx<=tile_x; tx++) {
                for (let ty=0; ty<=tile_y; ty++) {
                    target.newline();
                    let bx = tx * tile + bounds.min.x;
                    let by = ty * tile + bounds.min.y;
                    poly.forEach(point => {
                        target.emit(bx + point.x * tile, by + point.y * tile);
                    });
                }
            }
        });
    }

    function fillGrid(target) {
        let bounds = target.bounds();
        let height = target.zHeight();
        let span_x = bounds.max.x - bounds.min.x;
        let span_y = bounds.max.y - bounds.min.y;
        let density = target.density();
        let offset = target.offset();
        let tile = 1 + (1 - density) * 3;
        let tile_x = tile + offset;
        let tile_xc = span_x / tile_x;
        let tile_yc = span_y / tile;

        for (let tx=0; tx<=tile_xc; tx++) {
            target.newline();
            for (let ty=0; ty<=tile_yc; ty++) {
                let bx = tx * tile_x + bounds.min.x;
                let by = ty * tile + bounds.min.y;
                if ((tx + ty) % 2) {
                    target.emit(bx, by);
                    target.emit(bx + tile_x - offset, by + tile);
                } else {
                    target.emit(bx + tile_x - offset, by);
                    target.emit(bx, by + tile);
                }
            }
        }
    }

    function fillTriangle(target) {
        let bounds = target.bounds();
        let height = target.zHeight();
        let span_x = bounds.max.x - bounds.min.x;
        let span_y = bounds.max.y - bounds.min.y;
        let density = target.density();
        let offset = target.offset();
        let line_w = target.lineWidth() / 2;
        let tile = 1 + (1 - density) * 3;
        let tile_x = tile + offset*2 + line_w;
        let tile_xc = span_x / tile_x;
        let tile_yc = span_y / tile;

        for (let tx=0; tx<=tile_xc; tx++) {
            target.newline();
            for (let ty=0; ty<=tile_yc; ty++) {
                let bx = tx * tile_x + bounds.min.x;
                let by = ty * tile + bounds.min.y;
                if ((tx + ty) % 2) {
                    target.emit(bx, by);
                    target.emit(bx + tile_x - offset - line_w, by + tile);
                } else {
                    target.emit(bx + tile_x - offset - line_w, by);
                    target.emit(bx, by + tile);
                }
            }
        }

        for (let tx=0; tx<=tile_xc; tx++) {
            target.newline();
            for (let ty=0; ty<=tile_yc; ty++) {
                let bx = tx * tile_x + bounds.min.x;
                let by = ty * tile + bounds.min.y;
                let xp = bx + tile_x - line_w/2 - offset/2;
                target.emit(xp, by);
                target.emit(xp, by + tile);
            }
        }
    }

})();
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict'

const fs = require('fs')
const crypto = require('crypto')
const process = require('process')
const https = require('https')
const child_process = require('child_process')
const path = require('path')
const lockfile = require('./yarnpkg-lockfile.js')
const { promisify } = require('util')

const execFile = promisify(child_process.execFile)

const exec = async (...args) => {
	const res = await execFile(...args)
	if (res.error) throw new Error(res.stderr)
	return res
}

// This has to match the logic in pkgs/development/tools/yarn2nix-moretea/yarn2nix/lib/urlToName.js
// so that fixup_yarn_lock produces the same paths
const urlToName = url => {
  const isCodeloadGitTarballUrl = url.startsWith('https://codeload.github.com/') && url.includes('/tar.gz/')

  if (url.startsWith('git+') || isCodeloadGitTarballUrl) {
    return path.basename(url)
  } else {
    return url
      .replace(/https:\/\/(.)*(.com)\//g, '') // prevents having long directory names
      .replace(/[@/%:-]/g, '_') // replace @ and : and - and % characters with underscore
  }
}

const downloadFileHttps = (fileName, url, expectedHash) => {
	return new Promise((resolve, reject) => {
		https.get(url, (res) => {
			const file = fs.createWriteStream(fileName)
			const hash = crypto.createHash('sha1')
			res.pipe(file)
			res.pipe(hash).setEncoding('hex')
			res.on('end', () => {
				file.close()
				const h = hash.read()
				if (h != expectedHash) return reject(new Error(`hash mismatch, expected ${expectedHash}, got ${h}`))
				resolve()
			})
                        res.on('error', e => reject(e))
		})
	})
}

const downloadGit = async (fileName, url, rev) => {
	await exec('nix-prefetch-git', [
		'--out', fileName + '.tmp',
		'--url', url,
		'--rev', rev,
		'--builder'
	])

	await exec('tar', [
		// hopefully make it reproducible across runs and systems
		'--owner=0', '--group=0', '--numeric-owner', '--format=gnu', '--sort=name', '--mtime=@1',

		// Set u+w because tar-fs can't unpack archives with read-only dirs: https://github.com/mafintosh/tar-fs/issues/79
		'--mode', 'u+w',

		'-C', fileName + '.tmp',
		'-cf', fileName, '.'
	])

	await exec('rm', [ '-rf', fileName + '.tmp', ])
}

const downloadPkg = (pkg, verbose) => {
	const [ url, hash ] = pkg.resolved.split('#')
	if (verbose) console.log('downloading ' + url)
	const fileName = urlToName(url)
	if (url.startsWith('https://codeload.github.com/') && url.includes('/tar.gz/')) {
		const s = url.split('/')
		downloadGit(fileName, `https://github.com/${s[3]}/${s[4]}.git`, s[6])
	} else if (url.startsWith('https://')) {
		return downloadFileHttps(fileName, url, hash)
	} else if (url.startsWith('git:')) {
		return downloadGit(fileName, url.replace(/^git\+/, ''), hash)
	} else if (url.startsWith('git+')) {
		return downloadGit(fileName, url.replace(/^git\+/, ''), hash)
	} else if (url.startsWith('file:')) {
		console.warn(`ignoring unsupported file:path url "${url}"`)
	} else {
		throw new Error('don\'t know how to download "' + url + '"')
	}
}

const performParallel = tasks => {
	const worker = async () => {
		while (tasks.length > 0) await tasks.shift()()
	}

	const workers = []
	for (let i = 0; i < 4; i++) {
		workers.push(worker())
	}

	return Promise.all(workers)
}

const prefetchYarnDeps = async (lockContents, verbose) => {
	const lockData = lockfile.parse(lockContents)
	const tasks = Object.values(
		Object.entries(lockData.object)
		.map(([key, value]) => {
			return { key, ...value }
		})
		.reduce((out, pkg) => {
			out[pkg.resolved] = pkg
			return out
		}, {})
	)
		.map(pkg => () => downloadPkg(pkg, verbose))

	await performParallel(tasks)
	await fs.promises.writeFile('yarn.lock', lockContents)
	if (verbose) console.log('Done')
}

const showUsage = async () => {
	process.stderr.write(`
syntax: prefetch-yarn-deps [path to yarn.lock] [options]

Options:
  -h --help         Show this help
  -v --verbose      Verbose output
  --builder         Only perform the download to current directory, then exit
`)
	process.exit(1)
}

const main = async () => {
	const args = process.argv.slice(2)
	let next, lockFile, verbose, isBuilder
	while (next = args.shift()) {
		if (next == '--builder') {
			isBuilder = true
		} else if (next == '--verbose' || next == '-v') {
			verbose = true
		} else if (next == '--help' || next == '-h') {
			showUsage()
		} else if (!lockFile) {
			lockFile = next
		} else {
			showUsage()
		}
	}
	let lockContents
	try {
		lockContents = await fs.promises.readFile(lockFile || 'yarn.lock', 'utf-8')
	} catch {
		showUsage()
	}

	if (isBuilder) {
		await prefetchYarnDeps(lockContents, verbose)
	} else {
		const { stdout: tmpDir } = await exec('mktemp', [ '-d' ])

		try {
			process.chdir(tmpDir.trim())
			await prefetchYarnDeps(lockContents, verbose)
			const { stdout: hash } = await exec('nix-hash', [ '--type', 'sha256', '--base32', tmpDir.trim() ])
			console.log(hash)
		} finally {
			await exec('rm', [ '-rf', tmpDir.trim() ])
		}
	}
}

main()
	.catch(e => {
		console.error(e)
		process.exit(1)
	})
<commit_msg>fetchYarnDeps: support more url types<commit_after>#!/usr/bin/env node
'use strict'

const fs = require('fs')
const crypto = require('crypto')
const process = require('process')
const https = require('https')
const child_process = require('child_process')
const path = require('path')
const lockfile = require('./yarnpkg-lockfile.js')
const { promisify } = require('util')
const url = require('url')

const execFile = promisify(child_process.execFile)

const exec = async (...args) => {
	const res = await execFile(...args)
	if (res.error) throw new Error(res.stderr)
	return res
}

// This has to match the logic in pkgs/development/tools/yarn2nix-moretea/yarn2nix/lib/urlToName.js
// so that fixup_yarn_lock produces the same paths
const urlToName = url => {
	const isCodeloadGitTarballUrl = url.startsWith('https://codeload.github.com/') && url.includes('/tar.gz/')

	if (url.startsWith('git+') || isCodeloadGitTarballUrl) {
		return path.basename(url)
	} else {
		return url
			.replace(/https:\/\/(.)*(.com)\//g, '') // prevents having long directory names
			.replace(/[@/%:-]/g, '_') // replace @ and : and - and % characters with underscore
	}
}

const downloadFileHttps = (fileName, url, expectedHash) => {
	return new Promise((resolve, reject) => {
		https.get(url, (res) => {
			const file = fs.createWriteStream(fileName)
			const hash = crypto.createHash('sha1')
			res.pipe(file)
			res.pipe(hash).setEncoding('hex')
			res.on('end', () => {
				file.close()
				const h = hash.read()
				if (h != expectedHash) return reject(new Error(`hash mismatch, expected ${expectedHash}, got ${h}`))
				resolve()
			})
                        res.on('error', e => reject(e))
		})
	})
}

const downloadGit = async (fileName, url, rev) => {
	await exec('nix-prefetch-git', [
		'--out', fileName + '.tmp',
		'--url', url,
		'--rev', rev,
		'--builder'
	])

	await exec('tar', [
		// hopefully make it reproducible across runs and systems
		'--owner=0', '--group=0', '--numeric-owner', '--format=gnu', '--sort=name', '--mtime=@1',

		// Set u+w because tar-fs can't unpack archives with read-only dirs: https://github.com/mafintosh/tar-fs/issues/79
		'--mode', 'u+w',

		'-C', fileName + '.tmp',
		'-cf', fileName, '.'
	])

	await exec('rm', [ '-rf', fileName + '.tmp', ])
}

const isGitUrl = pattern => {
	// https://github.com/yarnpkg/yarn/blob/3119382885ea373d3c13d6a846de743eca8c914b/src/resolvers/exotics/git-resolver.js#L15-L47
	const GIT_HOSTS = ['github.com', 'gitlab.com', 'bitbucket.com', 'bitbucket.org']
	const GIT_PATTERN_MATCHERS = [/^git:/, /^git\+.+:/, /^ssh:/, /^https?:.+\.git$/, /^https?:.+\.git#.+/]

	for (const matcher of GIT_PATTERN_MATCHERS) if (matcher.test(pattern)) return true

	const {hostname, path} = url.parse(pattern)
	if (hostname && path && GIT_HOSTS.indexOf(hostname) >= 0
		// only if dependency is pointing to a git repo,
		// e.g. facebook/flow and not file in a git repo facebook/flow/archive/v1.0.0.tar.gz
		&& path.split('/').filter(p => !!p).length === 2
	) return true

	return false
}

const downloadPkg = (pkg, verbose) => {
	const [ url, hash ] = pkg.resolved.split('#')
	if (verbose) console.log('downloading ' + url)
	const fileName = urlToName(url)
	if (url.startsWith('https://codeload.github.com/') && url.includes('/tar.gz/')) {
		const s = url.split('/')
		downloadGit(fileName, `https://github.com/${s[3]}/${s[4]}.git`, s[6])
	} else if (isGitUrl(url)) {
		return downloadGit(fileName, url.replace(/^git\+/, ''), hash)
	} else if (url.startsWith('https://')) {
		return downloadFileHttps(fileName, url, hash)
	} else if (url.startsWith('file:')) {
		console.warn(`ignoring unsupported file:path url "${url}"`)
	} else {
		throw new Error('don\'t know how to download "' + url + '"')
	}
}

const performParallel = tasks => {
	const worker = async () => {
		while (tasks.length > 0) await tasks.shift()()
	}

	const workers = []
	for (let i = 0; i < 4; i++) {
		workers.push(worker())
	}

	return Promise.all(workers)
}

const prefetchYarnDeps = async (lockContents, verbose) => {
	const lockData = lockfile.parse(lockContents)
	const tasks = Object.values(
		Object.entries(lockData.object)
		.map(([key, value]) => {
			return { key, ...value }
		})
		.reduce((out, pkg) => {
			out[pkg.resolved] = pkg
			return out
		}, {})
	)
		.map(pkg => () => downloadPkg(pkg, verbose))

	await performParallel(tasks)
	await fs.promises.writeFile('yarn.lock', lockContents)
	if (verbose) console.log('Done')
}

const showUsage = async () => {
	process.stderr.write(`
syntax: prefetch-yarn-deps [path to yarn.lock] [options]

Options:
  -h --help         Show this help
  -v --verbose      Verbose output
  --builder         Only perform the download to current directory, then exit
`)
	process.exit(1)
}

const main = async () => {
	const args = process.argv.slice(2)
	let next, lockFile, verbose, isBuilder
	while (next = args.shift()) {
		if (next == '--builder') {
			isBuilder = true
		} else if (next == '--verbose' || next == '-v') {
			verbose = true
		} else if (next == '--help' || next == '-h') {
			showUsage()
		} else if (!lockFile) {
			lockFile = next
		} else {
			showUsage()
		}
	}
	let lockContents
	try {
		lockContents = await fs.promises.readFile(lockFile || 'yarn.lock', 'utf-8')
	} catch {
		showUsage()
	}

	if (isBuilder) {
		await prefetchYarnDeps(lockContents, verbose)
	} else {
		const { stdout: tmpDir } = await exec('mktemp', [ '-d' ])

		try {
			process.chdir(tmpDir.trim())
			await prefetchYarnDeps(lockContents, verbose)
			const { stdout: hash } = await exec('nix-hash', [ '--type', 'sha256', '--base32', tmpDir.trim() ])
			console.log(hash)
		} finally {
			await exec('rm', [ '-rf', tmpDir.trim() ])
		}
	}
}

main()
	.catch(e => {
		console.error(e)
		process.exit(1)
	})
<|endoftext|>


<commit_before>(function() {
  document.body.style.margin = "0";

  var PATH_TO_VIDEO = "https://www.youtube.com/v/MAtCSio876c?version=3&autoplay=1&loop=1&playlist=MAtCSio876c";

  var allElements = document.querySelectorAll("body *");
  for (var i = 0; i < allElements.length; i++) {
    var element = allElements[i];

    setTimeout(function(element) {
      element.setAttribute("class", "animated infinite swing");
      element.style.WebkitAnimationDuration = "5s";
      element.style.animationDuration = "5s";
    }.bind(null, element), Math.random()*1000);
  }

  (function playVideo() {
    var video = document.createElement("iframe");
    video.setAttribute("class", "left-shark-video");
    (function moveVideo() {
      var x = ~~((window.innerWidth - 400)*Math.random());
      var y = ~~((window.innerHeight - 400)*Math.random());
      var scale = Math.random();
      video.style.transform = "translateX(" + x + "px) translateY(" + y + "px) scale(" + scale + ")";
      setTimeout(moveVideo, 4000);
    }());
    video.src = PATH_TO_VIDEO;
    video.height = 400;
    video.width = 400;
    video.autoplay = true;
    document.body.appendChild(video);
  }());

  function injectShark() {
    var img = document.createElement("img");
    img.setAttribute("class", "left-shark-gif");
    img.src = "http://localhost:1337/assets/left-shark.gif";
    (function moveShark() {
      var x = ~~((window.innerWidth)*Math.random());
      var y = ~~((window.innerHeight)*Math.random());
      var z = -~~(Math.random()*500);
      img.style.transform = "translateX(" + x + "px) translateY(" + y + "px) translateZ(" + z + "px)";
      img.style.WebkitAnimationDuration = "5s";
      img.style.animationDuration = "5s";
      setTimeout(moveShark, 4000);
    }());
    document.body.appendChild(img);
  }

  var i = 10;
  while (i--) {
    setTimeout(injectShark, i*100);
  }

  (function injectWave() {
    var img = document.createElement("img");
    // img.setAttribute("class", "waves wobble animated infinite");
    img.setAttribute("class", "waves");
    img.src = "http://www.skylinesup.com/assets/images/_bgs/xbg_waves.png.pagespeed.ic.pGjXSUvPiA.png";
    document.body.appendChild(img);
  }());

  (function injectFin() {
    var img = document.createElement("img");
    img.setAttribute("class", "fin");
    img.src = "http://images.clipartpanda.com/fin-clipart-blue-fin.svg";
    document.body.appendChild(img);
    var x = 0;
    requestAnimationFrame(function loop() {
      if (x > window.innerWidth) x = 0;
      img.style.transform = 'translateX(-' + (x++) + 'px)';
      requestAnimationFrame(loop);
    });
  }());

  (function injectPalm() {
    var img = document.createElement("img");
    img.setAttribute("class", "palm");
    img.src = "http://www.dzzyn.com/wp-content/uploads/2015/01/20-Free-Tree-PNG-Images-jamaicanroyalpalm01L.png";
    document.body.appendChild(img);
    img.onload = function() {
      setTimeout(function() {
        img.style.transform = 'translateY(0)';
      }, 10);
    };
    // var x = 0;
    // requestAnimationFrame(function loop() {
    //   if (x > window.innerWidth) x = 0;
    //   img.style.transform = 'translateX(-' + (x++) + 'px)';
    //   requestAnimationFrame(loop);
    // });

  }());

  return true;
})();
<commit_msg>fix: Don't override classes<commit_after>(function() {
  document.body.style.margin = "0";

  var PATH_TO_VIDEO = "https://www.youtube.com/v/MAtCSio876c?version=3&autoplay=1&loop=1&playlist=MAtCSio876c";

  var allElements = document.querySelectorAll("body *");
  for (var i = 0; i < allElements.length; i++) {
    var element = allElements[i];
    setTimeout(function(element) {
      element.classList.add("animated");
      element.classList.add("infinite");
      element.classList.add("swing");
      element.style.WebkitAnimationDuration = "5s";
      element.style.animationDuration = "5s";
    }.bind(null, element), Math.random()*1000);
  }

  (function playVideo() {
    var video = document.createElement("iframe");
    video.setAttribute("class", "left-shark-video");
    (function moveVideo() {
      var x = ~~((window.innerWidth - 400)*Math.random());
      var y = ~~((window.innerHeight - 400)*Math.random());
      var scale = Math.random();
      video.style.transform = "translateX(" + x + "px) translateY(" + y + "px) scale(" + scale + ")";
      setTimeout(moveVideo, 4000);
    }());
    video.src = PATH_TO_VIDEO;
    video.height = 400;
    video.width = 400;
    video.autoplay = true;
    document.body.appendChild(video);
  }());

  function injectShark() {
    var img = document.createElement("img");
    img.setAttribute("class", "left-shark-gif");
    img.src = "http://localhost:1337/assets/left-shark.gif";
    (function moveShark() {
      var x = ~~((window.innerWidth)*Math.random());
      var y = ~~((window.innerHeight)*Math.random());
      var z = -~~(Math.random()*500);
      img.style.transform = "translateX(" + x + "px) translateY(" + y + "px) translateZ(" + z + "px)";
      img.style.WebkitAnimationDuration = "5s";
      img.style.animationDuration = "5s";
      setTimeout(moveShark, 4000);
    }());
    document.body.appendChild(img);
  }

  var i = 10;
  while (i--) {
    setTimeout(injectShark, i*100);
  }

  (function injectWave() {
    var img = document.createElement("img");
    img.setAttribute("class", "waves");
    img.src = "http://www.skylinesup.com/assets/images/_bgs/xbg_waves.png.pagespeed.ic.pGjXSUvPiA.png";
    document.body.appendChild(img);
  }());

  (function injectFin() {
    var img = document.createElement("img");
    img.setAttribute("class", "fin");
    img.src = "http://images.clipartpanda.com/fin-clipart-blue-fin.svg";
    document.body.appendChild(img);
    var x = 0;
    requestAnimationFrame(function loop() {
      if (x > window.innerWidth) x = 0;
      img.style.transform = "translateX(-" + (x++) + "px)";
      requestAnimationFrame(loop);
    });
  }());

  (function injectPalm() {
    var img = document.createElement("img");
    img.setAttribute("class", "palm");
    img.src = "http://www.dzzyn.com/wp-content/uploads/2015/01/20-Free-Tree-PNG-Images-jamaicanroyalpalm01L.png";
    document.body.appendChild(img);
    img.onload = function() {
      setTimeout(function() {
        img.style.transform = "translateY(0)";
      }, 10);
    };
  }());

  return true;
})();
<|endoftext|>