<commit_before>var map;

function main() {

  var options = {
    center: [38.265, -85.771],
    zoom: 11,
    zoomControl: false,  // dont add the zoom overlay (it is added by default)
    loaderControl: false //dont show tiles loader
  };

  cartodb.createVis('map', 'http://cityresearch.cartodb.com/api/v2/viz/5c39067a-b3aa-11e4-a01f-0e9d821ea90d/viz.json', options)
        .done(function(vis, layers) {
      // there are two layers, base layer and points layer

      // add the tooltip show when hover on the point
      vis.addOverlay({
        type: 'tooltip',
        position: 'top|center',
        template: '
{{name_to_display}}
'
      });

    });

}

window.onload = main;
<commit_msg>Update app.js<commit_after>var map;

function main() {

  var options = {
    center: [38.270, -85.771],
    zoom: 11,
    zoomControl: false,  // dont add the zoom overlay (it is added by default)
    loaderControl: false //dont show tiles loader
  };

  cartodb.createVis('map', 'http://cityresearch.cartodb.com/api/v2/viz/5c39067a-b3aa-11e4-a01f-0e9d821ea90d/viz.json', options)
        .done(function(vis, layers) {
      // there are two layers, base layer and points layer

      // add the tooltip show when hover on the point
      vis.addOverlay({
        type: 'tooltip',
        position: 'top|center',
        template: '
{{name_to_display}}
'
      });

    });

}

window.onload = main;
<|endoftext|>


<commit_before>$(document).foundation()

context = new AudioContext()

// declare globals
var voices = []
    heldKeys = [],
    mixAmp = context.createGain(),
    ampEnvAttack = 0.05,
    ampEnvDelay = 0.2,
    ampEnvSustain = 0.9,
    ampEnvRelease = 0.1

$(document).ready(function() {
    initTuning()
})

// initialize tuning
function initTuning() {
    $('#voice-one-pitch').attr("value","440")
    $('#voice-two-pitch').attr("value","493.88")
    $('#voice-three-pitch').attr("value","523.33")
    $('#voice-four-pitch').attr("value","587.33")
    $('#voice-five-pitch').attr("value","659.26")
    $('#voice-six-pitch').attr("value","698.46")
    $('#voice-seven-pitch').attr("value","783.99")
    $('#voice-eight-pitch').attr("value","880")
    $('#gain').attr("value","1")
}

// initialize gain
mixAmp.gain.value = 0.1

// ---------- start and stop voices------------
function startVoice(n,freq) {
    voices[n] = new Voice(mixAmp)
    voices[n].play(freq)
}

function stopVoice(n) {
    voices[n].stop()
}

// ---------- Voice class ----------------
function Voice(mixAmp) {
    this.osc = context.createOscillator()
    this.oscAmp = context.createGain()
    this.ampEnv = ADSR(context)

    this.play = function(frequency) {
        this.osc.type = 'triangle'
        this.osc.frequency.value = frequency
        console.log(frequency)

        this.oscAmp.gain = 0.1

        console.log(ampEnvAttack)
        this.ampEnv.attack = ampEnvAttack
        this.ampEnv.delay = ampEnvDelay
        this.ampEnv.sustain = ampEnvSustain
        this.ampEnv.release = ampEnvRelease
        this.ampEnv.value.value = 2     // ???

        // routing
        this.osc.connect(this.oscAmp)
        this.oscAmp.connect(mixAmp)
        this.ampEnv.connect(this.oscAmp.gain)
        mixAmp.connect(context.destination)

        this.ampEnv.start(context.currentTime)
        this.osc.start(context.CurrentTime)
    }

    this.stop = function() {
        var stopAt = this.ampEnv.stop(context.currentTime + ampEnvRelease)
        this.osc.stop(stopAt)
    }
}
<commit_msg>Add retrigger and increase oscAmp gain<commit_after>$(document).foundation()

context = new AudioContext()

// declare globals
var voices = []
    heldKeys = [],
    mixAmp = context.createGain(),
    ampEnvAttack = 0.1,
    ampEnvDelay = 0.1,
    ampEnvSustain = 0.9,
    ampEnvRelease = 0.1

$(document).ready(function() {
    initTuning()
})

// initialize tuning
function initTuning() {
    $('#voice-one-pitch').attr("value","440")
    $('#voice-two-pitch').attr("value","493.88")
    $('#voice-three-pitch').attr("value","523.33")
    $('#voice-four-pitch').attr("value","587.33")
    $('#voice-five-pitch').attr("value","659.26")
    $('#voice-six-pitch').attr("value","698.46")
    $('#voice-seven-pitch').attr("value","783.99")
    $('#voice-eight-pitch').attr("value","880")
    $('#gain').attr("value","1")
}

// initialize gain
mixAmp.gain.value = 0.1

// ---------- start and stop voices------------
function startVoice(n,freq) {
    // check for retrigger
    if (voices[n]) {
        voices[n].osc.stop()
    }

    // instantiate and start voice
    voices[n] = new Voice(mixAmp)
    voices[n].play(freq)
}

function stopVoice(n) {
    voices[n].stop()
}

// ---------- Voice class ----------------
function Voice(mixAmp) {
    this.osc = context.createOscillator()
    this.oscAmp = context.createGain()
    this.ampEnv = ADSR(context)

    this.play = function(frequency) {
        this.osc.type = 'triangle'
        this.osc.frequency.value = frequency
        console.log(frequency)

        this.oscAmp.gain = 1

        console.log(ampEnvAttack)
        this.ampEnv.attack = ampEnvAttack
        this.ampEnv.delay = ampEnvDelay
        this.ampEnv.sustain = ampEnvSustain
        this.ampEnv.release = ampEnvRelease
        this.ampEnv.value.value = 2     // ???

        // routing
        this.osc.connect(this.oscAmp)
        this.oscAmp.connect(mixAmp)
        this.ampEnv.connect(this.oscAmp.gain)
        mixAmp.connect(context.destination)

        this.ampEnv.start(context.currentTime)
        this.osc.start(context.CurrentTime)
    }

    this.stop = function() {
        var stopAt = this.ampEnv.stop(context.currentTime + ampEnvRelease)
        this.osc.stop(stopAt)
    }
}
<|endoftext|>


<commit_before>// general web MIDI variables
var midiAccess;
var selectedInput;
var selectedOutput;
var queue = []; // the queue. for now we'll only support one note cannon
var previewQueue = []; // preview queue for hearing before adding
var lastQueue = []; // last queue for retroactively adding
var keyPositions = {}; // keep a dictionary of which keys held correspond to which notes
var replaceOnRest = true; // if this flag is set then clear the queue the next note played
// TODO: allow MIDI input to be used in "performance" mode or define an octave or note range for each cannon
var arrowDown = '▼';
var insertPosition = 0; // the position of the next not we'll be inserting. if 0, means we'll insert at the very beginning (shifting the previous first note up to #2, etc.)
// the position in the current queue
var position = -1;

$(document).ready(function() {
	if (navigator.requestMIDIAccess !== undefined) {
		navigator.requestMIDIAccess().then(initMIDI, alert);
	} else {
		alert('No access to MIDI devices: browser does not support Web MIDI! :(');
	}

	$('#selInputs').change(function() {
		var inputs = midiAccess.inputs;
		inputs.forEach(function(port) {
			if (port.id === $('#selInputs :selected').val()) {
				selectedInput = port;
				hookUpMIDI(selectedInput);
			}
		});
	});

	$('#selOutputs').change(function() {
		var outputs = midiAccess.outputs;
		outputs.forEach(function(port) {
			if (port.id === $('#selOutputs :selected').val()) {
				selectedOutput = port;
			}
		});
	});

	// Listen for replace checkbox change
	$('#cbReplaceOnRest').change(function() {
		replaceOnRest = this.checked;
	});

	for (var i = 1; i < 17; i++) {
		$('#selInputChannel').append($('<option>').val(i).text(i));
		// $('#selOutputChannel').append($('<option>').val(i).text(i));
	};

	// Don't allow the space key to trigger buttons
	$('button').focus(function() {
        this.blur();
    });

	// Queue logic
	$('#btnPlay').mousedown(function(ev) {
		advanceQueue(ev.which);
	});

	$('#btnPlay').mouseup(function(ev) {
		finishAdvanceQueue(ev.which);
	});

	$('#btnReset').click(function() {
		position = -1;
		$('#queue tbody tr').removeClass('active');
	})

	$('#triggerZone').keydown(function(ev) {
		advanceQueue(ev.which);
		return false;
	});

	$('#triggerZone').keyup(function(ev) {
		finishAdvanceQueue(ev.which);
		return false;
	});

	$('#triggerZone').keypress(function () {
		return false;
	});

	$('#btnClear').click(clearQueue);
	$('#btnUndo').click(removeFromQueue);
	$('#btnAddLast').click(function() { addToQueue(true); });
	$('#btnPreview, #btnAddLast').mousedown(startPreviewNotes).mouseup(endPreviewNotes);

	$(document).on('click', '.remove-sequence', function() {
		removeFromQueue($(this).data('position'));
	});

	key('command+z, ctrl+z', removeFromQueue);

	$(document).on('click', '.position', function() {
		setQueuePosition(this);
	});

	// window.beforeunload = function() {
	// 	stopAllOutput();
	// }
});

// When MIDI access is requested this function is run.
function initMIDI(access) {
	midiAccess = access;
	showMIDIPorts();
	midiAccess.onstatechange = showMIDIPorts;
}

// Populates select box with MIDI port list.
function showMIDIPorts() {
	var inputs = midiAccess.inputs;
	var first = true;
	inputs.forEach(function(port) {
		if (first && !selectedInput) selectedInput = port;
		else first = false;
		if (!_.contains(_.pluck($('#selInputs option'), 'value'), port.id)) {
			$('#selInputs').append($('<option>').val(port.id).text(port.manufacturer + " " + port.name));
		}
	});

	var outputs = midiAccess.outputs;
	first = true;
	outputs.forEach(function(port) {
		if (first && !selectedOutput) selectedOutput = port;
		else first = false;
		if (!_.contains(_.pluck($('#selOutputs option'), 'value'), port.id)) {
			$('#selOutputs').append($('<option>').val(port.id).text(port.manufacturer + " " + port.name));
		}
	});

	if (inputs.length === 0) alert('No inputs are available! :(');
	else hookUpMIDI(selectedInput);
	if (outputs.length === 0) alert('No outputs are available! :(');
}

// Hooks up one MIDI port and unhooks all the others.
function hookUpMIDI(port) {
	for (var input of midiAccess.inputs.values())
		input.onmidimessage = null;
	port.onmidimessage = midiMessageReceived;
}

// Every time we receive a MIDI message, determine whether it's a note and deal with it accordingly.
function midiMessageReceived(ev) {
	var cmd = ev.data[0] >> 4;
    var channel = ev.data[0] & 0xf;
    var noteNumber = ev.data[1];
    var velocity = 0;
    if (ev.data.length > 2)
    	velocity = ev.data[2];

    // MIDI noteon with velocity = 0 is the same as noteoff
    if (cmd === 8 || ((cmd === 9) && (velocity === 0))) { // noteoff
      noteOff(noteNumber, channel);
    } else if (cmd === 9) { // note on
      noteOn(noteNumber, velocity, channel);
    } else if (cmd === 11) { // controller message
      //controller(noteNumber, velocity);
    }
}

// When a note is ON, this function will execute
function noteOn(noteNumber, velocity, channel) {
	// Log the note
	logNote(true, noteNumber, velocity, channel);

	if ($('#cbUseChannelFiltering').prop('checked') && channel.toString() !== $('#selInputChannel :selected').val()) return;

	var note = {number: noteNumber, velocity: velocity};

	// Clear the queue if we're replacing notes on rest
	if (replaceOnRest) {
		lastQueue = [];
		replaceOnRest = false;
	}

	// If the note is already in the queue (same number) don't include it
	if (!_.findWhere(lastQueue, {number: note.number})) lastQueue.push(note);

	// Preview the note
	previewQueue.push(note);
	if (selectedOutput) selectedOutput.send([0x90, note.number, $('#cbFixedVelocity').prop('checked') ? 127 : note.velocity]);

	// Display it on the output
	$('#lastQueue tr td').remove();
	$.each(lastQueue, function(i, _note) {
		$('#lastQueue tr').append($('<td>').text(_note.number + ', ' + _note.velocity));
	});
}

// When a note is OFF, this function will execute
function noteOff(noteNumber, channel) {
	// Log the note
	logNote(false, noteNumber, 0, channel);

	// Remove it from the preview queue
	previewQueue = _.filter(previewQueue, function(note) {
		return note.number !== noteNumber;
	});

	if (selectedOutput) selectedOutput.send([0x90, noteNumber, 0]);

	if (previewQueue.length === 0) {
		// Shut off the envelope
		if ($('#cbEagerInput').prop('checked')) {
			// If there are no notes being played right now, add the last played notes to the queue
			addToQueue();
		} else if ($('#cbReplaceOnRest').prop('checked')) {
			// we need to set replaceOnRest again since the next note will be cleared out
			replaceOnRest = true;
		}
	}
}

// Adds a series of notes to the cannon
function addToQueue(keepQueue) {
	if (lastQueue.length <= 0) return;
	queue.splice(insertPosition + 1, 0, lastQueue);
	insertPosition++;
	var last = queue.length - 1;
	var longest = $('#queue th').length - $('#queue th.header').length;
	var next = $('#queue tbody tr').length + 1;
	var toAdd = lastQueue.length - longest;

	redrawQueue();

	// unless flag is set, remove the current queue
	if (!keepQueue) {
		$('#lastQueue tr td').remove();
		$('#lastQueue tr').append($('<td>').text('None'));
		lastQueue = [];
	}

	// scroll to note when added
	var queueBox = $('#box');
	var scrollTo = $('#queue tbody tr:last-child');
	queueBox.scrollTop(scrollTo.offset().top - queueBox.offset().top + queueBox.scrollTop());
}

// "Undo" functionality
function removeFromQueue(pos) {
	if (null === pos || undefined === pos) pos = queue.length - 1;
	queue.splice(pos, 1);
	redrawQueue();
	// TODO: remove empty columns
}

// Resets the cannon
function clearQueue() {
	queue = [];
	lastQueue = [];
	previewQueue = [];
	insertPosition = 0; // reset position when queue is cleared
	position = -1;
	keyPositions = {}; // ??? does this have to do with TODO below?
	// TODO: stop playing all notes still playing
	$('#queue thead th:not(.header), #queue tbody tr').remove();
}

// Advances the cannon's position by one and sends out the start of a note
function advanceQueue(keyCode) {
	var longest = $('#queue tbody tr').length;
	if ((longest === 0) || (null !== keyPositions[keyCode] && undefined !== keyPositions[keyCode])) return;
	if (position < 0 || position === longest - 1) position = 0;
	else position++;
	keyPositions[keyCode] = position;

	$('#queue tbody tr').removeClass('active');
	$($('#queue tbody tr')[position]).addClass('active');

	// scroll to note being played
	var queueBox = $('#box');
	var scrollTo = $('#queue tbody tr.active');
	queueBox.scrollTop(scrollTo.offset().top - queueBox.offset().top + queueBox.scrollTop());

	var notes = queue[position];
	$.each(notes, function(i, note) {
		selectedOutput.send([0x90, note.number, $('#cbFixedVelocity').prop('checked') ? 127 : note.velocity]);
	});
}

// Finishes advancing the cannon's position and sends the end of the note
function finishAdvanceQueue(keyCode) {
	var longest = $('#queue tbody tr').length;
	if (longest === 0) return;
	if (keyCode > 0 && keyCode < 4) {
		// mouse: since it doesn't play well with keyboard, silence everything
		var allActiveNotes = [];
		$.each(_.values(keyPositions), function(i, p) {
			allActiveNotes.push.apply(allActiveNotes, _.pluck(queue[p], 'number'));
		});

		$.each(allActiveNotes, function(i, note) {
			selectedOutput.send([0x90, note, 0]);
		});
		keyPositions = {};
	} else {
		var pos = (null !== keyPositions[keyCode] && undefined !== keyPositions[keyCode]) ? keyPositions[keyCode] : position;

		var notes = queue[pos];
		delete keyPositions[keyCode];

		// get big list of all notes in keyPositions still, don't turn any of those off
		var stillActiveNotes = [];
		$.each(_.values(keyPositions), function(i, p) {
			stillActiveNotes.push.apply(stillActiveNotes, _.pluck(queue[p], 'number'));
		});

		$.each(notes, function(i, note) {
			if (!_.contains(stillActiveNotes, note.number)) selectedOutput.send([0x90, note.number, 0]);
		});
	}
}

// It may be best at times to completely redraw the queue such as after deleting rows
function redrawQueue() {
	var toAdd = _.max(queue, 'length').length;
	if (toAdd === 0) insertPosition = 0; // reset position when queue is cleared

	if (insertPosition !== -1) $('#queue thead .header.position').text('#');
	else $('#queue thead .header.position').html(arrowDown + ' ' + '#');

	// clear queue table
	$('#queue thead th:not(.header), #queue tbody tr').remove();

	// fill out the rest of the headers with <th>'s
	for (var i = 1; i < toAdd + 1; i++) {
		$('#queue thead tr').append($('<th>').text('Note #' + i));
		$('#queue tbody tr').append($('<td>'));
	}

	$.each(queue, function(c, sequence) {
		var row = $('<tr>');
		row.append($('<td>')
			.addClass('remove-sequence')
			.data('position', c)
			.attr('title', 'Remove from sequence')
			.text('x'));
		row.append($('<td>')
			.addClass('position')
			.data('position', c)
			.attr('title', 'Insert notes here')
			.html((insertPosition === c ? arrowDown + ' ' : '') + (c + 1)));

		for (var i = 0; i < toAdd; i++) {
			var note = sequence[i];
			if (!note) row.append($('<td>'));
			else row.append($('<td>').text(note.number + ', ' + note.velocity));
		};

		// fill out the rest of the row with empty <td>'s if necessary
		if (toAdd * -1 > 0) {
			for (var i = 0; i < toAdd * -1; i++) {
				row.append($('<td>'));
			}
		}

		$('#queue tbody').append(row);
	});
}

function setQueuePosition(element) {
	insertPosition = $(element).data('position');
	redrawQueue();
}

// Preview notes
function startPreviewNotes() {
	$.each(lastQueue, function(i, note) {
		selectedOutput.send([0x90, note.number, $('#cbFixedVelocity').prop('checked') ? 127 : note.velocity]);
	});
}
// Preview notes
function endPreviewNotes() {
	$.each(lastQueue, function(i, note) {
		selectedOutput.send([0x90, note.number, 0]);
	});
}

// Log note to the MIDI monitor
function logNote(pressed, noteNumber, velocity, channel) {
	onOrOff = pressed ? 'ON: ' : 'OFF: ';
	$('#monitor').append($('<div>').addClass(pressed ? 'note-on' : 'note-off').text(onOrOff + noteNumber + (pressed ? ',' + velocity : '') + ', CH: ' + channel));
	$('#monitor').scrollTop($('#monitor')[0].scrollHeight);
}<commit_msg>#7 - fix bug introduced by shorthand .click() calling: event passed in instead of integer<commit_after>// general web MIDI variables
var midiAccess;
var selectedInput;
var selectedOutput;
var queue = []; // the queue. for now we'll only support one note cannon
var previewQueue = []; // preview queue for hearing before adding
var lastQueue = []; // last queue for retroactively adding
var keyPositions = {}; // keep a dictionary of which keys held correspond to which notes
var replaceOnRest = true; // if this flag is set then clear the queue the next note played
// TODO: allow MIDI input to be used in "performance" mode or define an octave or note range for each cannon
var arrowDown = '▼';
var insertPosition = 0; // the position of the next not we'll be inserting. if 0, means we'll insert at the very beginning (shifting the previous first note up to #2, etc.)
// the position in the current queue
var position = -1;

$(document).ready(function() {
	if (navigator.requestMIDIAccess !== undefined) {
		navigator.requestMIDIAccess().then(initMIDI, alert);
	} else {
		alert('No access to MIDI devices: browser does not support Web MIDI! :(');
	}

	$('#selInputs').change(function() {
		var inputs = midiAccess.inputs;
		inputs.forEach(function(port) {
			if (port.id === $('#selInputs :selected').val()) {
				selectedInput = port;
				hookUpMIDI(selectedInput);
			}
		});
	});

	$('#selOutputs').change(function() {
		var outputs = midiAccess.outputs;
		outputs.forEach(function(port) {
			if (port.id === $('#selOutputs :selected').val()) {
				selectedOutput = port;
			}
		});
	});

	// Listen for replace checkbox change
	$('#cbReplaceOnRest').change(function() {
		replaceOnRest = this.checked;
	});

	for (var i = 1; i < 17; i++) {
		$('#selInputChannel').append($('<option>').val(i).text(i));
		// $('#selOutputChannel').append($('<option>').val(i).text(i));
	};

	// Don't allow the space key to trigger buttons
	$('button').focus(function() {
        this.blur();
    });

	// Queue logic
	$('#btnPlay').mousedown(function(ev) {
		advanceQueue(ev.which);
	});

	$('#btnPlay').mouseup(function(ev) {
		finishAdvanceQueue(ev.which);
	});

	$('#btnReset').click(function() {
		position = -1;
		$('#queue tbody tr').removeClass('active');
	})

	$('#triggerZone').keydown(function(ev) {
		advanceQueue(ev.which);
		return false;
	});

	$('#triggerZone').keyup(function(ev) {
		finishAdvanceQueue(ev.which);
		return false;
	});

	$('#triggerZone').keypress(function () {
		return false;
	});

	$('#btnClear').click(clearQueue);
	$('#btnUndo').click(removeFromQueue);
	$('#btnAddLast').click(function() { addToQueue(true); });
	$('#btnPreview, #btnAddLast').mousedown(startPreviewNotes).mouseup(endPreviewNotes);

	$(document).on('click', '.remove-sequence', function() {
		removeFromQueue($(this).data('position'));
	});

	key('command+z, ctrl+z', removeFromQueue);

	$(document).on('click', '.position', function() {
		setQueuePosition(this);
	});

	// window.beforeunload = function() {
	// 	stopAllOutput();
	// }
});

// When MIDI access is requested this function is run.
function initMIDI(access) {
	midiAccess = access;
	showMIDIPorts();
	midiAccess.onstatechange = showMIDIPorts;
}

// Populates select box with MIDI port list.
function showMIDIPorts() {
	var inputs = midiAccess.inputs;
	var first = true;
	inputs.forEach(function(port) {
		if (first && !selectedInput) selectedInput = port;
		else first = false;
		if (!_.contains(_.pluck($('#selInputs option'), 'value'), port.id)) {
			$('#selInputs').append($('<option>').val(port.id).text(port.manufacturer + " " + port.name));
		}
	});

	var outputs = midiAccess.outputs;
	first = true;
	outputs.forEach(function(port) {
		if (first && !selectedOutput) selectedOutput = port;
		else first = false;
		if (!_.contains(_.pluck($('#selOutputs option'), 'value'), port.id)) {
			$('#selOutputs').append($('<option>').val(port.id).text(port.manufacturer + " " + port.name));
		}
	});

	if (inputs.length === 0) alert('No inputs are available! :(');
	else hookUpMIDI(selectedInput);
	if (outputs.length === 0) alert('No outputs are available! :(');
}

// Hooks up one MIDI port and unhooks all the others.
function hookUpMIDI(port) {
	for (var input of midiAccess.inputs.values())
		input.onmidimessage = null;
	port.onmidimessage = midiMessageReceived;
}

// Every time we receive a MIDI message, determine whether it's a note and deal with it accordingly.
function midiMessageReceived(ev) {
	var cmd = ev.data[0] >> 4;
    var channel = ev.data[0] & 0xf;
    var noteNumber = ev.data[1];
    var velocity = 0;
    if (ev.data.length > 2)
    	velocity = ev.data[2];

    // MIDI noteon with velocity = 0 is the same as noteoff
    if (cmd === 8 || ((cmd === 9) && (velocity === 0))) { // noteoff
      noteOff(noteNumber, channel);
    } else if (cmd === 9) { // note on
      noteOn(noteNumber, velocity, channel);
    } else if (cmd === 11) { // controller message
      //controller(noteNumber, velocity);
    }
}

// When a note is ON, this function will execute
function noteOn(noteNumber, velocity, channel) {
	// Log the note
	logNote(true, noteNumber, velocity, channel);

	if ($('#cbUseChannelFiltering').prop('checked') && channel.toString() !== $('#selInputChannel :selected').val()) return;

	var note = {number: noteNumber, velocity: velocity};

	// Clear the queue if we're replacing notes on rest
	if (replaceOnRest) {
		lastQueue = [];
		replaceOnRest = false;
	}

	// If the note is already in the queue (same number) don't include it
	if (!_.findWhere(lastQueue, {number: note.number})) lastQueue.push(note);

	// Preview the note
	previewQueue.push(note);
	if (selectedOutput) selectedOutput.send([0x90, note.number, $('#cbFixedVelocity').prop('checked') ? 127 : note.velocity]);

	// Display it on the output
	$('#lastQueue tr td').remove();
	$.each(lastQueue, function(i, _note) {
		$('#lastQueue tr').append($('<td>').text(_note.number + ', ' + _note.velocity));
	});
}

// When a note is OFF, this function will execute
function noteOff(noteNumber, channel) {
	// Log the note
	logNote(false, noteNumber, 0, channel);

	// Remove it from the preview queue
	previewQueue = _.filter(previewQueue, function(note) {
		return note.number !== noteNumber;
	});

	if (selectedOutput) selectedOutput.send([0x90, noteNumber, 0]);

	if (previewQueue.length === 0) {
		// Shut off the envelope
		if ($('#cbEagerInput').prop('checked')) {
			// If there are no notes being played right now, add the last played notes to the queue
			addToQueue();
		} else if ($('#cbReplaceOnRest').prop('checked')) {
			// we need to set replaceOnRest again since the next note will be cleared out
			replaceOnRest = true;
		}
	}
}

// Adds a series of notes to the cannon
function addToQueue(keepQueue) {
	if (lastQueue.length <= 0) return;
	queue.splice(insertPosition + 1, 0, lastQueue);
	insertPosition++;
	var last = queue.length - 1;
	var longest = $('#queue th').length - $('#queue th.header').length;
	var next = $('#queue tbody tr').length + 1;
	var toAdd = lastQueue.length - longest;

	redrawQueue();

	// unless flag is set, remove the current queue
	if (!keepQueue) {
		$('#lastQueue tr td').remove();
		$('#lastQueue tr').append($('<td>').text('None'));
		lastQueue = [];
	}

	// scroll to note when added
	var queueBox = $('#box');
	var scrollTo = $('#queue tbody tr:last-child');
	queueBox.scrollTop(scrollTo.offset().top - queueBox.offset().top + queueBox.scrollTop());
}

// "Undo" functionality
function removeFromQueue(pos) {
	if (null === pos || undefined === pos || typeof pos !== 'number') pos = queue.length - 1;
	queue.splice(pos, 1);
	redrawQueue();
}

// Resets the cannon
function clearQueue() {
	queue = [];
	lastQueue = [];
	previewQueue = [];
	insertPosition = 0; // reset position when queue is cleared
	position = -1;
	keyPositions = {}; // ??? does this have to do with TODO below?
	// TODO: stop playing all notes still playing
	$('#queue thead th:not(.header), #queue tbody tr').remove();
}

// Advances the cannon's position by one and sends out the start of a note
function advanceQueue(keyCode) {
	var longest = $('#queue tbody tr').length;
	if ((longest === 0) || (null !== keyPositions[keyCode] && undefined !== keyPositions[keyCode])) return;
	if (position < 0 || position === longest - 1) position = 0;
	else position++;
	keyPositions[keyCode] = position;

	$('#queue tbody tr').removeClass('active');
	$($('#queue tbody tr')[position]).addClass('active');

	// scroll to note being played
	var queueBox = $('#box');
	var scrollTo = $('#queue tbody tr.active');
	queueBox.scrollTop(scrollTo.offset().top - queueBox.offset().top + queueBox.scrollTop());

	var notes = queue[position];
	$.each(notes, function(i, note) {
		selectedOutput.send([0x90, note.number, $('#cbFixedVelocity').prop('checked') ? 127 : note.velocity]);
	});
}

// Finishes advancing the cannon's position and sends the end of the note
function finishAdvanceQueue(keyCode) {
	var longest = $('#queue tbody tr').length;
	if (longest === 0) return;
	if (keyCode > 0 && keyCode < 4) {
		// mouse: since it doesn't play well with keyboard, silence everything
		var allActiveNotes = [];
		$.each(_.values(keyPositions), function(i, p) {
			allActiveNotes.push.apply(allActiveNotes, _.pluck(queue[p], 'number'));
		});

		$.each(allActiveNotes, function(i, note) {
			selectedOutput.send([0x90, note, 0]);
		});
		keyPositions = {};
	} else {
		var pos = (null !== keyPositions[keyCode] && undefined !== keyPositions[keyCode]) ? keyPositions[keyCode] : position;

		var notes = queue[pos];
		delete keyPositions[keyCode];

		// get big list of all notes in keyPositions still, don't turn any of those off
		var stillActiveNotes = [];
		$.each(_.values(keyPositions), function(i, p) {
			stillActiveNotes.push.apply(stillActiveNotes, _.pluck(queue[p], 'number'));
		});

		$.each(notes, function(i, note) {
			if (!_.contains(stillActiveNotes, note.number)) selectedOutput.send([0x90, note.number, 0]);
		});
	}
}

// It may be best at times to completely redraw the queue such as after deleting rows
function redrawQueue() {
	var toAdd = _.max(queue, 'length').length;
	if (toAdd === 0) insertPosition = 0; // reset position when queue is cleared

	if (insertPosition !== -1) $('#queue thead .header.position').text('#');
	else $('#queue thead .header.position').html(arrowDown + ' ' + '#');

	// clear queue table
	$('#queue thead th:not(.header), #queue tbody tr').remove();

	// fill out the rest of the headers with <th>'s
	for (var i = 1; i < toAdd + 1; i++) {
		$('#queue thead tr').append($('<th>').text('Note #' + i));
		$('#queue tbody tr').append($('<td>'));
	}

	$.each(queue, function(c, sequence) {
		var row = $('<tr>');
		row.append($('<td>')
			.addClass('remove-sequence')
			.data('position', c)
			.attr('title', 'Remove from sequence')
			.text('x'));
		row.append($('<td>')
			.addClass('position')
			.data('position', c)
			.attr('title', 'Insert notes here')
			.html((insertPosition === c ? arrowDown + ' ' : '') + (c + 1)));

		for (var i = 0; i < toAdd; i++) {
			var note = sequence[i];
			if (!note) row.append($('<td>'));
			else row.append($('<td>').text(note.number + ', ' + note.velocity));
		};

		// fill out the rest of the row with empty <td>'s if necessary
		if (toAdd * -1 > 0) {
			for (var i = 0; i < toAdd * -1; i++) {
				row.append($('<td>'));
			}
		}

		$('#queue tbody').append(row);
	});
}

function setQueuePosition(element) {
	insertPosition = $(element).data('position');
	redrawQueue();
}

// Preview notes
function startPreviewNotes() {
	$.each(lastQueue, function(i, note) {
		selectedOutput.send([0x90, note.number, $('#cbFixedVelocity').prop('checked') ? 127 : note.velocity]);
	});
}
// Preview notes
function endPreviewNotes() {
	$.each(lastQueue, function(i, note) {
		selectedOutput.send([0x90, note.number, 0]);
	});
}

// Log note to the MIDI monitor
function logNote(pressed, noteNumber, velocity, channel) {
	onOrOff = pressed ? 'ON: ' : 'OFF: ';
	$('#monitor').append($('<div>').addClass(pressed ? 'note-on' : 'note-off').text(onOrOff + noteNumber + (pressed ? ',' + velocity : '') + ', CH: ' + channel));
	$('#monitor').scrollTop($('#monitor')[0].scrollHeight);
}<|endoftext|>


<commit_before>// var ref = new Firebase("https://pricetracker2015.firebaseio.com/");
// var fbData;
// var userData;
// var baseUrl = 'http://localhost:3000/'
// var baseUrl = 'https://calm-island-3256.herokuapp.com/'

$(document).ready(function(){
  console.log("hello")
//   $('#login').on('click', function(e){
//     e.preventDefault();

//     fbAuth().then(function(authData){
//       fbData = authData;
//       var fbString = JSON.stringify(authData);
//       window.localStorage.setItem("fbData", fbString);
//       ajaxLogin(authData);
//       setProfile(authData);
//     });
  });

// //function definitions only ++++++++++++++++++++++++++++++++++++++++++++++++++++++

// var fbAuth = function(){
//   var promise = new Promise(function(resolve, reject){
//     ref.authWithOAuthPopup("facebook", function(error, authData) {
//       if (error) {
//         alert("login failed!");
//         reject(error);
//       } else {
//         resolve(authData);
//       };
//     });
//   })
//   return promise;
// };

// var ajaxLogin = function(authData){
//   userId = authData.facebook.id;
//   var ajaxData = {user:{oauth_id:userId}};
//   $.ajax({
//     url: baseUrl + 'users/'+userId+'/identify',
//     type: 'GET',
//     data: ajaxData
//   }).done(function(response) {
//     userData = response;
//     window.location.href = '#page-map';
//   }).fail(function() {
//     alert("Login Failed");
//   });
// };<commit_msg>added more comments<commit_after>// Unsure about this
// ***********************************
// var ref = new Firebase("https://pricetracker2015.firebaseio.com/");

// The following two lines are globally scoped. These are initialized as empty and populated once facebook OAuth succeeds.
// ***********************************
// var fbData;
// var userData;

// Unsure about this
// ***********************************
// var baseUrl = 'http://localhost:3000/'
// var baseUrl = 'https://calm-island-3256.herokuapp.com/'

$(document).ready(function(){
  console.log("hello")

// Unsure about this
// ***********************************
//   $('#login').on('click', function(e){
//     e.preventDefault();

// Unsure about this
// ***********************************
//     fbAuth().then(function(authData){
//       fbData = authData;
//       var fbString = JSON.stringify(authData);
//       window.localStorage.setItem("fbData", fbString);
//       ajaxLogin(authData);
//       setProfile(authData);
//     });
  });

// Unsure about alllllll this
// ***********************************

//function definitions only ++++++++++++++++++++++++++++++++++++++++++++++++++++++

// var fbAuth = function(){
//   var promise = new Promise(function(resolve, reject){
//     ref.authWithOAuthPopup("facebook", function(error, authData) {
//       if (error) {
//         alert("login failed!");
//         reject(error);
//       } else {
//         resolve(authData);
//       };
//     });
//   })
//   return promise;
// };

// var ajaxLogin = function(authData){
//   userId = authData.facebook.id;
//   var ajaxData = {user:{oauth_id:userId}};
//   $.ajax({
//     url: baseUrl + 'users/'+userId+'/identify',
//     type: 'GET',
//     data: ajaxData
//   }).done(function(response) {
//     userData = response;
//     window.location.href = '#page-map';
//   }).fail(function() {
//     alert("Login Failed");
//   });
// };<|endoftext|>


<commit_before>const WINDOW_SIZE = 16;

var canvas = document.querySelector("#canvas");
var video = document.querySelector("#preview");
var log = document.querySelector("#log");
var context;

var ctx = canvas.getContext("2d");

var position = {x:0, y:0};
var topLeft = {x:0, y:0};
var colors = [];

function setPosition(event){
	position.x = event.layerX - canvas.offsetLeft;
	position.y = event.layerY - canvas.offsetTop;
	topLeft.x = Math.max(0, position.x - WINDOW_SIZE / 2);
	topLeft.y = Math.max(0, position.y - WINDOW_SIZE / 2);
}

function checkColor(event){
  var x = topLeft.x;
  var y = topLeft.y;
  var pixels = ctx.getImageData(x, y, WINDOW_SIZE, WINDOW_SIZE);
  colors = [0, 0, 0];
  for(var i = 0; i < pixels.data.length; i = i + 4){
      colors[0] += pixels.data[i];
      colors[1] += pixels.data[i + 1];
      colors[2] += pixels.data[i + 2];
  }

  for (var i=0; i<3; i++){
  	colors[i] = Math.floor(colors[i] / pixels.data.length * 4);
  }

  log.textContent = "平均値 = " +
    colors[0] + "," +
    colors[1] + "," +
    colors[2];
}

function update(){
	if (video.readyState == 4){
			ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      document.body.style.backgroundColor = "rgb("+colors[0]+","+colors[1]+","+colors[2]+")";
	}
    checkColor();
  	requestAnimationFrame(update);
}

function streamAcquired(stream){
    video.src = window.URL.createObjectURL(stream);

    video.play();
  	setTimeout(update,1000);
    setTimeout(audio,1000);
}

function error(msg){
  console.log(msg);
}

function initialize(){
  navigator.getUserMedia =
    navigator.getUserMedia ||
    navigator.mozGetUserMedia;

  navigator.getUserMedia({video: true, audio:false},
                         streamAcquired,
                         error);

    try{
        context = new AudioContext();
    } catch(e) {
        console.log(e);
    }
    context.samplingRate = 48000;
  console.log(context);
}

canvas.addEventListener("click", setPosition);
initialize();

function getFreq(color1) {
  return (color1 * 10) + 200;
}

function getVolume(color2){
  return color2/128;
}

function getFilterType(color3) {
  if (color3 >= 0 && color3 <= 64) {
    return "lowpass";
  } else if (color3 >= 192 && color3 <= 255) {
    return "highpass";
  }
  return null;
}

function getFilterFreq(color3) {
  return color3 * 4;
}

function audio(){
    var buffer = context.createBuffer( 1, 48000, 48000 );
    var channel = buffer.getChannelData(0);
    //周波数
    for( var i=0; i < channel.length; i++ )
    {
        channel[i] = Math.sin( i / 48000 * getFreq(colors[0]) * 2 * Math.PI);//色1
    }
    var src = context.createBufferSource();
    src.buffer = buffer;
    src.connect(context.destination);
    src.addEventListener("ended", function(){
      gainNode.disconnect();
      src.disconnect();
      audio();
    });

    //音量
    var gainNode = context.createGain();
    src.connect(gainNode);
    gainNode.connect(context.destination);
    gainNode.gain.value = getVolume(colors[1]);//色2

    //フィルター
    var filter = context.createBiquadFilter();
    src.connect(filter);
    filter.connect(context.destination);
    filter.type = getFilterType(colors[2]);//色3
    filter.frequency.value = getFilterFreq(colors[2]);//色3
    filter.Q.value = 100;

    src.start(context.currentTime);
};
<commit_msg>サイン波の出力をAudioBufferSourceNodeではなく、OscillatorNodeを利用するように変更<commit_after>const WINDOW_SIZE = 16;

var canvas = document.querySelector("#canvas");
var video = document.querySelector("#preview");
var log = document.querySelector("#log");
var context;
var oscillator;
var gainNode;
var filter;

var ctx = canvas.getContext("2d");

var position = {x:0, y:0};
var topLeft = {x:0, y:0};
var colors = [];

function setPosition(event){
	position.x = event.layerX - canvas.offsetLeft;
	position.y = event.layerY - canvas.offsetTop;
	topLeft.x = Math.max(0, position.x - WINDOW_SIZE / 2);
	topLeft.y = Math.max(0, position.y - WINDOW_SIZE / 2);
}

function checkColor(event){
  var x = topLeft.x;
  var y = topLeft.y;
  var pixels = ctx.getImageData(x, y, WINDOW_SIZE, WINDOW_SIZE);
  colors = [0, 0, 0];
  for(var i = 0; i < pixels.data.length; i = i + 4){
      colors[0] += pixels.data[i];
      colors[1] += pixels.data[i + 1];
      colors[2] += pixels.data[i + 2];
  }

  for (var i=0; i<3; i++){
  	colors[i] = Math.floor(colors[i] / pixels.data.length * 4);
  }

  log.textContent = "平均値 = " +
    colors[0] + "," +
    colors[1] + "," +
    colors[2];
}

function update(){
	if (video.readyState == 4){
		ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
    checkColor();
    document.body.style.backgroundColor = "rgb("+colors[0]+","+colors[1]+","+colors[2]+")";

    audio();
	}
  requestAnimationFrame(update);
}

function streamAcquired(stream){
    video.src = window.URL.createObjectURL(stream);
    video.play();
  	setTimeout(update,1000);
}

function error(msg){
  console.log(msg);
}

function initAudioContext(){
  try{
    context = new AudioContext();
    oscillator = context.createOscillator();
    gainNode = context.createGain();
    filter = context.createBiquadFilter();
    filter.Q.value = 100;
    oscillator.connect(gainNode);
    gainNode.connect(filter);
    filter.connect(context.destination);

    oscillator.start();
  } catch(e) {
    console.log(e);
  }
  context.samplingRate = 48000;
}

function initialize(){
  navigator.getUserMedia =
    navigator.getUserMedia ||
    navigator.mozGetUserMedia;

  navigator.getUserMedia({video: true, audio:false},
                         streamAcquired,
                         error);

  initAudioContext();
}

canvas.addEventListener("click", setPosition);
initialize();

function getFreq(color1) {
  return (color1 * 10) + 200;
}

function getVolume(color2){
  return color2/128;
}

function getFilterType(color3) {
  if (color3 >= 0 && color3 <= 64) {
    return "lowpass";
  } else if (color3 >= 192 && color3 <= 255) {
    return "highpass";
  }
  return null;
}

function getFilterFreq(color3) {
  return color3 * 4;
}

function audio(){
  oscillator.frequency.value = getFreq(colors[0] * 2);
  gainNode.gain.value = getVolume(colors[1]);//色2
  filter.type = getFilterType(colors[2]);//色3
  filter.frequency.value = getFilterFreq(colors[2]);//色3
}
<|endoftext|>


<commit_before>$(document).ready(function() {

	// Get Money Raised Data and Adjust Progress Bar
	// Spreadsheet: https://docs.google.com/spreadsheets/d/1PE1umwfQwSwaNxX_Hishe8kKmcNPRQmRBv-GrPrBFDw/pubhtml & https://spreadsheets.google.com/feeds/list/1PE1umwfQwSwaNxX_Hishe8kKmcNPRQmRBv-GrPrBFDw/od6/public/basic?alt=json
	var khs_spreadsheet = "https://spreadsheets.google.com/feeds/list/1PE1umwfQwSwaNxX_Hishe8kKmcNPRQmRBv-GrPrBFDw/od6/public/basic/d9ney";

//	  $.ajax({
 //   url: "https://spreadsheets.google.com/feeds/list/1PE1umwfQwSwaNxX_Hishe8kKmcNPRQmRBv-GrPrBFDw/od6/public/basic/d9ney",
  //  type: "GET",
   // dataType: "xml",
//	success: function(data) {
  //      	 var xmlDoc = $.parseXML(data),
 	//	 $xmlDoc = $(xmlDoc),
  //		xml = $xmlDoc.find("<content type='text'>");
	//	var money_raised = xml

		var money_raised = 18058;
		var goal = 50000;
		var current_money = (money_raised / goal) * 100;
		var current_moneyrounded = Math.floor(current_money);

		if(current_money > 100) {
			$("#money_raised_bar").css({"width": 100 + "%" });
		} else {
			$("#money_raised_bar").css({"width": current_money + "%" });
		}

		$("#money_raised_bar").attr("aria-valuenow", current_money);
    $("#current_money").replaceWith(money_raised);
		$("#percentagetext").replaceWith(current_moneyrounded);

	})
	//.fail(function(jqxhr, textStatus, error ) {

//		var status = textStatus + ", " + error;
//		console.error("Request Failed: " + status );
//
//	});

  // Image Gallery Initiation and Settings
  // **VIDEO POP-UP ONLY WORK IN A SERVER**
	$('.swipebox').swipebox();
	$('.swipebox-video').swipebox();

<commit_msg>Money bar 24764<commit_after>$(document).ready(function() {

	// Get Money Raised Data and Adjust Progress Bar
	// Spreadsheet: https://docs.google.com/spreadsheets/d/1PE1umwfQwSwaNxX_Hishe8kKmcNPRQmRBv-GrPrBFDw/pubhtml & https://spreadsheets.google.com/feeds/list/1PE1umwfQwSwaNxX_Hishe8kKmcNPRQmRBv-GrPrBFDw/od6/public/basic?alt=json
	var khs_spreadsheet = "https://spreadsheets.google.com/feeds/list/1PE1umwfQwSwaNxX_Hishe8kKmcNPRQmRBv-GrPrBFDw/od6/public/basic/d9ney";

//	  $.ajax({
 //   url: "https://spreadsheets.google.com/feeds/list/1PE1umwfQwSwaNxX_Hishe8kKmcNPRQmRBv-GrPrBFDw/od6/public/basic/d9ney",
  //  type: "GET",
   // dataType: "xml",
//	success: function(data) {
  //      	 var xmlDoc = $.parseXML(data),
 	//	 $xmlDoc = $(xmlDoc),
  //		xml = $xmlDoc.find("<content type='text'>");
	//	var money_raised = xml

		var money_raised = 24764;
		var goal = 50000;
		var current_money = (money_raised / goal) * 100;
		var current_moneyrounded = Math.floor(current_money);

		if(current_money > 100) {
			$("#money_raised_bar").css({"width": 100 + "%" });
		} else {
			$("#money_raised_bar").css({"width": current_money + "%" });
		}

		$("#money_raised_bar").attr("aria-valuenow", current_money);
    $("#current_money").replaceWith(money_raised);
		$("#percentagetext").replaceWith(current_moneyrounded);

	})
	//.fail(function(jqxhr, textStatus, error ) {

//		var status = textStatus + ", " + error;
//		console.error("Request Failed: " + status );
//
//	});

  // Image Gallery Initiation and Settings
  // **VIDEO POP-UP ONLY WORK IN A SERVER**
	$('.swipebox').swipebox();
	$('.swipebox-video').swipebox();

<|endoftext|>


<commit_before>var deps = [
    'ui.router',
    'ngAnimate',
    'ngMaterial',
    'mdl',
    'ngIntercom',
    'ngStorage',
    'MinecraftlyAppControllers',
    'MinecraftlyAppServices'
];
angular.module("MinecraftlyAppControllers", []);
angular.module("MinecraftlyAppServices", []);
angular.module('MinecraftlyApp', deps)
        .run(function ($window) {
        })
        .config(function ($stateProvider, $locationProvider, $urlRouterProvider, IntercomProvider) {// $mdThemingProvider, $mdIconProvider,
            IntercomProvider.init('t02jhyr0');
//            $mdThemingProvider.theme('MinecraftlyTheme')
//                    .primaryPalette('blue')
//                    .accentPalette('purple')
//                    .warnPalette('deep-purple');
//            $mdThemingProvider.setDefaultTheme('MinecraftlyTheme');
//            $mdIconProvider
//                    .defaultIconSet('/img/mdi.svg');
//            $locationProvider.html5Mode(true);
            $stateProvider
                    .state('app', {
                        url: "",
                        abstract: true,
                        templateUrl: "templates/app.html",
                        controller: 'AppCtrl'
                    })
                    .state('app.home', {
                        cache: false,
                        url: "/home",
                        views: {
                            'appContent': {
                                templateUrl: "templates/home.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    })
		    .state('app.play', {
                        cache: false,
                        url: "/play",
                        views: {
                            'appContent': {
                                templateUrl: "templates/play.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    });
			.state('app.about', {
                        cache: false,
                        url: "/about",
                        views: {
                            'appContent': {
                                templateUrl: "templates/about.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    });
		    .state('app.features', {
                        cache: false,
                        url: "/features",
                        views: {
                            'appContent': {
                                templateUrl: "templates/features.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    });
		    .state('app.vote', {
                        cache: false,
                        url: "/vote",
                        views: {
                            'appContent': {
                                templateUrl: "templates/vote.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    });
		    .state('app.team', {
                        cache: false,
                        url: "/team",
                        views: {
                            'appContent': {
                                templateUrl: "templates/team.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    });
		    .state('app.terms', {
                        cache: false,
                        url: "/terms",
                        views: {
                            'appContent': {
                                templateUrl: "templates/terms.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    });
		    .state('app.privacy', {
                        cache: false,
                        url: "/privacy",
                        views: {
                            'appContent': {
                                templateUrl: "templates/privacy.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    });
		    .state('app.jobs', {
                        cache: false,
                        url: "/jobs",
                        views: {
                            'appContent': {
                                templateUrl: "templates/jobs.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    });
		    .state('app.education', {
                        cache: false,
                        url: "/education",
                        views: {
                            'appContent': {
                                templateUrl: "templates/education.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    });
            $urlRouterProvider.otherwise('/home');
        });

<commit_msg>Add play<commit_after>var deps = [
    'ui.router',
    'ngAnimate',
    'ngMaterial',
    'mdl',
    'ngIntercom',
    'ngStorage',
    'MinecraftlyAppControllers',
    'MinecraftlyAppServices'
];
angular.module("MinecraftlyAppControllers", []);
angular.module("MinecraftlyAppServices", []);
angular.module('MinecraftlyApp', deps)
        .run(function ($window) {
        })
        .config(function ($stateProvider, $locationProvider, $urlRouterProvider, IntercomProvider) {// $mdThemingProvider, $mdIconProvider,
            IntercomProvider.init('t02jhyr0');
//            $mdThemingProvider.theme('MinecraftlyTheme')
//                    .primaryPalette('blue')
//                    .accentPalette('purple')
//                    .warnPalette('deep-purple');
//            $mdThemingProvider.setDefaultTheme('MinecraftlyTheme');
//            $mdIconProvider
//                    .defaultIconSet('/img/mdi.svg');
//            $locationProvider.html5Mode(true);
            $stateProvider
                    .state('app', {
                        url: "",
                        abstract: true,
                        templateUrl: "templates/app.html",
                        controller: 'AppCtrl'
                    })
                    .state('app.home', {
                        cache: false,
                        url: "/",
                        views: {
                            'appContent': {
                                templateUrl: "templates/home.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    })
		    .state('app.features', {
                        cache: false,
                        url: "/features",
                        views: {
                            'appContent': {
                                templateUrl: "templates/features.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    });
            $urlRouterProvider.otherwise('/');
		    .state('app.play', {
                        cache: false,
                        url: "/play",
                        views: {
                            'appContent': {
                                templateUrl: "templates/play.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    });
            $urlRouterProvider.otherwise('/');
        });

<|endoftext|>


<commit_before>/* global console, VirtualJoystick, RollingSpiderHelper */
'use strict';

window.addEventListener('resize', function ResizeHandler() {
  var width = document.body.clientWidth;
  var height = document.body.clientHeight;
  if (width >= height) {
    window.removeEventListener('resize', ResizeHandler);
    init(width, height);
  }
});

function init(clientWidth, clientHeight) {
  console.log("touchscreen is " +
    (VirtualJoystick.touchScreenAvailable() ? "available" : "not available"));

  var joystickLeft  = new VirtualJoystick({
    container : document.getElementById('joystickArea'),
    strokeStyle	: 'cyan',
    // at middle of left side.
    baseX: (document.body.clientWidth/2)*0.5,
    baseY: (document.body.clientHeight/2),
    stationaryBase: true,
    limitStickTravel: true,
    stickRadius: 100,
    mouseSupport  : false
  });
  joystickLeft.addEventListener('touchStart', function(){
    console.log('L down');
  });
  joystickLeft.addEventListener('touchEnd', function(){
    console.log('L up');
  });
  joystickLeft.addEventListener('touchStartValidation', function(event){
    var touch	= event.changedTouches[0];
    if( touch.pageX >= window.innerWidth/2 ){
      return false;
    }
    return true;
  });

  var joystickRight  = new VirtualJoystick({
    container : document.getElementById('joystickArea'),
    strokeStyle	: 'orange',
    // at middle of right side.
    baseX: (document.body.clientWidth/2)*1.5,
    baseY: (document.body.clientHeight/2),
    stationaryBase: true,
    limitStickTravel: true,
    stickRadius: 100,
    mouseSupport  : false
  });
  joystickRight.addEventListener('touchStart', function(){
    console.log('R down');
  });
  joystickRight.addEventListener('touchEnd', function(){
    console.log('R up');
  });
  joystickRight.addEventListener('touchStartValidation', function(event){
    var touch	= event.changedTouches[0];
    if( touch.pageX < window.innerWidth/2 ){
      return false;
    }
    return true;
  });

  function showDebugInfo(tilt, forward, turn, up){
    var eLeft = document.querySelector('#info > .left');
    eLeft.innerHTML = 'tilt:' + tilt +
      '
forward:' + forward + '
' +
      (joystickLeft.right() ? ' right':'') +
      (joystickLeft.up()  ? ' up'   : '') +
      (joystickLeft.left()  ? ' left' : '') +
      (joystickLeft.down()  ? ' down'   : '');

    var eRight = document.querySelector('#info > .right');
    eRight.innerHTML = 'turn:' + turn +
      '
up:' + up + '
' +
      (joystickRight.right() ? ' right'  : '') +
      (joystickRight.up()  ? ' up'   : '') +
      (joystickRight.left()  ? ' left' : '') +
      (joystickRight.down()  ? ' down'   : '');
  }

  setInterval(function(){
    var tilt = Math.round(joystickLeft.deltaX()) * -1;
    var forward = Math.round(joystickLeft.deltaY()) * -1;
    var turn = Math.round(joystickRight.deltaX()) * -1;
    var up = Math.round(joystickRight.deltaY()) * -1;
    showDebugInfo(tilt, forward, turn, up);
    rsHelper.motors(true, tilt, forward, turn, up, 0, 2);
  }, 50);

  var rsHelper = new RollingSpiderHelper();

  var connectButton = document.getElementById('connect');
  var toggleConnectButton = function(isConnected) {
    if (isConnected) {
      connectButton.textContent = 'Disconnect';
    } else {
      connectButton.textContent = 'Connect';
    }
  };
  rsHelper.on('connect', function() {
    toggleConnectButton(true);
  });
  rsHelper.on('disconnect', function() {
    toggleConnectButton(false);
  });

  connectButton.addEventListener('click', function() {
    if (rsHelper.isAbleToConnect()) {
      rsHelper.connect().then(function onResolve() {
        toggleConnectButton(true);
      }, function onReject() {
        toggleConnectButton(false);
      });
    } else {
      rsHelper.disconnect().then(function onResolve() {
        toggleConnectButton(false);
      }, function onReject() {
        // XXX
      });
    }
  });

  var elTakeOff = document.getElementById('takeoff');
  elTakeOff.onclick = function (){
    rsHelper.takeOff();
  };

  var elLanding = document.getElementById('landing');
  elLanding.onclick = function (){
    rsHelper.landing();
  };

  var flyingStatusHandler = function (eventName){
    document.getElementById('flyingStatus').textContent = eventName;
  };

  /**
   * Flying statuses:
   *
   * 0: Landed
   * 1: Taking off
   * 2: Hovering
   * 3: ??
   * 4: Landing
   * 5: Emergency / Cut out
   */
  ['fsLanded', 'fsTakingOff', 'fsHovering','fsUnknown', 'fsLanding',
    'fsCutOff'].forEach(function(eventName){
    rsHelper.on(eventName, flyingStatusHandler.bind(this, eventName));
  });
}
<commit_msg>Display connecting and discovering services<commit_after>/* global console, VirtualJoystick, RollingSpiderHelper */
'use strict';

window.addEventListener('resize', function ResizeHandler() {
  var width = document.body.clientWidth;
  var height = document.body.clientHeight;
  if (width >= height) {
    window.removeEventListener('resize', ResizeHandler);
    init(width, height);
  }
});

function init(clientWidth, clientHeight) {
  console.log("touchscreen is " +
    (VirtualJoystick.touchScreenAvailable() ? "available" : "not available"));

  var joystickLeft  = new VirtualJoystick({
    container : document.getElementById('joystickArea'),
    strokeStyle	: 'cyan',
    // at middle of left side.
    baseX: (document.body.clientWidth/2)*0.5,
    baseY: (document.body.clientHeight/2),
    stationaryBase: true,
    limitStickTravel: true,
    stickRadius: 100,
    mouseSupport  : false
  });
  joystickLeft.addEventListener('touchStart', function(){
    console.log('L down');
  });
  joystickLeft.addEventListener('touchEnd', function(){
    console.log('L up');
  });
  joystickLeft.addEventListener('touchStartValidation', function(event){
    var touch	= event.changedTouches[0];
    if( touch.pageX >= window.innerWidth/2 ){
      return false;
    }
    return true;
  });

  var joystickRight  = new VirtualJoystick({
    container : document.getElementById('joystickArea'),
    strokeStyle	: 'orange',
    // at middle of right side.
    baseX: (document.body.clientWidth/2)*1.5,
    baseY: (document.body.clientHeight/2),
    stationaryBase: true,
    limitStickTravel: true,
    stickRadius: 100,
    mouseSupport  : false
  });
  joystickRight.addEventListener('touchStart', function(){
    console.log('R down');
  });
  joystickRight.addEventListener('touchEnd', function(){
    console.log('R up');
  });
  joystickRight.addEventListener('touchStartValidation', function(event){
    var touch	= event.changedTouches[0];
    if( touch.pageX < window.innerWidth/2 ){
      return false;
    }
    return true;
  });

  function showDebugInfo(tilt, forward, turn, up){
    var eLeft = document.querySelector('#info > .left');
    eLeft.innerHTML = 'tilt:' + tilt +
      '
forward:' + forward + '
' +
      (joystickLeft.right() ? ' right':'') +
      (joystickLeft.up()  ? ' up'   : '') +
      (joystickLeft.left()  ? ' left' : '') +
      (joystickLeft.down()  ? ' down'   : '');

    var eRight = document.querySelector('#info > .right');
    eRight.innerHTML = 'turn:' + turn +
      '
up:' + up + '
' +
      (joystickRight.right() ? ' right'  : '') +
      (joystickRight.up()  ? ' up'   : '') +
      (joystickRight.left()  ? ' left' : '') +
      (joystickRight.down()  ? ' down'   : '');
  }

  setInterval(function(){
    var tilt = Math.round(joystickLeft.deltaX()) * -1;
    var forward = Math.round(joystickLeft.deltaY()) * -1;
    var turn = Math.round(joystickRight.deltaX()) * -1;
    var up = Math.round(joystickRight.deltaY()) * -1;
    showDebugInfo(tilt, forward, turn, up);
    rsHelper.motors(true, tilt, forward, turn, up, 0, 2);
  }, 50);

  var rsHelper = new RollingSpiderHelper();

  var connectButton = document.getElementById('connect');
  var changeConnectButtonText = function(state) {
    switch (state) {
      case 'connecting':
        connectButton.textContent = 'Connecting';
        connectButton.disabled = true;
        break;
      case 'discovering-services':
        connectButton.textContent = 'Discovering Services...';
        connectButton.disabled = true;
        break;
      case 'connected':
        connectButton.textContent = 'Disconnect';
        connectButton.disabled = false;
        break;
      case 'disconnect':
        connectButton.textContent = 'Connect';
        connectButton.disabled = false;
        break;
    }
  };
  // XXX
  ['connecting', 'discovering-services', 'connected', 'disconnect'].forEach(
      function(eventName) {
    rsHelper.on(eventName, function() {
      changeConnectButtonText(eventName);
    });
  });
  connectButton.addEventListener('click', function() {
    if (rsHelper.isAbleToConnect()) {
      rsHelper.connect().then(function onResolve() {
        changeConnectButtonText('connected');
      }, function onReject() {
        changeConnectButtonText('disconnect');
      });
    } else {
      rsHelper.disconnect().then(function onResolve() {
        changeConnectButtonText('disconnect');
      }, function onReject() {
        // XXX
      });
    }
  });

  var elTakeOff = document.getElementById('takeoff');
  elTakeOff.onclick = function (){
    rsHelper.takeOff();
  };

  var elLanding = document.getElementById('landing');
  elLanding.onclick = function (){
    rsHelper.landing();
  };

  var flyingStatusHandler = function (eventName){
    document.getElementById('flyingStatus').textContent = eventName;
  };

  /**
   * Flying statuses:
   *
   * 0: Landed
   * 1: Taking off
   * 2: Hovering
   * 3: ??
   * 4: Landing
   * 5: Emergency / Cut out
   */
  ['fsLanded', 'fsTakingOff', 'fsHovering','fsUnknown', 'fsLanding',
    'fsCutOff'].forEach(function(eventName){
    rsHelper.on(eventName, flyingStatusHandler.bind(this, eventName));
  });
}
<|endoftext|>


<commit_before>$(function() {
  var Facility, Service;

  Facility = Backbone.Model.extend({
    defaults: function() {
      return {
        name:         'glide sf',
        addr:         '123 street',
        description:  'a place with services',
        phone:        '(111)222-3333',
        hours:        {},
        notes:        'line up early!',
        demographics: [],
        geopoint:     {}
      };
    },

  });

  Service = Backbone.Model.extend({
    defaults: function() {
      return {
        facilityId:   'glide sf', // reference to Facility
        name:         'showers',  // like 'showers', 'hiv testing'
        category:     'hygiene',  // 'hygiene'|'food'|'medical'|'shelter'|'technology'
        hours:        {},
        notes:        '3 showers',
        demographics: []          // maybe?  unclear whether necessary
      };
    }
  });
});
<commit_msg>add AppView and App<commit_after>$(function() {
  var AppView = Backbone.View.extend({
    el: $("#linksf")
  });

  var Facility = Backbone.Model.extend({
    defaults: function() {
      return {
        name:         'glide sf',
        addr:         '123 street',
        description:  'a place with services',
        phone:        '(111)222-3333',
        hours:        {},
        notes:        'line up early!',
        demographics: [],
        geopoint:     {}
      };
    },

  });

  var Service = Backbone.Model.extend({
    defaults: function() {
      return {
        facilityId:   'glide sf', // reference to Facility
        name:         'showers',  // like 'showers', 'hiv testing'
        category:     'hygiene',  // 'hygiene'|'food'|'medical'|'shelter'|'technology'
        hours:        {},
        notes:        '3 showers',
        demographics: []          // maybe?  unclear whether necessary
      };
    }
  });

  var App = new Appview;
});
<|endoftext|>


<commit_before>// My JS will be in here

var kiosk = {
  place: 'Pike Place Market',
  minCus: 14,
  maxCus: 55,
  cupsPerCus: 1.2,
  poundsPerCus: 3.7,

  generate: function() {
    return Math.random() * ((kiosk.maxCus - kiosk.minCus) + kiosk.minCus) * kiosk.cupsPerCus;
  },

  generateCus: function() {
    return Math.random() * (kiosk.maxCus - kiosk.minCus) + kiosk.minCus;
  },

  generateCups: function() {
    return Math.random() * ((kiosk.maxCus - kiosk.minCus) + kiosk.minCus) * kiosk.cupsPerCus;
  }
};

var headEl = document.createElement('h2');
headEl.textContent = 'Pike Place Market data';
document.body.appendChild(headEl);

var hourCoffee = ['6am: ', '7am: ', '8am: ', '9am: ', '10am: ', '11am: ', '12pm: ', '1pm: ', '2pm: ', '3pm: ', '4pm: ', '5pm: ', '6pm: ', '7pm: ', '8pm: '];

for (i = 0; i < hourCoffee.length; i++) {
  var paragraphEl = document.createElement('ul');
  paragraphEl.textContent = hourCoffee[i] + 'We will need ' + kiosk.generate() + ' pounds.' + ' We\'ll have ' + kiosk.generateCus() + ' customers and will need ' + kiosk.generateCups() + ' cups.';
  document.body.appendChild(paragraphEl);
}

// var paragraphEl2 = document.createElement('ul');
// paragraphEl2.textContent = 'Todays estimated coffee needs for Pike Place at 7am are: ' + kiosk.generate(14, 55) + ' pounds.'
// document.body.appendChild(paragraphEl2);
//
// var paragraphEl3 = document.createElement('ul');
// paragraphEl3.textContent = 'Todays estimated coffee needs for Pike Place at 8am are: ' + kiosk.generate(14, 55) + ' pounds.'
// document.body.appendChild(paragraphEl3);
//
// var paragraphEl4 = document.createElement('ul');
// paragraphEl4.textContent = 'Todays estimated coffee needs for Pike Place at 9am are: ' + kiosk.generate(14, 55) + ' pounds.'
// document.body.appendChild(paragraphEl4);
//
// var paragraphEl5 = document.createElement('ul');
// paragraphEl5.textContent = 'Todays estimated coffee needs for Pike Place at 6am are: ' + kiosk.generate(14, 55) + ' pounds.'
// document.body.appendChild(paragraphEl5);
//
// var paragraphEl6 = document.createElement('ul');
// paragraphEl6.textContent = 'Todays estimated coffee needs for Pike Place at 6am are: ' + kiosk.generate(14, 55) + ' pounds.'
// document.body.appendChild(paragraphEl6);
//
// var paragraphEl7 = document.createElement('ul');
// paragraphEl7.textContent = 'Todays estimated coffee needs for Pike Place at 6am are: ' + kiosk.generate(14, 55) + ' pounds.'
// document.body.appendChild(paragraphEl7);

var kiosk2 = {
  place: 'Cap Hill',
  minCus: 32,
  maxCus: 48,
  cupsPerCus: 3.2,
  poundsPerCus: 0.4,

  generate: function() {
    return Math.random() * ((48 - 32) + 32) * 0.4;
  }
};

var headEl2 = document.createElement('h2');
headEl2.textContent = 'Cap Hill data';
document.body.appendChild(headEl2);

var paragraphEl = document.createElement('ul');
paragraphEl.textContent = 'Todays estimated coffee needs for Cap Hill are: ' + kiosk2.generate(32, 48) + ' pounds.'
document.body.appendChild(paragraphEl);

var kiosk3 = {
  place: 'Seattle Public Library',
  minCus: 49,
  maxCus: 75,
  cupsPerCus: 2.6,
  poundsPerCus: 0.2,

  generate: function() {
    return Math.random() * ((75 - 49) + 49) * 0.2;
  }
};

var headEl3 = document.createElement('h2');
headEl3.textContent = 'Seattle Public Library data';
document.body.appendChild(headEl3);

var paragraphEl = document.createElement('ul');
paragraphEl.textContent = 'Todays estimated coffee needs for Seattle Public Library are: ' + kiosk3.generate(49, 75) + ' pounds.'
document.body.appendChild(paragraphEl);

var kiosk4 = {
  place: 'South Lake Union',
  minCus: 35,
  maxCus: 88,
  cupsPerCus: 1.3,
  poundsPerCus: 3.7,

  generate: function() {
    return Math.random() * ((88 - 35) + 35) * 3.7;
  }
};

var headEl4 = document.createElement('h2');
headEl4.textContent = 'South Lake Union data';
document.body.appendChild(headEl4);

var paragraphEl = document.createElement('ul');
paragraphEl.textContent = 'Todays estimated coffee needs for South Lake Union are: ' + kiosk4.generate(35, 88) + ' pounds.'
document.body.appendChild(paragraphEl);

var kiosk5 = {
  place: 'SeaTac',
  minCus: 68,
  maxCus: 124,
  cupsPerCus: 1.1,
  poundsPerCus: 2.7,

  generate: function() {
    return Math.random() * ((124 - 68) + 68) * 2.7;
  }
};

var headEl5 = document.createElement('h2');
headEl5.textContent = 'SeaTac data';
document.body.appendChild(headEl5);

var paragraphEl = document.createElement('ul');
paragraphEl.textContent = 'Todays estimated coffee needs for SeaTac are: ' + kiosk5.generate(68, 124) + ' pounds.'
document.body.appendChild(paragraphEl);

var kiosk6 = {
  place: 'Web Sales',
  minCus: 3,
  maxCus: 6,
  cupsPerCus: 0,
  poundsPerCus: 6.7,

  generate: function() {
    return Math.random() * ((6 - 3) + 3) * 6.7;
  }
};

var headEl6 = document.createElement('h2');
headEl6.textContent = 'Web Sales data';
document.body.appendChild(headEl6);

var paragraphEl = document.createElement('ul');
paragraphEl.textContent = 'Todays estimated coffee needs for Web Sales are: ' + kiosk6.generate(3, 6) + ' pounds.'
document.body.appendChild(paragraphEl);

// var duck = {
//   material: 'rubber',
//   color: 'yellow',
//   squeaks: false,
//   favoriteFoods: ['duckweed', 'peanut butter', 'children'],
//
//   says: function() {
//     console.log('QUACK');
//   }
// };
//
// var paragraphEl = document.createElement('p')
// paragraphEl.textContent = duck.favoriteFoods
// document.body.appendChild(ParagraphEl)
<commit_msg>more JS changes, almost ready a few randomization issues<commit_after>// My JS will be in here

var kiosk = {
  place: 'Pike Place Market',
  minCus: 14,
  maxCus: 55,
  cupsPerCus: 1.2,
  poundsPerCus: 3.7,

  generateCus: function() {
    return Math.floor(Math.random() * (kiosk.maxCus - kiosk.minCus + 1)) + kiosk.minCus;
  },

  generatePounds: function() {
    return kiosk.generateCus() * kiosk.poundsPerCus;
  },

  generateCups: function() {
    return kiosk.generateCus() * kiosk.cupsPerCus;
  }
};

var headEl = document.createElement('h2');
headEl.textContent = 'Pike Place Market data';
document.body.appendChild(headEl);

var hourCoffee = ['6am: ', '7am: ', '8am: ', '9am: ', '10am: ', '11am: ', '12pm: ', '1pm: ', '2pm: ', '3pm: ', '4pm: ', '5pm: ', '6pm: ', '7pm: ', '8pm: '];

for (i = 0; i < hourCoffee.length; i++) {
  var paragraphEl = document.createElement('ul');
  paragraphEl.textContent = hourCoffee[i] + 'We will need ' + kiosk.generatePounds() + ' pounds.' + ' We\'ll have ' + kiosk.generateCus() + ' customers and will need ' + kiosk.generateCups() + ' cups.';
  document.body.appendChild(paragraphEl);
}

// var paragraphEl2 = document.createElement('ul');
// paragraphEl2.textContent = 'Todays estimated coffee needs for Pike Place at 7am are: ' + kiosk.generate(14, 55) + ' pounds.'
// document.body.appendChild(paragraphEl2);
//
// var paragraphEl3 = document.createElement('ul');
// paragraphEl3.textContent = 'Todays estimated coffee needs for Pike Place at 8am are: ' + kiosk.generate(14, 55) + ' pounds.'
// document.body.appendChild(paragraphEl3);
//
// var paragraphEl4 = document.createElement('ul');
// paragraphEl4.textContent = 'Todays estimated coffee needs for Pike Place at 9am are: ' + kiosk.generate(14, 55) + ' pounds.'
// document.body.appendChild(paragraphEl4);
//
// var paragraphEl5 = document.createElement('ul');
// paragraphEl5.textContent = 'Todays estimated coffee needs for Pike Place at 6am are: ' + kiosk.generate(14, 55) + ' pounds.'
// document.body.appendChild(paragraphEl5);
//
// var paragraphEl6 = document.createElement('ul');
// paragraphEl6.textContent = 'Todays estimated coffee needs for Pike Place at 6am are: ' + kiosk.generate(14, 55) + ' pounds.'
// document.body.appendChild(paragraphEl6);
//
// var paragraphEl7 = document.createElement('ul');
// paragraphEl7.textContent = 'Todays estimated coffee needs for Pike Place at 6am are: ' + kiosk.generate(14, 55) + ' pounds.'
// document.body.appendChild(paragraphEl7);

var kiosk2 = {
  place: 'Cap Hill',
  minCus: 32,
  maxCus: 48,
  cupsPerCus: 3.2,
  poundsPerCus: 0.4,

  generate: function() {
    return Math.random() * ((48 - 32) + 32) * 0.4;
  }
};

var headEl2 = document.createElement('h2');
headEl2.textContent = 'Cap Hill data';
document.body.appendChild(headEl2);

var paragraphEl = document.createElement('ul');
paragraphEl.textContent = 'Todays estimated coffee needs for Cap Hill are: ' + kiosk2.generate(32, 48) + ' pounds.'
document.body.appendChild(paragraphEl);

var kiosk3 = {
  place: 'Seattle Public Library',
  minCus: 49,
  maxCus: 75,
  cupsPerCus: 2.6,
  poundsPerCus: 0.2,

  generate: function() {
    return Math.random() * ((75 - 49) + 49) * 0.2;
  }
};

var headEl3 = document.createElement('h2');
headEl3.textContent = 'Seattle Public Library data';
document.body.appendChild(headEl3);

var paragraphEl = document.createElement('ul');
paragraphEl.textContent = 'Todays estimated coffee needs for Seattle Public Library are: ' + kiosk3.generate(49, 75) + ' pounds.'
document.body.appendChild(paragraphEl);

var kiosk4 = {
  place: 'South Lake Union',
  minCus: 35,
  maxCus: 88,
  cupsPerCus: 1.3,
  poundsPerCus: 3.7,

  generate: function() {
    return Math.random() * ((88 - 35) + 35) * 3.7;
  }
};

var headEl4 = document.createElement('h2');
headEl4.textContent = 'South Lake Union data';
document.body.appendChild(headEl4);

var paragraphEl = document.createElement('ul');
paragraphEl.textContent = 'Todays estimated coffee needs for South Lake Union are: ' + kiosk4.generate(35, 88) + ' pounds.'
document.body.appendChild(paragraphEl);

var kiosk5 = {
  place: 'SeaTac',
  minCus: 68,
  maxCus: 124,
  cupsPerCus: 1.1,
  poundsPerCus: 2.7,

  generate: function() {
    return Math.random() * ((124 - 68) + 68) * 2.7;
  }
};

var headEl5 = document.createElement('h2');
headEl5.textContent = 'SeaTac data';
document.body.appendChild(headEl5);

var paragraphEl = document.createElement('ul');
paragraphEl.textContent = 'Todays estimated coffee needs for SeaTac are: ' + kiosk5.generate(68, 124) + ' pounds.'
document.body.appendChild(paragraphEl);

var kiosk6 = {
  place: 'Web Sales',
  minCus: 3,
  maxCus: 6,
  cupsPerCus: 0,
  poundsPerCus: 6.7,

  generate: function() {
    return Math.random() * ((6 - 3) + 3) * 6.7;
  }
};

var headEl6 = document.createElement('h2');
headEl6.textContent = 'Web Sales data';
document.body.appendChild(headEl6);

var paragraphEl = document.createElement('ul');
paragraphEl.textContent = 'Todays estimated coffee needs for Web Sales are: ' + kiosk6.generate(3, 6) + ' pounds.'
document.body.appendChild(paragraphEl);

// var duck = {
//   material: 'rubber',
//   color: 'yellow',
//   squeaks: false,
//   favoriteFoods: ['duckweed', 'peanut butter', 'children'],
//
//   says: function() {
//     console.log('QUACK');
//   }
// };
//
// var paragraphEl = document.createElement('p')
// paragraphEl.textContent = duck.favoriteFoods
// document.body.appendChild(ParagraphEl)
<|endoftext|>


<commit_before>/* Magic Mirror
 * The Core App (Server)
 *
 * By Michael Teeuw http://michaelteeuw.nl
 * MIT Licensed.
 */

var fs = require("fs");
var Server = require(__dirname + "/server.js");
var Utils = require(__dirname + "/utils.js");
var defaultModules = require(__dirname + "/../modules/default/defaultmodules.js");
var path = require("path");

// Get version number.
global.version = JSON.parse(fs.readFileSync("package.json", "utf8")).version;
console.log("Starting MagicMirror: v" + global.version);

// global absolute root path
global.root_path = path.resolve(__dirname + "/../");

if (process.env.MM_CONFIG_FILE) {
	global.configuration_file = process.env.MM_CONFIG_FILE;
}

// FIXME: Hotfix Pull Request
// https://github.com/MichMich/MagicMirror/pull/673
if (process.env.MM_PORT) {
	global.mmPort = process.env.MM_PORT;
}

// The next part is here to prevent a major exception when there
// is no internet connection. This could probable be solved better.
process.on("uncaughtException", function (err) {
	console.log("Whoops! There was an uncaught exception...");
	console.error(err);
	console.log("MagicMirror will not quit, but it might be a good idea to check why this happened. Maybe no internet connection?");
	console.log("If you think this really is an issue, please open an issue on GitHub: https://github.com/MichMich/MagicMirror/issues");
});

/* App - The core app.
 */
var App = function() {
	var nodeHelpers = [];

	/* loadConfig(callback)
	 * Loads the config file. combines it with the defaults,
	 * and runs the callback with the found config as argument.
	 *
	 * argument callback function - The callback function.
	 */

	var loadConfig = function(callback) {
		console.log("Loading config ...");
		var defaults = require(__dirname + "/defaults.js");

		// For this check proposed to TestSuite
		// https://forum.magicmirror.builders/topic/1456/test-suite-for-magicmirror/8
		var configFilename = path.resolve(global.root_path + "/config/config.js");
		if (typeof(global.configuration_file) !== "undefined") {
		    configFilename = path.resolve(global.configuration_file);
		}

		try {
			fs.accessSync(configFilename, fs.F_OK);
			var c = require(configFilename);
			checkDeprecatedOptions(c);
			var config = Object.assign(defaults, c);
			callback(config);
		} catch (e) {
			if (e.code == "ENOENT") {
				console.error(Utils.colors.error("WARNING! Could not find config file. Please create one. Starting with default configuration."));
			} else if (e instanceof ReferenceError || e instanceof SyntaxError) {
				console.error(Utils.colors.error("WARNING! Could not validate config file. Please correct syntax errors. Starting with default configuration."));
			} else {
				console.error(Utils.colors.error("WARNING! Could not load config file. Starting with default configuration. Error found: " + e));
			}
			callback(defaults);
		}
	};

	var checkDeprecatedOptions = function(userConfig) {
		var deprecated = require(global.root_path + "/js/deprecated.js");
		var deprecatedOptions = deprecated.configs;

		var usedDeprecated = [];

		deprecatedOptions.forEach(function(option) {
			if (userConfig.hasOwnProperty(option)) {
				usedDeprecated.push(option);
			}
		});
		if (usedDeprecated.length > 0) {
			console.warn(Utils.colors.warn(
				"WARNING! Your config is using deprecated options: " +
				usedDeprecated.join(", ") +
				". Check README and CHANGELOG for more up-to-date ways of getting the same functionality.")
			);
		}
	}

	/* loadModule(module)
	 * Loads a specific module.
	 *
	 * argument module string - The name of the module (including subpath).
	 */
	var loadModule = function(module, callback) {

		var elements = module.split("/");
		var moduleName = elements[elements.length - 1];
		var moduleFolder =  __dirname + "/../modules/" + module;

		if (defaultModules.indexOf(moduleName) !== -1) {
			moduleFolder =  __dirname + "/../modules/default/" + module;
		}

		var helperPath = moduleFolder + "/node_helper.js";

		var loadModule = true;
		try {
			fs.accessSync(helperPath, fs.R_OK);
		} catch (e) {
			loadModule = false;
			console.log("No helper found for module: " + moduleName + ".");
		}

		if (loadModule) {
			var Module = require(helperPath);
			var m = new Module();

			if (m.requiresVersion) {
				console.log("Check MagicMirror version for node helper '" + moduleName + "' - Minimum version:  " + m.requiresVersion + " - Current version: " + global.version);
				if (cmpVersions(global.version, m.requiresVersion) >= 0) {
					console.log("Version is ok!");
				} else {
					console.log("Version is incorrect. Skip module: '" + moduleName + "'");
					return;
				}
			}

			m.setName(moduleName);
			m.setPath(path.resolve(moduleFolder));
			nodeHelpers.push(m);

			m.loaded(callback);
		} else {
			callback();
		}
	};

	/* loadModules(modules)
	 * Loads all modules.
	 *
	 * argument module string - The name of the module (including subpath).
	 */
	var loadModules = function(modules, callback) {
		console.log("Loading module helpers ...");

		var loadNextModule = function() {
			if (modules.length > 0) {
				var nextModule = modules[0];
				loadModule(nextModule, function() {
					modules = modules.slice(1);
					loadNextModule();
				});
			} else {
				// All modules are loaded
				console.log("All module helpers loaded.");
				callback();
			}
		};

		loadNextModule();
	};

	/* cmpVersions(a,b)
	 * Compare two symantic version numbers and return the difference.
	 *
	 * argument a string - Version number a.
	 * argument a string - Version number b.
	 */
	function cmpVersions(a, b) {
		var i, diff;
		var regExStrip0 = /(\.0+)+$/;
		var segmentsA = a.replace(regExStrip0, "").split(".");
		var segmentsB = b.replace(regExStrip0, "").split(".");
		var l = Math.min(segmentsA.length, segmentsB.length);

		for (i = 0; i < l; i++) {
			diff = parseInt(segmentsA[i], 10) - parseInt(segmentsB[i], 10);
			if (diff) {
				return diff;
			}
		}
		return segmentsA.length - segmentsB.length;
	}

	/* start(callback)
	 * This methods starts the core app.
	 * It loads the config, then it loads all modules.
	 * When it"s done it executs the callback with the config as argument.
	 *
	 * argument callback function - The callback function.
	 */
	this.start = function(callback) {

		loadConfig(function(c) {
			config = c;

			var modules = [];

			for (var m in config.modules) {
				var module = config.modules[m];
				if (modules.indexOf(module.module) === -1 && !module.disabled) {
					modules.push(module.module);
				}
			}

			loadModules(modules, function() {
				var server = new Server(config, function(app, io) {
					console.log("Server started ...");

					for (var h in nodeHelpers) {
						var nodeHelper = nodeHelpers[h];
						nodeHelper.setExpressApp(app);
						nodeHelper.setSocketIO(io);
						nodeHelper.start();
					}

					console.log("Sockets connected & modules started ...");

					if (typeof callback === "function") {
						callback(config);
					}

				});
			});
		});
	};
};

module.exports = new App();
<commit_msg>Update app.js<commit_after>/* Smart Mirror
 * The Core App (Server)
 */

var fs = require("fs");
var Server = require(__dirname + "/server.js");
var Utils = require(__dirname + "/utils.js");
var defaultModules = require(__dirname + "/../modules/default/defaultmodules.js");
var path = require("path");

// Get version number.
global.version = JSON.parse(fs.readFileSync("package.json", "utf8")).version;
console.log("Starting SmartMirror: v" + global.version);

// global absolute root path
global.root_path = path.resolve(__dirname + "/../");

if (process.env.MM_CONFIG_FILE) {
	global.configuration_file = process.env.MM_CONFIG_FILE;
}

// FIXME: Hotfix Pull Request
// https://github.com/ShivamShrivastava/SmartMirror/pull/673
if (process.env.MM_PORT) {
	global.mmPort = process.env.MM_PORT;
}

// The next part is here to prevent a major exception when there
// is no internet connection. This could probable be solved better.
process.on("uncaughtException", function (err) {
	console.log("Whoops! There was an uncaught exception...");
	console.error(err);
	console.log("SmartMirror will not quit, but it might be a good idea to check why this happened. Maybe no internet connection?");
	console.log("If you think this really is an issue, please open an issue on GitHub: https://github.com/ShivamShrivastava/SmartMirror/issues");
});

/* App - The core app.
 */
var App = function() {
	var nodeHelpers = [];

	/* loadConfig(callback)
	 * Loads the config file. combines it with the defaults,
	 * and runs the callback with the found config as argument.
	 *
	 * argument callback function - The callback function.
	 */

	var loadConfig = function(callback) {
		console.log("Loading config ...");
		var defaults = require(__dirname + "/defaults.js");

		// For this check proposed to TestSuite
		// https://forum.smartmirror.builders/topic/1456/test-suite-for-smartmirror/8
		var configFilename = path.resolve(global.root_path + "/config/config.js");
		if (typeof(global.configuration_file) !== "undefined") {
		    configFilename = path.resolve(global.configuration_file);
		}

		try {
			fs.accessSync(configFilename, fs.F_OK);
			var c = require(configFilename);
			checkDeprecatedOptions(c);
			var config = Object.assign(defaults, c);
			callback(config);
		} catch (e) {
			if (e.code == "ENOENT") {
				console.error(Utils.colors.error("WARNING! Could not find config file. Please create one. Starting with default configuration."));
			} else if (e instanceof ReferenceError || e instanceof SyntaxError) {
				console.error(Utils.colors.error("WARNING! Could not validate config file. Please correct syntax errors. Starting with default configuration."));
			} else {
				console.error(Utils.colors.error("WARNING! Could not load config file. Starting with default configuration. Error found: " + e));
			}
			callback(defaults);
		}
	};

	var checkDeprecatedOptions = function(userConfig) {
		var deprecated = require(global.root_path + "/js/deprecated.js");
		var deprecatedOptions = deprecated.configs;

		var usedDeprecated = [];

		deprecatedOptions.forEach(function(option) {
			if (userConfig.hasOwnProperty(option)) {
				usedDeprecated.push(option);
			}
		});
		if (usedDeprecated.length > 0) {
			console.warn(Utils.colors.warn(
				"WARNING! Your config is using deprecated options: " +
				usedDeprecated.join(", ") +
				". Check README and CHANGELOG for more up-to-date ways of getting the same functionality.")
			);
		}
	}

	/* loadModule(module)
	 * Loads a specific module.
	 *
	 * argument module string - The name of the module (including subpath).
	 */
	var loadModule = function(module, callback) {

		var elements = module.split("/");
		var moduleName = elements[elements.length - 1];
		var moduleFolder =  __dirname + "/../modules/" + module;

		if (defaultModules.indexOf(moduleName) !== -1) {
			moduleFolder =  __dirname + "/../modules/default/" + module;
		}

		var helperPath = moduleFolder + "/node_helper.js";

		var loadModule = true;
		try {
			fs.accessSync(helperPath, fs.R_OK);
		} catch (e) {
			loadModule = false;
			console.log("No helper found for module: " + moduleName + ".");
		}

		if (loadModule) {
			var Module = require(helperPath);
			var m = new Module();

			if (m.requiresVersion) {
				console.log("Check SmartMirror version for node helper '" + moduleName + "' - Minimum version:  " + m.requiresVersion + " - Current version: " + global.version);
				if (cmpVersions(global.version, m.requiresVersion) >= 0) {
					console.log("Version is ok!");
				} else {
					console.log("Version is incorrect. Skip module: '" + moduleName + "'");
					return;
				}
			}

			m.setName(moduleName);
			m.setPath(path.resolve(moduleFolder));
			nodeHelpers.push(m);

			m.loaded(callback);
		} else {
			callback();
		}
	};

	/* loadModules(modules)
	 * Loads all modules.
	 *
	 * argument module string - The name of the module (including subpath).
	 */
	var loadModules = function(modules, callback) {
		console.log("Loading module helpers ...");

		var loadNextModule = function() {
			if (modules.length > 0) {
				var nextModule = modules[0];
				loadModule(nextModule, function() {
					modules = modules.slice(1);
					loadNextModule();
				});
			} else {
				// All modules are loaded
				console.log("All module helpers loaded.");
				callback();
			}
		};

		loadNextModule();
	};

	/* cmpVersions(a,b)
	 * Compare two symantic version numbers and return the difference.
	 *
	 * argument a string - Version number a.
	 * argument a string - Version number b.
	 */
	function cmpVersions(a, b) {
		var i, diff;
		var regExStrip0 = /(\.0+)+$/;
		var segmentsA = a.replace(regExStrip0, "").split(".");
		var segmentsB = b.replace(regExStrip0, "").split(".");
		var l = Math.min(segmentsA.length, segmentsB.length);

		for (i = 0; i < l; i++) {
			diff = parseInt(segmentsA[i], 10) - parseInt(segmentsB[i], 10);
			if (diff) {
				return diff;
			}
		}
		return segmentsA.length - segmentsB.length;
	}

	/* start(callback)
	 * This methods starts the core app.
	 * It loads the config, then it loads all modules.
	 * When it"s done it executs the callback with the config as argument.
	 *
	 * argument callback function - The callback function.
	 */
	this.start = function(callback) {

		loadConfig(function(c) {
			config = c;

			var modules = [];

			for (var m in config.modules) {
				var module = config.modules[m];
				if (modules.indexOf(module.module) === -1 && !module.disabled) {
					modules.push(module.module);
				}
			}

			loadModules(modules, function() {
				var server = new Server(config, function(app, io) {
					console.log("Server started ...");

					for (var h in nodeHelpers) {
						var nodeHelper = nodeHelpers[h];
						nodeHelper.setExpressApp(app);
						nodeHelper.setSocketIO(io);
						nodeHelper.start();
					}

					console.log("Sockets connected & modules started ...");

					if (typeof callback === "function") {
						callback(config);
					}

				});
			});
		});
	};
};

module.exports = new App();

<|endoftext|>


<commit_before>;(function(exports) {

  var RootView = new (NavigationView.extend({}))({
    el: $('#app')
  });

  var ChatList = BaseView.extend({
    collection: new MessageCollection(),

    title: 'Chat',
    rightBarButtons: [
      { html: '<button class="barButton">Settings</button>', click: 'settings' }
    ],

    events: {
      "keyup #new-message-text": 'toggleSendButton',
      "submit #new-message-form": 'send'
    },

    initialize: function() {
    	this.listenTo(this.collection, 'reset', this.render);
    	this.listenTo(this.collection, 'add', this.addMessage);
    	if(!this.collection.hasUsername()) this.settings();
    },

    // navigation view calls render
    render: function() {
      delete this.$textField, this.$button;
      this.$el.empty();

      this.$el.html(Templates['messages-list']({
        has_messages: this.collection.length > 0,
        messages: this.collection.map(this.renderMessage, this).join('')
      }));

      this.$textField = this.$('#new-message-text');
      this.$button = this.$('#new-message-button');

      // scroll to last message if there is one
      var last_message = this.$('.chat-message:last-child');
      if(last_message && last_message.length > 0) {
        _.defer(function() { last_message[0].scrollIntoView(); });
      }
    },
    renderMessage: function(message) {
      return Templates.message(message.toJSON());
    },

    addMessage: function(message) {
      var $message = $(this.renderMessage(message)),
          scrollParent = this.$el.parent(),
          isAtBottom = (scrollParent.scrollTop() + scrollParent.height() >= scrollParent[0].scrollHeight - 10);
      this.$('#chat-messages').append($message);
      // scroll to message if they are already scrolled to the bottom
      if(isAtBottom) {
        $message[0].scrollIntoView();
      }
    },

    toggleSendButton: function() {
      if(this.$textField.val() !== '') this.$button.removeAttr('disabled');
      else this.$button.attr('disabled', 'disabled');
    },

    send: function() {
      if(this.$textField.val() === '') return false;
      this.collection.send(this.$textField.val());
      this.$textField.val('');
      this.toggleSendButton();
      return false;
    },

    settings: function() {
      var modal = new ModalView();
      modal.pushView(new ChatSettings({ collection: this.collection }));
      $(document.body).append(modal.el);
      modal.show();
      return false;
    },

    cleanup: function() {
      delete this.$textField, this.$button;
      this._cleanup();
    }
  });

  var ChatSettings = BaseView.extend({
    title: 'Chat Settings',
    rightBarButtons: [
      { html: '<button class="barButton saveBarButton" disabled>Save</button>', click: 'done' }
    ],

    events: {
      "keyup #settings-username": 'updateSaveButton'
    },

    initialize: function() {},

    render: function() {
      this.$el.html(Templates.settings());
      this.$textField = this.$('#settings-username');
      this.$saveButton = this.navigation.$rightBarButtons.find('.saveBarButton');
      this.$textField.val(!this.collection.hasUsername() ? '' : this.collection.getUsername());
      this.updateSaveButton();
    },

    updateSaveButton: function() {
      if(this.$textField.val() !== '') this.$saveButton.removeAttr('disabled');
      else this.$saveButton.attr('disabled', 'disabled');
    },

    done: function() {
      this.collection.setUsername(this.$('#settings-username').val());
      this.navigation.hide(function() {
        this.cleanup();
      });
    },

    cleanup: function() {
      delete this.$textField, this.$saveButton;
      this._cleanup();
    }
  });

  RootView.pushView( new ChatList() );

  window.addEventListener('load', function() {
    new FastClick(document.body);
  }, false);

})(this);
<commit_msg>fix scroll detection<commit_after>;(function(exports) {

  var RootView = new (NavigationView.extend({}))({
    el: $('#app')
  });

  var ChatList = BaseView.extend({
    collection: new MessageCollection(),

    title: 'Chat',
    rightBarButtons: [
      { html: '<button class="barButton">Settings</button>', click: 'settings' }
    ],

    events: {
      "keyup #new-message-text": 'toggleSendButton',
      "submit #new-message-form": 'send'
    },

    initialize: function() {
    	this.listenTo(this.collection, 'reset', this.render);
    	this.listenTo(this.collection, 'add', this.addMessage);
    	if(!this.collection.hasUsername()) this.settings();
    },

    // navigation view calls render
    render: function() {
      delete this.$textField, this.$button;
      this.$el.empty();

      this.$el.html(Templates['messages-list']({
        has_messages: this.collection.length > 0,
        messages: this.collection.map(this.renderMessage, this).join('')
      }));

      this.$textField = this.$('#new-message-text');
      this.$button = this.$('#new-message-button');

      // scroll to last message if there is one
      var last_message = this.$('.chat-message:last-child');
      if(last_message && last_message.length > 0) {
        _.defer(function() { last_message[0].scrollIntoView(); });
      }
    },
    renderMessage: function(message) {
      return Templates.message(message.toJSON());
    },

    addMessage: function(message) {
      var $message = $(this.renderMessage(message)),
          scrollParent = this.$('#chat-messages'),
          isAtBottom = (scrollParent.scrollTop() + scrollParent.height() >= scrollParent[0].scrollHeight - 10);
      this.$('#chat-messages').append($message);
      // scroll to message if they are already scrolled to the bottom
      if(isAtBottom) {
        $message[0].scrollIntoView();
      }
    },

    toggleSendButton: function() {
      if(this.$textField.val() !== '') this.$button.removeAttr('disabled');
      else this.$button.attr('disabled', 'disabled');
    },

    send: function() {
      if(this.$textField.val() === '') return false;
      this.collection.send(this.$textField.val());
      this.$textField.val('');
      this.toggleSendButton();
      return false;
    },

    settings: function() {
      var modal = new ModalView();
      modal.pushView(new ChatSettings({ collection: this.collection }));
      $(document.body).append(modal.el);
      modal.show();
      return false;
    },

    cleanup: function() {
      delete this.$textField, this.$button;
      this._cleanup();
    }
  });

  var ChatSettings = BaseView.extend({
    title: 'Chat Settings',
    rightBarButtons: [
      { html: '<button class="barButton saveBarButton" disabled>Save</button>', click: 'done' }
    ],

    events: {
      "keyup #settings-username": 'updateSaveButton'
    },

    initialize: function() {},

    render: function() {
      this.$el.html(Templates.settings());
      this.$textField = this.$('#settings-username');
      this.$saveButton = this.navigation.$rightBarButtons.find('.saveBarButton');
      this.$textField.val(!this.collection.hasUsername() ? '' : this.collection.getUsername());
      this.updateSaveButton();
    },

    updateSaveButton: function() {
      if(this.$textField.val() !== '') this.$saveButton.removeAttr('disabled');
      else this.$saveButton.attr('disabled', 'disabled');
    },

    done: function() {
      this.collection.setUsername(this.$('#settings-username').val());
      this.navigation.hide(function() {
        this.cleanup();
      });
    },

    cleanup: function() {
      delete this.$textField, this.$saveButton;
      this._cleanup();
    }
  });

  RootView.pushView( new ChatList() );

  window.addEventListener('load', function() {
    new FastClick(document.body);
  }, false);

})(this);
<|endoftext|>


<commit_before>$(document).ready(function() {
    $('#loader').fadeIn(500).hide(0);
    $('#landing_page').fadeIn(1000).show(0);
    jQuery.validator.addMethod("lettersonly", function(value, element) {
        return this.optional(element) || /^[a-z0-9_-]+$/i.test(value);
    }, "Please use only a-z0-9_-");
    $('#form-signin').submit(function(e) {
        e.preventDefault();
    }).validate({
        rules: {
            login: {
                minlength: 3,
                maxlength: 15,
                required: true,
                lettersonly: true
            },
            password: {
                minlength: 3,
                maxlength: 15,
                required: true,
                lettersonly: true
            }
        },
        highlight: function(element) {
            $(element).closest('.control-group').addClass('has-error');
        },
        unhighlight: function(element) {
            $(element).closest('.control-group').removeClass('has-error');
        },
        submitHandler: function(form) {
            //submit via ajax
            $('html,body').animate({
                    scrollTop: $("#status_board").offset().top
                },
                'slow');

            $('#landing_left').fadeIn(1000).hide();
            $('#landing_right').fadeIn(1000).hide();
            $('#status_board1').slideDown("slow");
            $('#page1').fadeIn(1000).show();
            $('#footer').fadeIn(1000).show();

            return false; //This doesn't prevent the form from submitting.
        }
    });

    $('#addItem').click(function(e) {
        e.preventDefault();
    });

    $('#box').blur(function() {
        var number_of_box = $('#box').val();
        var perCost = $('#perCost').val();
        var total = number_of_box * perCost;
        $('#totalCost').val(total);
    });

    if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
        console.log("Incompatible");
        $('#landing_page').css('display','none');
        $('.mobile_device_error').removeClass('hide');
    }
    $("button").submit(function(e) {
        e.preventDefault();

        var target = e || window.event;
        var target = e.target || e.srcElement;
        var divNum = target.id;
        console.log(divNum);
        if (divNum == 'submit1' && $('input[type="text"]').hasClass('has-error')) {
            return;
        } else {
            $('html,body').animate({
                    scrollTop: $("#page1").offset().top
                },
                'slow');
        }
    });

});
<commit_msg>Delete app.js<commit_after><|endoftext|>