<commit_before>define([
	"dojo/_base/declare", "dojo/_base/lang",
	"dojo/request",
	"./TabViewerBase",
	"../FeatureOverview", "../GenomeBrowser", "../CompareRegionContainer",
	"../GeneExpressionContainer", "../CorrelatedGenesContainer", "../InteractionContainer",
	"../../util/PathJoin"

], function(declare, lang,
			xhr,
			TabViewerBase,
			FeatureOverview, GenomeBrowser, CompareRegionContainer,
			GeneExpressionContainer, CorrelatedGenesContainer, InteractionContainer,
			PathJoin){

	return declare([TabViewerBase], {
		"baseClass": "FeatureGroup",
		"disabled": false,
		containerType: "feature_group",
		feature_id: "",
		perspectiveLabel: "Feature View",
		perspectiveIconClass: "icon-selection-Feature",

		_setFeature_idAttr: function(id){

			if(!id){
				return;
			}

			if(this.feature_id == id){
				return;
			}

			this.state = this.state || {};
			this.feature_id = id;
			this.state.feature_id = id;

			if(id.match(/^fig/)){
				id = id.replace(/\|/g, '%7C');
				//console.log("fig id = ", id);
				id = "?eq(patric_id," + id + ")&limit(1)";
			}

			// console.log("Get Feature: ", id);
			xhr.get(PathJoin(this.apiServiceUrl, "genome_feature", id), {
				headers: {
					accept: "application/json",
					'X-Requested-With': null,
					'Authorization': (window.App.authorizationToken || "")
				},
				handleAs: "json"
			}).then(lang.hitch(this, function(feature){
				if(feature instanceof Array){
					// this.set("feature", feature[0])
					this.redirectToPATRICFeature(feature[0]);
				}else{
					// this.set("feature", feature)
					this.redirectToPATRICFeature(feature);
				}
			}));
		},

		setActivePanelState: function(){
			var activeQueryState;
			if(!this._started){
				console.log("Feature Viewer not started");
				return;
			}

			if(this.state.feature_id){
				activeQueryState = lang.mixin({}, this.state, {search: "eq(feature_id," + this.state.feature_id + ")"});
			}
			var active = (this.state && this.state.hashParams && this.state.hashParams.view_tab) ? this.state.hashParams.view_tab : "overview";
			var activeTab = this[active];

			switch(active){
				case "overview":
				case "correlatedGenes":
					if(this.state && this.state.feature){
						activeTab.set("state", lang.mixin({}, this.state));
					}
					break;
				case "interactions":
					if(this.state && this.state.feature){
						activeTab.set("state", lang.mixin({}, this.state, {
							search: "secondDegreeInteraction(" + this.state.feature.feature_id + ")"
						}));
					}
					break;
				default:
					if(activeQueryState){
						activeTab.set("state", activeQueryState);
					}
					break;
			}

			if(this.feature){
				var label = (this.feature.patric_id) ? this.feature.patric_id : (this.feature.refseq_locus_tag) ? this.feature.refseq_locus_tag : (this.feature.protein_id) ? this.feature.protein_id : this.feature.feature_id;
				var pageTitle = label + "::Feature " + activeTab.title;
				// console.log("Feature setActivePanelState: ", pageTitle);
				if(window.document.title !== pageTitle){
					window.document.title = pageTitle;
				}
			}
		},

		onSetState: function(attr, oldState, state){
			var parts = this.state.pathname.split("/");
			this.set("feature_id", parts[parts.length - 1]);
			state.feature_id = parts[parts.length - 1];

			if(state && state.feature_id && !state.feature){
				if(oldState && oldState.feature_id){
					if((state.feature_id == oldState.feature_id)){
						if(oldState.feature || this.feature){
							this.state.feature = state.feature = oldState.feature || this.feature;
						}else{
							console.log("oldState missing Featture");
						}
					}
				}
			}

			this.setActivePanelState();
			if(state.hashParams && state.hashParams.view_tab){

				if(this[state.hashParams.view_tab]){
					var vt = this[state.hashParams.view_tab];
					vt.set("visible", true);
					this.viewer.selectChild(vt);
				}else{
					console.log("No view-tab supplied in State Object");
				}
			}

			this.setActivePanelState();
		},

		buildHeaderContent: function(feature){

			xhr.get(PathJoin(this.apiServiceUrl, "taxonomy", feature.taxon_id), {
				headers: {
					accept: "application/json"
				},
				handleAs: "json"
			}).then(lang.hitch(this, function(taxon){
				var taxon_lineage_names = taxon.lineage_names;
				var taxon_lineage_ids = taxon.lineage_ids;
				var taxon_lineage_ranks = taxon.lineage_ranks;

				var visibleRanks = ["superkingdom", "phylum", "class", "order", "family", "genus", "species"];
				var visibleIndexes = taxon_lineage_ranks.filter(function(rank){
					return visibleRanks.indexOf(rank) > -1;
				}).map(function(rank){
					return taxon_lineage_ranks.indexOf(rank);
				});

				var out = visibleIndexes.map(function(idx){
					return '' + taxon_lineage_names[idx] + '';
				});
				this.queryNode.innerHTML = out.join(" » ") + " » " + lang.replace('{feature.genome_name}', {feature: feature});
			}));

			var content = [];
			if(feature.hasOwnProperty('patric_id')){
				content.push(feature.patric_id);
			}
			if(feature.hasOwnProperty('refseq_locus_tag')){
				content.push(feature.refseq_locus_tag);
			}
			if(feature.hasOwnProperty('gene')){
				content.push(feature.gene);
			}
			if(feature.hasOwnProperty('product')){
				content.push(feature.product);
			}

			this.totalCountNode.innerHTML = "
" + content.map(function(d){
					return '' + d + '';
				}).join(' | ');
		},

		redirectToPATRICFeature: function(feature){

			if(feature.annotation === 'PATRIC'){
				this.set("feature", feature);
			}else{
				if(feature.hasOwnProperty('pos_group')){
					xhr.get(PathJoin(this.apiServiceUrl, "/genome_feature/?and(eq(annotation,PATRIC),eq(pos_group," + encodeURIComponent('"' + feature.pos_group + '"') + "))"), {
						headers: {
							accept: "application/json",
							'X-Requested-With': null,
							'Authorization': (window.App.authorizationToken || "")
						},
						handleAs: "json"
					}).then(lang.hitch(this, function(features){
						if(features.length === 0){
							// no PATRIC feature found
							this.set("feature", feature);
						}else{
							this.set("feature", features[0]);
						}
					}));
				}else{
					this.set("feature", feature);
				}
			}
		},

		_setFeatureAttr: function(feature){

			this.feature = this.state.feature = feature;

			this.buildHeaderContent(feature);

			this.setActivePanelState();
			this.resize();
		},

		postCreate: function(){
			if(!this.state){
				this.state = {};
			}

			this.inherited(arguments);

			this.overview = new FeatureOverview({
				content: "Overview",
				title: "Overview",
				id: this.viewer.id + "_" + "overview"
			});

			this.genomeBrowser = new GenomeBrowser({
				title: "Genome Browser",
				id: this.viewer.id + "_genomeBrowser",
				content: "Genome Browser",
				tooltip: 'The "Browser" tab shows genome sequence and genomic features using linear genome browser',
				state: lang.mixin({}, this.state)
			});
			if(window.App.appLabel !== ""){
				this.compareRegionViewer = new CompareRegionContainer({
					title: "Compare Region Viewer",
					id: this.viewer.id + "_compareRegionViewer"
				});
			}
			// TODO: implement pathways tab

			this.transcriptomics = new GeneExpressionContainer({
				title: "Transcriptomics",
				id: this.viewer.id + "_transcriptomics"
			});

			this.correlatedGenes = new CorrelatedGenesContainer({
				title: "Correlated Genes",
				id: this.viewer.id + "_correlatedGenes"
			});

			if(window.App.appLabel !== ""){
				this.interactions = new InteractionContainer({
					title: "Interactions",
					id: this.viewer.id + "_interactions",
					state: this.state
				});
			}

			this.viewer.addChild(this.overview);
			this.viewer.addChild(this.genomeBrowser);
			if(window.App.appLabel !== ""){
				this.viewer.addChild(this.compareRegionViewer);
			}
			this.viewer.addChild(this.transcriptomics);
			this.viewer.addChild(this.correlatedGenes);
			if(window.App.appLabel !== ""){
				this.viewer.addChild(this.interactions);
			}
		}
	});
});
<commit_msg>prevents null query<commit_after>define([
	"dojo/_base/declare", "dojo/_base/lang",
	"dojo/request",
	"./TabViewerBase",
	"../FeatureOverview", "../GenomeBrowser", "../CompareRegionContainer",
	"../GeneExpressionContainer", "../CorrelatedGenesContainer", "../InteractionContainer",
	"../../util/PathJoin"

], function(declare, lang,
			xhr,
			TabViewerBase,
			FeatureOverview, GenomeBrowser, CompareRegionContainer,
			GeneExpressionContainer, CorrelatedGenesContainer, InteractionContainer,
			PathJoin){

	return declare([TabViewerBase], {
		"baseClass": "FeatureGroup",
		"disabled": false,
		containerType: "feature_group",
		feature_id: "",
		perspectiveLabel: "Feature View",
		perspectiveIconClass: "icon-selection-Feature",

		_setFeature_idAttr: function(id){

			if(!id){
				return;
			}

			if(this.feature_id == id){
				return;
			}

			this.state = this.state || {};
			this.feature_id = id;
			this.state.feature_id = id;

			if(id.match(/^fig/)){
				id = id.replace(/\|/g, '%7C');
				//console.log("fig id = ", id);
				id = "?eq(patric_id," + id + ")&limit(1)";
			}

			// console.log("Get Feature: ", id);
			xhr.get(PathJoin(this.apiServiceUrl, "genome_feature", id), {
				headers: {
					accept: "application/json",
					'X-Requested-With': null,
					'Authorization': (window.App.authorizationToken || "")
				},
				handleAs: "json"
			}).then(lang.hitch(this, function(feature){
				if(feature instanceof Array){
					// this.set("feature", feature[0])
					this.redirectToPATRICFeature(feature[0]);
				}else{
					// this.set("feature", feature)
					this.redirectToPATRICFeature(feature);
				}
			}));
		},

		setActivePanelState: function(){
			var activeQueryState;
			if(!this._started){
				console.log("Feature Viewer not started");
				return;
			}

			if(this.state.feature_id){
				activeQueryState = lang.mixin({}, this.state, {search: "eq(feature_id," + this.state.feature_id + ")"});
			}
			var active = (this.state && this.state.hashParams && this.state.hashParams.view_tab) ? this.state.hashParams.view_tab : "overview";
			var activeTab = this[active];

			switch(active){
				case "overview":
				case "correlatedGenes":
					if(this.state && this.state.feature){
						activeTab.set("state", lang.mixin({}, this.state));
					}
					break;
				case "interactions":
					if(this.state && this.state.feature){
						activeTab.set("state", lang.mixin({}, this.state, {
							search: "secondDegreeInteraction(" + this.state.feature.feature_id + ")"
						}));
					}
					break;
				default:
					if(activeQueryState){
						activeTab.set("state", activeQueryState);
					}
					break;
			}

			if(this.feature){
				var label = (this.feature.patric_id) ? this.feature.patric_id : (this.feature.refseq_locus_tag) ? this.feature.refseq_locus_tag : (this.feature.protein_id) ? this.feature.protein_id : this.feature.feature_id;
				var pageTitle = label + "::Feature " + activeTab.title;
				// console.log("Feature setActivePanelState: ", pageTitle);
				if(window.document.title !== pageTitle){
					window.document.title = pageTitle;
				}
			}
		},

		onSetState: function(attr, oldState, state){
			var parts = this.state.pathname.split("/");
			this.set("feature_id", parts[parts.length - 1]);
			state.feature_id = parts[parts.length - 1];

			if(state && state.feature_id && !state.feature){
				if(oldState && oldState.feature_id){
					if((state.feature_id == oldState.feature_id)){
						if(oldState.feature || this.feature){
							this.state.feature = state.feature = oldState.feature || this.feature;
						}else{
							console.log("oldState missing Featture");
						}
					}
				}
			}

			this.setActivePanelState();
			if(state.hashParams && state.hashParams.view_tab){

				if(this[state.hashParams.view_tab]){
					var vt = this[state.hashParams.view_tab];
					vt.set("visible", true);
					this.viewer.selectChild(vt);
				}else{
					console.log("No view-tab supplied in State Object");
				}
			}

			this.setActivePanelState();
		},

		buildHeaderContent: function(feature){

			xhr.get(PathJoin(this.apiServiceUrl, "taxonomy", feature.taxon_id), {
				headers: {
					accept: "application/json"
				},
				handleAs: "json"
			}).then(lang.hitch(this, function(taxon){
				var taxon_lineage_names = taxon.lineage_names;
				var taxon_lineage_ids = taxon.lineage_ids;
				var taxon_lineage_ranks = taxon.lineage_ranks;

				var visibleRanks = ["superkingdom", "phylum", "class", "order", "family", "genus", "species"];
				var visibleIndexes = taxon_lineage_ranks.filter(function(rank){
					return visibleRanks.indexOf(rank) > -1;
				}).map(function(rank){
					return taxon_lineage_ranks.indexOf(rank);
				});

				var out = visibleIndexes.map(function(idx){
					return '' + taxon_lineage_names[idx] + '';
				});
				this.queryNode.innerHTML = out.join(" » ") + " » " + lang.replace('{feature.genome_name}', {feature: feature});
			}));

			var content = [];
			if(feature.hasOwnProperty('patric_id')){
				content.push(feature.patric_id);
			}
			if(feature.hasOwnProperty('refseq_locus_tag')){
				content.push(feature.refseq_locus_tag);
			}
			if(feature.hasOwnProperty('gene')){
				content.push(feature.gene);
			}
			if(feature.hasOwnProperty('product')){
				content.push(feature.product);
			}

			this.totalCountNode.innerHTML = "
" + content.map(function(d){
					return '' + d + '';
				}).join(' | ');
		},

		redirectToPATRICFeature: function(feature){

			if(feature.annotation === 'PATRIC'){
				this.set("feature", feature);
			}else{
				if(feature.hasOwnProperty('pos_group')){
					xhr.get(PathJoin(this.apiServiceUrl, "/genome_feature/?and(eq(annotation,PATRIC),eq(pos_group," + encodeURIComponent('"' + feature.pos_group + '"') + "))"), {
						headers: {
							accept: "application/json",
							'X-Requested-With': null,
							'Authorization': (window.App.authorizationToken || "")
						},
						handleAs: "json"
					}).then(lang.hitch(this, function(features){
						if(features.length === 0){
							// no PATRIC feature found
							this.set("feature", feature);
						}else{
							this.set("feature", features[0]);
						}
					}));
				}else{
					this.set("feature", feature);
				}
			}
		},

		_setFeatureAttr: function(feature){

			this.feature = this.state.feature = feature;

			this.buildHeaderContent(feature);

			this.setActivePanelState();
			this.resize();
		},

		postCreate: function(){
			if(!this.state){
				this.state = {};
			}

			this.inherited(arguments);

			this.overview = new FeatureOverview({
				content: "Overview",
				title: "Overview",
				id: this.viewer.id + "_" + "overview"
			});

			this.genomeBrowser = new GenomeBrowser({
				title: "Genome Browser",
				id: this.viewer.id + "_genomeBrowser",
				content: "Genome Browser",
				tooltip: 'The "Browser" tab shows genome sequence and genomic features using linear genome browser',
				state: lang.mixin({}, this.state)
			});
			if(window.App.appLabel !== ""){
				this.compareRegionViewer = new CompareRegionContainer({
					title: "Compare Region Viewer",
					id: this.viewer.id + "_compareRegionViewer"
				});
			}
			// TODO: implement pathways tab

			this.transcriptomics = new GeneExpressionContainer({
				title: "Transcriptomics",
				id: this.viewer.id + "_transcriptomics"
			});

			this.correlatedGenes = new CorrelatedGenesContainer({
				title: "Correlated Genes",
				id: this.viewer.id + "_correlatedGenes"
			});

			if(window.App.appLabel !== ""){
				this.interactions = new InteractionContainer({
					title: "Interactions",
					id: this.viewer.id + "_interactions"
				});
			}

			this.viewer.addChild(this.overview);
			this.viewer.addChild(this.genomeBrowser);
			if(window.App.appLabel !== ""){
				this.viewer.addChild(this.compareRegionViewer);
			}
			this.viewer.addChild(this.transcriptomics);
			this.viewer.addChild(this.correlatedGenes);
			if(window.App.appLabel !== ""){
				this.viewer.addChild(this.interactions);
			}
		}
	});
});
<|endoftext|>


<commit_before>/**
 * Created by Mordekaiser on 04/06/16.
 */
"use strict";
angular.module('smartBusiness')
.controller('LoginCtrl', ['$scope', 'AuthService', '$location', 'AuthToken', '$window', 'mvNotifier', '$timeout', LoginCtrl]);

function LoginCtrl($scope, AuthService, $location, AuthToken, $window, mvNotifier, $timeout) {
    $scope.login = function () {
        var query = {
            email: $scope.email,
            password: $scope.password
        };
        AuthService.authenticate(query).then(function (success) {
            if(success) {
                mvNotifier.notify('Acceso exitoso');
                $timeout(function(){
                    $location.path('/products');
                    $window.location.reload();
                },300);
            } else
                mvNotifier.error('No se puedo iniciar sesión');
        });
    }

    $scope.logout = function() {
        console.log('Sesisón finalizada');
        mvNotifier.error('Sesisón finalizada');
        AuthToken.removeToken();
        $timeout(function(){
            $location.path('/');
            $window.location.reload();
        },300);
    }
}<commit_msg>ga event<commit_after>/**
 * Created by Mordekaiser on 04/06/16.
 */
"use strict";
angular.module('smartBusiness')
.controller('LoginCtrl', ['$scope', 'AuthService', '$location', 'AuthToken', '$window', 'mvNotifier', '$timeout', LoginCtrl]);

function LoginCtrl($scope, AuthService, $location, AuthToken, $window, mvNotifier, $timeout) {
    $scope.login = function () {
        var query = {
            email: $scope.email,
            password: $scope.password
        };
        AuthService.authenticate(query).then(function (success) {
            if(success) {
                $window.ga('send', 'event', 'Action', 'Login', $scope.email);
                mvNotifier.notify('Acceso exitoso');
                $timeout(function(){
                    $location.path('/products');
                    $window.location.reload();
                },300);
            } else
                mvNotifier.error('No se puedo iniciar sesión');
        });
    };

    $scope.logout = function() {
        console.log('Sesisón finalizada');
        mvNotifier.error('Sesisón finalizada');
        AuthToken.removeToken();
        $timeout(function(){
            $location.path('/');
            $window.location.reload();
        },300);
    }
}<|endoftext|>


<commit_before>$(function() {
	channel = new goog.appengine.Channel(CHANNEL_API_TOKEN);
	socket = channel.open();
	socket.onopen = onOpened;
	socket.onmessage = onMessage;
	socket.onerror = onError;
	socket.onclose = onClose;
});

function onOpened() {
	console.log("onOpened");
}

function onMessage(message) {
	var msg;
	try {
		msg = JSON.parse(message.data.trim());
		console.info(msg);
	} catch (e) {
		console.log('JSON.parse failed:', data);
	}

	var nome = msg.subscription.substr(1, msg.subscription.indexOf('push') - 1);

	var stack = msg.message;
	var messaggio = '';

	if (stack !== null && stack.length > 0) {

		if (typeof stack == "string") {
			messaggio = stack;
		} else {
			var popped = stack.pop();
			var dur = popped.duration || 1000;
			if (popped.color) {
				document.getElementById('scheda-' + nome).style.borderColor = popped.color;
				setTimeout(
						function() {
							document.getElementById('scheda-' + nome).style.borderColor = 'white';
						}, dur);
				messaggio += 'LCD [' + popped.color + '], ';
			}

			if (popped.arm) {
				document.getElementById('forchetta-' + nome).style.visibility = 'visible';
				setTimeout(
						function() {
							document.getElementById('forchetta-' + nome).style.visibility = 'hidden';
						}, dur);
				messaggio += 'Raise fork, ';
			}

			if (popped.buzzer) {

			}

			if (dur) {
				messaggio += 'Dur: ' + dur + 'ms';
			}
		}
	}

	var newRow = document.createElement('tr');
	var newSender = document.createElement('td');
	var newMessage = document.createElement('td');
	newRow.className = 'success';
	newSender.innerText = nome;
	newMessage.innerText = messaggio;
	newRow.appendChild(newSender);
	newRow.appendChild(newMessage);
	$("#message-list").prepend(newRow);
	setTimeout(function() {
		newRow.className = '';
	}, 1000);
}

function onError(error) {
	console.log("onError: " + error);
	// alert + refresh page

}

function onClose() {
	console.log("onClose");
}<commit_msg>web ok<commit_after>$(function() {
	channel = new goog.appengine.Channel(CHANNEL_API_TOKEN);
	socket = channel.open();
	socket.onopen = onOpened;
	socket.onmessage = onMessage;
	socket.onerror = onError;
	socket.onclose = onClose;
});

function onOpened() {
	console.log("onOpened");
}

function onMessage(message) {
	var msg;
	try {
		msg = JSON.parse(message.data.trim());
		console.info(msg);
	} catch (e) {
		console.log('JSON.parse failed:', data);
	}

	var nome = msg.subscription.substr(1, msg.subscription.indexOf('push') - 1);
	var stack = null;
	try {
		stack =  JSON.parse(msg.message);
	} catch (e) {
		stack = msg.message;
	}
	var messaggio = '';

	if (stack !== null && stack.length > 0) {

		if (typeof stack == "string") {
			messaggio = stack;
		} else {
			var popped = stack.pop();
			var dur = popped.duration || 1000;
			if (popped.color) {
				document.getElementById('scheda-' + nome).style.borderColor = popped.color;
				setTimeout(
						function() {
							document.getElementById('scheda-' + nome).style.borderColor = 'white';
						}, dur);
				messaggio += 'LCD [' + popped.color + '], ';
			}

			if (popped.arm) {
				document.getElementById('forchetta-' + nome).style.visibility = 'visible';
				setTimeout(
						function() {
							document.getElementById('forchetta-' + nome).style.visibility = 'hidden';
						}, dur);
				messaggio += 'Raise fork, ';
			}

			if (popped.buzzer) {

			}

			if (dur) {
				messaggio += 'Dur: ' + dur + 'ms';
			}
		}
	}

	var newRow = document.createElement('tr');
	var newSender = document.createElement('td');
	var newMessage = document.createElement('td');
	newRow.className = 'success';
	newSender.innerText = nome;
	newMessage.innerText = messaggio;
	newRow.appendChild(newSender);
	newRow.appendChild(newMessage);
	$("#message-list").prepend(newRow);
	setTimeout(function() {
		newRow.className = '';
	}, 1000);
}

function onError(error) {
	console.log("onError: " + error);
	// alert + refresh page

}

function onClose() {
	console.log("onClose");
}<|endoftext|>


<commit_before>var c;
var ctx;
var enemynum;
var enemycounter;

var FPS;
var player;
var enemies = [];

function Initialise()
{
  c=document.getElementById("canvas");
  ctx=c.getContext("2d");
  enemynum = 0;
  enemycounter=100;
  FPS = 60;
  canvas.addEventListener('mousemove', MouseMove, false);
  setInterval(function() {
  update();
  draw();
}, 1000/FPS);

  player = {
  color: "#00A",
  x: 220,
  y: 270,
  width: 32,
  height: 32,
  draw: function() {
    ctx.fillStyle = this.color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
};
}

function draw(){
ctx.clearRect(0, 0, 400, 400);
player.draw();
for(var i = 0; i<enemynum; i++)
  {
    enemies[i].y++;
    enemies[i].draw();
  }
}

function update(){
  // Add only 4 enemies to the screen
  if(enemynum<4)
  {
    enemycounter++;
    if(enemycounter > 100)
    // Spacing of enemies
    {
      enemycounter = 0;
      enemynum++;
    }
  }

  for(var i = 0; i<enemynum; i++)
  {
    enemies.push({
    color: "#0F0",
    x: 0,
    y: -20,
    width: 400,
    height: 20,
    draw: function() {
      if(this.y>400)
      {
        this.y=-this.height;
      }
      ctx.fillStyle = this.color;
      ctx.fillRect(this.x, this.y, this.width, this.height);
      }
    };)
  }
}

function MouseMove(e){

player.x = e.clientX-canvas.offsetLeft-player.height/2;
document.getElementById("testout").innerHTML=String(player.x)+",";
player.y = e.clientY-canvas.offsetTop-player.height/2;
document.getElementById("testout").innerHTML+=String(player.y);

}
<commit_msg>Update games.js<commit_after>var c;
var ctx;
var enemynum;
var enemycounter;

var FPS;
var player;
var enemies = [];

function Initialise()
{
  c=document.getElementById("canvas");
  ctx=c.getContext("2d");
  enemynum = 0;
  enemycounter=100;
  FPS = 60;
  canvas.addEventListener('mousemove', MouseMove, false);
  setInterval(function() {
  update();
  draw();
}, 1000/FPS);

  player = {
  color: "#00A",
  x: 220,
  y: 270,
  width: 32,
  height: 32,
  draw: function() {
    ctx.fillStyle = this.color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
};
}

function draw(){
ctx.clearRect(0, 0, 400, 400);
player.draw();
for(var i = 0; i<enemynum; i++)
  {
    enemies[i].y++;
    enemies[i].draw();
  }
}

function update(){
  // Add only 4 enemies to the screen
  if(enemynum<4)
  {
    enemycounter++;
    if(enemycounter > 100)
    // Spacing of enemies
    {
      enemycounter = 0;
      enemynum++;
    }
  }

  for(var i = 0; i<enemynum; i++)
  {
    enemies.push({
    color: "#0F0",
    x: 0,
    y: -20,
    width: 400,
    height: 20,
    draw: function() {
      if(this.y>400)
      {
        this.y=-this.height;
      }
      ctx.fillStyle = this.color;
      ctx.fillRect(this.x, this.y, this.width, this.height);
      }
    });
  }
}

function MouseMove(e){

player.x = e.clientX-canvas.offsetLeft-player.height/2;
document.getElementById("testout").innerHTML=String(player.x)+",";
player.y = e.clientY-canvas.offsetTop-player.height/2;
document.getElementById("testout").innerHTML+=String(player.y);

}
<|endoftext|>


<commit_before>
// on click get map's coordinates
map.on('click', function(e) {
   $('#myModal').modal('show');
});<commit_msg>minor<commit_after>// on click get map's coordinates
map.on('click', function(e) {
   $('#myModal').modal('show');
});
<|endoftext|>


<commit_before>define(["jquery", "gvis"], function($, gvis) {

    function ElevationProfile(track, targetDiv) {
        addChildElements(targetDiv);

        var dashboard = createDashboard(targetDiv);
        var controlWrapper = createControlWrapper();
        var chartWrapper = createChartWrapper();
        var dataTable = buildDataTable(track);

        dashboard.bind(controlWrapper, chartWrapper);
        dashboard.draw(dataTable);

        addControlWrapperStateChangeListener(controlWrapper, dataTable, track);
        addChartWrapperListener(chartWrapper, track);
    }

    function addChildElements(targetDiv) {
        $(targetDiv).append("

");
        $(targetDiv).append("

");
    }

    function createDashboard(targetDiv) {
        return new gvis.Dashboard($(targetDiv)[0]);
    }

    function createControlWrapper() {
        var controlWrapper = new gvis.ControlWrapper({
            "controlType": "ChartRangeFilter",
            "containerId": "control",
            "options": {
                "filterColumnIndex": 0, // filter by distance
                "ui": {
                    "width": "50%",
                    "chartType": "AreaChart",
                    "chartOptions": {
                        "chartArea": { "width": "90%" },
                        "hAxis": {"baselineColor": "none"},
                    },
                    "snapToData": true
                }
            }
        });

        return controlWrapper;
    }

    function createChartWrapper() {
        return new gvis.ChartWrapper({
            "chartType": "AreaChart",
            "containerId": "chart",
            "options": {
                "width": "50%",
                "chartArea": { "width": "90%" },
                "legend": "none",
                "titleY": "Elevation (m)",
                "titleX": "Distance (m)",
                "focusBorderColor": "#00ff00",
            }
        });
    }

    function buildDataTable(track) {
        var dataArray = [];

        $.each(track.trackPoints, function(trackPointNr, trackPoint) {
            dataArray.push([
                trackPoint.dist,
                parseFloat(trackPoint.ele)
            ]);
        });

        var dt = new gvis.DataTable();
        dt.addColumn("number", "Distance");
        dt.addColumn("number", "Elevation");
        dt.addRows(dataArray);

        return dt;
    }

    function addControlWrapperStateChangeListener(controlWrapper, dataTable, track) {
        gvis.events.addListener(controlWrapper, 'statechange', function(e) {
            if (!e.inProgress) {
				var range = controlWrapper.getState().range;
				var filteredRowIds = dataTable.getFilteredRows(
					[{
						"column": 0,
					"minValue": range.start,
					"maxValue": range.end
					}]
				);
                fireChartRangeChangedEvent(track.getTrackPoints(filteredRowIds[0], filteredRowIds[filteredRowIds.length - 1]));
            }
        });
    }

    function fireChartRangeChangedEvent(trackPoints) {
		var event = document.createEvent("Event");
		event.initEvent("onChartRangeChanged", true, true);
		event.trackPoints = trackPoints;
		document.dispatchEvent(event);
	}

    function addChartWrapperListener(chartWrapper, track) {
        gvis.events.addListener(chartWrapper, "ready", function() {
			gvis.events.addListener(chartWrapper.getChart(), "onmouseover", function(data) {
				var trackPoint = track.getTrackPoint(data.row);
				fireOnTrackPointHoverEvent(trackPoint);
		   	});
		});
    }

    function fireOnTrackPointHoverEvent(trackPoint) {
		var event = document.createEvent("Event");
		event.initEvent("onTrackPointHover", true, true);
		event.trackPoint = trackPoint;
		document.dispatchEvent(event);
	}

    return {
        build: ElevationProfile
    }

});
<commit_msg>Bugfix: Send correct trackpoint on hover in case of limited chart range.<commit_after>define(["jquery", "gvis"], function($, gvis) {

    function ElevationProfile(track, targetDiv) {

		this.track = track;
        addChildElements(targetDiv);

        this.dashboard = createDashboard(targetDiv);
        this.controlWrapper = createControlWrapper();
        this.chartWrapper = createChartWrapper();
        this.dataTable = buildDataTable(track);
		this.firstRow = 0;

        this.dashboard.bind(this.controlWrapper, this.chartWrapper);
        this.dashboard.draw(this.dataTable);

        this.addControlWrapperStateChangeListener();
        this.addChartWrapperListener();
    }

    function addChildElements(targetDiv) {
        $(targetDiv).append("

");
        $(targetDiv).append("

");
    }

    function createDashboard(targetDiv) {
        return new gvis.Dashboard($(targetDiv)[0]);
    }

    function createControlWrapper() {
        var controlWrapper = new gvis.ControlWrapper({
            "controlType": "ChartRangeFilter",
            "containerId": "control",
            "options": {
                "filterColumnIndex": 0, // filter by distance
                "ui": {
                    "width": "50%",
                    "chartType": "AreaChart",
                    "chartOptions": {
                        "chartArea": { "width": "90%" },
                        "hAxis": {"baselineColor": "none"},
                    },
                    "snapToData": true
                }
            }
        });

        return controlWrapper;
    }

    function createChartWrapper() {
        return new gvis.ChartWrapper({
            "chartType": "AreaChart",
            "containerId": "chart",
            "options": {
                "width": "50%",
                "chartArea": { "width": "90%" },
                "legend": "none",
                "titleY": "Elevation (m)",
                "titleX": "Distance (m)",
                "focusBorderColor": "#00ff00",
            }
        });
    }

    function buildDataTable(track) {
        var dataArray = [];

        $.each(track.trackPoints, function(trackPointNr, trackPoint) {
            dataArray.push([
                trackPoint.dist,
                parseFloat(trackPoint.ele)
            ]);
        });

        var dt = new gvis.DataTable();
        dt.addColumn("number", "Distance");
        dt.addColumn("number", "Elevation");
        dt.addRows(dataArray);

        return dt;
    }

    ElevationProfile.prototype.addControlWrapperStateChangeListener = function() {
		var self = this;
        gvis.events.addListener(self.controlWrapper, 'statechange', function(e) {
            if (!e.inProgress) {
				var range = self.controlWrapper.getState().range;
				var filteredRowIds = self.dataTable.getFilteredRows(
					[{
						"column": 0,
						"minValue": range.start,
						"maxValue": range.end
					}]
				);
				self.firstRow = filteredRowIds[0];
				self.lastRow = filteredRowIds[filteredRowIds.length - 1];
                fireChartRangeChangedEvent(self.track.getTrackPoints(self.firstRow, self.lastRow));
            }
        });
    };

    function fireChartRangeChangedEvent(trackPoints) {
		var event = document.createEvent("Event");
		event.initEvent("onChartRangeChanged", true, true);
		event.trackPoints = trackPoints;
		document.dispatchEvent(event);
	}

    ElevationProfile.prototype.addChartWrapperListener = function() {
		var self = this;
        gvis.events.addListener(self.chartWrapper, "ready", function() {
			gvis.events.addListener(self.chartWrapper.getChart(), "onmouseover", function(data) {
				var trackPoint = self.track.getTrackPoint(self.firstRow + data.row);
				fireOnTrackPointHoverEvent(trackPoint);
		   	});
		});
    }

    function fireOnTrackPointHoverEvent(trackPoint) {
		var event = document.createEvent("Event");
		event.initEvent("onTrackPointHover", true, true);
		event.trackPoint = trackPoint;
		document.dispatchEvent(event);
	}

	function build(track, targetDiv) {
		return new ElevationProfile(track, targetDiv);
	}

    return {
        build: build
    }

});
<|endoftext|>


<commit_before>var lastLookup = [];
var lastSearch = [];
var bool = [true];
/*
 * Search the yelp api
 */
var searchYelp = function (term, near, category_filters, offset) {
  if (offset == undefined) {
    var opt_int = 0;
  } else {
    var opt_int = offset;
  }
  if (category_filters == undefined) {
    var opt_cat = "";
  } else {
    var opt_cat = category_filters;
  }
  if (near && term){
    searchQuery(term, near, opt_cat, opt_int);
  } else {
    if(bool[0]) {
      bool = [];
      bool.push(false);
      $('#middle').append('
' +
      '<button type="button" onclick="bool.pop(); bool.push(true);" class="close" data-dismiss="alert">×</button>'+
      'Error! Please include the appropriate info in the appropriate fields.'+
      '
');
    }

  }

}

/*
 *
 */
var getBookmarks = function(term) {
  var bookmarks = searchFavorites(term);
  browseFavorites(bookmarks);
}

/*
 * Browses Favorites
 */
var browseFavorites = function(data) {
  var current = $('.active1').text();
  if (current != 'Lookup'){
    lastLookup.push(data);
    $('.active1').remove();
  $('.columnCenter').empty();
        $('.breadcrumb').empty();
        $('.breadcrumb').append('
' + 'Home' + ' /
');
        $('.breadcrumb').append('
Lookup
 ');
    history.pushState({}, 'Yelptastic- Browse Favorite', '#bookmarksearch');
  }
  $('.columnCenter').empty();

  browseBookmarks(data, 0);
}

/*
 * Displays the view for searching yelp.
 */

var addFavoritesView = function(data, total, opt_term, opt_location, opt_cat, opt_offset) {
  //$('.breadcrumbs').removeClass('.active');
  var current = $('.active1').text();
  $('.alert').remove();
  bool = [];
  bool.push(true);

  lastSearch.push(data);
    lastSearch.push(total);
  lastSearch.push(opt_term);
  lastSearch.push(opt_location);
  lastSearch.push(opt_cat);
  lastSearch.push(opt_offset);
  if (current != 'Search'){
    $('.active1').remove();
     $('.columnCenter').empty();
     $('.breadcrumb').empty();
     $('.breadcrumb').append('
' + 'Home' + ' /
');
     $('.breadcrumb').append('
Search
 ');
    history.pushState({}, 'Yelptastic- Yelp Search', '#yelpsearch');
  }
  $('.columnLeft').empty();
  $('.columnCenter').empty();
  var allcategories = $.getJSON("scripts/categories.json", function(y){
  	  var x = y;
  	  parseYelpCategories(opt_term, opt_location, x);
  });
  addQuery(data, opt_offset, total, opt_term, opt_location, opt_cat);

}

/*
 * Takes in the results and appends them to the thumbnails grids
 */
var addQuery = function (results, opt_int, opt_total, opt_term, opt_location, opt_cat) {
  $('.columnCenter').empty();
  $thumbnailswrapper = $('

');
  var data = [];
    for (var i = 0; i < results.length; i ++) {
      $button = $('<button>Favorite</button>');
      if(results[i].image_url) {
        var image_url = results[i].image_url;
      } else {
        var image_url = 'http://s3-media3.ak.yelpcdn.com/assets/2/www/img/305e17fe6ed8/gfx/blank_biz_medium_sq.png';
      }
      data.push({
        name:results[i].name,
        image:image_url,
        quote:results[i].snippet_text,
        ratingImage:results[i].rating_img_url,
        button:'Favorite',
        object:JSON.stringify(results[i]),
        url:results[i].url,
        phonenumber:results[i].display_phone,
        n:i.toString(),
        views:results[i].review_count,
        distance:results[i].distance,
        address:results[i].location.display_address[0] +" " + results[i].location.display_address[1]+" " + results[i].location.display_address[2],
      });
  }
  var source = $('#results').html();
  var template = Handlebars.compile(source);
  var string = template(data);
  $thumbnailswrapper.append(string);
  if (opt_total > 20) {
    $buttonRow = $('

');

    if (opt_int >= 20) {
      $see_prev = $('<input type="button" value="Previous 20" name="nextButton">');
      $see_prev.click(function() {
        searchYelp(opt_term, opt_location, opt_cat, opt_int-20);
       });
     $buttonRow.append($see_prev);
    }
    if (opt_int + 20 <= opt_total) {
       $see_all = $('<input type="button" value="Next 20" name="prevButton">');
       $see_all.click(function() {
          searchYelp(opt_term, opt_location, opt_cat, opt_int + 20);
       });
     $buttonRow.append($see_all);
    }
  $thumbnailswrapper.append($buttonRow);
  }
  $('.columnCenter').append($thumbnailswrapper);
  window.scroll();
}

/*
 * Takes in the results and appends them to the thumbnails grids
 */
var browseBookmarks = function (results, opt_int) {
  $('.columnCenter').empty();
  $thumbnailswrapper = $('

');
  $buttonRow = $('

');
  var data = [];
  if (results.length >=20) {
    for (var i = opt_int; i < opt_int + 20; i ++) {
      if(results[i].image_url) {
        var image_url = results[i].image_url;
      } else {
        var image_url = 'http://s3-media3.ak.yelpcdn.com/assets/2/www/img/305e17fe6ed8/gfx/blank_biz_medium_sq.png';
      }
      $button = $('<button>Favorite</button>');
      alert('results[i].location.display_address[0]');
      data.push({
        name:results[i].name,
        image:image_url,
        quote:results[i].snippet_text,
        ratingImage:results[i].rating_img_url,
        tags:results[i].tags,
        object:JSON.stringify(results[i]),
        url:results[i].url,
        notes:results[i].notes,
        views:results[i].review_count,
        distance:results[i].distance,
        address:results[i].location.display_address[0] +" " + results[i].location.display_address[1]+" "+ results[i].location.display_address[2],

      });
    }
  } else {
    for (var i = opt_int; i < results.length; i ++) {
      if(results[i].image_url) {
        var image_url = results[i].image_url;
      } else {
        var image_url = 'http://s3-media3.ak.yelpcdn.com/assets/2/www/img/305e17fe6ed8/gfx/blank_biz_medium_sq.png';
      }
      $button = $('<button>Favorite</button>');
      data.push({
        name:results[i].name,
        image:image_url,
        quote:results[i].snippet_text,
        ratingImage:results[i].rating_img_url,
        tags:results[i].tags,
        url:results[i].url,
        views:results[i].review_count,
        distance:results[i].distance,
        address:results[i].location.display_address[0] +" " + results[i].location.display_address[1]+" " + results[i].location.display_address[2],
      });
    }
  }
  var source = $('#browse').html();
  var template = Handlebars.compile(source);
  var string = template(data);
  $thumbnailswrapper.append(string);
  if (data.length >= 20) {
    if (opt_int >= 20) {
      $see_prev = $('<input type="button" value="Previous" name="nextButton">');
      $see_prev.click(function() {
        addQuery(results, opt_int-1);
       });
      $buttonRow.append($see_prev);
      }
    if (opt_int + 20 <= data.length) {
       $see_all = $('<input type="button" value="Next" name="prevButton">');
       $see_all.click(function() {
          addQuery(results, opt_int + 20);
       });
      $buttonRow.append($see_all);
    }
  }

  $thumbnailswrapper.append($buttonRow);
  $('.columnCenter').append($thumbnailswrapper);
}
/*
 * Function to send the bookmarks to the backend
 */
var saveFavorite = function (jsonString, tags1, notes1) {
  var object1 = jsonString;
  saveBookmark(object1, tags1, notes1);
}

var parseYelpCategories = function (term, location, categories) {

	var categories_wrapper = '
';
	for (var i in categories)
	{
		var genCategory = i;
		var genCategoryTag = i;
		genCategoryTag = genCategoryTag.replace(/ /g, "_");
		genCategoryTag = genCategoryTag.replace(/&/g, "And");

    	categories_wrapper = categories_wrapper + '
';
        categories_wrapper = categories_wrapper + '
';
        categories_wrapper = categories_wrapper + '';
		categories_wrapper = categories_wrapper + genCategory;
        categories_wrapper = categories_wrapper + '';
        categories_wrapper = categories_wrapper + '
';
        categories_wrapper = categories_wrapper + '
';
        categories_wrapper = categories_wrapper + '
';

        for (var j in categories[i])
        {
        	var subCategory = j;
        	var subCategoryTag = categories[i][j];

        	categories_wrapper = categories_wrapper + '
';
            categories_wrapper = categories_wrapper + '
';
            categories_wrapper = categories_wrapper + '';

            categories_wrapper = categories_wrapper + subCategory;
            categories_wrapper = categories_wrapper + '';
            categories_wrapper = categories_wrapper + '
';

            if (typeof categories[i][j] != "string")
            {
            	categories_wrapper = categories_wrapper + '
';
                categories_wrapper = categories_wrapper + '
';

            	for (var k in categories[i][j])
            	{

            		var subSubCategory = k;
            		var subSubCategoryTag = categories[i][j][k];

                    categories_wrapper = categories_wrapper + '
';
                    categories_wrapper = categories_wrapper + '
';
                    categories_wrapper = categories_wrapper + '';
                    categories_wrapper = categories_wrapper + subSubCategory;
                    categories_wrapper = categories_wrapper + '';
                    categories_wrapper = categories_wrapper + '
';
                    categories_wrapper = categories_wrapper + '
';

            	}

            	    categories_wrapper = categories_wrapper + '
';
                    categories_wrapper = categories_wrapper + '
';

            }

            categories_wrapper = categories_wrapper + '
';
        }

        categories_wrapper = categories_wrapper + '
';
        categories_wrapper = categories_wrapper + '
';
        categories_wrapper = categories_wrapper + '
';

	}

	categories_wrapper = categories_wrapper + "
";
	console.log(categories_wrapper);
	$('.columnLeft').append(categories_wrapper);
}
<commit_msg>fixed undefined type from third level tags<commit_after>var lastLookup = [];
var lastSearch = [];
var bool = [true];
/*
 * Search the yelp api
 */
var searchYelp = function (term, near, category_filters, offset) {
  if (offset == undefined) {
    var opt_int = 0;
  } else {
    var opt_int = offset;
  }
  if (category_filters == undefined) {
    var opt_cat = "";
  } else {
    var opt_cat = category_filters;
  }
  if (near && term){
    searchQuery(term, near, opt_cat, opt_int);
  } else {
    if(bool[0]) {
      bool = [];
      bool.push(false);
      $('#middle').append('
' +
      '<button type="button" onclick="bool.pop(); bool.push(true);" class="close" data-dismiss="alert">×</button>'+
      'Error! Please include the appropriate info in the appropriate fields.'+
      '
');
    }

  }

}

/*
 *
 */
var getBookmarks = function(term) {
  var bookmarks = searchFavorites(term);
  browseFavorites(bookmarks);
}

/*
 * Browses Favorites
 */
var browseFavorites = function(data) {
  var current = $('.active1').text();
  if (current != 'Lookup'){
    lastLookup.push(data);
    $('.active1').remove();
  $('.columnCenter').empty();
        $('.breadcrumb').empty();
        $('.breadcrumb').append('
' + 'Home' + ' /
');
        $('.breadcrumb').append('
Lookup
 ');
    history.pushState({}, 'Yelptastic- Browse Favorite', '#bookmarksearch');
  }
  $('.columnCenter').empty();

  browseBookmarks(data, 0);
}

/*
 * Displays the view for searching yelp.
 */

var addFavoritesView = function(data, total, opt_term, opt_location, opt_cat, opt_offset) {
  //$('.breadcrumbs').removeClass('.active');
  var current = $('.active1').text();
  $('.alert').remove();
  bool = [];
  bool.push(true);

  lastSearch.push(data);
    lastSearch.push(total);
  lastSearch.push(opt_term);
  lastSearch.push(opt_location);
  lastSearch.push(opt_cat);
  lastSearch.push(opt_offset);
  if (current != 'Search'){
    $('.active1').remove();
     $('.columnCenter').empty();
     $('.breadcrumb').empty();
     $('.breadcrumb').append('
' + 'Home' + ' /
');
     $('.breadcrumb').append('
Search
 ');
    history.pushState({}, 'Yelptastic- Yelp Search', '#yelpsearch');
  }
  $('.columnLeft').empty();
  $('.columnCenter').empty();
  var allcategories = $.getJSON("scripts/categories.json", function(y){
  	  var x = y;
  	  parseYelpCategories(opt_term, opt_location, x);
  });
  addQuery(data, opt_offset, total, opt_term, opt_location, opt_cat);

}

/*
 * Takes in the results and appends them to the thumbnails grids
 */
var addQuery = function (results, opt_int, opt_total, opt_term, opt_location, opt_cat) {
  $('.columnCenter').empty();
  $thumbnailswrapper = $('

');
  var data = [];
    for (var i = 0; i < results.length; i ++) {
      $button = $('<button>Favorite</button>');
      if(results[i].image_url) {
        var image_url = results[i].image_url;
      } else {
        var image_url = 'http://s3-media3.ak.yelpcdn.com/assets/2/www/img/305e17fe6ed8/gfx/blank_biz_medium_sq.png';
      }
      data.push({
        name:results[i].name,
        image:image_url,
        quote:results[i].snippet_text,
        ratingImage:results[i].rating_img_url,
        button:'Favorite',
        object:JSON.stringify(results[i]),
        url:results[i].url,
        phonenumber:results[i].display_phone,
        n:i.toString(),
        views:results[i].review_count,
        distance:results[i].distance,
        address:results[i].location.display_address[0] +" " + results[i].location.display_address[1]+" " + results[i].location.display_address[2],
      });
  }
  var source = $('#results').html();
  var template = Handlebars.compile(source);
  var string = template(data);
  $thumbnailswrapper.append(string);
  if (opt_total > 20) {
    $buttonRow = $('

');

    if (opt_int >= 20) {
      $see_prev = $('<input type="button" value="Previous 20" name="nextButton">');
      $see_prev.click(function() {
        searchYelp(opt_term, opt_location, opt_cat, opt_int-20);
       });
     $buttonRow.append($see_prev);
    }
    if (opt_int + 20 <= opt_total) {
       $see_all = $('<input type="button" value="Next 20" name="prevButton">');
       $see_all.click(function() {
          searchYelp(opt_term, opt_location, opt_cat, opt_int + 20);
       });
     $buttonRow.append($see_all);
    }
  $thumbnailswrapper.append($buttonRow);
  }
  $('.columnCenter').append($thumbnailswrapper);
  window.scroll();
}

/*
 * Takes in the results and appends them to the thumbnails grids
 */
var browseBookmarks = function (results, opt_int) {
  $('.columnCenter').empty();
  $thumbnailswrapper = $('

');
  $buttonRow = $('

');
  var data = [];
  if (results.length >=20) {
    for (var i = opt_int; i < opt_int + 20; i ++) {
      if(results[i].image_url) {
        var image_url = results[i].image_url;
      } else {
        var image_url = 'http://s3-media3.ak.yelpcdn.com/assets/2/www/img/305e17fe6ed8/gfx/blank_biz_medium_sq.png';
      }
      $button = $('<button>Favorite</button>');
      alert('results[i].location.display_address[0]');
      data.push({
        name:results[i].name,
        image:image_url,
        quote:results[i].snippet_text,
        ratingImage:results[i].rating_img_url,
        tags:results[i].tags,
        object:JSON.stringify(results[i]),
        url:results[i].url,
        notes:results[i].notes,
        views:results[i].review_count,
        distance:results[i].distance,
        address:results[i].location.display_address[0] +" " + results[i].location.display_address[1]+" "+ results[i].location.display_address[2],

      });
    }
  } else {
    for (var i = opt_int; i < results.length; i ++) {
      if(results[i].image_url) {
        var image_url = results[i].image_url;
      } else {
        var image_url = 'http://s3-media3.ak.yelpcdn.com/assets/2/www/img/305e17fe6ed8/gfx/blank_biz_medium_sq.png';
      }
      $button = $('<button>Favorite</button>');
      data.push({
        name:results[i].name,
        image:image_url,
        quote:results[i].snippet_text,
        ratingImage:results[i].rating_img_url,
        tags:results[i].tags,
        url:results[i].url,
        views:results[i].review_count,
        distance:results[i].distance,
        address:results[i].location.display_address[0] +" " + results[i].location.display_address[1]+" " + results[i].location.display_address[2],
      });
    }
  }
  var source = $('#browse').html();
  var template = Handlebars.compile(source);
  var string = template(data);
  $thumbnailswrapper.append(string);
  if (data.length >= 20) {
    if (opt_int >= 20) {
      $see_prev = $('<input type="button" value="Previous" name="nextButton">');
      $see_prev.click(function() {
        addQuery(results, opt_int-1);
       });
      $buttonRow.append($see_prev);
      }
    if (opt_int + 20 <= data.length) {
       $see_all = $('<input type="button" value="Next" name="prevButton">');
       $see_all.click(function() {
          addQuery(results, opt_int + 20);
       });
      $buttonRow.append($see_all);
    }
  }

  $thumbnailswrapper.append($buttonRow);
  $('.columnCenter').append($thumbnailswrapper);
}
/*
 * Function to send the bookmarks to the backend
 */
var saveFavorite = function (jsonString, tags1, notes1) {
  var object1 = jsonString;
  saveBookmark(object1, tags1, notes1);
}

var parseYelpCategories = function (term, location, categories) {

	var categories_wrapper = '
';
	for (var i in categories)
	{
		var genCategory = i;
		var genCategoryTag = i;
		genCategoryTag = genCategoryTag.replace(/ /g, "_");
		genCategoryTag = genCategoryTag.replace(/&/g, "And");

    	categories_wrapper = categories_wrapper + '
';
        categories_wrapper = categories_wrapper + '
';
        categories_wrapper = categories_wrapper + '';
		categories_wrapper = categories_wrapper + genCategory;
        categories_wrapper = categories_wrapper + '';
        categories_wrapper = categories_wrapper + '
';
        categories_wrapper = categories_wrapper + '
';
        categories_wrapper = categories_wrapper + '
';

        for (var j in categories[i])
        {
        	var subCategory = j;
        	var subCategoryTag = categories[i][j];

        	if (typeof categories[i][j] != "string")
        	{
        		subCategoryTag = subCategory;
        		subCategoryTag = subCategoryTag.replace(/ /g, "_");
				subCategoryTag = subCategoryTag.replace(/&/g, "And");
        	}

        	categories_wrapper = categories_wrapper + '
';
            categories_wrapper = categories_wrapper + '
';
            categories_wrapper = categories_wrapper + '';

            categories_wrapper = categories_wrapper + subCategory;
            categories_wrapper = categories_wrapper + '';
            categories_wrapper = categories_wrapper + '
';

            if (typeof categories[i][j] != "string")
            {
            	categories_wrapper = categories_wrapper + '
';
                categories_wrapper = categories_wrapper + '
';

            	for (var k in categories[i][j])
            	{

            		var subSubCategory = k;
            		var subSubCategoryTag = categories[i][j][k];

                    categories_wrapper = categories_wrapper + '
';
                    categories_wrapper = categories_wrapper + '
';
                    categories_wrapper = categories_wrapper + '';
                    categories_wrapper = categories_wrapper + subSubCategory;
                    categories_wrapper = categories_wrapper + '';
                    categories_wrapper = categories_wrapper + '
';
                    categories_wrapper = categories_wrapper + '
';

            	}

            	    categories_wrapper = categories_wrapper + '
';
                    categories_wrapper = categories_wrapper + '
';

            }

            categories_wrapper = categories_wrapper + '
';
        }

        categories_wrapper = categories_wrapper + '
';
        categories_wrapper = categories_wrapper + '
';
        categories_wrapper = categories_wrapper + '
';

	}

	categories_wrapper = categories_wrapper + "
";
	console.log(categories_wrapper);
	$('.columnLeft').append(categories_wrapper);
}
<|endoftext|>


<commit_before>class Dada2Module extends Module {
  constructor (params) {
    // lien de la doc
    super ("DADA2", "https://benjjneb.github.io/dada2/tutorial.html");
    this.params = params;
  }

  getConfiguration () {
    let conf = super.getConfiguration();

    // retieve the checked value of the radio html for by_lib
    var radios = document.getElementsByName('by_lib');
    for (let i=0 ; i<radios.length ; i++)
    	if (radios[i].checked)
    		conf.params.by_lib = radios[i].value

    var radios = document.getElementsByName('pool');
    for (let i=0 ; i<radios.length ; i++)
        if (radios[i].checked)
        conf.params.pool = radios[i].value

    return conf;
  };
};

module_manager.moduleCreators['DADA2'] = (params) => {
  return new Dada2Module(params);
}
<commit_msg>added the wiki page<commit_after>class Dada2Module extends Module {
  constructor (params) {
    // lien de la doc
    super ("DADA2", "https://github.com/trtcrd/SLIM/wiki/DADA2");
    this.params = params;
  }

  getConfiguration () {
    let conf = super.getConfiguration();

    // retieve the checked value of the radio html for by_lib
    var radios = document.getElementsByName('by_lib');
    for (let i=0 ; i<radios.length ; i++)
    	if (radios[i].checked)
    		conf.params.by_lib = radios[i].value

    var radios = document.getElementsByName('pool');
    for (let i=0 ; i<radios.length ; i++)
        if (radios[i].checked)
        conf.params.pool = radios[i].value

    return conf;
  };
};

module_manager.moduleCreators['DADA2'] = (params) => {
  return new Dada2Module(params);
}
<|endoftext|>


<commit_before>var stringify     = require("querystring").stringify,
    hmac          = require("crypto").createHmac,
    request       = require("request"),
    publicMethods = ['marketdata','marketdatav2','orderdata','singleorderdata','singlemarketdata'];

function CryptsyClient(key, secret) {
  var self    = this;
  self.key    = key;
  self.secret = secret;
  self.jar    = request.jar();

  function api_query(method, callback, args)
  {
    var args_tmp = {};

    for(i in args) {
      if(args[i]) {
        args_tmp[i] = args[i];
      }
    }

    args = args_tmp;

    var options = {
      uri     : 'https://api.cryptsy.com/api',
      agent   : false,
      method  : 'POST',
      jar     : self.jar,
      headers : {
        "User-Agent": "Mozilla/4.0 (compatible; Cryptsy API node client)",
        "Content-type": "application/x-www-form-urlencoded"
      }
    };

    args.method = method;

    if(publicMethods.indexOf(method) > -1)
    {
      options.method = 'GET';
      options.uri    = 'http://pubapi.cryptsy.com/api.php?' + stringify(args);
    }
    else
    {
      if (!self.key || !self.secret) {
        throw new Error("Must provide key and secret to make this API request.");
      }
      else
      {
        args.nonce = new Date().getTime();

        var message        = stringify(args);
        var signed_message = new hmac("sha512", self.secret);

        signed_message.update(message);

        options.headers.Key  = self.key;
        options.headers.Sign = signed_message.digest('hex');
        options.body         = message;
      }
    }
    request(options, function(err, res, body) {
      var error = null;

      if(!body || !res || res.statusCode != 200) {
        error = "Error in server response.";

        setTimeout(function() {
          api_query(method, callback, args);
        }, 500);
      }
      else {
        var response = JSON.parse(body);

        if(response.error) {
          error = response.error;
        }
      }

      if(typeof callback === 'function') {
        if(error) {
          callback.call(this, error, null);
        }
        else {
          callback.call(this, null, response.return);
        }
      }
    });
  }

  // This function gets the market id for a market in the format 'LTCBTC'
  self.getmarketid = function(marketname, callback) {
    if(typeof callback !== 'function') {
      throw new Error("'callback' argument must be a function.");
    }

    if(!self.markets || !self.markets.length) {
      self.getmarkets(function(error, markets) {
        callback.call(this, error, markets[marketname]);
      });
    }
    else {
      callback.call(this, null, self.markets[marketname]);
    }
  };

  // Old API method
  self.marketdata = function(callback) {
    api_query('marketdata', callback);
  }

  // New API method
  self.marketdatav2 = function(callback) {
    api_query('marketdatav2', callback);
  }

  self.singlemarketdata = function(marketid, callback) {
    api_query('singlemarketdata', callback, { marketid: marketid });
  }

  self.orderdata = function(callback) {
    api_query('orderdata', callback);
  }

  self.singleorderdata = function(marketid, callback) {
    api_query('singleorderdata', callback, { marketid: marketid });
  }

  self.getinfo = function(callback) {
    api_query("getinfo", callback);
  }

  self.getmarkets = function(callback) {
    callback2 = function(error, markets) {
      self.markets = {};
      for(var i in markets)
      {
        var primary   = markets[i].primary_currency_code;
        var secondary = markets[i].secondary_currency_code;

        self.markets[primary + secondary] = markets[i].marketid;
      }
      callback(error, markets);
    }
    api_query('getmarkets', callback2);
  }

  self.mytransactions = function(callback) {
    api_query('mytransactions', callback);
  }

  self.markettrades = function(marketid, callback) {
    api_query('markettrades', callback, { marketid: marketid });
  }

  self.marketorders = function(marketid, callback) {
    api_query('marketorders', callback, { marketid: marketid });
  }

  self.mytrades = function(marketid, limit, callback) {
    api_query('mytrades', callback, { marketid: marketid, limit: limit })
  }

  self.allmytrades = function(callback) {
    api_query('allmytrades', callback);
  }

  self.allmytradesdaterange = function(dates, callback) {
    api_query('allmytrades', callback, { startdate: dates.startdate, enddate: dates.enddate });
  }

  self.myorders = function(marketid, callback) {
    api_query('myorders', callback, { marketid: marketid });
  }

  self.allmyorders = function(callback) {
    api_query('allmyorders', callback);
  }

  self.createorder = function(marketid, ordertype, quantity, price, callback) {
    api_query('createorder', callback, { marketid: marketid, ordertype: ordertype, quantity: quantity, price: price });
  }

  self.cancelorder = function(orderid, callback) {
    api_query('cancelorder', callback, { orderid: orderid });
  }

  self.calculatefees = function(ordertype, quantity, price, callback) {
    api_query('calculatefees', callback, { ordertype: ordertype, quantity: quantity, price: price });
  }

  self.mytransfers = function(callback) {
    api_query('mytransfers', callback);
  }

  self.getwalletstatus = function(callback) {
    api_query('getwalletstatus', callback);
  }

  self.makewithdrawal = function(address, amount, callback) {
    api_query('makewithdrawal', callback, { address: address, amount: amount });
  }
}

module.exports = CryptsyClient;
<commit_msg>Now returns correct aggregated markets list when calling "getmarkets"<commit_after>var stringify     = require("querystring").stringify,
    hmac          = require("crypto").createHmac,
    request       = require("request"),
    publicMethods = ['marketdata','marketdatav2','orderdata','singleorderdata','singlemarketdata'];

function CryptsyClient(key, secret) {
  var self    = this;
  self.key    = key;
  self.secret = secret;
  self.jar    = request.jar();

  function api_query(method, callback, args)
  {
    var args_tmp = {};

    for(i in args) {
      if(args[i]) {
        args_tmp[i] = args[i];
      }
    }

    args = args_tmp;

    var options = {
      uri     : 'https://api.cryptsy.com/api',
      agent   : false,
      method  : 'POST',
      jar     : self.jar,
      headers : {
        "User-Agent": "Mozilla/4.0 (compatible; Cryptsy API node client)",
        "Content-type": "application/x-www-form-urlencoded"
      }
    };

    args.method = method;

    if(publicMethods.indexOf(method) > -1)
    {
      options.method = 'GET';
      options.uri    = 'http://pubapi.cryptsy.com/api.php?' + stringify(args);
    }
    else
    {
      if (!self.key || !self.secret) {
        throw new Error("Must provide key and secret to make this API request.");
      }
      else
      {
        args.nonce = new Date().getTime();

        var message        = stringify(args);
        var signed_message = new hmac("sha512", self.secret);

        signed_message.update(message);

        options.headers.Key  = self.key;
        options.headers.Sign = signed_message.digest('hex');
        options.body         = message;
      }
    }
    request(options, function(err, res, body) {
      var error = null;

      if(!body || !res || res.statusCode != 200) {
        error = "Error in server response.";

        setTimeout(function() {
          api_query(method, callback, args);
        }, 500);
      }
      else {
        var response = JSON.parse(body);

        if(response.error) {
          error = response.error;
        }
      }

      if(typeof callback === 'function') {
        if(error) {
          callback.call(this, error, null);
        }
        else {
          callback.call(this, null, response.return);
        }
      }
    });
  }

  // This function gets the market id for a market in the format 'LTCBTC'
  self.getmarketid = function(marketname, callback) {
    if(typeof callback !== 'function') {
      throw new Error("'callback' argument must be a function.");
    }

    if(!self.markets || !self.markets.length) {
      self.getmarkets(function(error, markets) {
        callback.call(this, error, markets[marketname]);
      });
    }
    else {
      callback.call(this, null, self.markets[marketname]);
    }
  };

  // Old API method
  self.marketdata = function(callback) {
    api_query('marketdata', callback);
  }

  // New API method
  self.marketdatav2 = function(callback) {
    api_query('marketdatav2', callback);
  }

  self.singlemarketdata = function(marketid, callback) {
    api_query('singlemarketdata', callback, { marketid: marketid });
  }

  self.orderdata = function(callback) {
    api_query('orderdata', callback);
  }

  self.singleorderdata = function(marketid, callback) {
    api_query('singleorderdata', callback, { marketid: marketid });
  }

  self.getinfo = function(callback) {
    api_query("getinfo", callback);
  }

  self.getmarkets = function(callback) {
    callback2 = function(error, markets) {
      self.markets = {};
      for(var i in markets)
      {
        var primary   = markets[i].primary_currency_code;
        var secondary = markets[i].secondary_currency_code;

        self.markets[primary + secondary] = markets[i].marketid;
      }
      callback(error, self.markets);
    }
    api_query('getmarkets', callback2);
  }

  self.mytransactions = function(callback) {
    api_query('mytransactions', callback);
  }

  self.markettrades = function(marketid, callback) {
    api_query('markettrades', callback, { marketid: marketid });
  }

  self.marketorders = function(marketid, callback) {
    api_query('marketorders', callback, { marketid: marketid });
  }

  self.mytrades = function(marketid, limit, callback) {
    api_query('mytrades', callback, { marketid: marketid, limit: limit })
  }

  self.allmytrades = function(callback) {
    api_query('allmytrades', callback);
  }

  self.allmytradesdaterange = function(dates, callback) {
    api_query('allmytrades', callback, { startdate: dates.startdate, enddate: dates.enddate });
  }

  self.myorders = function(marketid, callback) {
    api_query('myorders', callback, { marketid: marketid });
  }

  self.allmyorders = function(callback) {
    api_query('allmyorders', callback);
  }

  self.createorder = function(marketid, ordertype, quantity, price, callback) {
    api_query('createorder', callback, { marketid: marketid, ordertype: ordertype, quantity: quantity, price: price });
  }

  self.cancelorder = function(orderid, callback) {
    api_query('cancelorder', callback, { orderid: orderid });
  }

  self.calculatefees = function(ordertype, quantity, price, callback) {
    api_query('calculatefees', callback, { ordertype: ordertype, quantity: quantity, price: price });
  }

  self.mytransfers = function(callback) {
    api_query('mytransfers', callback);
  }

  self.getwalletstatus = function(callback) {
    api_query('getwalletstatus', callback);
  }

  self.makewithdrawal = function(address, amount, callback) {
    api_query('makewithdrawal', callback, { address: address, amount: amount });
  }
}

module.exports = CryptsyClient;
<|endoftext|>


<commit_before>
var originalSetTimeout = window.setTimeout,
    originalDateValueOf = Date.prototype.valueOf;

module('Ember.run.later', {
  teardown: function() {
    window.setTimeout = originalSetTimeout;
    Date.prototype.valueOf = originalDateValueOf;
  }
});

var previousPreventRunloop;

asyncTest('should invoke after specified period of time - function only', function() {

  var invoked = false;

  Ember.run(function() {
    Ember.run.later(function() { invoked = true; }, 100);
  });

  setTimeout(function() {
    start();
    equal(invoked, true, 'should have invoked later item');
  }, 150);

});

asyncTest('should invoke after specified period of time - target/method', function() {

  var obj = { invoked: false } ;

  Ember.run(function() {
    Ember.run.later(obj, function() { this.invoked = true; }, 100);
  });

  setTimeout(function() {
    start();
    equal(obj.invoked, true, 'should have invoked later item');
  }, 150);

});

asyncTest('should invoke after specified period of time - target/method/args', function() {

  var obj = { invoked: 0 } ;

  Ember.run(function() {
    Ember.run.later(obj, function(amt) { this.invoked += amt; }, 10, 100);
  });

  setTimeout(function() {
    start();
    equal(obj.invoked, 10, 'should have invoked later item');
  }, 150);

});

asyncTest('should always invoke within a separate runloop', function() {
  var obj = { invoked: 0 }, firstRunLoop, secondRunLoop;

  Ember.run(function() {
    firstRunLoop = Ember.run.currentRunLoop;

    Ember.run.later(obj, function(amt) {
      this.invoked += amt;
      secondRunLoop = Ember.run.currentRunLoop;
    }, 10, 1);

    // Synchronous "sleep". This simulates work being done
    // after run.later was called but before the run loop
    // has flushed. In previous versions, this would have
    // caused the run.later callback to have run from
    // within the run loop flush, since by the time the
    // run loop has to flush, it would have considered
    // the timer already expired.
    var pauseUntil = +new Date() + 100;
    while(+new Date() < pauseUntil) { /* do nothing - sleeping */ }
  });

  ok(firstRunLoop, "first run loop captured");
  ok(!Ember.run.currentRunLoop, "shouldn't be in a run loop after flush");
  equal(obj.invoked, 0, "shouldn't have invoked later item yet");

  setTimeout(function() {
    start();
    equal(obj.invoked, 10, "should have invoked later item");
    ok(secondRunLoop, "second run loop took place");
    ok(secondRunLoop !== firstRunLoop, "two different run loops took place");
  }, 150);
});

asyncTest('callback order', function() {

  var array = [];
  function fn(val) { array.push(val); }

  Ember.run(function() {
    Ember.run.later(this, fn, 4, 130);
    Ember.run.later(this, fn, 1, 10);
    Ember.run.later(this, fn, 5, 200);
    Ember.run.later(this, fn, 2, 80);
    Ember.run.later(this, fn, 3, 80);
  });

  deepEqual(array, []);

  setTimeout(function() {
    start();
    deepEqual(array, [1,2,3,4,5], 'callbacks were called in expected order');
  }, 250);
});

asyncTest('callbacks coalesce into same run loop if expiring at the same time', function() {

  var array = [];
  function fn(val) { array.push(Ember.run.currentRunLoop); }

  Ember.run(function() {

    // Force +new Date to return the same result while scheduling
    // run.later timers. Otherwise: non-determinism!
    var now = +new Date();
    Date.prototype.valueOf = function() { return now; };

    Ember.run.later(this, fn, 10);
    Ember.run.later(this, fn, 100);
    Ember.run.later(this, fn, 100);

    Date.prototype.valueOf = originalDateValueOf;
  });

  deepEqual(array, []);

  setTimeout(function() {
    start();
    equal(array.length, 3, 'all callbacks called');
    ok(array[0] !== array[1], 'first two callbacks have different run loops');
    ok(array[0], 'first runloop present');
    ok(array[1], 'second runloop present');
    equal(array[1], array[2], 'last two callbacks got the same run loop');
  }, 200);
});

asyncTest('inception calls to run.later should run callbacks in separate run loops', function() {

  var runLoop, finished;

  Ember.run(function() {
    runLoop = Ember.run.currentRunLoop;
    ok(runLoop);

    Ember.run.later(function() {
      ok(Ember.run.currentRunLoop && Ember.run.currentRunLoop !== runLoop,
         'first later callback has own run loop');
      runLoop = Ember.run.currentRunLoop;

      Ember.run.later(function() {
        ok(Ember.run.currentRunLoop && Ember.run.currentRunLoop !== runLoop,
           'second later callback has own run loop');
        finished = true;
      }, 40);
    }, 40);
  });

  setTimeout(function() {
    start();
    ok(finished, 'all .later callbacks run');
  }, 150);
});

asyncTest('setTimeout should never run with a negative wait', function() {

  // Rationale: The old run loop code was susceptible to an occasional
  // bug where invokeLaterTimers would be scheduled with a setTimeout
  // with a negative wait. Modern browsers normalize this to 0, but
  // older browsers (IE <= 8) break with a negative wait, which
  // happens when an expired timer callback takes a while to run,
  // which is what we simulate here.
  var newSetTimeoutUsed;
  window.setTimeout = function() {
    var wait = arguments[arguments.length - 1];
    newSetTimeoutUsed = true;
    ok(!isNaN(wait) && wait >= 0, 'wait is a non-negative number');
    originalSetTimeout.apply(this, arguments);
  };

  var count = 0;
  Ember.run(function() {

    Ember.run.later(function() {
      count++;

      // This will get run first. Waste some time.
      // This is intended to break invokeLaterTimers code by taking a
      // long enough time that other timers should technically expire. It's
      // fine that they're not called in this run loop; just need to
      // make sure that invokeLaterTimers doesn't end up scheduling
      // a negative setTimeout.
      var pauseUntil = +new Date() + 60;
      while(+new Date() < pauseUntil) { /* do nothing - sleeping */ }
    }, 1);

    Ember.run.later(function() {
      equal(count, 1, 'callbacks called in order');
    }, 50);
  });

  originalSetTimeout(function() {
    window.setTimeout = originalSetTimeout;
    start();
    ok(newSetTimeoutUsed, 'stub setTimeout was used');
  }, 200);
});
<commit_msg>Reduce late time to less than resolution capability of `setTimeout`<commit_after>
var originalSetTimeout = window.setTimeout,
    originalDateValueOf = Date.prototype.valueOf;

module('Ember.run.later', {
  teardown: function() {
    window.setTimeout = originalSetTimeout;
    Date.prototype.valueOf = originalDateValueOf;
  }
});

var previousPreventRunloop;

asyncTest('should invoke after specified period of time - function only', function() {

  var invoked = false;

  Ember.run(function() {
    Ember.run.later(function() { invoked = true; }, 100);
  });

  setTimeout(function() {
    start();
    equal(invoked, true, 'should have invoked later item');
  }, 150);

});

asyncTest('should invoke after specified period of time - target/method', function() {

  var obj = { invoked: false } ;

  Ember.run(function() {
    Ember.run.later(obj, function() { this.invoked = true; }, 100);
  });

  setTimeout(function() {
    start();
    equal(obj.invoked, true, 'should have invoked later item');
  }, 150);

});

asyncTest('should invoke after specified period of time - target/method/args', function() {

  var obj = { invoked: 0 } ;

  Ember.run(function() {
    Ember.run.later(obj, function(amt) { this.invoked += amt; }, 10, 100);
  });

  setTimeout(function() {
    start();
    equal(obj.invoked, 10, 'should have invoked later item');
  }, 150);

});

asyncTest('should always invoke within a separate runloop', function() {
  var obj = { invoked: 0 }, firstRunLoop, secondRunLoop;

  Ember.run(function() {
    firstRunLoop = Ember.run.currentRunLoop;

    Ember.run.later(obj, function(amt) {
      this.invoked += amt;
      secondRunLoop = Ember.run.currentRunLoop;
    }, 10, 1);

    // Synchronous "sleep". This simulates work being done
    // after run.later was called but before the run loop
    // has flushed. In previous versions, this would have
    // caused the run.later callback to have run from
    // within the run loop flush, since by the time the
    // run loop has to flush, it would have considered
    // the timer already expired.
    var pauseUntil = +new Date() + 100;
    while(+new Date() < pauseUntil) { /* do nothing - sleeping */ }
  });

  ok(firstRunLoop, "first run loop captured");
  ok(!Ember.run.currentRunLoop, "shouldn't be in a run loop after flush");
  equal(obj.invoked, 0, "shouldn't have invoked later item yet");

  setTimeout(function() {
    start();
    equal(obj.invoked, 10, "should have invoked later item");
    ok(secondRunLoop, "second run loop took place");
    ok(secondRunLoop !== firstRunLoop, "two different run loops took place");
  }, 150);
});

asyncTest('callback order', function() {
  var array = [];
  function fn(val) { array.push(val); }

  Ember.run(function() {
    Ember.run.later(this, fn, 4, 5);
    Ember.run.later(this, fn, 1, 1);
    Ember.run.later(this, fn, 5, 10);
    Ember.run.later(this, fn, 2, 3);
    Ember.run.later(this, fn, 3, 3);
  });

  deepEqual(array, []);

  setTimeout(function() {
    start();
    deepEqual(array, [1,2,3,4,5], 'callbacks were called in expected order');
  }, 100);
});

asyncTest('callbacks coalesce into same run loop if expiring at the same time', function() {
  var array = [];
  function fn(val) { array.push(Ember.run.currentRunLoop); }

  Ember.run(function() {

    // Force +new Date to return the same result while scheduling
    // run.later timers. Otherwise: non-determinism!
    var now = +new Date();
    Date.prototype.valueOf = function() { return now; };

    Ember.run.later(this, fn, 10);
    Ember.run.later(this, fn, 100);
    Ember.run.later(this, fn, 100);

    Date.prototype.valueOf = originalDateValueOf;
  });

  deepEqual(array, []);

  setTimeout(function() {
    start();
    equal(array.length, 3, 'all callbacks called');
    ok(array[0] !== array[1], 'first two callbacks have different run loops');
    ok(array[0], 'first runloop present');
    ok(array[1], 'second runloop present');
    equal(array[1], array[2], 'last two callbacks got the same run loop');
  }, 200);
});

asyncTest('inception calls to run.later should run callbacks in separate run loops', function() {

  var runLoop, finished;

  Ember.run(function() {
    runLoop = Ember.run.currentRunLoop;
    ok(runLoop);

    Ember.run.later(function() {
      ok(Ember.run.currentRunLoop && Ember.run.currentRunLoop !== runLoop,
         'first later callback has own run loop');
      runLoop = Ember.run.currentRunLoop;

      Ember.run.later(function() {
        ok(Ember.run.currentRunLoop && Ember.run.currentRunLoop !== runLoop,
           'second later callback has own run loop');
        finished = true;
      }, 40);
    }, 40);
  });

  setTimeout(function() {
    start();
    ok(finished, 'all .later callbacks run');
  }, 150);
});

asyncTest('setTimeout should never run with a negative wait', function() {

  // Rationale: The old run loop code was susceptible to an occasional
  // bug where invokeLaterTimers would be scheduled with a setTimeout
  // with a negative wait. Modern browsers normalize this to 0, but
  // older browsers (IE <= 8) break with a negative wait, which
  // happens when an expired timer callback takes a while to run,
  // which is what we simulate here.
  var newSetTimeoutUsed;
  window.setTimeout = function() {
    var wait = arguments[arguments.length - 1];
    newSetTimeoutUsed = true;
    ok(!isNaN(wait) && wait >= 0, 'wait is a non-negative number');
    originalSetTimeout.apply(this, arguments);
  };

  var count = 0;
  Ember.run(function() {

    Ember.run.later(function() {
      count++;

      // This will get run first. Waste some time.
      // This is intended to break invokeLaterTimers code by taking a
      // long enough time that other timers should technically expire. It's
      // fine that they're not called in this run loop; just need to
      // make sure that invokeLaterTimers doesn't end up scheduling
      // a negative setTimeout.
      var pauseUntil = +new Date() + 60;
      while(+new Date() < pauseUntil) { /* do nothing - sleeping */ }
    }, 1);

    Ember.run.later(function() {
      equal(count, 1, 'callbacks called in order');
    }, 50);
  });

  originalSetTimeout(function() {
    window.setTimeout = originalSetTimeout;
    start();
    ok(newSetTimeoutUsed, 'stub setTimeout was used');
  }, 200);
});
<|endoftext|>


<commit_before>require('ember-views/views/container_view');
require('ember-runtime/system/string');

/**
@module ember
@submodule ember-views
*/

var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt;

/**
  `Ember.CollectionView` is an `Ember.View` descendent responsible for managing
  a collection (an array or array-like object) by maintaing a child view object
  and associated DOM representation for each item in the array and ensuring
  that child views and their associated rendered HTML are updated when items in
  the array are added, removed, or replaced.

  ## Setting content

  The managed collection of objects is referenced as the `Ember.CollectionView`
  instance's `content` property.

  ```javascript
  someItemsView = Ember.CollectionView.create({
    content: ['A', 'B','C']
  })
  ```

  The view for each item in the collection will have its `content` property set
  to the item.

  ## Specifying itemViewClass

  By default the view class for each item in the managed collection will be an
  instance of `Ember.View`. You can supply a different class by setting the
  `CollectionView`'s `itemViewClass` property.

  Given an empty `<body>` and the following code:

  ```javascript
  someItemsView = Ember.CollectionView.create({
    classNames: ['a-collection'],
    content: ['A','B','C'],
    itemViewClass: Ember.View.extend({
      template: Ember.Handlebars.compile("the letter: {{view.content}}")
    })
  });

  someItemsView.appendTo('body');
  ```

  Will result in the following HTML structure

  ```html
  <div class="ember-view a-collection">
    <div class="ember-view">the letter: A</div>
    <div class="ember-view">the letter: B</div>
    <div class="ember-view">the letter: C</div>
  </div>
  ```

  ## Automatic matching of parent/child tagNames

  Setting the `tagName` property of a `CollectionView` to any of
  "ul", "ol", "table", "thead", "tbody", "tfoot", "tr", or "select" will result
  in the item views receiving an appropriately matched `tagName` property.

  Given an empty `<body>` and the following code:

  ```javascript
  anUndorderedListView = Ember.CollectionView.create({
    tagName: 'ul',
    content: ['A','B','C'],
    itemViewClass: Ember.View.extend({
      template: Ember.Handlebars.compile("the letter: {{view.content}}")
    })
  });

  anUndorderedListView.appendTo('body');
  ```

  Will result in the following HTML structure

  ```html
  <ul class="ember-view a-collection">
    <li class="ember-view">the letter: A</li>
    <li class="ember-view">the letter: B</li>
    <li class="ember-view">the letter: C</li>
  </ul>
  ```

  Additional `tagName` pairs can be provided by adding to
  `Ember.CollectionView.CONTAINER_MAP `

  ```javascript
  Ember.CollectionView.CONTAINER_MAP['article'] = 'section'
  ```

  ## Programatic creation of child views

  For cases where additional customization beyond the use of a single
  `itemViewClass` or `tagName` matching is required CollectionView's
  `createChildView` method can be overidden:

  ```javascript
  CustomCollectionView = Ember.CollectionView.extend({
    createChildView: function(viewClass, attrs) {
      if (attrs.content.kind == 'album') {
        viewClass = App.AlbumView;
      } else {
        viewClass = App.SongView;
      }
      this._super(viewClass, attrs);
    }
  });
  ```

  ## Empty View

  You can provide an `Ember.View` subclass to the `Ember.CollectionView`
  instance as its `emptyView` property. If the `content` property of a
  `CollectionView` is set to `null` or an empty array, an instance of this view
  will be the `CollectionView`s only child.

  ```javascript
  aListWithNothing = Ember.CollectionView.create({
    classNames: ['nothing']
    content: null,
    emptyView: Ember.View.extend({
      template: Ember.Handlebars.compile("The collection is empty")
    })
  });

  aListWithNothing.appendTo('body');
  ```

  Will result in the following HTML structure

  ```html
  <div class="ember-view nothing">
    <div class="ember-view">
      The collection is empty
    </div>
  </div>
  ```

  ## Adding and Removing items

  The `childViews` property of a `CollectionView` should not be directly
  manipulated. Instead, add, remove, replace items from its `content` property.
  This will trigger appropriate changes to its rendered HTML.

  ## Use in templates via the `{{collection}}` `Ember.Handlebars` helper

  `Ember.Handlebars` provides a helper specifically for adding
  `CollectionView`s to templates. See `Ember.Handlebars.collection` for more
  details

  @class CollectionView
  @namespace Ember
  @extends Ember.ContainerView
  @since Ember 0.9
*/
Ember.CollectionView = Ember.ContainerView.extend(
/** @scope Ember.CollectionView.prototype */ {

  /**
    A list of items to be displayed by the `Ember.CollectionView`.

    @property content
    @type Ember.Array
    @default null
  */
  content: null,

  /**
    @private

    This provides metadata about what kind of empty view class this
    collection would like if it is being instantiated from another
    system (like Handlebars)

    @property emptyViewClass
  */
  emptyViewClass: Ember.View,

  /**
    An optional view to display if content is set to an empty array.

    @property emptyView
    @type Ember.View
    @default null
  */
  emptyView: null,

  /**
    @property itemViewClass
    @type Ember.View
    @default Ember.View
  */
  itemViewClass: Ember.View,

  init: function() {
    var ret = this._super();
    this._contentDidChange();
    return ret;
  },

  _contentWillChange: Ember.beforeObserver(function() {
    var content = this.get('content');

    if (content) { content.removeArrayObserver(this); }
    var len = content ? get(content, 'length') : 0;
    this.arrayWillChange(content, 0, len);
  }, 'content'),

  /**
    @private

    Check to make sure that the content has changed, and if so,
    update the children directly. This is always scheduled
    asynchronously, to allow the element to be created before
    bindings have synchronized and vice versa.

    @method _contentDidChange
  */
  _contentDidChange: Ember.observer(function() {
    var content = get(this, 'content');

    if (content) {
      Ember.assert(fmt("an Ember.CollectionView's content must implement Ember.Array. You passed %@", [content]), Ember.Array.detect(content));
      content.addArrayObserver(this);
    }

    var len = content ? get(content, 'length') : 0;
    this.arrayDidChange(content, 0, null, len);
  }, 'content'),

  willDestroy: function() {
    var content = get(this, 'content');
    if (content) { content.removeArrayObserver(this); }

    this._super();
  },

  arrayWillChange: function(content, start, removedCount) {
    // If the contents were empty before and this template collection has an
    // empty view remove it now.
    var emptyView = get(this, 'emptyView');
    if (emptyView && emptyView instanceof Ember.View) {
      emptyView.removeFromParent();
    }

    // Loop through child views that correspond with the removed items.
    // Note that we loop from the end of the array to the beginning because
    // we are mutating it as we go.
    var childViews = this._childViews, childView, idx, len;

    len = this._childViews.length;

    var removingAll = removedCount === len;

    if (removingAll) {
      this.currentState.empty(this);
    }

    for (idx = start + removedCount - 1; idx >= start; idx--) {
      childView = childViews[idx];
      if (removingAll) { childView.removedFromDOM = true; }
      childView.destroy();
    }
  },

  /**
    Called when a mutation to the underlying content array occurs.

    This method will replay that mutation against the views that compose the
    `Ember.CollectionView`, ensuring that the view reflects the model.

    This array observer is added in `contentDidChange`.

    @method arrayDidChange
    @param {Array} addedObjects the objects that were added to the content
    @param {Array} removedObjects the objects that were removed from the content
    @param {Number} changeIndex the index at which the changes occurred
  */
  arrayDidChange: function(content, start, removed, added) {
    var itemViewClass = get(this, 'itemViewClass'),
        addedViews = [], view, item, idx, len, itemTagName;

    if ('string' === typeof itemViewClass) {
      itemViewClass = get(itemViewClass);
    }

    Ember.assert(fmt("itemViewClass must be a subclass of Ember.View, not %@", [itemViewClass]), Ember.View.detect(itemViewClass));

    len = content ? get(content, 'length') : 0;
    if (len) {
      for (idx = start; idx < start+added; idx++) {
        item = content.objectAt(idx);

        view = this.createChildView(itemViewClass, {
          content: item,
          contentIndex: idx
        });

        addedViews.push(view);
      }
    } else {
      var emptyView = get(this, 'emptyView');
      if (!emptyView) { return; }

      emptyView = this.createChildView(emptyView);
      addedViews.push(emptyView);
      set(this, 'emptyView', emptyView);
    }
    this.replace(start, 0, addedViews);
  },

  createChildView: function(view, attrs) {
    view = this._super(view, attrs);

    var itemTagName = get(view, 'tagName');
    var tagName = (itemTagName === null || itemTagName === undefined) ? Ember.CollectionView.CONTAINER_MAP[get(this, 'tagName')] : itemTagName;

    set(view, 'tagName', tagName);

    return view;
  }
});

/**
  A map of parent tags to their default child tags. You can add
  additional parent tags if you want collection views that use
  a particular parent tag to default to a child tag.

  @property CONTAINER_MAP
  @type Hash
  @static
  @final
*/
Ember.CollectionView.CONTAINER_MAP = {
  ul: 'li',
  ol: 'li',
  table: 'tr',
  thead: 'tr',
  tbody: 'tr',
  tfoot: 'tr',
  tr: 'td',
  select: 'option'
};
<commit_msg>CollectionView cleans up emptyView - Fixes #1957<commit_after>require('ember-views/views/container_view');
require('ember-runtime/system/string');

/**
@module ember
@submodule ember-views
*/

var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt;

/**
  `Ember.CollectionView` is an `Ember.View` descendent responsible for managing
  a collection (an array or array-like object) by maintaing a child view object
  and associated DOM representation for each item in the array and ensuring
  that child views and their associated rendered HTML are updated when items in
  the array are added, removed, or replaced.

  ## Setting content

  The managed collection of objects is referenced as the `Ember.CollectionView`
  instance's `content` property.

  ```javascript
  someItemsView = Ember.CollectionView.create({
    content: ['A', 'B','C']
  })
  ```

  The view for each item in the collection will have its `content` property set
  to the item.

  ## Specifying itemViewClass

  By default the view class for each item in the managed collection will be an
  instance of `Ember.View`. You can supply a different class by setting the
  `CollectionView`'s `itemViewClass` property.

  Given an empty `<body>` and the following code:

  ```javascript
  someItemsView = Ember.CollectionView.create({
    classNames: ['a-collection'],
    content: ['A','B','C'],
    itemViewClass: Ember.View.extend({
      template: Ember.Handlebars.compile("the letter: {{view.content}}")
    })
  });

  someItemsView.appendTo('body');
  ```

  Will result in the following HTML structure

  ```html
  <div class="ember-view a-collection">
    <div class="ember-view">the letter: A</div>
    <div class="ember-view">the letter: B</div>
    <div class="ember-view">the letter: C</div>
  </div>
  ```

  ## Automatic matching of parent/child tagNames

  Setting the `tagName` property of a `CollectionView` to any of
  "ul", "ol", "table", "thead", "tbody", "tfoot", "tr", or "select" will result
  in the item views receiving an appropriately matched `tagName` property.

  Given an empty `<body>` and the following code:

  ```javascript
  anUndorderedListView = Ember.CollectionView.create({
    tagName: 'ul',
    content: ['A','B','C'],
    itemViewClass: Ember.View.extend({
      template: Ember.Handlebars.compile("the letter: {{view.content}}")
    })
  });

  anUndorderedListView.appendTo('body');
  ```

  Will result in the following HTML structure

  ```html
  <ul class="ember-view a-collection">
    <li class="ember-view">the letter: A</li>
    <li class="ember-view">the letter: B</li>
    <li class="ember-view">the letter: C</li>
  </ul>
  ```

  Additional `tagName` pairs can be provided by adding to
  `Ember.CollectionView.CONTAINER_MAP `

  ```javascript
  Ember.CollectionView.CONTAINER_MAP['article'] = 'section'
  ```

  ## Programatic creation of child views

  For cases where additional customization beyond the use of a single
  `itemViewClass` or `tagName` matching is required CollectionView's
  `createChildView` method can be overidden:

  ```javascript
  CustomCollectionView = Ember.CollectionView.extend({
    createChildView: function(viewClass, attrs) {
      if (attrs.content.kind == 'album') {
        viewClass = App.AlbumView;
      } else {
        viewClass = App.SongView;
      }
      this._super(viewClass, attrs);
    }
  });
  ```

  ## Empty View

  You can provide an `Ember.View` subclass to the `Ember.CollectionView`
  instance as its `emptyView` property. If the `content` property of a
  `CollectionView` is set to `null` or an empty array, an instance of this view
  will be the `CollectionView`s only child.

  ```javascript
  aListWithNothing = Ember.CollectionView.create({
    classNames: ['nothing']
    content: null,
    emptyView: Ember.View.extend({
      template: Ember.Handlebars.compile("The collection is empty")
    })
  });

  aListWithNothing.appendTo('body');
  ```

  Will result in the following HTML structure

  ```html
  <div class="ember-view nothing">
    <div class="ember-view">
      The collection is empty
    </div>
  </div>
  ```

  ## Adding and Removing items

  The `childViews` property of a `CollectionView` should not be directly
  manipulated. Instead, add, remove, replace items from its `content` property.
  This will trigger appropriate changes to its rendered HTML.

  ## Use in templates via the `{{collection}}` `Ember.Handlebars` helper

  `Ember.Handlebars` provides a helper specifically for adding
  `CollectionView`s to templates. See `Ember.Handlebars.collection` for more
  details

  @class CollectionView
  @namespace Ember
  @extends Ember.ContainerView
  @since Ember 0.9
*/
Ember.CollectionView = Ember.ContainerView.extend(
/** @scope Ember.CollectionView.prototype */ {

  /**
    A list of items to be displayed by the `Ember.CollectionView`.

    @property content
    @type Ember.Array
    @default null
  */
  content: null,

  /**
    @private

    This provides metadata about what kind of empty view class this
    collection would like if it is being instantiated from another
    system (like Handlebars)

    @property emptyViewClass
  */
  emptyViewClass: Ember.View,

  /**
    An optional view to display if content is set to an empty array.

    @property emptyView
    @type Ember.View
    @default null
  */
  emptyView: null,

  /**
    @property itemViewClass
    @type Ember.View
    @default Ember.View
  */
  itemViewClass: Ember.View,

  init: function() {
    var ret = this._super();
    this._contentDidChange();
    return ret;
  },

  _contentWillChange: Ember.beforeObserver(function() {
    var content = this.get('content');

    if (content) { content.removeArrayObserver(this); }
    var len = content ? get(content, 'length') : 0;
    this.arrayWillChange(content, 0, len);
  }, 'content'),

  /**
    @private

    Check to make sure that the content has changed, and if so,
    update the children directly. This is always scheduled
    asynchronously, to allow the element to be created before
    bindings have synchronized and vice versa.

    @method _contentDidChange
  */
  _contentDidChange: Ember.observer(function() {
    var content = get(this, 'content');

    if (content) {
      Ember.assert(fmt("an Ember.CollectionView's content must implement Ember.Array. You passed %@", [content]), Ember.Array.detect(content));
      content.addArrayObserver(this);
    }

    var len = content ? get(content, 'length') : 0;
    this.arrayDidChange(content, 0, null, len);
  }, 'content'),

  willDestroy: function() {
    var content = get(this, 'content');
    if (content) { content.removeArrayObserver(this); }

    this._super();

    if (this._createdEmptyView) {
      this._createdEmptyView.destroy();
    }
  },

  arrayWillChange: function(content, start, removedCount) {
    // If the contents were empty before and this template collection has an
    // empty view remove it now.
    var emptyView = get(this, 'emptyView');
    if (emptyView && emptyView instanceof Ember.View) {
      emptyView.removeFromParent();
    }

    // Loop through child views that correspond with the removed items.
    // Note that we loop from the end of the array to the beginning because
    // we are mutating it as we go.
    var childViews = this._childViews, childView, idx, len;

    len = this._childViews.length;

    var removingAll = removedCount === len;

    if (removingAll) {
      this.currentState.empty(this);
    }

    for (idx = start + removedCount - 1; idx >= start; idx--) {
      childView = childViews[idx];
      if (removingAll) { childView.removedFromDOM = true; }
      childView.destroy();
    }
  },

  /**
    Called when a mutation to the underlying content array occurs.

    This method will replay that mutation against the views that compose the
    `Ember.CollectionView`, ensuring that the view reflects the model.

    This array observer is added in `contentDidChange`.

    @method arrayDidChange
    @param {Array} addedObjects the objects that were added to the content
    @param {Array} removedObjects the objects that were removed from the content
    @param {Number} changeIndex the index at which the changes occurred
  */
  arrayDidChange: function(content, start, removed, added) {
    var itemViewClass = get(this, 'itemViewClass'),
        addedViews = [], view, item, idx, len, itemTagName;

    if ('string' === typeof itemViewClass) {
      itemViewClass = get(itemViewClass);
    }

    Ember.assert(fmt("itemViewClass must be a subclass of Ember.View, not %@", [itemViewClass]), Ember.View.detect(itemViewClass));

    len = content ? get(content, 'length') : 0;
    if (len) {
      for (idx = start; idx < start+added; idx++) {
        item = content.objectAt(idx);

        view = this.createChildView(itemViewClass, {
          content: item,
          contentIndex: idx
        });

        addedViews.push(view);
      }
    } else {
      var emptyView = get(this, 'emptyView');
      if (!emptyView) { return; }

      var isClass = Ember.CoreView.detect(emptyView);

      emptyView = this.createChildView(emptyView);
      addedViews.push(emptyView);
      set(this, 'emptyView', emptyView);

      if (isClass) { this._createdEmptyView = emptyView; }
    }
    this.replace(start, 0, addedViews);
  },

  createChildView: function(view, attrs) {
    view = this._super(view, attrs);

    var itemTagName = get(view, 'tagName');
    var tagName = (itemTagName === null || itemTagName === undefined) ? Ember.CollectionView.CONTAINER_MAP[get(this, 'tagName')] : itemTagName;

    set(view, 'tagName', tagName);

    return view;
  }
});

/**
  A map of parent tags to their default child tags. You can add
  additional parent tags if you want collection views that use
  a particular parent tag to default to a child tag.

  @property CONTAINER_MAP
  @type Hash
  @static
  @final
*/
Ember.CollectionView.CONTAINER_MAP = {
  ul: 'li',
  ol: 'li',
  table: 'tr',
  thead: 'tr',
  tbody: 'tr',
  tfoot: 'tr',
  tr: 'td',
  select: 'option'
};
<|endoftext|>