<commit_before>const FETCH_DELAY = 1000;
var outstandingUrls = [];
var currentUrl = null;

function elts(root, t) { return root.getElementsByTagName(t); }

/* Ah, irony. */

NodeList.prototype.eltEach = function(f) {
    for (var i = 0; i < this.length; i++) f(this[i]);
}

/* An overly-simple XMLHttpRequest wrapper */

function xhrGet(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.onreadystatechange = function(resp) {
        if (xhr.readyState == 4)
            callback(xhr);
    };
    xhr.send();
}

/* The services list seems to be incomplete, so prefill with my
 * favorites for now. Fetch it on init so we can pick up any new
 * additions. */

var services = {
    'j.mp': true,
    'flic.kr': true
};

xhrGet('http://api.longurl.org/v2/services', function(xhr) {
    elts(xhr.responseXML, 'service').eltEach(function(s) {
        services[s.textContent] = true;
    });
});

chrome.extension.onConnect.addListener(function(port) {
    switch (port.name) {
    case 'explodeUrlRequest':
        port.onMessage.addListener(handleReq);
        break;
    }
});

function handleReq(msg) {
    if (localStorage[msg.url]) {
        console.log('cached: ' + msg.url);
        sendDone(msg.url);
    } else if (services[hostForUrl(msg.url)]) {
        console.log('new: ' + msg.url);
        outstandingUrls.push(msg.url);
        fetchUrls();
    }
}

function hostForUrl(url) {
    var a = document.createElement('a');
    a.href = url;
    return a.hostname;
}

function expanderUrl(url) {
    return 'http://api.longurl.org/v2/expand?user-agent=Explode%2F0.1' +
        '&title=1&url=' + url;
}

function fetchUrls() {
    if (!currentUrl && outstandingUrls.length > 0) {
        currentUrl = outstandingUrls.shift();
        var url = currentUrl;
        xhrGet(expanderUrl(url), function(xhr) {
            localStorage[url] = JSON.stringify({
                longUrl: extract(xhr, 'long-url'),
                title: extract(xhr, 'title')
            });
            sendDone(url);
            currentUrl = null;
            setTimeout(fetchUrls, FETCH_DELAY);
        });
    }
}

function extract(xhr, n) {
    try {
        return elts(xhr.responseXML, n)[0].textContent;
    } catch(e) {
        return null;
    }
}

function sendDone(url) {
    chrome.tabs.getSelected(null, function(tab) {
        var port = chrome.tabs.connect(tab.id, {name: 'explodeUrlDone'});
        var info = JSON.parse(localStorage[url]);
        port.postMessage({
            url: url,
            longUrl: info.longUrl,
            title: info.title
        });
    });
}
<commit_msg>Don't refetch when duplicate links<commit_after>const FETCH_DELAY = 1000;
var outstandingUrls = [];
var currentUrl = null;

function elts(root, t) { return root.getElementsByTagName(t); }

/* Ah, irony. */

NodeList.prototype.eltEach = function(f) {
    for (var i = 0; i < this.length; i++) f(this[i]);
}

/* An overly-simple XMLHttpRequest wrapper */

function xhrGet(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.onreadystatechange = function(resp) {
        if (xhr.readyState == 4)
            callback(xhr);
    };
    xhr.send();
}

/* The services list seems to be incomplete, so prefill with my
 * favorites for now. Fetch it on init so we can pick up any new
 * additions. */

var services = {
    'j.mp': true,
    'flic.kr': true
};

xhrGet('http://api.longurl.org/v2/services', function(xhr) {
    elts(xhr.responseXML, 'service').eltEach(function(s) {
        services[s.textContent] = true;
    });
});

chrome.extension.onConnect.addListener(function(port) {
    switch (port.name) {
    case 'explodeUrlRequest':
        port.onMessage.addListener(handleReq);
        break;
    }
});

function handleReq(msg) {
    if (localStorage[msg.url]) {
        console.log('cached: ' + msg.url);
        sendDone(msg.url);
    } else if (services[hostForUrl(msg.url)]) {
        console.log('new: ' + msg.url);
        outstandingUrls.push(msg.url);
        fetchUrls();
    }
}

function hostForUrl(url) {
    var a = document.createElement('a');
    a.href = url;
    return a.hostname;
}

function expanderUrl(url) {
    return 'http://api.longurl.org/v2/expand?user-agent=Explode%2F0.1' +
        '&title=1&url=' + url;
}

function fetchUrls() {
    if (!currentUrl && outstandingUrls.length > 0) {
        currentUrl = outstandingUrls.shift();
        if (localStorage[currentUrl]) {
            currentUrl = null;
            setTimeout(fetchUrls, FETCH_DELAY);
        } else {
            xhrGet(expanderUrl(currentUrl), function(xhr) {
                localStorage[currentUrl] = JSON.stringify({
                    longUrl: extract(xhr, 'long-url'),
                    title: extract(xhr, 'title')
                });
                sendDone(currentUrl);
                currentUrl = null;
                setTimeout(fetchUrls, FETCH_DELAY);
            });
        }
    }
}

function extract(xhr, n) {
    try {
        return elts(xhr.responseXML, n)[0].textContent;
    } catch(e) {
        return null;
    }
}

function sendDone(url) {
    chrome.tabs.getSelected(null, function(tab) {
        var port = chrome.tabs.connect(tab.id, {name: 'explodeUrlDone'});
        var info = JSON.parse(localStorage[url]);
        port.postMessage({
            url: url,
            longUrl: info.longUrl,
            title: info.title
        });
    });
}
<|endoftext|>


<commit_before>(function(){
	'use strict';

	// https://en.wikipedia.org/wiki/List_of_pitch_intervals
	// https://en.wikipedia.org/wiki/Equal_temperament

	var oscillators = {};
	var stringGains = {};
	var setGains = {};

	function stopAll(){
		Object.keys(oscillators).forEach(function(key){
			oscillators[key].stop();
			oscillators[key].disconnect();
		});
		Object.keys(stringGains).forEach(function(key){
			stringGains[key].disconnect();
		});
		Object.keys(setGains).forEach(function(key){
			setGains[key].disconnect();
		});

		oscillators = {};
		stringGains = {};
		setGains = {};
	}

	/*
	function addFreq(ctx, freq){
		var o = ctx.createOscillator();
		o.type = 'sine';
		o.frequency.value = freq;
		o.start();
		return o;
	}
	*/

	var ctx;
	try{
		ctx = new (window.AudioContext || window.webkitAudioContext)();
	}catch(e){
		alert('Web Audio API is not supported by this browser.\nTo see, which browsers support the Web Audio API, visit: http://caniuse.com/#feat=audio-api');
	}

	var mainGain = ctx.createGain();
	mainGain.connect(ctx.destination);
	mainGain.gain.value = 1;

	// ---------------------

	var app = angular.module('Microtonal', []);

	app.directive('stringToNumber', function() {
		return {
			require: 'ngModel',
			link: function(scope, element, attrs, ngModel) {
				ngModel.$parsers.push(function(value) {
					return '' + value;
				});
				ngModel.$formatters.push(function(value) {
					return parseFloat(value, 10);
				});
			}
		};
	});

	var lastStringId = 0;
	var lastSetId = 0;

	app.controller('MonochordCtrl', ['$scope', '$http', '$rootScope', '$location', function($scope, $http, $rootScope, $location){
		$scope.baseFrequency = 100;
		$scope.sets = [];
		$scope.presets = {};
		$scope.presetVolume = 0;
		$scope._normalizeStringTargets = {};

		function findSetById(setId, run){
			$scope.sets.some(function(set, index, array){
				if(set.id === setId){
					run(set, index, array);
					return true;
				}
			});
		}
		function findStringById(stringId, run){
			$scope.sets.some(function(set){
				return set.strings.some(function(string, index, array){
					if(string.id === stringId){
						run(string, index, array, set);
						return true;
					}
				});
			});
		}
		function getNormalizeStringTargets(excludedSetId){
			var list = [{
				label : 'Base frequency (' + $scope.baseFrequency + ' Hz)',
				value : 0,
				group : 'Miscellaneous'
			}];

			$scope.sets.forEach(function(set, index){
				if(set.id !== excludedSetId){
					set.strings.forEach(function(string){
						list.push({
							label : 'String with harmonic level ' + string.multiplier,
							value : string.id,
							group : 'String set #' + (index + 1)
						});
					});
				}
			});

			return list;
		}

		$scope.addSet = function(){
			$scope.sets.push({
				id : ++lastSetId,
				normalize : {
					type : 'off',
					subject : 0,
					target : 0
				},
				volume : 100,
				strings : []
			});
			return lastSetId;
		};
		$scope.removeSet = function(setId){
			findSetById(setId, function(set, index, array){
				array.splice(index, 1);
			});
		};

		$scope.addString = function(setId, multiplier, volume){
			findSetById(setId, function(set){
				set.strings.push({
					id : ++lastStringId,
					multiplier : multiplier || 1,
					volume : volume || 0
				});
			});
			return lastStringId;
		};
		$scope.removeString = function(stringId){
			findStringById(stringId, function(string, index, array){
				array.splice(index, 1);
			});
		};

		$scope.lowerHarmonics = function(setId){
			findSetById(setId, function(set){
				var ratios = [];
				set.strings.forEach(function(string){
					ratios.push(string.multiplier);
				});
				if(ratios.sort(function(a, b){
					return a - b;
				})[0] > 1){
					set.strings.forEach(function(string){
						string.multiplier--;
					});
				}
			});
		};
		$scope.raiseHarmonics = function(setId){
			findSetById(setId, function(set){
				var ratios = [];
				set.strings.forEach(function(string){
					ratios.push(string.multiplier);
				});
				if(ratios.sort(function(a, b){
					return b - a;
				})[0] < 100){
					set.strings.forEach(function(string){
						string.multiplier++;
					});
				}
			});
		};

		$scope.addPreset = function(ratio, volume){
			var setId = $scope.addSet();
			ratio.sort(function(a, b){
				return a - b;
			}).forEach(function(multiplier){
				$scope.addString(setId, multiplier, volume);
			});
		};

		function _import(){
			$scope.sets = [];
			stopAll();

			// todo, load from URL
			$scope.addPreset([4, 5, 6], 30);
			$scope.addPreset([21, 25], 30);

			// todo, load normalization
		};
		function _export(){
			return ''; // todo: export to url or localStorage?
		}

		function calculateFrequency(stringId, stack){
			var frequency;
			var baseFrequency;

			if(set.normalize.target > 0){
				stack = stack || [];
				if(stack.indexOf(stringId) !== -1){
					alert('Infinite normalization target loop! There are no sets, that normalize to the default baseFrequency!');
					return 0;
				}else{
					stack.push(stringId);
					baseFrequency = calculateFrequency(set.normalize.target, stack);
				}
			}else{
				baseFrequency = $scope.baseFrequency
			}

			findStringById(stringId, function(string, index, array, set){
				if(set.normalize.type === 'off'){
					frequency = baseFrequency * string.multiplier;
				}else{
					var normalizedBaseFreq;

					switch(set.normalize.type){
						case 'lowest' : {
							var ratios = [];
							set.strings.forEach(function(string){
								ratios.push(string.multiplier);
							});
							ratios = ratios.sort(function(a, b){
								return a - b;
							});
							normalizedBaseFreq = baseFrequency / ratios[0];
							break;
						}
						case 'highest' : {
							var ratios = [];
							set.strings.forEach(function(string){
								ratios.push(string.multiplier);
							});
							ratios = ratios.sort(function(a, b){
								return b - a;
							});
							normalizedBaseFreq = baseFrequency / ratios[0];
							break;
						}
						case 'manual' : {
							findStringById(set.normalize.subject, function(string){
								normalizedBaseFreq = baseFrequency / string.multiplier;
							})
							break;
						}
					}

					frequency = normalizedBaseFreq * string.multiplier;
				}
			});

			return frequency;
		}

		function calculateVolume(stringId){
			var volume = 0;
			findStringById(stringId, function(string){
				volume = string.volume / 100;
			});
			return volume;
		}
		function calculateMasterVolume(setId){
			var volume = 0;
			findSetById(setId, function(set){
				volume = set.volume / 100;
			});
			return volume;
		}

		function updateNormalizeStringTargets(){
			$scope._normalizeStringTargets = {};
			$scope.sets.forEach(function(set){
				$scope._normalizeStringTargets[set.id] = getNormalizeStringTargets(set.id);
			});
		}

		function updateFrequencies(){
			$scope.sets.forEach(function(set){
				set.strings.forEach(function(string){
					if(oscillators[string.id]){
						oscillators[string.id].frequency.value = calculateFrequency(string.id);
					}
				});
			});
		}

		$scope.$watch('baseFrequency', function(newValue, oldValue){
			if(newValue !== oldValue){
				updateFrequencies();
			}
			updateNormalizeStringTargets();
		});

		$scope.$watch('sets', function(newValue, oldValue){
			if(newValue !== oldValue){
				var sets = {
					added : [],
					removed : [],
					changed : []
				};
				var strings = {
					added : [],
					removed : [],
					changed : []
				};

				newValue.forEach(function(newSet){
					var group = 'added';
					var oldSet;
					oldValue.some(function(_oldSet){
						if(_oldSet.id === newSet.id){
							oldSet = _oldSet;
							group = 'changed';
							return true;
						}
					});

					sets[group].push(newSet);

					newSet.strings.forEach(function(newString){
						strings[
							group !== 'added'
							&& oldSet.strings.some(function(oldString){
								return oldString.id == newString.id;
							})
							? 'changed'
							: 'added'
						].push(newString);
					});
				});

				oldValue.forEach(function(oldSet){
					if(
						!sets.added.some(function(addedSet){
							return addedSet.id === oldSet.id;
						})
						&& !sets.changed.some(function(changedSet){
							return changedSet.id === oldSet.id;
						})
					){
						sets.removed.push(oldSet);
						oldSet.strings.forEach(function(oldString){
							strings.removed.push(oldString);
						});
					}else{
						oldSet.strings.forEach(function(oldString){
							if(
								!strings.added.some(function(addedString){
									return addedString.id === oldString.id;
								})
								&& !strings.changed.some(function(changedString){
									return changedString.id === oldString.id;
								})
							){
								strings.removed.push(oldString);
							}
						});
					}
				});

				// todo
				/*
				changed.forEach(function(string){
					oscillators[string.id].frequency.value = $scope.baseFrequency * string.multiplier;
					gains[string.id].gain.value = string.volume / 100;
				});

				added.forEach(function(string){
					var o = addFreq(ctx, $scope.baseFrequency * string.multiplier);
					var g = ctx.createGain();
					g.connect(mainGain);
					o.connect(g);
					g.gain.value = string.volume / 100;

					oscillators[string.id] = o;
					gains[string.id] = g;
				});

				removed.forEach(function(string){
					gains[string.id].disconnect(mainGain);
					oscillators[string.id].stop();
					delete gains[string.id];
					delete oscillators[string.id];
				});
				*/

				updateFrequencies();
				updateNormalizeStringTargets();
			}
		}, true);

		$http.get('presets.json').success(function(data){
			$scope.presets = data;
			$scope.activePresetTuning = $scope.presets.tunings[0];
		});

		_import();
	}]);
})();<commit_msg>fixed _import() not invoking the watcher<commit_after>(function(){
	'use strict';

	// https://en.wikipedia.org/wiki/List_of_pitch_intervals
	// https://en.wikipedia.org/wiki/Equal_temperament

	var oscillators = {};
	var stringGains = {};
	var setGains = {};

	function stopAll(){
		Object.keys(oscillators).forEach(function(key){
			oscillators[key].stop();
			oscillators[key].disconnect();
		});
		Object.keys(stringGains).forEach(function(key){
			stringGains[key].disconnect();
		});
		Object.keys(setGains).forEach(function(key){
			setGains[key].disconnect();
		});

		oscillators = {};
		stringGains = {};
		setGains = {};
	}

	/*
	function addFreq(ctx, freq){
		var o = ctx.createOscillator();
		o.type = 'sine';
		o.frequency.value = freq;
		o.start();
		return o;
	}
	*/

	var ctx;
	try{
		ctx = new (window.AudioContext || window.webkitAudioContext)();
	}catch(e){
		alert('Web Audio API is not supported by this browser.\nTo see, which browsers support the Web Audio API, visit: http://caniuse.com/#feat=audio-api');
	}

	var mainGain = ctx.createGain();
	mainGain.connect(ctx.destination);
	mainGain.gain.value = 1;

	// ---------------------

	var app = angular.module('Microtonal', []);

	app.directive('stringToNumber', function() {
		return {
			require: 'ngModel',
			link: function(scope, element, attrs, ngModel) {
				ngModel.$parsers.push(function(value) {
					return '' + value;
				});
				ngModel.$formatters.push(function(value) {
					return parseFloat(value, 10);
				});
			}
		};
	});

	var lastStringId = 0;
	var lastSetId = 0;

	app.controller('MonochordCtrl', ['$scope', '$http', '$rootScope', '$location', function($scope, $http, $rootScope, $location){
		$scope.baseFrequency = 100;
		$scope.sets = [];
		$scope.presets = {};
		$scope.presetVolume = 0;
		$scope._normalizeStringTargets = {};

		function findSetById(setId, run){
			$scope.sets.some(function(set, index, array){
				if(set.id === setId){
					run(set, index, array);
					return true;
				}
			});
		}
		function findStringById(stringId, run){
			$scope.sets.some(function(set){
				return set.strings.some(function(string, index, array){
					if(string.id === stringId){
						run(string, index, array, set);
						return true;
					}
				});
			});
		}
		function getNormalizeStringTargets(excludedSetId){
			var list = [{
				label : 'Base frequency (' + $scope.baseFrequency + ' Hz)',
				value : 0,
				group : 'Miscellaneous'
			}];

			$scope.sets.forEach(function(set, index){
				if(set.id !== excludedSetId){
					set.strings.forEach(function(string){
						list.push({
							label : 'String with harmonic level ' + string.multiplier,
							value : string.id,
							group : 'String set #' + (index + 1)
						});
					});
				}
			});

			return list;
		}

		$scope.addSet = function(){
			$scope.sets.push({
				id : ++lastSetId,
				normalize : {
					type : 'off',
					subject : 0,
					target : 0
				},
				volume : 100,
				strings : []
			});
			return lastSetId;
		};
		$scope.removeSet = function(setId){
			findSetById(setId, function(set, index, array){
				array.splice(index, 1);
			});
		};

		$scope.addString = function(setId, multiplier, volume){
			findSetById(setId, function(set){
				set.strings.push({
					id : ++lastStringId,
					multiplier : multiplier || 1,
					volume : volume || 0
				});
			});
			return lastStringId;
		};
		$scope.removeString = function(stringId){
			findStringById(stringId, function(string, index, array){
				array.splice(index, 1);
			});
		};

		$scope.lowerHarmonics = function(setId){
			findSetById(setId, function(set){
				var ratios = [];
				set.strings.forEach(function(string){
					ratios.push(string.multiplier);
				});
				if(ratios.sort(function(a, b){
					return a - b;
				})[0] > 1){
					set.strings.forEach(function(string){
						string.multiplier--;
					});
				}
			});
		};
		$scope.raiseHarmonics = function(setId){
			findSetById(setId, function(set){
				var ratios = [];
				set.strings.forEach(function(string){
					ratios.push(string.multiplier);
				});
				if(ratios.sort(function(a, b){
					return b - a;
				})[0] < 100){
					set.strings.forEach(function(string){
						string.multiplier++;
					});
				}
			});
		};

		$scope.addPreset = function(ratio, volume){
			var setId = $scope.addSet();
			ratio.sort(function(a, b){
				return a - b;
			}).forEach(function(multiplier){
				$scope.addString(setId, multiplier, volume);
			});
		};

		function _import(){
			$scope.sets = [];
			stopAll();

			// todo, load from URL
			$scope.addPreset([4, 5, 6], 30);
			$scope.addPreset([21, 25], 30);

			// todo, load normalization
		};
		function _export(){
			return ''; // todo: export to url or localStorage?
		}

		function calculateFrequency(stringId, stack){
			var frequency;
			var baseFrequency;

			if(set.normalize.target > 0){
				stack = stack || [];
				if(stack.indexOf(stringId) !== -1){
					alert('Infinite normalization target loop! There are no sets, that normalize to the default baseFrequency!');
					return 0;
				}else{
					stack.push(stringId);
					baseFrequency = calculateFrequency(set.normalize.target, stack);
				}
			}else{
				baseFrequency = $scope.baseFrequency
			}

			findStringById(stringId, function(string, index, array, set){
				if(set.normalize.type === 'off'){
					frequency = baseFrequency * string.multiplier;
				}else{
					var normalizedBaseFreq;

					switch(set.normalize.type){
						case 'lowest' : {
							var ratios = [];
							set.strings.forEach(function(string){
								ratios.push(string.multiplier);
							});
							ratios = ratios.sort(function(a, b){
								return a - b;
							});
							normalizedBaseFreq = baseFrequency / ratios[0];
							break;
						}
						case 'highest' : {
							var ratios = [];
							set.strings.forEach(function(string){
								ratios.push(string.multiplier);
							});
							ratios = ratios.sort(function(a, b){
								return b - a;
							});
							normalizedBaseFreq = baseFrequency / ratios[0];
							break;
						}
						case 'manual' : {
							findStringById(set.normalize.subject, function(string){
								normalizedBaseFreq = baseFrequency / string.multiplier;
							})
							break;
						}
					}

					frequency = normalizedBaseFreq * string.multiplier;
				}
			});

			return frequency;
		}

		function calculateVolume(stringId){
			var volume = 0;
			findStringById(stringId, function(string){
				volume = string.volume / 100;
			});
			return volume;
		}
		function calculateMasterVolume(setId){
			var volume = 0;
			findSetById(setId, function(set){
				volume = set.volume / 100;
			});
			return volume;
		}

		function updateNormalizeStringTargets(){
			$scope._normalizeStringTargets = {};
			$scope.sets.forEach(function(set){
				$scope._normalizeStringTargets[set.id] = getNormalizeStringTargets(set.id);
			});
		}

		function updateFrequencies(){
			$scope.sets.forEach(function(set){
				set.strings.forEach(function(string){
					if(oscillators[string.id]){
						oscillators[string.id].frequency.value = calculateFrequency(string.id);
					}
				});
			});
		}

		$scope.$watch('baseFrequency', function(newValue, oldValue){
			if(newValue !== oldValue){
				updateFrequencies();
			}
			updateNormalizeStringTargets();
		});

		$scope.$watch('sets', function(newValue, oldValue){
			if(newValue !== oldValue){
				var sets = {
					added : [],
					removed : [],
					changed : []
				};
				var strings = {
					added : [],
					removed : [],
					changed : []
				};

				newValue.forEach(function(newSet){
					var group = 'added';
					var oldSet;
					oldValue.some(function(_oldSet){
						if(_oldSet.id === newSet.id){
							oldSet = _oldSet;
							group = 'changed';
							return true;
						}
					});

					sets[group].push(newSet);

					newSet.strings.forEach(function(newString){
						strings[
							group !== 'added'
							&& oldSet.strings.some(function(oldString){
								return oldString.id == newString.id;
							})
							? 'changed'
							: 'added'
						].push(newString);
					});
				});

				oldValue.forEach(function(oldSet){
					if(
						!sets.added.some(function(addedSet){
							return addedSet.id === oldSet.id;
						})
						&& !sets.changed.some(function(changedSet){
							return changedSet.id === oldSet.id;
						})
					){
						sets.removed.push(oldSet);
						oldSet.strings.forEach(function(oldString){
							strings.removed.push(oldString);
						});
					}else{
						oldSet.strings.forEach(function(oldString){
							if(
								!strings.added.some(function(addedString){
									return addedString.id === oldString.id;
								})
								&& !strings.changed.some(function(changedString){
									return changedString.id === oldString.id;
								})
							){
								strings.removed.push(oldString);
							}
						});
					}
				});

				// todo
				/*
				changed.forEach(function(string){
					oscillators[string.id].frequency.value = $scope.baseFrequency * string.multiplier;
					gains[string.id].gain.value = string.volume / 100;
				});

				added.forEach(function(string){
					var o = addFreq(ctx, $scope.baseFrequency * string.multiplier);
					var g = ctx.createGain();
					g.connect(mainGain);
					o.connect(g);
					g.gain.value = string.volume / 100;

					oscillators[string.id] = o;
					gains[string.id] = g;
				});

				removed.forEach(function(string){
					gains[string.id].disconnect(mainGain);
					oscillators[string.id].stop();
					delete gains[string.id];
					delete oscillators[string.id];
				});
				*/

				updateFrequencies();
				updateNormalizeStringTargets();
			}
		}, true);

		$http.get('presets.json').success(function(data){
			$scope.presets = data;
			$scope.activePresetTuning = $scope.presets.tunings[0];
		});

		setTimeout(_import, 0);
	}]);
})();<|endoftext|>


<commit_before>import MenuBuilder from "../menubuilder";

const HelpMenu = MenuBuilder.extend({

  initialize: function(data) {
    return this.g = data.g;
  },

  render: function() {
    this.setName("Help");
    this.addNode("About the project", () => {
      return window.open("https://github.com/wilzbach/msa");
    });
    this.addNode("Report issues", () => {
      return window.open("https://github.com/wilzbach/msa/issues");
    });
    this.addNode("User manual", () => {
      return window.open("https://github.com/wilzbach/msa/wiki");
    });
    this.el.style.display = "inline-block";
    this.el.appendChild(this.buildDOM());
    return this;
  }
});
export default HelpMenu;
<commit_msg>fix link to user manual<commit_after>import MenuBuilder from "../menubuilder";

const HelpMenu = MenuBuilder.extend({

  initialize: function(data) {
    return this.g = data.g;
  },

  render: function() {
    this.setName("Help");
    this.addNode("About the project", () => {
      return window.open("https://github.com/wilzbach/msa");
    });
    this.addNode("Report issues", () => {
      return window.open("https://github.com/wilzbach/msa/issues");
    });
    this.addNode("User manual", () => {
      return window.open("https://github.com/wilzbach/msa/wiki/User-manual");
    });
    this.el.style.display = "inline-block";
    this.el.appendChild(this.buildDOM());
    return this;
  }
});
export default HelpMenu;
<|endoftext|>


<commit_before>
var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update
});

function preload() {
    game.load.tilemap('ClassicMap', '../assets/RoyalPac-mapV2.json', null, Phaser.Tilemap.TILED_JSON);
    game.load.image('tiles', '../assets/TileSet.png');
    game.load.image('star', '../assets/star.png');
    game.load.spritesheet('pacman','../assets/pacman_test.png',25,25,13);
}

var map;
var layer;
var player;
var tiles;
var tileset;
var cursors;

function create() {
    game.physics.startSystem(Phaser.Physics.ARCADE);

    //Création Map
    map = game.add.tilemap('ClassicMap', 'tiles');
    map.addTilesetImage('TileSet', 'tiles');
    layer = map.createLayer('Calque de Tile 1');
    layer.resizeWorld();

    map.setCollision(2);
    map.setCollision(1);

    game.physics.arcade.collide(player, layer);
    player = game.add.sprite(375,375,'pacman');

    game.physics.enable(player);

    player.body.collideWorldBounds = true;
    //player.body.setSize(23, 23, 0, 0);
    player.animations.add('left', [6, 5, 4], 10, true);
    player.animations.add('right', [9, 8, 7], 10, true);
    player.animations.add('down', [3, 2, 1], 10, true);
    player.animations.add('up', [12, 11, 10], 10, true);

    var m_un = new monster(game,200,300);
    game.add.existing(m_un);

    cursors = game.input.keyboard.createCursorKeys();
}

function update() {
  game.physics.arcade.collide(player, layer);

  //Get Tiles around player
  var leftTile = map.getTileWorldXY(player.position.x -30, player.position.y, 25, 25, layer).index;
  var rightTile = map.getTileWorldXY(player.position.x +30, player.position.y, 25, 25, layer).index;
  var upTile = map.getTileWorldXY(player.position.x, player.position.y +30, 25, 25, layer).index;
  var downTile = map.getTileWorldXY(player.position.x, player.position.y -30, 25, 25, layer).index;
  var isWall;

  if (cursors.left.isDown){
      //  Move to the left
      isWall = (leftTile == 1);
      if (isWall) {
        console.log("it s a wall");
      }
      if (!isWall){
        player.body.velocity.x = -150;
        player.body.velocity.y = 0;
        player.animations.play('left');
      }
  }
  if (cursors.right.isDown){
      //  Move to the right
      isWall = (rightTile == 1);
      if (isWall) {
        console.log("it s a wall");
      }
      if (!isWall){
        player.body.velocity.x = 150;
        player.body.velocity.y = 0;
        player.animations.play('right');
      }
  }
  if (cursors.up.isDown){
      //  Move up
      isWall = (upTile == 1);
      if (isWall) {
        console.log("it s a wall");
      }
      if (!isWall){
        player.body.velocity.y = -150;
        player.body.velocity.x = 0;
        player.animations.play('up');
      }
  }
  if (cursors.down.isDown){
      //  Move down
      isWall = (downTile == 1);
      if (isWall) {
        console.log("it s a wall");
      }
      if (!isWall){
        player.body.velocity.y = 150;
        player.body.velocity.x = 0;
        player.animations.play('down');
      }
  }

}

monster = function(game,x,y){
  Phaser.Sprite.call(this,game,x,y,'star');
}

monster.prototype = Object.create(Phaser.Sprite.prototype);
monster.prototype.constructor = monster;

monster.prototype.create = function(){
  game.physics.enable(this);
  game.physics.arcade.collide(this, layer);
}

monster.prototype.update = function(){
  //console.log("hello");
}

//bat les couilles wallah déconne pas<commit_msg>Test nouvelle facon de tourner<commit_after>
var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update
});

function preload() {
    game.load.tilemap('ClassicMap', '../assets/RoyalPac-mapV2.json', null, Phaser.Tilemap.TILED_JSON);
    game.load.image('tiles', '../assets/TileSet.png');
    game.load.image('star', '../assets/star.png');
    game.load.spritesheet('pacman','../assets/pacman_test.png',25,25,13);
}

var map;
var layer;
var player;
var tiles;
var tileset;
var cursors;

function create() {
    game.physics.startSystem(Phaser.Physics.ARCADE);

    //Création Map
    map = game.add.tilemap('ClassicMap', 'tiles');
    map.addTilesetImage('TileSet', 'tiles');
    layer = map.createLayer('Calque de Tile 1');
    layer.resizeWorld();

    map.setCollision(2);
    map.setCollision(1);

    game.physics.arcade.collide(player, layer);
    player = game.add.sprite(375,375,'pacman');

    game.physics.enable(player);

    player.body.collideWorldBounds = true;
    //player.body.setSize(23, 23, 0, 0);
    player.animations.add('left', [6, 5, 4], 10, true);
    player.animations.add('right', [9, 8, 7], 10, true);
    player.animations.add('down', [3, 2, 1], 10, true);
    player.animations.add('up', [12, 11, 10], 10, true);

    var m_un = new monster(game,200,300);
    game.add.existing(m_un);

    cursors = game.input.keyboard.createCursorKeys();
}

function update() {
  game.physics.arcade.collide(player, layer);

  //Get Tiles around player
  var leftTile = map.getTileWorldXY(player.position.x -25, player.position.y, 25, 25, layer).index;
  var rightTile = map.getTileWorldXY(player.position.x +25, player.position.y, 25, 25, layer).index;
  var upTile = map.getTileWorldXY(player.position.x, player.position.y +25, 25, 25, layer).index;
  var downTile = map.getTileWorldXY(player.position.x, player.position.y -25, 25, 25, layer).index;
  var isWall;

  if (cursors.left.isDown){
      //  Move to the left
      isWall = (leftTile == 136);
      if (isWall) {
        console.log("it s a wall");
      }
      if (!isWall){
        player.body.velocity.x = -150;
        player.body.velocity.y = 0;
        player.animations.play('left');
      }
  }
  if (cursors.right.isDown){
      //  Move to the right
      isWall = (rightTile == 136);
      if (isWall) {
        console.log("it s a wall");
      }
      if (!isWall){
        player.body.velocity.x = 150;
        player.body.velocity.y = 0;
        player.animations.play('right');
      }
  }
  if (cursors.up.isDown){
      //  Move up
      isWall = (upTile == 136);
      if (isWall) {
        console.log("it s a wall");
      }
      if (!isWall){
        player.body.velocity.y = -150;
        player.body.velocity.x = 0;
        player.animations.play('up');
      }
  }
  if (cursors.down.isDown){
      //  Move down
      isWall = (downTile == 136);
      if (isWall) {
        console.log("it s a wall");
      }
      if (!isWall){
        player.body.velocity.y = 150;
        player.body.velocity.x = 0;
        player.animations.play('down');
      }
  }

}

monster = function(game,x,y){
  Phaser.Sprite.call(this,game,x,y,'star');
}

monster.prototype = Object.create(Phaser.Sprite.prototype);
monster.prototype.constructor = monster;

monster.prototype.create = function(){
  game.physics.enable(this);
  game.physics.arcade.collide(this, layer);
}

monster.prototype.update = function(){
  //console.log("hello");
}

//bat les couilles wallah déconne pas<|endoftext|>


<commit_before>'use strict';

var GoogleMap = (function() {
  var $mapContent, mapMarkers, map, bounds;

  function init() {
    $mapContent = $('#content');
    $mapContent.height(window.innerHeight / 2);
    mapMarkers = [];
  }

  function processEventResults(json) {
    console.log('Maps got these results', json);
    let events = json._embedded.events;
    let eventObjects = events.map(event => {
      return {
        name: event.name,
        type: event.type,
        url: event.url,
        startDate: event.dates.start.localDate,
        venue: {
          name: event._embedded.venues[0].name,
          url: event._embedded.venues[0].url,
          location: event._embedded.venues[0].location
        }
      };
    });
    console.log(eventObjects);
    deleteMarkers();
    makeEventMarkers(eventObjects);
    setMarkers();
    resizeMap();
  }

  function makeEventMarkers(events) {
    mapMarkers = events
      .filter(event => {
        if (event.venue.location) {
          return event;
        }
      })
      .map(event => {
        let marker = new google.maps.Marker({
          position: new google.maps.LatLng(
            Number(event.venue.location.latitude),
            Number(event.venue.location.longitude)
          )
        });

        let infoWindow = new google.maps.InfoWindow({ content: makeEventInfoWindow(event) });

        marker.addListener('click', function() {
          infoWindow.open(map, marker);
        });
        return marker;
      });
  }

  function makeEventInfoWindow(event) {
    return `<h5 class='text-center'>${event.name}</h5>`;
  }

  function setMarkers() {
    if (mapMarkers.length < 1) {
      console.error('Nothin in map markers!');
      return;
    }
    mapMarkers.forEach(marker => marker.setMap(map));
  }

  function deleteMarkers() {
    if (mapMarkers.length < 1) {
      return;
    }
    mapMarkers.forEach(marker => marker.setMap(null));
    mapMarkers = [];
  }

  function resizeMap() {
    bounds = new google.maps.LatLngBounds();
    mapMarkers.forEach(marker => bounds.extend(marker.position));
    map.fitBounds(bounds);
  }

  function initMap() {
    // Map options - This is where the map starts
    var options = {
      zoom: 7,

      // This Lat and Long could be set as the intial page Lat and Long location
      center: { lat: 40.7128, lng: -74.0059 }
    };

    // New map
    map = new google.maps.Map(document.getElementById('content'), options);
  }
  EVT.on('init', init);
  EVT.on('eventResultsReturned', processEventResults);

  return {
    initMap: initMap
  };
})();
<commit_msg>Force only one info window open at a time<commit_after>'use strict';

var GoogleMap = (function() {
  var $mapContent, mapMarkers, map, bounds, infoWindow;

  function init() {
    $mapContent = $('#content');
    $mapContent.height(window.innerHeight / 2);
    mapMarkers = [];
    infoWindow = new google.maps.InfoWindow({});
  }

  function processEventResults(json) {
    console.log('Maps got these results', json);
    let events = json._embedded.events;
    let eventObjects = events.map(event => {
      return {
        name: event.name,
        type: event.type,
        url: event.url,
        startDate: event.dates.start.localDate,
        venue: {
          name: event._embedded.venues[0].name,
          url: event._embedded.venues[0].url,
          location: event._embedded.venues[0].location
        }
      };
    });
    console.log(eventObjects);
    deleteMarkers();
    makeEventMarkers(eventObjects);
    setMarkers();
    resizeMap();
  }

  function makeEventMarkers(events) {
    mapMarkers = events
      .filter(event => {
        if (event.venue.location) {
          return event;
        }
      })
      .map(event => {
        let marker = new google.maps.Marker({
          position: new google.maps.LatLng(
            Number(event.venue.location.latitude),
            Number(event.venue.location.longitude)
          )
        });

        marker.addListener('click', function() {
          infoWindow.close();
          infoWindow.setContent(makeEventInfoWindow(event));
          infoWindow.open(map, marker);
        });
        return marker;
      });
  }

  function makeEventInfoWindow(event) {
    return `<div class="infoWindow"><h5 class='text-center'>${event.name}</h5></div>`;
  }

  function setMarkers() {
    if (mapMarkers.length < 1) {
      console.error('Nothin in map markers!');
      return;
    }
    mapMarkers.forEach(marker => marker.setMap(map));
  }

  function deleteMarkers() {
    if (mapMarkers.length < 1) {
      return;
    }
    mapMarkers.forEach(marker => marker.setMap(null));
    mapMarkers = [];
  }

  function resizeMap() {
    bounds = new google.maps.LatLngBounds();
    mapMarkers.forEach(marker => bounds.extend(marker.position));
    map.fitBounds(bounds);
  }

  function initMap() {
    // Map options - This is where the map starts
    var options = {
      zoom: 7,

      // This Lat and Long could be set as the intial page Lat and Long location
      center: { lat: 40.7128, lng: -74.0059 }
    };

    // New map
    map = new google.maps.Map(document.getElementById('content'), options);
  }
  EVT.on('init', init);
  EVT.on('eventResultsReturned', processEventResults);

  return {
    initMap: initMap
  };
})();
<|endoftext|>


<commit_before>// modulr (c) 2010 codespeaks sàrl
// Freely distributable under the terms of the MIT license.
// For details, see:
//   http://github.com/codespeaks/modulr/blob/master/LICENSE

var modulr = (function(global) {
  var _modules = {},
      _moduleObjects = {},
      _exports = {},
      _oldDir = '',
      _currentDir = '',
      PREFIX = '__module__', // Prefix identifiers to avoid issues in IE.
      RELATIVE_IDENTIFIER_PATTERN = /^\.\.?\//;

  var _forEach = (function() {
    var hasOwnProp = Object.prototype.hasOwnProperty,
        DONT_ENUM_PROPERTIES = [
          'constructor',
          'toString',
          'toLocaleString',
          'valueOf',
          'hasOwnProperty',
          'isPrototypeOf',
          'propertyIsEnumerable'
        ],
        LENGTH = DONT_ENUM_PROPERTIES.length,
        DONT_ENUM_BUG = true;

    function _forEach(obj, callback) {
      for(var prop in obj) {
        if (hasOwnProp.call(obj, prop)) {
          callback(prop, obj[prop]);
        }
      }
    }

    for(var prop in { toString: true }) {
      DONT_ENUM_BUG = false
    }

    if (DONT_ENUM_BUG) {
      return function(obj, callback) {
         _forEach(obj, callback);
         for (var i = 0; i < LENGTH; i++) {
           var prop = DONT_ENUM_PROPERTIES[i];
           if (hasOwnProp.call(obj, prop)) {
             callback(prop, obj[prop]);
           }
         }
       }
    }

    return _forEach;
  })();

  function log(str) {
    if (global.console && console.log) { console.log(str); }
  }

  function require(identifier) {
    var fn, modObj,
        id = resolveIdentifier(identifier),
        key = PREFIX + id,
        expts = _exports[key];

    log('Required module "' + identifier + '".');

    if (!expts) {
      _exports[key] = expts = {};
      _moduleObjects[key] = modObj = { id: id };

      if (!require.main) { require.main = modObj; }

      fn = _modules[key];
      _oldDir = _currentDir;
      _currentDir = id.slice(0, id.lastIndexOf('/'));

      try {
        if (!fn) { throw 'Can\'t find module "' + identifier + '".'; }
        if (typeof fn === 'string') {
          fn = new Function('require', 'exports', 'module', fn);
        }
        fn(require, expts, modObj);
        _currentDir = _oldDir;
      } catch(e) {
        _currentDir = _oldDir;
        // We'd use a finally statement here if it wasn't for IE.
        throw e;
      }
    }
    return expts;
  }

  function resolveIdentifier(identifier) {
    var parts, part, path;

    if (!RELATIVE_IDENTIFIER_PATTERN.test(identifier)) {
      return identifier;
    }

    parts = (_currentDir + '/' + identifier).split('/');
    path = [];
    for (var i = 0, length = parts.length; i < length; i++) {
      part = parts[i];
      switch (part) {
        case '':
        case '.':
          continue;
        case '..':
          path.pop();
          break;
        default:
          path.push(part);
      }
    }
    return path.join('/');
  }

  function cache(id, fn) {
    var key = PREFIX + id;

    log('Cached module "' + id + '".');
    _modules[key] = fn;
  }

  function define(moduleDescriptors) {
    _forEach(moduleDescriptors, function(k, v) {
      _modules[PREFIX + k] = v;
    });
  }

  function ensure(identifiers, onAvailable, onMissing) {
    for (var i = 0, length = identifiers.length; i < length; i++) {
      var identifier = identifiers[i];
      if (!_modules[PREFIX + identifier]) {
        var error = new Error('Can\'t find module "' + identifier + '".')
        if (typeof onMissing === 'function') {
          onMissing(error);
          return;
        }
        throw error;
      }
    }
    onAvailable();
  }

  require.define = define;
  require.ensure = ensure;

  return {
    require: require,
    cache: cache
  };
})(this);
<commit_msg>Remove now deprecated modulr.cache method.<commit_after>// modulr (c) 2010 codespeaks sàrl
// Freely distributable under the terms of the MIT license.
// For details, see:
//   http://github.com/codespeaks/modulr/blob/master/LICENSE

var modulr = (function(global) {
  var _modules = {},
      _moduleObjects = {},
      _exports = {},
      _oldDir = '',
      _currentDir = '',
      PREFIX = '__module__', // Prefix identifiers to avoid issues in IE.
      RELATIVE_IDENTIFIER_PATTERN = /^\.\.?\//;

  var _forEach = (function() {
    var hasOwnProp = Object.prototype.hasOwnProperty,
        DONT_ENUM_PROPERTIES = [
          'constructor',
          'toString',
          'toLocaleString',
          'valueOf',
          'hasOwnProperty',
          'isPrototypeOf',
          'propertyIsEnumerable'
        ],
        LENGTH = DONT_ENUM_PROPERTIES.length,
        DONT_ENUM_BUG = true;

    function _forEach(obj, callback) {
      for(var prop in obj) {
        if (hasOwnProp.call(obj, prop)) {
          callback(prop, obj[prop]);
        }
      }
    }

    for(var prop in { toString: true }) {
      DONT_ENUM_BUG = false
    }

    if (DONT_ENUM_BUG) {
      return function(obj, callback) {
         _forEach(obj, callback);
         for (var i = 0; i < LENGTH; i++) {
           var prop = DONT_ENUM_PROPERTIES[i];
           if (hasOwnProp.call(obj, prop)) {
             callback(prop, obj[prop]);
           }
         }
       }
    }

    return _forEach;
  })();

  function log(str) {
    if (global.console && console.log) { console.log(str); }
  }

  function require(identifier) {
    var fn, modObj,
        id = resolveIdentifier(identifier),
        key = PREFIX + id,
        expts = _exports[key];

    log('Required module "' + identifier + '".');

    if (!expts) {
      _exports[key] = expts = {};
      _moduleObjects[key] = modObj = { id: id };

      if (!require.main) { require.main = modObj; }

      fn = _modules[key];
      _oldDir = _currentDir;
      _currentDir = id.slice(0, id.lastIndexOf('/'));

      try {
        if (!fn) { throw 'Can\'t find module "' + identifier + '".'; }
        if (typeof fn === 'string') {
          fn = new Function('require', 'exports', 'module', fn);
        }
        fn(require, expts, modObj);
        _currentDir = _oldDir;
      } catch(e) {
        _currentDir = _oldDir;
        // We'd use a finally statement here if it wasn't for IE.
        throw e;
      }
    }
    return expts;
  }

  function resolveIdentifier(identifier) {
    var parts, part, path;

    if (!RELATIVE_IDENTIFIER_PATTERN.test(identifier)) {
      return identifier;
    }

    parts = (_currentDir + '/' + identifier).split('/');
    path = [];
    for (var i = 0, length = parts.length; i < length; i++) {
      part = parts[i];
      switch (part) {
        case '':
        case '.':
          continue;
        case '..':
          path.pop();
          break;
        default:
          path.push(part);
      }
    }
    return path.join('/');
  }

  function define(moduleDescriptors) {
    _forEach(moduleDescriptors, function(k, v) {
      _modules[PREFIX + k] = v;
    });
  }

  function ensure(identifiers, onAvailable, onMissing) {
    for (var i = 0, length = identifiers.length; i < length; i++) {
      var identifier = identifiers[i];
      if (!_modules[PREFIX + identifier]) {
        var error = new Error('Can\'t find module "' + identifier + '".')
        if (typeof onMissing === 'function') {
          onMissing(error);
          return;
        }
        throw error;
      }
    }
    onAvailable();
  }

  require.define = define;
  require.ensure = ensure;

  return {
    require: require
  };
})(this);
<|endoftext|>


<commit_before>/*global require*/
var gulp = require('gulp');
var args = require('yargs').argv;
var config = require('./gulp.config')();
var del = require('del');
var $ = require('gulp-load-plugins')({lazy: true});

//var jshint = require('gulp-jshint');
//var jscs = require('gulp-jscs');
//var util = require('gulp-util');
//var gulpprint = require('gulp-print');
//var gulpif = require('gulp-if');

function log(msg) {
    'use strict';
    var item;
    if (typeof (msg) === 'object') {
        for (item in msg) {
            if (msg.hasOwnProperty(item)) {
                $.util.log($.util.colors.blue(msg[item]));
            }
        }
    } else {
        $.util.log($.util.colors.green(msg));
    }
}
//gulp vet --verbose
gulp.task('vet', function () {
    'use strict';
    log('Analyzing source with JSHint and JSCS');

    return gulp
        .src(config.alljs)
        .pipe($.if(args.verbose, $.print()))
        .pipe($.jscs())
        .pipe($.jshint())
        .pipe($.jshint.reporter('jshint-stylish', {verbose: true}))
        .pipe($.jshint.reporter('fail'));
});

function errorLogger(error) {
    log('Start of Error');
    log(error);
    log('End of Error');
    this.emit('end');
}

gulp.task('styles', ['clean-styles'], function () {
    'use strict';
    log('Compile Less --->CSS');

    return gulp
        .src(config.less) //TODO
        .pipe($.plumber())
        .pipe($.less())
        .pipe($.autoprefixer({browsers: ['last 2 version', '> 5%']}))
        .pipe(gulp.dest(config.temp));
});

function clean(path, done) {
    'use strict';
    log('Cleaning: ' + $.util.colors.blue(path));
    del(path).then(done());
}

gulp.task('clean-styles', function (done) {
    'use strict';
    log('Clean files');
    var files = config.temp + '**/*.css';
    clean(files, done);
});

gulp.task('less-watcher', function () {
    'use strict';
    gulp.watch([config.less], ['styles']);
});
<commit_msg>remove logger function<commit_after>/*global require*/
var gulp = require('gulp');
var args = require('yargs').argv;
var config = require('./gulp.config')();
var del = require('del');
var $ = require('gulp-load-plugins')({lazy: true});

//var jshint = require('gulp-jshint');
//var jscs = require('gulp-jscs');
//var util = require('gulp-util');
//var gulpprint = require('gulp-print');
//var gulpif = require('gulp-if');

function log(msg) {
    'use strict';
    var item;
    if (typeof (msg) === 'object') {
        for (item in msg) {
            if (msg.hasOwnProperty(item)) {
                $.util.log($.util.colors.blue(msg[item]));
            }
        }
    } else {
        $.util.log($.util.colors.green(msg));
    }
}
//gulp vet --verbose
gulp.task('vet', function () {
    'use strict';
    log('Analyzing source with JSHint and JSCS');

    return gulp
        .src(config.alljs)
        .pipe($.if(args.verbose, $.print()))
        .pipe($.jscs())
        .pipe($.jshint())
        .pipe($.jshint.reporter('jshint-stylish', {verbose: true}))
        .pipe($.jshint.reporter('fail'));
});

gulp.task('styles', ['clean-styles'], function () {
    'use strict';
    log('Compile Less --->CSS');

    return gulp
        .src(config.less) //TODO
        .pipe($.plumber())
        .pipe($.less())
        .pipe($.autoprefixer({browsers: ['last 2 version', '> 5%']}))
        .pipe(gulp.dest(config.temp));
});

function clean(path, done) {
    'use strict';
    log('Cleaning: ' + $.util.colors.blue(path));
    del(path).then(done());
}

gulp.task('clean-styles', function (done) {
    'use strict';
    log('Clean files');
    var files = config.temp + '**/*.css';
    clean(files, done);
});

gulp.task('less-watcher', function () {
    'use strict';
    gulp.watch([config.less], ['styles']);
});
<|endoftext|>


<commit_before>/* global exports */

// An example configuration file.
exports.config = {
  specs: ['e2e/**/*Spec.js'],
  baseUrl: 'http://localhost:8000',
  sauceUser: process.env.SAUCE_USERNAME,
  sauceKey: process.env.SAUCE_ACCESS_KEY,
  multiCapabilities: [{
    browserName: 'chrome',
    'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER
  }, {
    browserName: 'firefox',
    'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER
  }, {
    browserName: 'internet explorer',
    'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER
  }, {
    browserName: 'safari',
    'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER
  }],
  getPageTimeout: 2000
};
<commit_msg>ci(sauce): remove safari from test suite<commit_after>/* global exports */

// An example configuration file.
exports.config = {
  specs: ['e2e/**/*Spec.js'],
  baseUrl: 'http://localhost:8000',
  sauceUser: process.env.SAUCE_USERNAME,
  sauceKey: process.env.SAUCE_ACCESS_KEY,
  multiCapabilities: [{
    browserName: 'chrome',
    'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER
  }, {
    browserName: 'firefox',
    'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER
  }, {
    browserName: 'internet explorer',
    'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER
  // }, {
    // browserName: 'safari',
    // 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER
  }]
};
<|endoftext|>


<commit_before>const bcrypt = require('bcryptjs');
const salt   = 'YOUR_SALT'

require('./local-signup')(salt);
require('./local-login')(salt);
require('./helpers');
<commit_msg>added correct salt<commit_after>const bcrypt = require('bcryptjs');
const salt   = '$2a$10$wENMOiXaNvkXN9BmCbh4ZO';

require('./local-signup')(salt);
require('./local-login')(salt);
require('./helpers');
<|endoftext|>


<commit_before>import {Button} from 'widget/button'
import {ButtonGroup} from 'widget/buttonGroup'
import {Scrollable, ScrollableContainer} from 'widget/scrollable'
import {msg} from 'translate'
import React from 'react'
import Tagline from './tagline'
import Title from './title'
import image_01 from './intro/bhutan.jpg'
import image_02 from './intro/senegal.jpg'
import image_03 from './intro/namibia.jpg'
import image_04 from './intro/terminal.jpg'
import image_gee from './intro/tools/gee.png'
import image_jupyter from './intro/tools/jupyter.png'
import image_rstudio from './intro/tools/rstudio.png'
import image_shiny from './intro/tools/shiny.jpg'
import partner_ec from './intro/partners/ec.png'
import partner_esa from './intro/partners/esa.png'
import partner_eth from './intro/partners/eth.png'
import partner_formin from './intro/partners/formin.png'
import partner_germany from './intro/partners/germany.png'
import partner_gfoi from './intro/partners/gfoi.png'
import partner_google from './intro/partners/google.png'
import partner_jaxa from './intro/partners/jaxa.png'
import partner_jica from './intro/partners/jica.png'
import partner_kfw from './intro/partners/kfw.png'
import partner_nasa from './intro/partners/nasa.png'
import partner_nicfi from './intro/partners/nicfi.png'
import partner_openforis from './intro/partners/openforis.png'
import partner_sc from './intro/partners/sc.png'
import partner_servir from './intro/partners/servir.png'
import partner_sig from './intro/partners/sig.png'
import partner_wageningen from './intro/partners/wageningen.png'
import styles from './intro.module.css'

const signupUrl = 'https://docs.google.com/forms/d/e/1FAIpQLSci4hopXNtMOQKJzsUybaJETrAPQp8j6TCqycSBQ0XO37jBwA/viewform?c=0&w=1'

const Intro = ({onLaunch}) =>
    <ScrollableContainer>
        <Scrollable className={styles.intro}>

            <Info/>

        </Scrollable>
    </ScrollableContainer>

const Main = ({onLaunch}) =>

        <Title className={styles.title}/>
        <Tagline className={styles.tagline}/>
        <ButtonGroup layout='horizontal-nowrap' spacing='loose'>
            <Button
                look='default'
                size='x-large'
                air='more'
                label={msg('landing.signup')}
                tabIndex={1}
                linkUrl={signupUrl}
                linkTarget='_self'
                additionalClassName={styles.button}
            />
            <Button
                type='submit'
                look='apply'
                size='x-large'
                air='more'
                label={msg('landing.launch')}
                tabIndex={2}
                onClick={onLaunch}
                additionalClassName={styles.button}
            />
        </ButtonGroup>
        <ButtonGroup layout='horizontal-nowrap' alignment='center'>
            <Button
                look='transparent'
                shape='circle'
                size='xx-large'
                icon='chevron-down'
                onClick={scrollToInfo}
                additionalClassName={styles.pulse}
            />
        </ButtonGroup>

const Block = ({theme, image, imagePosition, maxImageSize, textKey, responsive, classNames = []}) =>

{msg(`${textKey}.title`)}

{msg(`${textKey}.description`)}

const Info = () =>

        <Block
            theme='dark'
            image={image_01}
            imagePosition='left'
            textKey='landing.intro.easeOfUse'
            responsive
        />
        <Block
            theme='dark'
            image={image_02}
            imagePosition='right'
            textKey='landing.intro.computingPower'
            responsive
        />
        <Block
            theme='light'
            image={image_gee}
            imagePosition='left'
            maxImageSize={150}
            textKey='landing.intro.googleEarthEngine'
            classNames={[styles.tool]}
        />
        <Block
            theme='light'
            image={image_jupyter}
            imagePosition='right'
            maxImageSize={150}
            textKey='landing.intro.jupyterNotebook'
            classNames={[styles.tool]}
        />
        <Block
            theme='light'
            image={image_shiny}
            imagePosition='left'
            maxImageSize={150}
            textKey='landing.intro.shiny'
            classNames={[styles.tool]}
        />
        <Block
            theme='light'
            image={image_rstudio}
            imagePosition='right'
            maxImageSize={150}
            textKey='landing.intro.rstudio'
            classNames={[styles.tool]}
        />
        <Block
            theme='dark'
            image={image_03}
            imagePosition='left'
            textKey='landing.intro.integrations'
            responsive
        />
        <Block
            theme='dark'
            image={image_04}
            imagePosition='right'
            textKey='landing.intro.powerUsers'
            responsive
        />
        <About/>
        <Partners/>

const About = () =>

{msg('landing.intro.about.title')}

{msg('landing.intro.about.description')}

const Partners = () =>

{msg('landing.intro.partners.title')}

const Footer = () =>
    <ButtonGroup
        className={styles.footer}
        layout='horizontal-nowrap'
        alignment='spaced'>
        <Button
            chromeless
            look='transparent'
            shape='pill'
            size='x-large'
            linkUrl='http://www.openforis.org'
            linkTarget='openforis'
            label='Openforis'>
        </Button>
        <Button
            chromeless
            look='transparent'
            shape='pill'
            size='x-large'
            linkUrl='https://github.com/openforis/sepal'
            linkTarget='github-project'
            label='GitHub'>
        </Button>
        <Button
            chromeless
            look='transparent'
            shape='pill'
            size='x-large'
            linkUrl='/privacy-policy'
            linkTarget='privacy-policy'
            label={msg('landing.privacyPolicy')}>
        </Button>
    </ButtonGroup>

const scrollToInfo = () =>
    document.getElementById('info').scrollIntoView({
        behavior: 'smooth'
    })

export default Intro
<commit_msg>Added keybindings to Intro.<commit_after>import {Button} from 'widget/button'
import {ButtonGroup} from 'widget/buttonGroup'
import {Scrollable, ScrollableContainer} from 'widget/scrollable'
import {msg} from 'translate'
import Keybinding from 'widget/keybinding'
import React from 'react'
import Tagline from './tagline'
import Title from './title'
import image_01 from './intro/bhutan.jpg'
import image_02 from './intro/senegal.jpg'
import image_03 from './intro/namibia.jpg'
import image_04 from './intro/terminal.jpg'
import image_gee from './intro/tools/gee.png'
import image_jupyter from './intro/tools/jupyter.png'
import image_rstudio from './intro/tools/rstudio.png'
import image_shiny from './intro/tools/shiny.jpg'
import partner_ec from './intro/partners/ec.png'
import partner_esa from './intro/partners/esa.png'
import partner_eth from './intro/partners/eth.png'
import partner_formin from './intro/partners/formin.png'
import partner_germany from './intro/partners/germany.png'
import partner_gfoi from './intro/partners/gfoi.png'
import partner_google from './intro/partners/google.png'
import partner_jaxa from './intro/partners/jaxa.png'
import partner_jica from './intro/partners/jica.png'
import partner_kfw from './intro/partners/kfw.png'
import partner_nasa from './intro/partners/nasa.png'
import partner_nicfi from './intro/partners/nicfi.png'
import partner_openforis from './intro/partners/openforis.png'
import partner_sc from './intro/partners/sc.png'
import partner_servir from './intro/partners/servir.png'
import partner_sig from './intro/partners/sig.png'
import partner_wageningen from './intro/partners/wageningen.png'
import styles from './intro.module.css'

const signupUrl = 'https://docs.google.com/forms/d/e/1FAIpQLSci4hopXNtMOQKJzsUybaJETrAPQp8j6TCqycSBQ0XO37jBwA/viewform?c=0&w=1'

const Intro = ({onLaunch}) =>
    <ScrollableContainer>
        <Scrollable className={styles.intro}>

            <Info/>

        </Scrollable>
    </ScrollableContainer>

const Main = ({onLaunch}) =>
    <Keybinding keymap={{'Enter': onLaunch, 'Escape': onLaunch}}>

            <Title className={styles.title}/>
            <Tagline className={styles.tagline}/>
            <ButtonGroup layout='horizontal-nowrap' spacing='loose'>
                <Button
                    look='default'
                    size='x-large'
                    air='more'
                    label={msg('landing.signup')}
                    tabIndex={1}
                    linkUrl={signupUrl}
                    linkTarget='_self'
                    additionalClassName={styles.button}
                />
                <Button
                    type='submit'
                    look='apply'
                    size='x-large'
                    air='more'
                    label={msg('landing.launch')}
                    tabIndex={2}
                    onClick={onLaunch}
                    additionalClassName={styles.button}
                />
            </ButtonGroup>
            <ButtonGroup layout='horizontal-nowrap' alignment='center'>
                <Button
                    look='transparent'
                    shape='circle'
                    size='xx-large'
                    icon='chevron-down'
                    onClick={scrollToInfo}
                    additionalClassName={styles.pulse}
                />
            </ButtonGroup>

    </Keybinding>

const Block = ({theme, image, imagePosition, maxImageSize, textKey, responsive, classNames = []}) =>

{msg(`${textKey}.title`)}

{msg(`${textKey}.description`)}

const Info = () =>

        <Block
            theme='dark'
            image={image_01}
            imagePosition='left'
            textKey='landing.intro.easeOfUse'
            responsive
        />
        <Block
            theme='dark'
            image={image_02}
            imagePosition='right'
            textKey='landing.intro.computingPower'
            responsive
        />
        <Block
            theme='light'
            image={image_gee}
            imagePosition='left'
            maxImageSize={150}
            textKey='landing.intro.googleEarthEngine'
            classNames={[styles.tool]}
        />
        <Block
            theme='light'
            image={image_jupyter}
            imagePosition='right'
            maxImageSize={150}
            textKey='landing.intro.jupyterNotebook'
            classNames={[styles.tool]}
        />
        <Block
            theme='light'
            image={image_shiny}
            imagePosition='left'
            maxImageSize={150}
            textKey='landing.intro.shiny'
            classNames={[styles.tool]}
        />
        <Block
            theme='light'
            image={image_rstudio}
            imagePosition='right'
            maxImageSize={150}
            textKey='landing.intro.rstudio'
            classNames={[styles.tool]}
        />
        <Block
            theme='dark'
            image={image_03}
            imagePosition='left'
            textKey='landing.intro.integrations'
            responsive
        />
        <Block
            theme='dark'
            image={image_04}
            imagePosition='right'
            textKey='landing.intro.powerUsers'
            responsive
        />
        <About/>
        <Partners/>

const About = () =>

{msg('landing.intro.about.title')}

{msg('landing.intro.about.description')}

const Partners = () =>

{msg('landing.intro.partners.title')}

const Footer = () =>
    <ButtonGroup
        className={styles.footer}
        layout='horizontal-nowrap'
        alignment='spaced'>
        <Button
            chromeless
            look='transparent'
            shape='pill'
            size='x-large'
            linkUrl='http://www.openforis.org'
            linkTarget='openforis'
            label='Openforis'>
        </Button>
        <Button
            chromeless
            look='transparent'
            shape='pill'
            size='x-large'
            linkUrl='https://github.com/openforis/sepal'
            linkTarget='github-project'
            label='GitHub'>
        </Button>
        <Button
            chromeless
            look='transparent'
            shape='pill'
            size='x-large'
            linkUrl='/privacy-policy'
            linkTarget='privacy-policy'
            label={msg('landing.privacyPolicy')}>
        </Button>
    </ButtonGroup>

const scrollToInfo = () =>
    document.getElementById('info').scrollIntoView({
        behavior: 'smooth'
    })

export default Intro
<|endoftext|>


<commit_before>
var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update
});

function preload() {
    game.load.tilemap('ClassicMap', '../assets/RoyalPac-mapV2.json', null, Phaser.Tilemap.TILED_JSON);
    game.load.image('tiles', '../assets/TileSet.png');
    game.load.image('star', '../assets/star.png');
    game.load.spritesheet('pacman','../assets/pacman_test.png',25,25,13);
}

var map;
var layer;
var player;
var tiles;
var tileset;
var cursors;

function create() {
    game.physics.startSystem(Phaser.Physics.ARCADE);

    //Création Map
    map = game.add.tilemap('ClassicMap', 'tiles');
    map.addTilesetImage('TileSet', 'tiles');
    layer = map.createLayer('Calque de Tile 1');
    layer.resizeWorld();

    map.setCollision(2);
    map.setCollision(1);

    game.physics.arcade.collide(player, layer);
    player = game.add.sprite(375,375,'pacman');

    game.physics.enable(player);

    player.body.collideWorldBounds = true;
    //player.body.setSize(23, 23, 0, 0);
    player.animations.add('left', [6, 5, 4], 10, true);
    player.animations.add('right', [9, 8, 7], 10, true);
    player.animations.add('down', [3, 2, 1], 10, true);
    player.animations.add('up', [12, 11, 10], 10, true);

    var m_un = new monster(game,200,300);
    game.add.existing(m_un);

    cursors = game.input.keyboard.createCursorKeys();
}

function canGoDown(player, layer, map){ // le + 24 c'est pour quoi ?
    return((map.getTileWorldXY(player.position.x + (24), player.position.y +25, 25, 25, layer).index == 136) && (map.getTileWorldXY(player.position.x, player.position.y +25, 25, 25, layer).index == 136));
}

function canGoUp(player, layer, map){
//     return((map.getTileWorldXY(player.position.x + (24), player.position.y +25, 25, 25, layer).index == 136) && (map.getTileWorldXY(player.position.x, player.position.y -25, 25, 25, layer).index == 136));
}

function canGoRight(player, layer, map){
//     return((map.getTileWorldXY(player.position.x + (24), player.position.y +25, 25, 25, layer).index == 136) && (map.getTileWorldXY(player.position.x +25, player.position.y, 25, 25, layer).index == 136));
}

function canGoLeft(player, layer, map){
//     return((map.getTileWorldXY(player.position.x + (24), player.position.y +25, 25, 25, layer).index == 136) && (map.getTileWorldXY(player.position.x -25, player.position.y, 25, 25, layer).index == 136));
}

function update() {
  game.physics.arcade.collide(player, layer);

  //Get Tiles around player
  var leftTile = map.getTileWorldXY(player.position.x -1, player.position.y, 25, 25, layer).index;
  var rightTile = map.getTileWorldXY(player.position.x +25, player.position.y, 25, 25, layer).index;
  var upTile = map.getTileWorldXY(player.position.x, player.position.y -1, 25, 25, layer).index;
  var downTile = map.getTileWorldXY(player.position.x, player.position.y +25, 25, 25, layer).index;
  var isWall;

  if (canGoDown(player,layer,map)) {
    console.log("il y a un passage en dessous");
  }

  //Actuellement ne fonctionne presque correctement qu'à gauche, les autres directions c'est un peu random
  if (cursors.left.isDown){
      //  Move to the left
      isWall = (leftTile == 2);
      if (isWall) {
        console.log("it s a wall");
      }
      if (!isWall){
        player.body.velocity.x = -50;
        player.body.velocity.y = 0;
        player.animations.play('left');
      }
  }
  if (cursors.right.isDown){
      //  Move to the right
      isWall = (rightTile == 2);
      if (isWall) {
        console.log("it s a wall");
      }
      if (!isWall){
        player.body.velocity.x = 50;
        player.body.velocity.y = 0;
        player.animations.play('right');
      }
  }
  if (cursors.up.isDown){
      //  Move up
      isWall = (upTile == 2);
      if (isWall) {
        console.log("it s a wall");
      }
      if (!isWall){
        player.body.velocity.y = -50;
        player.body.velocity.x = 0;
        player.animations.play('up');
      }
  }
  if (cursors.down.isDown){
      //  Move down
      isWall = (downTile == 2);
      if (isWall) {
        console.log("it s a wall");
      }
      if (!isWall){
        player.body.velocity.y = 50;
        player.body.velocity.x = 0;
        player.animations.play('down');
      }
  }

}

monster = function(game,x,y){
  Phaser.Sprite.call(this,game,x,y,'star');
}

monster.prototype = Object.create(Phaser.Sprite.prototype);
monster.prototype.constructor = monster;

monster.prototype.create = function(){
  game.physics.enable(this);
  game.physics.arcade.collide(this, layer);
}

monster.prototype.update = function(){
  //console.log("hello");
}

//bat les couilles wallah déconne pas<commit_msg>Je dois go au Leclerc<commit_after>
var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update
});

function preload() {
    game.load.tilemap('ClassicMap', '../assets/RoyalPac-mapV2.json', null, Phaser.Tilemap.TILED_JSON);
    game.load.image('tiles', '../assets/TileSet.png');
    game.load.image('star', '../assets/star.png');
    game.load.spritesheet('pacman','../assets/pacman_test.png',25,25,13);
}

var map;
var layer;
var player;
var tiles;
var tileset;
var cursors;

function create() {
    game.physics.startSystem(Phaser.Physics.ARCADE);

    //Création Map
    map = game.add.tilemap('ClassicMap', 'tiles');
    map.addTilesetImage('TileSet', 'tiles');
    layer = map.createLayer('Calque de Tile 1');
    layer.resizeWorld();

    map.setCollision(2);
    map.setCollision(1);

    game.physics.arcade.collide(player, layer);
    player = game.add.sprite(375,375,'pacman');

    game.physics.enable(player);

    player.body.collideWorldBounds = true;
    //player.body.setSize(23, 23, 0, 0);
    player.animations.add('left', [6, 5, 4], 10, true);
    player.animations.add('right', [9, 8, 7], 10, true);
    player.animations.add('down', [3, 2, 1], 10, true);
    player.animations.add('up', [12, 11, 10], 10, true);

    var m_un = new monster(game,200,300);
    game.add.existing(m_un);

    cursors = game.input.keyboard.createCursorKeys();
}

function canGo(direction, player, layer, map){ // le + 24 c'est pour quoi ?
    if (direction == 'down') {
        return((map.getTileWorldXY(player.position.x + (24), player.position.y +25, 25, 25, layer).index == 136) && (map.getTileWorldXY(player.position.x, player.position.y +25, 25, 25, layer).index == 136)); //down
    }
    if (direction == 'up') {
        return((map.getTileWorldXY(player.position.x + (24), player.position.y +25, 25, 25, layer).index == 136) && (map.getTileWorldXY(player.position.x, player.position.y -25, 25, 25, layer).index == 136)); //up
    }
    if (direction == 'right'){
        return((map.getTileWorldXY(player.position.x + (24), player.position.y +25, 25, 25, layer).index == 136) && (map.getTileWorldXY(player.position.x +25, player.position.y, 25, 25, layer).index == 136)); //right
    }
    if (direction == 'left') {
        return((map.getTileWorldXY(player.position.x + (24), player.position.y +25, 25, 25, layer).index == 136) && (map.getTileWorldXY(player.position.x -25, player.position.y, 25, 25, layer).index == 136)); //left
    }
}

pacman = function(){
    pacman.direction;
}
pacman.prototype.constructor = pacman;

function update() {
  game.physics.arcade.collide(player, layer);

  if (canGo('left',player,layer,map) || canGo('right',player,layer,map) || canGo('up',player,layer,map) || canGo('down',player,layer,map)) {
    console.log("ça paaaasse !");
    console.log("LeftTile = " + map.getTileWorldXY(player.position.x -25, player.position.y, 25, 25, layer).index);
    console.log("RightTile = " + map.getTileWorldXY(player.position.x +25, player.position.y, 25, 25, layer).index);
    console.log("UpTile = " + map.getTileWorldXY(player.position.x, player.position.y -25, 25, 25, layer).index);
    console.log("DownTile = " + map.getTileWorldXY(player.position.x, player.position.y +25, 25, 25, layer).index);
}
    var caPasse = canGo('left',player,layer,map) + canGo('right',player,layer,map) + canGo('up',player,layer,map) + canGo('down',player,layer,map);
    if (caPasse) {
        console.log("caPasse = true");
    }
    else {
        console.log("caPasse = false");
    }
  //Actuellement ne fonctionne presque correctement qu'à gauche, les autres directions c'est un peu random
  if (cursors.left.isDown){
      //  Move to the left

      if (caPasse){
        player.body.velocity.x = -50;
        player.body.velocity.y = 0;
        player.animations.play('left');
        pacman.direction = 'left';
      }
  }
  if (cursors.right.isDown){
      //  Move to the right
      if (caPasse){
        player.body.velocity.x = 50;
        player.body.velocity.y = 0;
        player.animations.play('right');
        pacman.direction = 'right';
      }
  }
  if (cursors.up.isDown){
      //  Move up
      if (caPasse){
        player.body.velocity.y = -50;
        player.body.velocity.x = 0;
        player.animations.play('up');
        pacman.direction = 'up';
      }
  }
  if (cursors.down.isDown){
      //  Move down
      if (caPasse){
        player.body.velocity.y = 50;
        player.body.velocity.x = 0;
        player.animations.play('down');
        pacman.direction = 'down';
      }
  }

}

monster = function(game,x,y){
  Phaser.Sprite.call(this,game,x,y,'star');
}

monster.prototype = Object.create(Phaser.Sprite.prototype);
monster.prototype.constructor = monster;

monster.prototype.create = function(){
  game.physics.enable(this);
  game.physics.arcade.collide(this, layer);
}

monster.prototype.update = function(){
  //console.log("hello");
}

//bat les couilles wallah déconne pas
<|endoftext|>


<commit_before>//Start Parallax Animation
$('.parallax').parallax();

//Declare JQuery Selectors
var $submitBtn = $(".submit-btn");
var $nextBtn = $(".next-btn");
var $downExplainBtn = $("#down-explain");
var $downEmotchaBtn = $("#down-emotcha");
var $loginBtn = $(".login-btn");
var $exampleImg = $("#example-img");

//Initialize Video Variable
var video = document.querySelector('video');
var capturing = false;
var finished = false;
var firstFinish = true;
var updateInterval;

//Initialize Canvas Elements
var canvas = document.createElement('canvas');

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

canvas.width = 450;
canvas.height = 450;

var image = "happy.jpg"
//Initialize Emotional Varialbes
var exampleEmotions;
var liveEmotions;
var metric;

//Get Initial Example
getExample();

//On Click Functions
$submitBtn.click(function(){
    //Logic for play pause restart button on live card
    if(finished){
        getExample();
        $submitBtn.children().replaceWith("");
        $submitBtn.toggleClass('red', true);
        $submitBtn.toggleClass('green', false);
        $loginBtn.toggleClass('disabled', true);
        $('.how-to').toggleClass('hide', false);
        finished = false
    } else if(capturing){
        pauseCapture();
    } else {
        captureVideo();
    }
})

$nextBtn.click(function() {
    //Logic for new example button on example card
    getExample();
})

$downExplainBtn.click(function() {
    //First movement button
    console.log("down to explain")
    $.smoothScroll({scrollElemnt: $('.explaination-container'), scrollTarget: '#explanation-target', offset: -$('.explanation-container').height(), speed: 1000});
})

$downEmotchaBtn.click(function() {
    //second movement button
    $.smoothScroll({scrollElemnt: $('.emotcha-container'), scrollTarget: '#emotcha-target', offset: -75, speed: 1000, afterScroll: function(){
        setTimeout(captureVideo, 200);
        capturing = true;
    }});
})

$loginBtn.click(function(){
    //Sets alerts for login buttons
    if(!$loginBtn.hasClass('disabled')){
        alert('You could now sucessfully login if this was a real site!');
    } else {
        alert('You need to match emotional profiles with the picture on the left');
    }
});

function getExample() {
    //fetch picture and emotional profile from server
    console.log("button pushed")
    $.get('/image', {image:image})
    .done(function (data, status){
        exampleEmotions = data.emotions;
        image = data.file
        $exampleImg.attr('src', 'images/'+data.file);
        $('#ex-angry').css('width', (exampleEmotions.Angry*100)+'%');
        $('#ex-sad').css('width', (exampleEmotions.Sad*100)+'%');
        $('#ex-neutral').css('width', (exampleEmotions.Neutral*100)+'%');
        $('#ex-surprise').css('width', (exampleEmotions.Surprise*100)+'%');
        $('#ex-fear').css('width', (exampleEmotions.Fear*100)+'%');
        $('#ex-happy').css('width', (exampleEmotions.Happy*100)+'%');
    })
    .error(function (data, status){
        console.log(status);
    })
}

function pauseCapture(){
    //Grab image from video and put it on canvas, pause video
    capturing = false;
    ctx.drawImage(video, 0, 0, 600, 450);
    $(video).replaceWith(canvas);
    clearInterval(updateInterval);
    $('.submit-btn').children().replaceWith("");
    var dataURI = canvas.toDataURL('image/jpg');
    postImage(dataURI);
}

function update(){
    //Grab image from video, find face, and send to server every second
    ctx.drawImage(video, 0, 0, 600, 450);
    var dataURI = canvas.toDataURL('image/jpg');
    postImage(dataURI);
}

function postImage(dataURI){
    //send face to server and respond by changing bars
    $.post("/image", {data: dataURI})
    .done(function (data, status) {
        if (data['status'] === "found"){
            console.log("face!")
            data = data['data']
            liveEmotions = data;
            $('#lv-angry').css('width', (data.Angry*100)+'%');
            $('#lv-sad').css('width', (data.Sad*100)+'%');
            $('#lv-neutral').css('width', (data.Neutral*100)+'%');
            $('#lv-surprise').css('width', (data.Surprise*100)+'%');
            $('#lv-fear').css('width', (data.Fear*100)+'%');
            $('#lv-happy').css('width', (data.Happy*100)+'%');

            //Measure if emotions close enough to unlock system
            diffs =[Math.abs(liveEmotions.Angry - exampleEmotions.Angry),
                    Math.abs(liveEmotions.Sad - exampleEmotions.Sad),
                    Math.abs(liveEmotions.Neutral - exampleEmotions.Neutral),
                    Math.abs(liveEmotions.Surprise - exampleEmotions.Surprise),
                    Math.abs(liveEmotions.Fear - exampleEmotions.Fear),
                    Math.abs(liveEmotions.Happy - exampleEmotions.Happy)]

            sum = 0;
            for(i=0; i<diffs.length; i++){
                sum+= diffs[i];
            }

            metric = 2 - sum;

            if(metric>1.5){
                $submitBtn.children('i').replaceWith("");
                $submitBtn.toggleClass('red', false);
                $submitBtn.toggleClass('green', true);
                $loginBtn.toggleClass('disabled', false);
                $('.how-to').toggleClass('hide', true);
                finished = true;
                if(firstFinish){
                    alert("You've sucessfuly matched emotional profiles and unlocked the login button, tap the green arrow on your portrait to try again or the login button to complete the demo login");
                    firstFinish = false;
                }
            }
        }
    })
    .error(function (data, status){
        console.log(status);
    });
}

function captureVideo() {
    //Start webcam video playing

    navigator.getUserMedia  = navigator.getUserMedia ||navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

    if (navigator.getUserMedia) {
        navigator.getUserMedia({video: true}, function(stream) {
                video.src = window.URL.createObjectURL(stream);
        }, function (err){
            console.log("ERROR!", err);
        });
    }

    if(!capturing){
        $('canvas').replaceWith(video)
    };

    $('.submit-btn').children().replaceWith("");
    capturing = true;
    updateInterval = setInterval(update, 500);
}
<commit_msg>debug logs for heroku<commit_after>//Start Parallax Animation
$('.parallax').parallax();

//Declare JQuery Selectors
var $submitBtn = $(".submit-btn");
var $nextBtn = $(".next-btn");
var $downExplainBtn = $("#down-explain");
var $downEmotchaBtn = $("#down-emotcha");
var $loginBtn = $(".login-btn");
var $exampleImg = $("#example-img");

//Initialize Video Variable
var video = document.querySelector('video');
var capturing = false;
var finished = false;
var firstFinish = true;
var updateInterval;

//Initialize Canvas Elements
var canvas = document.createElement('canvas');

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

canvas.width = 450;
canvas.height = 450;

var image = "happy.jpg"
//Initialize Emotional Varialbes
var exampleEmotions;
var liveEmotions;
var metric;

//Get Initial Example
getExample();

//On Click Functions
$submitBtn.click(function(){
    //Logic for play pause restart button on live card
    if(finished){
        getExample();
        $submitBtn.children().replaceWith("");
        $submitBtn.toggleClass('red', true);
        $submitBtn.toggleClass('green', false);
        $loginBtn.toggleClass('disabled', true);
        $('.how-to').toggleClass('hide', false);
        finished = false
    } else if(capturing){
        pauseCapture();
    } else {
        captureVideo();
    }
})

$nextBtn.click(function() {
    //Logic for new example button on example card
    getExample();
})

$downExplainBtn.click(function() {
    //First movement button
    console.log("down to explain")
    $.smoothScroll({scrollElemnt: $('.explaination-container'), scrollTarget: '#explanation-target', offset: -$('.explanation-container').height(), speed: 1000});
})

$downEmotchaBtn.click(function() {
    //second movement button
    $.smoothScroll({scrollElemnt: $('.emotcha-container'), scrollTarget: '#emotcha-target', offset: -75, speed: 1000, afterScroll: function(){
        setTimeout(captureVideo, 200);
        capturing = true;
    }});
})

$loginBtn.click(function(){
    //Sets alerts for login buttons
    if(!$loginBtn.hasClass('disabled')){
        alert('You could now sucessfully login if this was a real site!');
    } else {
        alert('You need to match emotional profiles with the picture on the left');
    }
});

function getExample() {
    //fetch picture and emotional profile from server
    console.log("button pushed")
    $.get('/image', {image:image})
    .done(function (data, status){
        exampleEmotions = data.emotions;
        image = data.file
        $exampleImg.attr('src', 'images/'+data.file);
        $('#ex-angry').css('width', (exampleEmotions.Angry*100)+'%');
        $('#ex-sad').css('width', (exampleEmotions.Sad*100)+'%');
        $('#ex-neutral').css('width', (exampleEmotions.Neutral*100)+'%');
        $('#ex-surprise').css('width', (exampleEmotions.Surprise*100)+'%');
        $('#ex-fear').css('width', (exampleEmotions.Fear*100)+'%');
        $('#ex-happy').css('width', (exampleEmotions.Happy*100)+'%');
    })
    .error(function (data, status){
        console.log(status);
    })
}

function pauseCapture(){
    //Grab image from video and put it on canvas, pause video
    capturing = false;
    ctx.drawImage(video, 0, 0, 600, 450);
    $(video).replaceWith(canvas);
    clearInterval(updateInterval);
    $('.submit-btn').children().replaceWith("");
    var dataURI = canvas.toDataURL('image/jpg');
    postImage(dataURI);
}

function update(){
    //Grab image from video, find face, and send to server every second
    ctx.drawImage(video, 0, 0, 600, 450);
    var dataURI = canvas.toDataURL('image/jpeg', .5);
    postImage(dataURI);
}

function postImage(dataURI){
    //send face to server and respond by changing bars
    $.post("/image", {data: dataURI})
    .done(function (data, status) {
        if (data['status'] === "found"){
            console.log("face!")
            data = data['data']
            liveEmotions = data;
            $('#lv-angry').css('width', (data.Angry*100)+'%');
            $('#lv-sad').css('width', (data.Sad*100)+'%');
            $('#lv-neutral').css('width', (data.Neutral*100)+'%');
            $('#lv-surprise').css('width', (data.Surprise*100)+'%');
            $('#lv-fear').css('width', (data.Fear*100)+'%');
            $('#lv-happy').css('width', (data.Happy*100)+'%');

            //Measure if emotions close enough to unlock system
            diffs =[Math.abs(liveEmotions.Angry - exampleEmotions.Angry),
                    Math.abs(liveEmotions.Sad - exampleEmotions.Sad),
                    Math.abs(liveEmotions.Neutral - exampleEmotions.Neutral),
                    Math.abs(liveEmotions.Surprise - exampleEmotions.Surprise),
                    Math.abs(liveEmotions.Fear - exampleEmotions.Fear),
                    Math.abs(liveEmotions.Happy - exampleEmotions.Happy)]

            sum = 0;
            for(i=0; i<diffs.length; i++){
                sum+= diffs[i];
            }

            metric = 2 - sum;

            if(metric>1.5){
                $submitBtn.children('i').replaceWith("");
                $submitBtn.toggleClass('red', false);
                $submitBtn.toggleClass('green', true);
                $loginBtn.toggleClass('disabled', false);
                $('.how-to').toggleClass('hide', true);
                finished = true;
                if(firstFinish){
                    alert("You've sucessfuly matched emotional profiles and unlocked the login button, tap the green arrow on your portrait to try again or the login button to complete the demo login");
                    firstFinish = false;
                }
            }
        }
    })
    .error(function (data, status){
        console.log(status);
    });
}

function captureVideo() {
    //Start webcam video playing

    navigator.getUserMedia  = navigator.getUserMedia ||navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

    if (navigator.getUserMedia) {
        navigator.getUserMedia({video: true}, function(stream) {
                video.src = window.URL.createObjectURL(stream);
        }, function (err){
            console.log("ERROR!", err);
        });
    }

    if(!capturing){
        $('canvas').replaceWith(video)
    };

    $('.submit-btn').children().replaceWith("");
    capturing = true;
    updateInterval = setInterval(update, 500);
}
<|endoftext|>


<commit_before>Seed({
		name : "Mold.Lib.VDom.ValueNode",
		dna : "static"
	},
	function(){

		return function ValueNode(config){
			//°include Mold.Lib.VDom.ProtoNode

			this.type = VALUE_NODE;
			this.domPointer = false;
			this.isPointer = config.isPointer || false;
			this.hasParentValue = config.hasParentValue || false;
			this.filter = config.filter || false;
			this.parentName = false;
			this.childName = false;
			this.id = Mold.getId();

			var that = this;

			if(!this.isPointer && ~this.name.indexOf(".")){
				this.hasParentValue = true;
				this.parentName = config.name.split(".")[0];
				this.childName = config.name.split(".")[1];
			}

			this.onSetData = function(data, bind){

				if(Mold.isObject(data)){
					this.data = data[this.name]
				}

				if(data === false || !Mold.is(data)){
					this.data = "";
				}

				for(var filterName in this.filter){
					var filter = Mold.Lib.Filter.get(filterName);
					if(filter){
						this.data = filter(this.data, this.filter[filterName]);
					}
				}
			}

			this.clone = function(){
				var newNode =  new ValueNode({
					name : this.name,
					data : this.data,
					isString : this.isString
				});

				return newNode;
			}

			this.render = function(){
				if(!this.domPointer){
					this.domPointer = _doc.createTextNode(this.data);
				}else{
					this.domPointer.nodeValue = this.data;
				}
				return this.domPointer;
			}

			this.renderString = function(){
				return this.data;
			}

			this.setDataAndRender = function(data){
				if(data){
					this.setData(data);
				}
				if(this.isString){
					if(this.parent.type === ATTRIBUTE_NODE){
						this.parent.renderAttribute();
					}else{
						this.parent.render();
					}
				}else{
					this.render();
					this.domPointer.nodeValue = this.data;
				}

			}
		}
	}
)<commit_msg>services added, setData modified for 0 value<commit_after>Seed({
		name : "Mold.Lib.VDom.ValueNode",
		dna : "static"
	},
	function(){

		return function ValueNode(config){
			//°include Mold.Lib.VDom.ProtoNode

			this.type = VALUE_NODE;
			this.domPointer = false;
			this.isPointer = config.isPointer || false;
			this.hasParentValue = config.hasParentValue || false;
			this.hasIndexValue = config.hasIndexValue || false;
			this.filter = config.filter || false;
			this.parentName = false;
			this.childName = false;
			this.id = Mold.getId();

			var that = this;

			if(!this.isPointer && ~this.name.indexOf(".")){
				this.hasParentValue = true;
				this.parentName = config.name.split(".")[0];
				this.childName = config.name.split(".")[1];
			}

			if(!this.isPointer && ~this.name.indexOf("+")){
				this.hasIndexValue = true;
			}

			this.onSetData = function(data){
				if(Mold.isObject(data)){
					this.data = data[this.name]
				}

				if(data === false || !Mold.is(data)){
					this.data = "";
				}

				for(var filterName in this.filter){
					var filter = Mold.Lib.Filter.get(filterName);
					if(filter){
						this.data = filter(this.data, this.filter[filterName]);
					}
				}
			}

			this.clone = function(){
				var newNode =  new ValueNode({
					name : this.name,
					data : this.data,
					isString : this.isString,
					services : this.services
				});
				return newNode;
			}

			this.render = function(){

				if(!this.domPointer){
					this.domPointer = _doc.createTextNode(this.data);
				}else{
					this.domPointer.nodeValue = this.data;
				}

				return this.domPointer;
			}

			this.renderString = function(){
				return this.data;
			}

			this.setDataAndRender = function(data){
				this.setData(data);

				if(this.isString){
					if(this.parent.type === ATTRIBUTE_NODE){
						this.parent.renderAttribute();
					}else{
						this.parent.render();
					}
				}else{
					this.render();
					this.domPointer.nodeValue = this.data;
				}

			}
		}
	}
)<|endoftext|>