<commit_before>// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
//$.ajaxSetup provides the default settings for $.ajax()
// beforeSend - pre-request callback used to modify jqXHR (XMLHTTPRequest). Returning false in this function cancels the request.
// data - data to be sent to server, converted to a questy string. Object is key:value pair
/*success - function to be called with the request succeeds. data - data retunred from the server (formatted according
to dataType parameter), string describing statys and the jqXHR (XMLHTTPRequest object). In the code below,
xhr is used to specify jqXHR

jqXHR object- jQuery XMLHTTPRequest is superset of XMLHTTPRequest. It contains- responseTest, responseXML, getResponseHeader() method.
The XMLHttpRequest object is used to exchange data with a server behind the scenes.

*/

$(window).load(function(){
$.ajaxSetup({
'beforeSend': function(xhr) { xhr.setRequestHeader("Accept", "text/javascript") }
});

//sending height, width of resizable image. ID is sent as rid
  $("#.cat img").resizable({ handles:'n,e,s,w,ne,se,nw,sw' , maxHeight: 300, aspectRatio: true,
  stop: function(event, ui) {

$.ajax({
type: 'POST',
url: 'http://high-robot-603.heroku.com/jmsg',
dataType: 'json',
data:{ width: ui.size["width"], height: ui.size["height"], rid:$(this).parent().attr('id')},
success: function(json, status, xhr)
{ // alert ('Success')
//$("#show_message").html("hello world");
},
error: function(data, status, xhr){ //alert('Failure')
}
});
}
});

//sending height, width of resizable image. ID is sent as rid
$("#.cat img").load( function(){
$("#.cat img").resizable({ handles:'n,e,s,w,ne,se,nw,sw' , maxHeight: 300, aspectRatio: true,
  stop: function(event, ui) {

$.ajax({
type: 'POST',
url: 'http://high-robot-603.heroku.com/jmsg',
dataType: 'json',
data:{ width: ui.size["width"], height: ui.size["height"], rid:$(this).parent().attr('id')},
success: function(json, status, xhr)
{ // alert ('Success')
//$("#show_message").html("hello world");
},
error: function(data, status, xhr){ //alert('Failure')
}
});
}
});

});

// Making all cats draggable

    $("#cat1").draggable({containment: "#droppable", snap:false, cursor: "move"});
$("#cat2").draggable({containment: "#droppable", snap:false, cursor: "move"});
    $("#cat3").draggable({containment: "#droppable", snap:false, cursor: "move"});
	    $("#cat4").draggable({containment: "#droppable", snap:false, cursor: "move"});
	$("#cat5").draggable({containment: "#droppable", snap:false, cursor: "move"});
	    $("#cat6").draggable({containment: "#droppable", snap:false, cursor: "move"});

// Making all hats draggable
    $("#hat1").draggable({containment: "#droppable", snap:false, cursor: "move"});
$("#hat2").draggable({containment: "#droppable", snap:false, cursor: "move"});
    $("#hat3").draggable({containment: "#droppable", snap:false, cursor: "move"});
	  $("#hat4").draggable({containment: "#droppable", snap:false, cursor: "move"});
	$("#hat5").draggable({containment: "#droppable", snap:false, cursor: "move"});
	    $("#hat6").draggable({containment: "#droppable", snap:false, cursor: "move"});

  $( "#droppable" ).droppable({
      drop: function( event, ui ) {
        $( this ).find( "p" ).hide();
        var offset1=$("#droppable").offset();
$.ajax({
type: 'POST',
url: 'http://high-robot-603.heroku.com/jmsg',
dataType: 'json',
data:{ top: ui.offset["top"], left: ui.offset["left"], pid: (ui.draggable).attr("id"), backx: offset1.left, backy: offset1.top  },
success: function(json, status, xhr)
{ // alert ('Success')
//$("#show_message").html("hello world");
},
error: function(data, status, xhr){alert('Failure')}
});
      }
    });

   var resizeTimer;
	$(window).resize (function() {
		clearTimeout(resizeTimer, 100);
		resizeTimer=setTimeout(doSomething,100);
			});

	function doSomething(){
	var offset1 = $("#droppable").offset();
	$.ajax({
	type: 'POST',
	url: 'http://high-robot-603.heroku.com/jmsg',
	dataType: 'json',
	data:{ backx: offset1.left, backy: offset1.top  },
	success: function(json, status, xhr)
	{ // alert ('Success')
	//$("#show_message").html("hello world");
	},
	error: function(data, status, xhr){alert('Failure')}
	});
	}

	       $("#various1").fancybox({
					'titlePosition'		: 'inside',
					'transitionIn'		: 'none',
					'transitionOut'		: 'none'
		   });

	       $("#various2").fancybox({
					'titlePosition'		: 'inside',
					'transitionIn'		: 'none',
					'transitionOut'		: 'none'
		   });

		  $("#various3").fancybox({
					'titlePosition'		: 'inside',
					'transitionIn'		: 'none',
					'transitionOut'		: 'none'
		   });

          $("#various4").fancybox({
					'titlePosition'		: 'inside',
					'transitionIn'		: 'none',
					'transitionOut'		: 'none'
		   });
		$("#uploadcat").fancybox({
					'titlePosition'		: 'inside',
					'transitionIn'		: 'none',
					'transitionOut'		: 'none',
					'type' : 'iframe'
		   });

        $(".onesec-hor a:has(img)").fancybox();

});

$(document).ready(function (){
$(".background_choices img").click(function() {
  alert('Handler for .click() called.');
  var backimg=$(this).parent().find("img").attr("src");
  	$.ajax({
	type: 'POST',
	url: 'http://high-robot-603.heroku.com/jmsg',
	dataType: 'json',
	data:{ backimg: backimg},
	success: function(json, status, xhr)
	{ // alert ('Success')
	//$("#show_message").html("hello world");
	},
	error: function(data, status, xhr){alert('Failure')}
	});

   });

   });

<commit_msg>replacing background image in game page after click<commit_after>// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
//$.ajaxSetup provides the default settings for $.ajax()
// beforeSend - pre-request callback used to modify jqXHR (XMLHTTPRequest). Returning false in this function cancels the request.
// data - data to be sent to server, converted to a questy string. Object is key:value pair
/*success - function to be called with the request succeeds. data - data retunred from the server (formatted according
to dataType parameter), string describing statys and the jqXHR (XMLHTTPRequest object). In the code below,
xhr is used to specify jqXHR

jqXHR object- jQuery XMLHTTPRequest is superset of XMLHTTPRequest. It contains- responseTest, responseXML, getResponseHeader() method.
The XMLHttpRequest object is used to exchange data with a server behind the scenes.

*/

$(window).load(function(){
$.ajaxSetup({
'beforeSend': function(xhr) { xhr.setRequestHeader("Accept", "text/javascript") }
});

//sending height, width of resizable image. ID is sent as rid
  $("#.cat img").resizable({ handles:'n,e,s,w,ne,se,nw,sw' , maxHeight: 300, aspectRatio: true,
  stop: function(event, ui) {

$.ajax({
type: 'POST',
url: 'http://high-robot-603.heroku.com/jmsg',
dataType: 'json',
data:{ width: ui.size["width"], height: ui.size["height"], rid:$(this).parent().attr('id')},
success: function(json, status, xhr)
{ // alert ('Success')
//$("#show_message").html("hello world");
},
error: function(data, status, xhr){ //alert('Failure')
}
});
}
});

//sending height, width of resizable image. ID is sent as rid
$("#.cat img").load( function(){
$("#.cat img").resizable({ handles:'n,e,s,w,ne,se,nw,sw' , maxHeight: 300, aspectRatio: true,
  stop: function(event, ui) {

$.ajax({
type: 'POST',
url: 'http://high-robot-603.heroku.com/jmsg',
dataType: 'json',
data:{ width: ui.size["width"], height: ui.size["height"], rid:$(this).parent().attr('id')},
success: function(json, status, xhr)
{ // alert ('Success')
//$("#show_message").html("hello world");
},
error: function(data, status, xhr){ //alert('Failure')
}
});
}
});

});

// Making all cats draggable

    $("#cat1").draggable({containment: "#droppable", snap:false, cursor: "move"});
$("#cat2").draggable({containment: "#droppable", snap:false, cursor: "move"});
    $("#cat3").draggable({containment: "#droppable", snap:false, cursor: "move"});
	    $("#cat4").draggable({containment: "#droppable", snap:false, cursor: "move"});
	$("#cat5").draggable({containment: "#droppable", snap:false, cursor: "move"});
	    $("#cat6").draggable({containment: "#droppable", snap:false, cursor: "move"});

// Making all hats draggable
    $("#hat1").draggable({containment: "#droppable", snap:false, cursor: "move"});
$("#hat2").draggable({containment: "#droppable", snap:false, cursor: "move"});
    $("#hat3").draggable({containment: "#droppable", snap:false, cursor: "move"});
	  $("#hat4").draggable({containment: "#droppable", snap:false, cursor: "move"});
	$("#hat5").draggable({containment: "#droppable", snap:false, cursor: "move"});
	    $("#hat6").draggable({containment: "#droppable", snap:false, cursor: "move"});

  $( "#droppable" ).droppable({
      drop: function( event, ui ) {
        $( this ).find( "p" ).hide();
        var offset1=$("#droppable").offset();
$.ajax({
type: 'POST',
url: 'http://high-robot-603.heroku.com/jmsg',
dataType: 'json',
data:{ top: ui.offset["top"], left: ui.offset["left"], pid: (ui.draggable).attr("id"), backx: offset1.left, backy: offset1.top  },
success: function(json, status, xhr)
{ // alert ('Success')
//$("#show_message").html("hello world");
},
error: function(data, status, xhr){alert('Failure')}
});
      }
    });

   var resizeTimer;
	$(window).resize (function() {
		clearTimeout(resizeTimer, 100);
		resizeTimer=setTimeout(doSomething,100);
			});

	function doSomething(){
	var offset1 = $("#droppable").offset();
	$.ajax({
	type: 'POST',
	url: 'http://high-robot-603.heroku.com/jmsg',
	dataType: 'json',
	data:{ backx: offset1.left, backy: offset1.top  },
	success: function(json, status, xhr)
	{ // alert ('Success')
	//$("#show_message").html("hello world");
	},
	error: function(data, status, xhr){alert('Failure2')}
	});
	}

	       $("#various1").fancybox({
					'titlePosition'		: 'inside',
					'transitionIn'		: 'none',
					'transitionOut'		: 'none'
		   });

	       $("#various2").fancybox({
					'titlePosition'		: 'inside',
					'transitionIn'		: 'none',
					'transitionOut'		: 'none'
		   });

		  $("#various3").fancybox({
					'titlePosition'		: 'inside',
					'transitionIn'		: 'none',
					'transitionOut'		: 'none'
		   });

          $("#various4").fancybox({
					'titlePosition'		: 'inside',
					'transitionIn'		: 'none',
					'transitionOut'		: 'none'
		   });
		$("#uploadcat").fancybox({
					'titlePosition'		: 'inside',
					'transitionIn'		: 'none',
					'transitionOut'		: 'none',
					'type' : 'iframe'
		   });

        $(".onesec-hor a:has(img)").fancybox();

});

$(document).ready(function (){
$(".background_choices img").click(function() {
  alert('Handler for .click() called.');
  var backimg=$(this).parent().find("img").attr("src");
  	$.ajax({
	type: 'POST',
	url: 'http://high-robot-603.heroku.com/jmsg',
	dataType: 'json',
	data:{ backimg: backimg},
	success: function(json, status, xhr)
	{ // alert ('Success')
	//$("#show_message").html("hello world");
	},
	error: function(data, status, xhr){alert('Failure1')}
	});

   });

   });

<|endoftext|>


<commit_before>/*
This file is part of SOS Pomoc application.

SOS Pomoc application is free software: you can redistribute it and/or
modify it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

SOS Pomoc application is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public
License along with SOS Pomoc application.  If not, see
<http://www.gnu.org/licenses/>.
*/

var express = require('express')
  , nodemailer = require('nodemailer')
  , connectLivereload = require('connect-livereload');

module.exports = function() {
  this.mailer = nodemailer.createTransport('sendmail');
  this.config = {
    mail : {
      support_email :
    }
  }
  //XXX somehow this has to befor static middleware which is
  // completely opposite to connect-livereload documentation
  this.use(connectLivereload());
  this.use(express.static(__dirname + '/../../public'));
  this.use(express.static(__dirname + '/../../.tmp'));
  this.use(express.errorHandler());
}
<commit_msg>Dev env fix<commit_after>/*
This file is part of SOS Pomoc application.

SOS Pomoc application is free software: you can redistribute it and/or
modify it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

SOS Pomoc application is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public
License along with SOS Pomoc application.  If not, see
<http://www.gnu.org/licenses/>.
*/

var express = require('express')
  , nodemailer = require('nodemailer')
  , connectLivereload = require('connect-livereload');

module.exports = function() {
  this.mailer = nodemailer.createTransport('sendmail');
  //XXX somehow this has to befor static middleware which is
  // completely opposite to connect-livereload documentation
  this.use(connectLivereload());
  this.use(express.static(__dirname + '/../../public'));
  this.use(express.static(__dirname + '/../../.tmp'));
  this.use(express.errorHandler());
}
<|endoftext|>


<commit_before>var slackMsgs = require('./slackMsgs.js');
var url = require('url');
var Trello = require('node-trello');
var rp = require('request-promise');
var app_key = process.env.HUBOT_TRELLO_KEY;
var oauth_secret = process.env.HUBOT_TRELLO_OAUTH;
var db = require("./mlab-login").db();

module.exports = function(robot) {

    var oauth_secrets = {};
    var loginCallback = `https://andreasbot.herokuapp.com/hubot/trello-token`;
    var tOAuth = new Trello.OAuth(app_key, oauth_secret, loginCallback, 'Hubot');

    robot.respond(/trello auth/, function(res) {
        tOAuth.getRequestToken(function(err, data) {
            robot.logger.warning(data)
            oauth_secrets[data.oauth_token] = data.oauth_token_secret;
            res.send(data.redirect);
        })
    })

    robot.router.get('/hubot/trello-token', function(req, res) {
        let args = req.query;
        let query = url.parse(req.url, true).query;
        let token = query.oauth_token;
        args['oauth_token_secret'] = oauth_secrets[token];
        robot.logger.info(args);
        tOAuth.getAccessToken(args, function(err, data) {
            if (err) throw err;
            let token = data['oauth_access_token'];
			// ADD ONLY THR TOKEN and USERNAME
			// BCRYPT!!!!!!!!!!
            let t = new Trello(app_key, token);
            db.collection('trello').insert(t, function(err, result) {
                if (err) throw err;
                if (result) robot.logger.info('Token Added to DB!');
            })
        })
        res.redirect('/a');
    });

    robot.respond(/trello get token/i, function(res_r) {

        let scope = 'read,write,account';
        let name = 'Hubot';
        let expr = '30days';
        let cb_method = 'fragment';
        let return_url = 'https://andreasbot.herokuapp.com/hubot/trello-token';
        let url = `https://trello.com/1/authorize?expiration=${expr}&name=${name}&scope=${scope}&key=${key}&response_type=token&callback_method=${cb_method}&return_url=${return_url}`;
        var msg = slackMsgs.basicMessage();

        msg.attachments[0].pretext = "Please get a token to authorize your Trello account";
        msg.attachments[0].title = "Trello Token";
        msg.attachments[0].title_link = url;
        msg.attachments[0].text = "Copy the token from the link above and run\n *trello add token <YOUR TOKEN>*";
        msg.attachments[0].footer = "Trello";
        msg.attachments[0].footer_icon = "https://d2k1ftgv7pobq7.cloudfront.net/meta/u/res/images/b428584f224c42e98d158dad366351b0/trello-mark-blue.png";
        res_r.send(msg);
    })

    robot.respond(/trello add token (.*)/i, function(res_r) {
        var token = res_r.match[1];
        //***IMPORTANT***
        // the .env assignment doesnt work with HEROKU!
        // must set up a heroku client and communicate through their api
        process.env['HUBOT_TRELLO_TOKEN'] = token;
    })
}<commit_msg>testing html<commit_after>var slackMsgs = require('./slackMsgs.js');
var url = require('url');
var Trello = require('node-trello');
var rp = require('request-promise');
var app_key = process.env.HUBOT_TRELLO_KEY;
var oauth_secret = process.env.HUBOT_TRELLO_OAUTH;
var db = require("./mlab-login").db();

module.exports = function(robot) {

    var oauth_secrets = {};
    var loginCallback = `https://andreasbot.herokuapp.com/hubot/trello-token`;
    var tOAuth = new Trello.OAuth(app_key, oauth_secret, loginCallback, 'Hubot');

    robot.respond(/trello auth/, function(res) {
        tOAuth.getRequestToken(function(err, data) {
            robot.logger.warning(data)
            oauth_secrets[data.oauth_token] = data.oauth_token_secret;
            res.send(data.redirect);
        })
    })

    robot.router.get('/hubot/trello-token', function(req, res) {
        let args = req.query;
        let query = url.parse(req.url, true).query;
        let token = query.oauth_token;
        args['oauth_token_secret'] = oauth_secrets[token];
        robot.logger.info(args);
        tOAuth.getAccessToken(args, function(err, data) {
            if (err) throw err;
            let token = data['oauth_access_token'];
			// ADD ONLY THR TOKEN and USERNAME
			// BCRYPT!!!!!!!!!!
            let t = new Trello(app_key, token);
            db.collection('trello').insert(t, function(err, result) {
                if (err) throw err;
                if (result) robot.logger.info('Token Added to DB!');
            })
        })
        res.close();//('/a');
    });

    robot.respond(/trello get token/i, function(res_r) {

        let scope = 'read,write,account';
        let name = 'Hubot';
        let expr = '30days';
        let cb_method = 'fragment';
        let return_url = 'https://andreasbot.herokuapp.com/hubot/trello-token';
        let url = `https://trello.com/1/authorize?expiration=${expr}&name=${name}&scope=${scope}&key=${key}&response_type=token&callback_method=${cb_method}&return_url=${return_url}`;
        var msg = slackMsgs.basicMessage();

        msg.attachments[0].pretext = "Please get a token to authorize your Trello account";
        msg.attachments[0].title = "Trello Token";
        msg.attachments[0].title_link = url;
        msg.attachments[0].text = "Copy the token from the link above and run\n *trello add token <YOUR TOKEN>*";
        msg.attachments[0].footer = "Trello";
        msg.attachments[0].footer_icon = "https://d2k1ftgv7pobq7.cloudfront.net/meta/u/res/images/b428584f224c42e98d158dad366351b0/trello-mark-blue.png";
        res_r.send(msg);
    })

    robot.respond(/trello add token (.*)/i, function(res_r) {
        var token = res_r.match[1];
        //***IMPORTANT***
        // the .env assignment doesnt work with HEROKU!
        // must set up a heroku client and communicate through their api
        process.env['HUBOT_TRELLO_TOKEN'] = token;
    })
}<|endoftext|>


<commit_before>// register the directive with your app module
var app = angular.module('ddApp', ['ngAnimate', 'ui.bootstrap', 'rzModule']);

// function referenced by the drop target
app.controller('ddController', ['$scope', '$uibModal', '$log','$http', function($scope, $uibModal, $log, $http){
    $scope.sliderOptions = {
        floor: 0,
        ceil: 0,
        vertical: true,
        showSelectionBar: true,
        showTicksValues: true,
        ticksValuesTooltip: function (v) {
            return 'Level ' + v;
        }
    };
    $scope.z = 0;
    $scope.startTile = {x: 0, y: 0, z: 0};
    $scope.numberOfCheckpoints = 0;
    $scope.height = 1;
    $scope.sliderOptions.ceil = $scope.height - 1;
    $scope.width = 1;
    $scope.length = 1;
    $scope.name = "Awesome Testbana";
    $scope.cells = {};

    if(mapId){
        $http.get("/api/maps/" + mapId + "?populate=true").then(function(response){
            $scope.startTile = response.data.startTile;
            $scope.numberOfCheckpoints = response.data.numberOfCheckpoints;
            $scope.height = response.data.height;
            $scope.sliderOptions.ceil = $scope.height - 1;
            $scope.width = response.data.width;
            $scope.length = response.data.length;
            $scope.name = response.data.name;
        }, function(response){
            console.log("Error: " + response.statusText);
        });
    }

    $scope.range = function(n){
        arr = [];
        for (var i=0; i < n; i++) {
            arr.push(i);
        }
        return arr;
    }

    $scope.$watch('startTile', function(newValue, oldValue){
	$scope.cells[oldValue.x+','+oldValue.y+','+oldValue.z].checkpoint = false;
	$scope.cells[newValue.x+','+newValue.y+','+newValue.z].checkpoint = true;
    });

    $scope.saveMap = function(){
        var map = {
            name: $scope.name,
            length: $scope.length,
            height: $scope.height,
            width: $scope.width,
            numberOfCheckpoints: $scope.numberOfCheckpoints,
            startTile: $scope.startTile
        };

        $http.post("/api/maps/createmap/", map).then(function(response){
            alert("Success!");
            console.log(response.data);
            window.location.replace("/maze/editor/" + response.data.id)
        }, function(response){
            console.log(response);
            console.log("Error: " + response.statusText);
        });
    }

    $scope.cellClick = function(x,y,z,isWall,isTile){

	var cell = $scope.cells[x+','+y+','+z];

	// If wall
	if(isWall){
	    if(!cell){
		$scope.cells[x+','+y+','+z] = {isWall: true};
	    }else{
		cell.isWall = !cell.isWall;
	    }
	}
	else if(isTile){
	    if(!cell){
		$scope.cells[x+','+y+','+z] = {isTile: true};
	    }
	    $scope.open(x,y,z);
	}
    }

    $scope.open = function(x,y,z) {
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: '/templates/maze_editor_modal.html',
            controller: 'ModalInstanceCtrl',
            size: 'sm',
            resolve: {
                tile: function () {
                    return $scope.cells[x+','+y+','+z];
                },
                start: function(){
                    return $scope.startTile.x == x && $scope.startTile.y == y && $scope.startTile.z == z;
                }
            }
        });

        modalInstance.result.then(function(isStart) {
            if(isStart){
                $scope.startTile.x = x;
                $scope.startTile.y = y;
                $scope.startTile.z = z;
            }
        }, function () {
            console.log('Modal dismissed at: ' + new Date());
        });
    };

}]);

// Please note that $uibModalInstance represents a modal window (instance) dependency.
// It is not the same as the $uibModal service used above.

app.controller('ModalInstanceCtrl', function ($scope, $uibModalInstance, tile, start) {
    $scope.tile = tile;
    $scope.start = start;
    $scope.ok = function () {
	$uibModalInstance.close($scope.start);
    };
});

<commit_msg>Add debug prints<commit_after>// register the directive with your app module
var app = angular.module('ddApp', ['ngAnimate', 'ui.bootstrap', 'rzModule']);

// function referenced by the drop target
app.controller('ddController', ['$scope', '$uibModal', '$log','$http', function($scope, $uibModal, $log, $http){
    $scope.sliderOptions = {
        floor: 0,
        ceil: 0,
        vertical: true,
        showSelectionBar: true,
        showTicksValues: true,
        ticksValuesTooltip: function (v) {
            return 'Level ' + v;
        }
    };
    $scope.z = 0;
    $scope.startTile = {x: 0, y: 0, z: 0};
    $scope.numberOfCheckpoints = 0;
    $scope.height = 1;
    $scope.sliderOptions.ceil = $scope.height - 1;
    $scope.width = 1;
    $scope.length = 1;
    $scope.name = "Awesome Testbana";
    $scope.cells = {};

    if(mapId){
        $http.get("/api/maps/" + mapId + "?populate=true").then(function(response){
            $scope.startTile = response.data.startTile;
            $scope.numberOfCheckpoints = response.data.numberOfCheckpoints;
            $scope.height = response.data.height;
            $scope.sliderOptions.ceil = $scope.height - 1;
            $scope.width = response.data.width;
            $scope.length = response.data.length;
            $scope.name = response.data.name;
        }, function(response){
            console.log("Error: " + response.statusText);
        });
    }

    $scope.range = function(n){
        arr = [];
        for (var i=0; i < n; i++) {
            arr.push(i);
        }
        return arr;
    }

    $scope.$watch('startTile', function(newValue, oldValue){
	console.log("new:",newValue);
	console.log("old:",oldValue);
	$scope.cells[oldValue.x+','+oldValue.y+','+oldValue.z].checkpoint = false;
	$scope.cells[newValue.x+','+newValue.y+','+newValue.z].checkpoint = true;
    });

    $scope.saveMap = function(){
        var map = {
            name: $scope.name,
            length: $scope.length,
            height: $scope.height,
            width: $scope.width,
            numberOfCheckpoints: $scope.numberOfCheckpoints,
            startTile: $scope.startTile
        };

        $http.post("/api/maps/createmap/", map).then(function(response){
            alert("Success!");
            console.log(response.data);
            window.location.replace("/maze/editor/" + response.data.id)
        }, function(response){
            console.log(response);
            console.log("Error: " + response.statusText);
        });
    }

    $scope.cellClick = function(x,y,z,isWall,isTile){

	var cell = $scope.cells[x+','+y+','+z];

	// If wall
	if(isWall){
	    if(!cell){
		$scope.cells[x+','+y+','+z] = {isWall: true};
	    }else{
		cell.isWall = !cell.isWall;
	    }
	}
	else if(isTile){
	    if(!cell){
		$scope.cells[x+','+y+','+z] = {isTile: true};
	    }
	    $scope.open(x,y,z);
	}
    }

    $scope.open = function(x,y,z) {
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: '/templates/maze_editor_modal.html',
            controller: 'ModalInstanceCtrl',
            size: 'sm',
            resolve: {
                tile: function () {
                    return $scope.cells[x+','+y+','+z];
                },
                start: function(){
                    return $scope.startTile.x == x && $scope.startTile.y == y && $scope.startTile.z == z;
                }
            }
        });

        modalInstance.result.then(function(isStart) {
            if(isStart){
                $scope.startTile.x = x;
                $scope.startTile.y = y;
                $scope.startTile.z = z;
            }
        }, function () {
            console.log('Modal dismissed at: ' + new Date());
        });
    };

}]);

// Please note that $uibModalInstance represents a modal window (instance) dependency.
// It is not the same as the $uibModal service used above.

app.controller('ModalInstanceCtrl', function ($scope, $uibModalInstance, tile, start) {
    $scope.tile = tile;
    $scope.start = start;
    $scope.ok = function () {
	$uibModalInstance.close($scope.start);
    };
});

<|endoftext|>


<commit_before>var config = {
     environment: 'development'
    ,port: 8181
    ,host: '127.0.0.1'
    ,enable_cors: true
    ,cache_enabled: false
    ,postgres: {
        type: "postgis",
        user: "tileuser",
        host: '127.0.0.1',
        port: 5432,
        geometry_field: "the_geom",
        extent: "-180,-90,180,90",
        srid: 4326,
        max_size: 0,
        simplify: true
    }
    ,redis: {
        host: '127.0.0.1',
        port: 6379,
        idleTimeoutMillis: 1,
        reapIntervalMillis: 1
    }
    ,sqlapi: {
        protocol: 'http',
        host: 'localhost.lan',
        port: 8080,
        version: 'v1'
    }
    ,varnish: {
        host: 'localhost',
        port: 6082
    }
};

module.exports = config;<commit_msg>Have development env use the_geom_webmercator, matching production<commit_after>var config = {
     environment: 'development'
    ,port: 8181
    ,host: '127.0.0.1'
    ,enable_cors: true
    ,cache_enabled: false
    ,postgres: {
        type: "postgis",
        user: "tileuser",
        host: '127.0.0.1',
        port: 5432,
        /* experimental
        geometry_field: "the_geom",
        extent: "-180,-90,180,90",
        srid: 4326,
        */
        max_size: 0,
        simplify: true
    }
    ,redis: {
        host: '127.0.0.1',
        port: 6379,
        idleTimeoutMillis: 1,
        reapIntervalMillis: 1
    }
    ,sqlapi: {
        protocol: 'http',
        host: 'localhost.lan',
        port: 8080,
        version: 'v1'
    }
    ,varnish: {
        host: 'localhost',
        port: 6082
    }
};

module.exports = config;
<|endoftext|>


<commit_before>require('es6-shim');

var express = require('express');
var app;
var appMgr;
var devMgr;

var monitoredDevices = [];
var supportedTypes;

exports.createAppliance = function(applianceManager) {
  if (!app) {
    appMgr = applianceManager;
    devMgr = appMgr.deviceManager;

    app = express();
    app.set('views', __dirname + '/views');
    app.use(express.static(__dirname + '/public'));

    app.get('/', index);
    app.get('/getDevicesByType', getDevicesByType);
    app.get('/getSupportedTypes', getSupportedTypes);
    appMgr.io.of('/dashboard').on('connection', handleDashboardSocketConnection);

    //TODO: fill this array through plugins
    supportedTypes = [
      { 'name': 'All', 'value': [ devMgr.DeviceType.TEMPERATURE_SENSOR ] },
      { 'name': 'Temperature Sensor', 'value': [ devMgr.DeviceType.TEMPERATURE_SENSOR ] },
    ];
  }

  return app;
}

function index(req, res) {
  res.render('index.jade', { });
}

function getDevicesByType(req, res) {
  devMgr.getDevicesByType(req.query.types, function(devices) {
    res.json(devices.filter(function(element) { return monitoredDevices.indexOf(element) == -1; }).map(deviceDescriptor));
  });
}

function getSupportedTypes(req, res) {
  res.json(supportedTypes);
}

function handleDashboardSocketConnection(socket) {
  socket.emit('init', monitoredDevices.map(deviceDescriptor));
  socket.on('addMonitoredDevice', addMonitoredDevice);
  socket.on('removeDevice', removeDevice);
  socket.on('updateDevice', updateDevice);
}

function addMonitoredDevice(deviceID) {
  devMgr.getDeviceByID(deviceID, function(device) {
    monitoredDevices.push(device);
    getUpdatedDeviceData(device);
    appMgr.io.of('/dashboard').emit('deviceAdded', deviceDescriptor(device));
  });
}

function removeDevice(deviceID) {
  monitoredDevices = monitoredDevices.filter(function(dev) {
    return dev.id != deviceID;
  });

  appMgr.io.of('/dashboard').emit('deviceRemoved', deviceID);
}

function updateDevice(deviceID) {
  devMgr.getDeviceByID(deviceID, function(device) {
    getUpdatedDeviceData(device);
  });
}

function getUpdatedDeviceData(device) {
  //TODO: here registered plugins should be able to query data depending on types
  if (device.deviceInfo.type == devMgr.DeviceType.TEMPERATURE_SENSOR) {
    devMgr.getData(device, handleTemperatureDataReceived.bind(null, processFormattedResponse));
  }
}

function processFormattedResponse(command, formattedResponse) {
  appMgr.io.of('/dashboard').emit('deviceUpdated', command.device.id, formattedResponse);
}

function handleTemperatureDataReceived(cb, command, response) {
  var units = ['K', 'C', 'F'];
  var thermoData = response.getFirstChild(0xA1);

  var temperature = thermoData.getFirstChild(0x82).getIntValue() / thermoData.getFirstChild(0x81).getUIntValue();
  var unit = thermoData.getFirstChild(0x80).getUIntValue();
  cb(command, temperature + ' ' + units[unit]);
}

function deviceDescriptor(device) {
  return { 'id': device.id, 'name': device.deviceInfo.name, 'value': '...' };
}
<commit_msg>type id are converted back to numbers<commit_after>require('es6-shim');

var express = require('express');
var app;
var appMgr;
var devMgr;

var monitoredDevices = [];
var supportedTypes;

exports.createAppliance = function(applianceManager) {
  if (!app) {
    appMgr = applianceManager;
    devMgr = appMgr.deviceManager;

    app = express();
    app.set('views', __dirname + '/views');
    app.use(express.static(__dirname + '/public'));

    app.get('/', index);
    app.get('/getDevicesByType', getDevicesByType);
    app.get('/getSupportedTypes', getSupportedTypes);
    appMgr.io.of('/dashboard').on('connection', handleDashboardSocketConnection);

    //TODO: fill this array through plugins
    supportedTypes = [
      { 'name': 'All', 'value': [ devMgr.DeviceType.TEMPERATURE_SENSOR ] },
      { 'name': 'Temperature Sensor', 'value': [ devMgr.DeviceType.TEMPERATURE_SENSOR ] },
    ];
  }

  return app;
}

function index(req, res) {
  res.render('index.jade', { });
}

function getDevicesByType(req, res) {
  devMgr.getDevicesByType(req.query.types.map(function(a) { return parseInt(a); }), function(devices) {
    res.json(devices.filter(function(element) { return monitoredDevices.indexOf(element) == -1; }).map(deviceDescriptor));
  });
}

function getSupportedTypes(req, res) {
  res.json(supportedTypes);
}

function handleDashboardSocketConnection(socket) {
  socket.emit('init', monitoredDevices.map(deviceDescriptor));
  socket.on('addMonitoredDevice', addMonitoredDevice);
  socket.on('removeDevice', removeDevice);
  socket.on('updateDevice', updateDevice);
}

function addMonitoredDevice(deviceID) {
  devMgr.getDeviceByID(deviceID, function(device) {
    monitoredDevices.push(device);
    getUpdatedDeviceData(device);
    appMgr.io.of('/dashboard').emit('deviceAdded', deviceDescriptor(device));
  });
}

function removeDevice(deviceID) {
  monitoredDevices = monitoredDevices.filter(function(dev) {
    return dev.id != deviceID;
  });

  appMgr.io.of('/dashboard').emit('deviceRemoved', deviceID);
}

function updateDevice(deviceID) {
  devMgr.getDeviceByID(deviceID, function(device) {
    getUpdatedDeviceData(device);
  });
}

function getUpdatedDeviceData(device) {
  //TODO: here registered plugins should be able to query data depending on types
  if (device.deviceInfo.type == devMgr.DeviceType.TEMPERATURE_SENSOR) {
    devMgr.getData(device, handleTemperatureDataReceived.bind(null, processFormattedResponse));
  }
}

function processFormattedResponse(command, formattedResponse) {
  appMgr.io.of('/dashboard').emit('deviceUpdated', command.device.id, formattedResponse);
}

function handleTemperatureDataReceived(cb, command, response) {
  var units = ['K', 'C', 'F'];
  var thermoData = response.getFirstChild(0xA1);

  var temperature = thermoData.getFirstChild(0x82).getIntValue() / thermoData.getFirstChild(0x81).getUIntValue();
  var unit = thermoData.getFirstChild(0x80).getUIntValue();
  cb(command, temperature + ' ' + units[unit]);
}

function deviceDescriptor(device) {
  return { 'id': device.id, 'name': device.deviceInfo.name, 'value': '...' };
}
<|endoftext|>


<commit_before>var slackMsgs = require('./slackMsgs.js');
var url = require('url');
var Trello = require('node-trello');
var rp = require('request-promise');
var key = process.env.HUBOT_TRELLO_KEY;
var secret = process.env.HUBOT_TRELLO_OAUTH;

module.exports = function(robot) {

    var oauth_secrets = {};
    var loginCallback = `https://andreasbot.herokuapp.com/hubot/trello-token`;
    var t = new Trello.OAuth(key, secret, loginCallback, 'App Name');

	robot.respond(/trello auth/, function(res) {
        t.getRequestToken(function(err, data) {
            robot.logger.warning(data)
            oauth_secrets[data.oauth_token] = data.oauth_token_secret;
            res.send(data.redirect);
        })
    })

    robot.router.get('/hubot/trello-token', function(req, res) {
        let args = req.query;
        let query = url.parse(req.url, true).query;
        let token = query.oauth_token;
        args['oauth_token_secret'] = oauth_secrets[token];
        robot.logger.info(args);
        t.getAccessToken(args, function(err, data) {
            if (err) throw err;
            robot.logger.warning(data);
        })
        res.redirect('www.google.com')
    });

    robot.respond(/trello get token/i, function(res_r) {

        let scope = 'read,write,account';
        let name = 'Hubot';
        let expr = '30days';
        let cb_method = 'fragment';
        let return_url = 'https://andreasbot.herokuapp.com/hubot/trello-token';
        let url = `https://trello.com/1/authorize?expiration=${expr}&name=${name}&scope=${scope}&key=${key}&response_type=token&callback_method=${cb_method}&return_url=${return_url}`;
        var msg = slackMsgs.basicMessage();

        msg.attachments[0].pretext = "Please get a token to authorize your Trello account";
        msg.attachments[0].title = "Trello Token";
        msg.attachments[0].title_link = url;
        msg.attachments[0].text = "Copy the token from the link above and run\n *trello add token <YOUR TOKEN>*";
        msg.attachments[0].footer = "Trello";
        msg.attachments[0].footer_icon = "https://d2k1ftgv7pobq7.cloudfront.net/meta/u/res/images/b428584f224c42e98d158dad366351b0/trello-mark-blue.png";
        res_r.send(msg);
    })

    // robot.router.get('/hubot/trello-token', function (req, res) {
    // 	// TODO: do something with the token
    // 	// robot.logger.info(res.fragment);	// undefined
    // 	// var type = window.location.hash.substr(1);
    // 	// robot.logger.info(req);
    // 	res.send(`
Token succesfuly received. You can now close the window.
\n
    // 				<button onclick=window.close()>close</button>`)
    // });

    robot.respond(/trello add token (.*)/i, function(res_r) {
        var token = res_r.match[1];
        //***IMPORTANT***
        // the .env assignment doesnt work with HEROKU!
        // must set up a heroku client and communicate through their api
        process.env['HUBOT_TRELLO_TOKEN'] = token;
    })

    robot.respond(/trello request/, function(res_r) {
        var options = {
            uri: 'https://trello.com/1/authorize?expiration=30days&name=Hubot&scope=read,write,account&key=51def9cb08cf171cd0970d8607ad8f97&response_type=token&callback_method=postMessage&return_url=https://andreasbot.herokuapp.com/hubot/trello-token',
            headers: {
                'User-Agent': 'Request-Promise'
            },
            json: true // Automatically parses the JSON string in the response
        };

        rp(options)
            .then(function(res) {
                robot.logger.info(res);
            })
            .catch(function(err) {
                robot.logger.error(err)
                // API call failed...
            });
    })
}<commit_msg>trello token<commit_after>var slackMsgs = require('./slackMsgs.js');
var url = require('url');
var Trello = require('node-trello');
var rp = require('request-promise');
var key = process.env.HUBOT_TRELLO_KEY;
var secret = process.env.HUBOT_TRELLO_OAUTH;

module.exports = function(robot) {

    var oauth_secrets = {};
    var loginCallback = `https://andreasbot.herokuapp.com/hubot/trello-token`;
    var t = new Trello.OAuth(key, secret, loginCallback, 'App Name');

	robot.respond(/trello auth/, function(res) {
        t.getRequestToken(function(err, data) {
            robot.logger.warning(data)
            oauth_secrets[data.oauth_token] = data.oauth_token_secret;
            res.send(data.redirect);
        })
    })

    robot.router.get('/hubot/trello-token', function(req, res) {
        let args = req.query;
        let query = url.parse(req.url, true).query;
        let token = query.oauth_token;
        args['oauth_token_secret'] = oauth_secrets[token];
        robot.logger.info(args);
        t.getAccessToken(args, function(err, data) {
            if (err) throw err;
            robot.logger.warning(data);
        })
        res.close();
    });

    robot.respond(/trello get token/i, function(res_r) {

        let scope = 'read,write,account';
        let name = 'Hubot';
        let expr = '30days';
        let cb_method = 'fragment';
        let return_url = 'https://andreasbot.herokuapp.com/hubot/trello-token';
        let url = `https://trello.com/1/authorize?expiration=${expr}&name=${name}&scope=${scope}&key=${key}&response_type=token&callback_method=${cb_method}&return_url=${return_url}`;
        var msg = slackMsgs.basicMessage();

        msg.attachments[0].pretext = "Please get a token to authorize your Trello account";
        msg.attachments[0].title = "Trello Token";
        msg.attachments[0].title_link = url;
        msg.attachments[0].text = "Copy the token from the link above and run\n *trello add token <YOUR TOKEN>*";
        msg.attachments[0].footer = "Trello";
        msg.attachments[0].footer_icon = "https://d2k1ftgv7pobq7.cloudfront.net/meta/u/res/images/b428584f224c42e98d158dad366351b0/trello-mark-blue.png";
        res_r.send(msg);
    })

    // robot.router.get('/hubot/trello-token', function (req, res) {
    // 	// TODO: do something with the token
    // 	// robot.logger.info(res.fragment);	// undefined
    // 	// var type = window.location.hash.substr(1);
    // 	// robot.logger.info(req);
    // 	res.send(`
Token succesfuly received. You can now close the window.
\n
    // 				<button onclick=window.close()>close</button>`)
    // });

    robot.respond(/trello add token (.*)/i, function(res_r) {
        var token = res_r.match[1];
        //***IMPORTANT***
        // the .env assignment doesnt work with HEROKU!
        // must set up a heroku client and communicate through their api
        process.env['HUBOT_TRELLO_TOKEN'] = token;
    })

    robot.respond(/trello request/, function(res_r) {
        var options = {
            uri: 'https://trello.com/1/authorize?expiration=30days&name=Hubot&scope=read,write,account&key=51def9cb08cf171cd0970d8607ad8f97&response_type=token&callback_method=postMessage&return_url=https://andreasbot.herokuapp.com/hubot/trello-token',
            headers: {
                'User-Agent': 'Request-Promise'
            },
            json: true // Automatically parses the JSON string in the response
        };

        rp(options)
            .then(function(res) {
                robot.logger.info(res);
            })
            .catch(function(err) {
                robot.logger.error(err)
                // API call failed...
            });
    })
}<|endoftext|>


<commit_before>
'use strict';

var ace = require('brace');

require('brace/mode/markdown');
require('../documents/theme-dillinger');

module.exports =
  angular
  .module('diBase', [
    'diBase.controllers.about',
    'diBase.directives.switch',
    'diBase.directives.documentTitle',
    'diBase.directives.menuToggle',
    'diBase.directives.settingsToggle',
    'diBase.directives.previewToggle',
    'diBase.directives.preview'
  ])
  .controller('Base', function($scope, $timeout, $rootScope, userService, documentsService) {

  var updateDocument;

  $scope.profile             = userService.profile;
  $rootScope.currentDocument = documentsService.getCurrentDocument();
  $rootScope.editor          = ace.edit('editor');

  $rootScope.editor.getSession().setMode('ace/mode/markdown');
  $rootScope.editor.setTheme('ace/theme/dillinger');
  $rootScope.editor.getSession().setUseWrapMode(true);
  $rootScope.editor.setShowPrintMargin(false);
  $rootScope.editor.getSession().setValue($rootScope.currentDocument.body);
  $rootScope.editor.setOption('minLines', 50);
  $rootScope.editor.setOption('maxLines', 90000);

  updateDocument = function() {
    $rootScope.currentDocument = documentsService.getCurrentDocument();
    return $rootScope.editor.getSession().setValue($rootScope.currentDocument.body);
  };

  $scope.updateDocument = updateDocument;

  $rootScope.$on('document.refresh', updateDocument);

});
<commit_msg>Adds experimental code for D&D file import<commit_after>
'use strict';

var ace = require('brace');

require('brace/mode/markdown');
require('../documents/theme-dillinger');

module.exports =
  angular
  .module('diBase', [
    'diBase.controllers.about',
    'diBase.directives.switch',
    'diBase.directives.documentTitle',
    'diBase.directives.menuToggle',
    'diBase.directives.settingsToggle',
    'diBase.directives.previewToggle',
    'diBase.directives.preview'
  ])
  .controller('Base', function($scope, $rootScope, userService, documentsService) {

  $scope.profile             = userService.profile;
  $rootScope.currentDocument = documentsService.getCurrentDocument();
  $rootScope.editor          = ace.edit('editor');

  $rootScope.editor.getSession().setMode('ace/mode/markdown');
  $rootScope.editor.setTheme('ace/theme/dillinger');
  $rootScope.editor.getSession().setUseWrapMode(true);
  $rootScope.editor.setShowPrintMargin(false);
  $rootScope.editor.getSession().setValue($rootScope.currentDocument.body);
  $rootScope.editor.setOption('minLines', 50);
  $rootScope.editor.setOption('maxLines', 90000);

  var updateDocument = function() {
    $rootScope.currentDocument = documentsService.getCurrentDocument();
    return $rootScope.editor.getSession().setValue($rootScope.currentDocument.body);
  };

  $scope.updateDocument = updateDocument;

  $rootScope.$on('document.refresh', updateDocument);

  var holder=document.body;
//  alert(holder);
  holder.ondragover = function () { return false; };
holder.ondragend = function () { return false; };
  holder.ondrop = function(event) {
    //alert(event.dataTransfer.files[0]);
    //console.log(event.dataTransfer.files);
var file = event.dataTransfer.files[0];
    var reader = new FileReader();
    reader.onload = function(event) {
//alert(event.target.result);
//alert(document.querySelector('#editor textarea').value);
//alert(document.querySelector('#editor textarea').innerHTML);
//document.querySelector('#editor textarea').innerHTML = event.target.result;

//$rootScope.editor.getSession()
//$scope.$apply(function() {

documentsService.setCurrentDocumentTitle(file.name);
documentsService.setCurrentDocumentBody(event.target.result);
updateDocument();
//});
    };
     reader.readAsText(file);
    event.preventDefault();
  };

});
<|endoftext|>


<commit_before>define([
       'underscore',
       'basecollection',
       'models/Layer',
       './utils/Parser',
       './utils/Conf',
], function(_, BaseCollection, Layer, Parser, Conf){
    var private = {};

    var OpenLayersUtil = {
        getProjection: function() {
            return {
                projection: new OpenLayers.Projection("EPSG:900913"),
                displayProjection: new OpenLayers.Projection("EPSG:4326")
            };
        },

        getFeatureFields: function(callback) {
            var request = OpenLayers.Request.GET({
                url: 'https://owsdemo.exactearth.com/ows?service=wfs&version=1.1.0&request=DescribeFeatureType&typeName=exactAIS:LVI&authKey=tokencoin',
                proxy: Conf.featureSetProxy,
                success: function (response) {
                    var parser = new OpenLayers.Format.WFSDescribeFeatureType(),
                        parsedData = Parser.parseFeatures(parser.read(response.responseText));

                    callback(null, parsedData);
                },
                error: function(err) {
                    callback(err);
                }
            });
        },

        getFilterCapabilities: function(callback) {
            var request = OpenLayers.Request.GET({
                url: 'https://owsdemo.exactearth.com/ows?service=wfs&version=1.1.0&request=GetCapabilities&authKey=tokencoin',
                proxy: Conf.getCapabilitiesProxy,
                success: function (response) {
                    var capabilities = JSON.parse(response.responseText),
                        filterCapabilities = _.toArray(capabilities)[0]["ogc:Filter_Capabilities"];

                    callback(null, filterCapabilities);
                },
                error: function(err) {
                    callback(err);
                }
            });
        },

        parseLayerTypes: function(layers) {
            var parsedLayers = {};

            eeStoredLayers = layers.filter(function(layer) {
                return layer.get("isExactEarth");
            });
            customLayers = layers.reject(function(layer) {
                return (layer.get("isExactEarth") || layer.get("isBaseLayer"));
            });
            baseLayers = layers.filter(function(layer) {
                return layer.get("isBaseLayer");
            });

            parsedLayers.eeStoredLayers = new BaseCollection(eeStoredLayers, {model: Layer});
            parsedLayers.customLayers = new BaseCollection(customLayers, {model: Layer});
            parsedLayers.baseLayers = new BaseCollection(baseLayers, {model: Layer});

            return parsedLayers;
        },

        getLayers: function(layerCapabilitiesURL, callback) {
            var url = request = null;

            if (layerCapabilitiesURL === null)
                layerCapabilitiesURL = 'https://owsdemo.exactearth.com/ows?service=wms&version=1.3.0&request=GetCapabilities&authKey=tokencoin';

            request = OpenLayers.Request.GET({
                url: layerCapabilitiesURL,
                proxy: Conf.getCapabilitiesProxy,
                success: function (response) {
                    var capabilities = JSON.parse(response.responseText),
                        layers = _.toArray(capabilities.WMS_Capabilities.Capability.Layer.Layer);

                    callback(null, layers);
                },
                error: function(err) {
                    callback(err);
                }
            });
        },

        getTypeDropdownValues: function(type) {
            var values = Conf.scalarFilterCapabilties.byType[type];

            return values || ["na"];
        },

        determineNumberOfInputs: function(propertyType) {
            propertyType = propertyType.toLowerCase();
            console.log(propertyType);
            switch (propertyType) {
                case "string":
                    return 1;
                    break;
                case "integer":
                case "int":
                case "double":
                case "long":
                case "decimal":
                    return 2;
                    break;
            }

            return -1; //This means it's a geometric constraint
        },

        convertXMLFilterToOLFilter: function(xmlFilter) {
            var parser,
                xml,
                mapFilterConverted,
                newFilter,
                filters = [newFilter]

            parser = new OpenLayers.Format.Filter.v1_1_0 ();
            xml = new OpenLayers.Format.XML();

            olFilter = parser.read(xml.read(xmlFilter).documentElement);

            return olFilter;
        },

        mergeActiveFilters: function(newFilter, mapFilter) {
            var filters = [newFilter];

            if (mapFilter) {
                mapFilterConverted = this.convertXMLFilterToOLFilter(mapFilter);
                filters.push(mapFilterConverted);
            }

            newFilter = new OpenLayers.Filter.Logical({
                type: OpenLayers.Filter.Logical.AND,
                filters: filters
            });

            return newFilter;
        },

        createOpenLayersFilters: function(filters) {
            var simplifiedFilters = [];

            for (var i = 0, len = filters.length; i< len; i++) {
                simplifiedFilters.push({operators: filters[i].get("operators")})
            };

            return this.convertFilterToFilterParam(simplifiedFilters);
        },

        convertFilterToFilterParam: function(filters) {
            var olFilters = new OpenLayers.Filter.Logical({
                type: OpenLayers.Filter.Logical.AND
            });

            for (var i = 0, len = filters.length; i< len; i++) {
                for (var j = 0, olen = filters[i].operators.length; j < olen; j++) {
                    olFilters.filters.push(filters[i].operators[j]);
                }
            }

            var filter_1_0 = new OpenLayers.Format.Filter({version: "1.1.0"});
            var xml = new OpenLayers.Format.XML();
            var filter_param = xml.write(filter_1_0.write(olFilters));
            console.log(filter_param);

            return filter_param;

        },

        addControlsToMap: function(view, currentFilter) {
            var map = view.model,
                oInfoControl = new OpenLayers.Control.WMSGetFeatureInfo({
                    name: "GetFeatureInfo",
                    url: 'https://owsdemo.exactearth.com/wms?authKey=tokencoin',
                        title: 'Identify features by clicking',
                    infoFormat: "application/vnd.ogc.gml",
                    queryVisible: true,
                    filter: this.convertXMLFilterToOLFilter(currentFilter),
                    eventListeners: {
                        getfeatureinfo: function(evt) {
                            view.showInfo(evt, view);
                            view.applyTrack(evt, view);
                        }
                    }
                });

            map.addControl(oInfoControl);
            oInfoControl.activate();

            /**************************
            * Measure Controls
            **************************/
            var measureControl = new OpenLayers.Control.DynamicMeasure(
                OpenLayers.Handler.Path,
                {
                    name: "Measure",
                    persist: true
                }
            );

            map.addControl(measureControl);

            var graticuleControl = new OpenLayers.Control.Graticule({
                name: "Graticule",
                numPoints: 2,
                labelled: true,
                autoActivate: false
            });

            map.addControl(graticuleControl);
        },

        addActiveLayersToMap: function(eeLayers, userLayers, view) {
            console.log(eeLayers);
            var layersToAddToMap = [];
                haveActiveBaseLayer = false, //Used to keep track if we've added a baselayer yet.
                parsedLayers = this.parseLayerTypes(userLayers);

            //I made four collection because I figure this is easier than filtering on demand.
            //Especially in the view designed to allow a user to choose styles. That page is divided
            //into EE layers and custom layers -- this will make it easier
            view.eeStoredLayers = parsedLayers.eeStoredLayers;
            view.customLayers = parsedLayers.customLayers;
            view.baseLayers = parsedLayers.baseLayers;

            view.baseLayers.each(function(baseLayer) {
                var eeBaseLayer;
                switch (baseLayer.get("mapType")) {
                    case "OSM":
                        eeBaseLayer = new OpenLayers.Layer.OSM("OSMBaseMap", null,
                            {
                                isBaseLayer: true,
                                wrapDateLine: true,
                                transitionEffect: "resize",
                                tileOptions: {crossOriginKeyword: null}
                            });
                        break;
                    case "WMS":
                        eeBaseLayer = new OpenLayers.Layer.WMS("WMSBaseMap", "http://vmap0.tiles.osgeo.org/wms/vmap0",
                            {
                                layers: "basic"
                            },
                            {
                                isBaseLayer: true,
                                wrapDateLine: true,
                                transitionEffect: "resize",
                                tileOptions: {crossOriginKeyword: null}
                            });
                        break;
                }

                view.model.addLayer(eeBaseLayer);

                if (baseLayer.get("active")) {
                    if (haveActiveBaseLayer) { //Dealing with duplicate base layer error
                        baseLayer.set("active", false);
                        baseLayer.update();
                    }

                    view.model.setBaseLayer(eeBaseLayer);
                    haveActiveBaseLayer = true;
                }
            });

            if (!haveActiveBaseLayer) {
                var basicMapLayer = new OpenLayers.Layer.OSM("OSMBaseMap", null,
                    {
                        isBaseLayer: true,
                        wrapDateLine: true,
                        transitionEffect: "resize",
                        tileOptions: {crossOriginKeyword: null}
                    });
                view.model.addLayer(basicMapLayer);

                var basicMapLayer = new OpenLayers.Layer.WMS("WMSBaseMap", "http://vmap0.tiles.osgeo.org/wms/vmap0",
                    {layers: "basic"},
                    {
                        isBaseLayer: true,
                        wrapDateLine: true,
                        transitionEffect: "resize"
                    });
            }

            _.each(eeLayers, function(eeLayer) {
                var layer,
                    userLayer = userLayers.findWhere({name: eeLayer.Name}),
                    params = {};

                    if (userLayer)
                        params = userLayer.get("exactEarthParams");

                    layer = new OpenLayers.Layer.WMS(
                        eeLayer.Name, "https://owsdemo.exactearth.com/wms?authKey=tokencoin",
                        params,
                        {
                            singleTile: false,
                            ratio: 1,
                            yx: { 'EPSG:4326': true },
                            wrapDateLine: true
                        }
                    );

                    view.model.addLayer(layer);
                    view.model.setLayerIndex(layer, userLayer.get("order"));
                    layer.setVisibility(userLayer && userLayer.get("active"));
            });

            //Combine ee and custom layers since they can intermingle when assigning order
            userLayers = userLayers.reject(function(layer) {
                return layer.get("isBaseLayer");
            });

            view.userLayers = new BaseCollection(userLayers, {model: Layer});

            view.layersLoaded = true;
            view.loadInitialFilters();

        },

        getShipCount: function(bounds, currentFilter, callback) {
            var filter,
                mapProjection = this.getProjection();

            filter = new OpenLayers.Filter.Spatial({
                type: OpenLayers.Filter.Spatial.BBOX,
                property: "position",
                value: bounds.transform(mapProjection.projection, mapProjection.displayProjection)
            });

            if (currentFilter instanceof Array)
                currentFilter = this.createOpenLayersFilters(currentFilter);

            filter = this.mergeActiveFilters(filter, currentFilter);

            var  wfsProtocol = new OpenLayers.Protocol.WFS.v1_1_0({
                url: "/proxy/getWFSFeatures?url=https://owsdemo.exactearth.com/ows?service=wfs&version=1.1.0&request=GetFeature&typeName=exactAIS:LVI&authKey=tokencoin",
                featurePrefix: "",
                featureType: "exactAIS:LVI",
            });

            wfsProtocol.read ({
                filter: filter,
                callback: function(response) {
                    Backbone.globalEvents.trigger("fetchedShipCount", response.numberOfFeatures);

                    if (_.isFunction(callback)) {
                        callback(response.numberOfFeatures);
                    }
                },
                readOptions: {output: "object"},
                resultType: "hits",
                maxFeatures: null,
                scope: new OpenLayers.Strategy.Fixed
            });

        }
    };

    return OpenLayersUtil;
});

<commit_msg>Refactored algorithm to apply subfilters. Everything works with ANDing only<commit_after>define([
       'underscore',
       'basecollection',
       'models/Layer',
       './utils/Parser',
       './utils/Conf',
], function(_, BaseCollection, Layer, Parser, Conf){
    var private = {};

    var OpenLayersUtil = {
        getProjection: function() {
            return {
                projection: new OpenLayers.Projection("EPSG:900913"),
                displayProjection: new OpenLayers.Projection("EPSG:4326")
            };
        },

        getFeatureFields: function(callback) {
            var request = OpenLayers.Request.GET({
                url: 'https://owsdemo.exactearth.com/ows?service=wfs&version=1.1.0&request=DescribeFeatureType&typeName=exactAIS:LVI&authKey=tokencoin',
                proxy: Conf.featureSetProxy,
                success: function (response) {
                    var parser = new OpenLayers.Format.WFSDescribeFeatureType(),
                        parsedData = Parser.parseFeatures(parser.read(response.responseText));

                    callback(null, parsedData);
                },
                error: function(err) {
                    callback(err);
                }
            });
        },

        getFilterCapabilities: function(callback) {
            var request = OpenLayers.Request.GET({
                url: 'https://owsdemo.exactearth.com/ows?service=wfs&version=1.1.0&request=GetCapabilities&authKey=tokencoin',
                proxy: Conf.getCapabilitiesProxy,
                success: function (response) {
                    var capabilities = JSON.parse(response.responseText),
                        filterCapabilities = _.toArray(capabilities)[0]["ogc:Filter_Capabilities"];

                    callback(null, filterCapabilities);
                },
                error: function(err) {
                    callback(err);
                }
            });
        },

        parseLayerTypes: function(layers) {
            var parsedLayers = {};

            eeStoredLayers = layers.filter(function(layer) {
                return layer.get("isExactEarth");
            });
            customLayers = layers.reject(function(layer) {
                return (layer.get("isExactEarth") || layer.get("isBaseLayer"));
            });
            baseLayers = layers.filter(function(layer) {
                return layer.get("isBaseLayer");
            });

            parsedLayers.eeStoredLayers = new BaseCollection(eeStoredLayers, {model: Layer});
            parsedLayers.customLayers = new BaseCollection(customLayers, {model: Layer});
            parsedLayers.baseLayers = new BaseCollection(baseLayers, {model: Layer});

            return parsedLayers;
        },

        getLayers: function(layerCapabilitiesURL, callback) {
            var url = request = null;

            if (layerCapabilitiesURL === null)
                layerCapabilitiesURL = 'https://owsdemo.exactearth.com/ows?service=wms&version=1.3.0&request=GetCapabilities&authKey=tokencoin';

            request = OpenLayers.Request.GET({
                url: layerCapabilitiesURL,
                proxy: Conf.getCapabilitiesProxy,
                success: function (response) {
                    var capabilities = JSON.parse(response.responseText),
                        layers = _.toArray(capabilities.WMS_Capabilities.Capability.Layer.Layer);

                    callback(null, layers);
                },
                error: function(err) {
                    callback(err);
                }
            });
        },

        getTypeDropdownValues: function(type) {
            var values = Conf.scalarFilterCapabilties.byType[type];

            return values || ["na"];
        },

        determineNumberOfInputs: function(propertyType) {
            propertyType = propertyType.toLowerCase();
            console.log(propertyType);
            switch (propertyType) {
                case "string":
                    return 1;
                    break;
                case "integer":
                case "int":
                case "double":
                case "long":
                case "decimal":
                    return 2;
                    break;
            }

            return -1; //This means it's a geometric constraint
        },

        convertXMLFilterToOLFilter: function(xmlFilter) {
            var parser,
                xml,
                mapFilterConverted,
                newFilter,
                filters = [newFilter]

            parser = new OpenLayers.Format.Filter.v1_1_0 ();
            xml = new OpenLayers.Format.XML();

            olFilter = parser.read(xml.read(xmlFilter).documentElement);

            return olFilter;
        },

        mergeActiveFilters: function(newFilter, mapFilter) {
            var filters = [newFilter];

            if (mapFilter) {
                mapFilterConverted = this.convertXMLFilterToOLFilter(mapFilter);
                filters.push(mapFilterConverted);
            }

            newFilter = new OpenLayers.Filter.Logical({
                type: OpenLayers.Filter.Logical.AND,
                filters: filters
            });

            return newFilter;
        },

        createOpenLayersFilters: function(filters) {
            var simplifiedFilters = [];
            var olFilters = new OpenLayers.Filter.Logical({
                type: OpenLayers.Filter.Logical.AND
            });

            for (var i = 0, len = filters.length; i< len; i++) {
                olFilters.filters.push(this.convertFilterToFilterParam(filters[i]))
            };

            var filter_1_0 = new OpenLayers.Format.Filter({version: "1.1.0"});
            var xml = new OpenLayers.Format.XML();
            var filter_param = xml.write(filter_1_0.write(olFilters));
            console.log(filter_param);

            return filter_param;
        },

        convertFilterToFilterParam: function(filter) {
            var olFilters = new OpenLayers.Filter.Logical({
                type: OpenLayers.Filter.Logical.AND
            }),
            operators = filter.getOperators();

            for (var j = 0, olen = operators.length; j < olen; j++) {
                var operator = operators[j];
                if (operator.get && operator.get("isSubFilter")) {
                    subFilter = this.convertFilterToFilterParam(operator);
                    olFilters.filters.push(subFilter);
                }
                else {
                    olFilters.filters.push(operator);
                }
            }

            return olFilters;
        },

        addControlsToMap: function(view, currentFilter) {
            var map = view.model,
                oInfoControl = new OpenLayers.Control.WMSGetFeatureInfo({
                    name: "GetFeatureInfo",
                    url: 'https://owsdemo.exactearth.com/wms?authKey=tokencoin',
                        title: 'Identify features by clicking',
                    infoFormat: "application/vnd.ogc.gml",
                    queryVisible: true,
                    filter: this.convertXMLFilterToOLFilter(currentFilter),
                    eventListeners: {
                        getfeatureinfo: function(evt) {
                            view.showInfo(evt, view);
                            view.applyTrack(evt, view);
                        }
                    }
                });

            map.addControl(oInfoControl);
            oInfoControl.activate();

            /**************************
            * Measure Controls
            **************************/
            var measureControl = new OpenLayers.Control.DynamicMeasure(
                OpenLayers.Handler.Path,
                {
                    name: "Measure",
                    persist: true
                }
            );

            map.addControl(measureControl);

            var graticuleControl = new OpenLayers.Control.Graticule({
                name: "Graticule",
                numPoints: 2,
                labelled: true,
                autoActivate: false
            });

            map.addControl(graticuleControl);
        },

        addActiveLayersToMap: function(eeLayers, userLayers, view) {
            console.log(eeLayers);
            var layersToAddToMap = [];
                haveActiveBaseLayer = false, //Used to keep track if we've added a baselayer yet.
                parsedLayers = this.parseLayerTypes(userLayers);

            //I made four collection because I figure this is easier than filtering on demand.
            //Especially in the view designed to allow a user to choose styles. That page is divided
            //into EE layers and custom layers -- this will make it easier
            view.eeStoredLayers = parsedLayers.eeStoredLayers;
            view.customLayers = parsedLayers.customLayers;
            view.baseLayers = parsedLayers.baseLayers;

            view.baseLayers.each(function(baseLayer) {
                var eeBaseLayer;
                switch (baseLayer.get("mapType")) {
                    case "OSM":
                        eeBaseLayer = new OpenLayers.Layer.OSM("OSMBaseMap", null,
                            {
                                isBaseLayer: true,
                                wrapDateLine: true,
                                transitionEffect: "resize",
                                tileOptions: {crossOriginKeyword: null}
                            });
                        break;
                    case "WMS":
                        eeBaseLayer = new OpenLayers.Layer.WMS("WMSBaseMap", "http://vmap0.tiles.osgeo.org/wms/vmap0",
                            {
                                layers: "basic"
                            },
                            {
                                isBaseLayer: true,
                                wrapDateLine: true,
                                transitionEffect: "resize",
                                tileOptions: {crossOriginKeyword: null}
                            });
                        break;
                }

                view.model.addLayer(eeBaseLayer);

                if (baseLayer.get("active")) {
                    if (haveActiveBaseLayer) { //Dealing with duplicate base layer error
                        baseLayer.set("active", false);
                        baseLayer.update();
                    }

                    view.model.setBaseLayer(eeBaseLayer);
                    haveActiveBaseLayer = true;
                }
            });

            if (!haveActiveBaseLayer) {
                var basicMapLayer = new OpenLayers.Layer.OSM("OSMBaseMap", null,
                    {
                        isBaseLayer: true,
                        wrapDateLine: true,
                        transitionEffect: "resize",
                        tileOptions: {crossOriginKeyword: null}
                    });
                view.model.addLayer(basicMapLayer);

                var basicMapLayer = new OpenLayers.Layer.WMS("WMSBaseMap", "http://vmap0.tiles.osgeo.org/wms/vmap0",
                    {layers: "basic"},
                    {
                        isBaseLayer: true,
                        wrapDateLine: true,
                        transitionEffect: "resize"
                    });
            }

            _.each(eeLayers, function(eeLayer) {
                var layer,
                    userLayer = userLayers.findWhere({name: eeLayer.Name}),
                    params = {};

                    if (userLayer)
                        params = userLayer.get("exactEarthParams");

                    layer = new OpenLayers.Layer.WMS(
                        eeLayer.Name, "https://owsdemo.exactearth.com/wms?authKey=tokencoin",
                        params,
                        {
                            singleTile: false,
                            ratio: 1,
                            yx: { 'EPSG:4326': true },
                            wrapDateLine: true
                        }
                    );

                    view.model.addLayer(layer);
                    view.model.setLayerIndex(layer, userLayer.get("order"));
                    layer.setVisibility(userLayer && userLayer.get("active"));
            });

            //Combine ee and custom layers since they can intermingle when assigning order
            userLayers = userLayers.reject(function(layer) {
                return layer.get("isBaseLayer");
            });

            view.userLayers = new BaseCollection(userLayers, {model: Layer});

            view.layersLoaded = true;
            view.loadInitialFilters();

        },

        getShipCount: function(bounds, currentFilter, callback) {
            var filter,
                mapProjection = this.getProjection();

            filter = new OpenLayers.Filter.Spatial({
                type: OpenLayers.Filter.Spatial.BBOX,
                property: "position",
                value: bounds.transform(mapProjection.projection, mapProjection.displayProjection)
            });

            if (currentFilter instanceof Array)
                currentFilter = this.createOpenLayersFilters(currentFilter);

            filter = this.mergeActiveFilters(filter, currentFilter);

            var  wfsProtocol = new OpenLayers.Protocol.WFS.v1_1_0({
                url: "/proxy/getWFSFeatures?url=https://owsdemo.exactearth.com/ows?service=wfs&version=1.1.0&request=GetFeature&typeName=exactAIS:LVI&authKey=tokencoin",
                featurePrefix: "",
                featureType: "exactAIS:LVI",
            });

            wfsProtocol.read ({
                filter: filter,
                callback: function(response) {
                    Backbone.globalEvents.trigger("fetchedShipCount", response.numberOfFeatures);

                    if (_.isFunction(callback)) {
                        callback(response.numberOfFeatures);
                    }
                },
                readOptions: {output: "object"},
                resultType: "hits",
                maxFeatures: null,
                scope: new OpenLayers.Strategy.Fixed
            });

        }
    };

    return OpenLayersUtil;
});

<|endoftext|>


<commit_before>$(function () {
    /* Include the built version of the our templates.  This means that grunt
    * must be run to generate these before the test. */
    girderTest.addCoveredScripts([
        '/static/built/plugins/jobs/templates.js',
        '/plugins/jobs/web_client/js/misc.js',
        '/plugins/jobs/web_client/js/views/JobDetailsWidget.js',
        '/plugins/jobs/web_client/js/views/JobListWidget.js'
    ]);
    girderTest.importStylesheet(
        '/static/built/plugins/jobs/plugin.min.css'
    );

    girder.events.trigger('g:appload.before');
    var app = new girder.App({
        el: 'body',
        parentView: null
    });
    girder.events.trigger('g:appload.after');

    describe('Unit test the job widget.', function () {
        it('Show a job detail widget.', function () {
            waitsFor('app to render', function () {
                return $('#g-app-body-container').length > 0;
            });

            runs(function () {
                var job = new girder.models.JobModel({
                    _id: 'foo',
                    title: 'My batch job',
                    status: girder.jobs_JobStatus.INACTIVE,
                    log: 'Hello world\ngoodbye world',
                    updated: '2015-01-12T12:00:00',
                    created: '2015-01-12T12:00:00',
                    when: '2015-01-12T12:00:00'
                });

                var widget = new girder.views.jobs_JobDetailsWidget({
                    el: $('#g-app-body-container'),
                    job: job,
                    parentView: app
                }).render();

                expect($('.g-monospace-viewer[property="kwargs"]').length).toBe(0);
                expect($('.g-monospace-viewer[property="log"]').text()).toBe(job.get('log'));
                expect($('.g-job-info-value[property="_id"]').text()).toBe(job.get('_id'));
                expect($('.g-job-info-value[property="title"]').text()).toBe(job.get('title'));
                expect($('.g-job-info-value[property="when"]').text()).toContain('January 12, 2015');
                expect($('.g-job-status-badge').text()).toContain('Inactive');

                job.on('change', widget.render, widget);
                job.set('status', girder.jobs_JobStatus.SUCCESS);

                expect($('.g-job-status-badge').text()).toContain('Success');
            });
        });
    });
});
<commit_msg>Add a test for the new widget<commit_after>$(function () {
    /* Include the built version of the our templates.  This means that grunt
    * must be run to generate these before the test. */
    girderTest.addCoveredScripts([
        '/static/built/plugins/jobs/templates.js',
        '/plugins/jobs/web_client/js/misc.js',
        '/plugins/jobs/web_client/js/views/JobDetailsWidget.js',
        '/plugins/jobs/web_client/js/views/JobListWidget.js'
    ]);
    girderTest.importStylesheet(
        '/static/built/plugins/jobs/plugin.min.css'
    );

    girder.events.trigger('g:appload.before');
    var app = new girder.App({
        el: 'body',
        parentView: null
    });
    girder.events.trigger('g:appload.after');

    describe('Unit test the job detail widget.', function () {
        it('Show a job detail widget.', function () {
            waitsFor('app to render', function () {
                return $('#g-app-body-container').length > 0;
            });

            runs(function () {
                var job = new girder.models.JobModel({
                    _id: 'foo',
                    title: 'My batch job',
                    status: girder.jobs_JobStatus.INACTIVE,
                    log: 'Hello world\ngoodbye world',
                    updated: '2015-01-12T12:00:00',
                    created: '2015-01-12T12:00:00',
                    when: '2015-01-12T12:00:00'
                });

                var widget = new girder.views.jobs_JobDetailsWidget({
                    el: $('#g-app-body-container'),
                    job: job,
                    parentView: app
                }).render();

                expect($('.g-monospace-viewer[property="kwargs"]').length).toBe(0);
                expect($('.g-monospace-viewer[property="log"]').text()).toBe(job.get('log'));
                expect($('.g-job-info-value[property="_id"]').text()).toBe(job.get('_id'));
                expect($('.g-job-info-value[property="title"]').text()).toBe(job.get('title'));
                expect($('.g-job-info-value[property="when"]').text()).toContain('January 12, 2015');
                expect($('.g-job-status-badge').text()).toContain('Inactive');

                job.on('change', widget.render, widget);
                job.set('status', girder.jobs_JobStatus.SUCCESS);

                expect($('.g-job-status-badge').text()).toContain('Success');
            });
        });
    });

    describe('Unit test the job list widget.', function () {
        it('Show a job list widget.', function () {
            var jobs, rows;

            runs(function () {
                jobs = _.map([1, 2, 3], function (i) {
                    return new girder.models.JobModel({
                        _id: 'foo' + i,
                        title: 'My batch job ' + i,
                        status: i,
                        updated: '2015-01-12T12:00:0' + i,
                        created: '2015-01-12T12:00:0' + i,
                        when: '2015-01-12T12:00:0' + i
                    });
                });

                var widget = new girder.views.jobs_JobListWidget({
                    el: $('#g-app-body-container'),
                    filter: {},
                    parentView: app
                }).render();

                expect($('.g-jobs-list-table>tbody>tr').length).toBe(0);

                // Add the jobs to the collection
                widget.collection.add(jobs);
            });

            waitsFor(function () {
                return $('.g-jobs-list-table>tbody>tr').length === 3;
            }, 'job list to auto-reload when collection is updated')

            runs(function () {
                // Make sure we are in reverse chronological order
                rows = $('.g-jobs-list-table>tbody>tr');
                expect($(rows[0]).text()).toContain('My batch job 3');
                expect($(rows[0]).text()).toContain('Success');
                expect($(rows[1]).text()).toContain('My batch job 2');
                expect($(rows[1]).text()).toContain('Running');
                expect($(rows[2]).text()).toContain('My batch job 1');
                expect($(rows[2]).text()).toContain('Queued');

                // Simulate an SSE notification that changes a job status
                girder.eventStream.trigger('g:event.job_status', {
                    data: _.extend({}, jobs[0].attributes, {
                        status: 4
                    })
                });
            });

            // Table row should update automatically
            waitsFor(function () {
                return $('td.g-job-status-cell', rows[2]).text() === 'Error';
            });
        });
    });
});
<|endoftext|>


<commit_before>/*!
Cloud4all Preferences Management Tools

Copyright 2013 CERTH/HIT

Licensed under the New BSD license. You may not use this file except in
compliance with this License.

You may obtain a copy of the License at
https://github.com/GPII/prefsEditors/LICENSE.txt
*/

/*global fluid, jQuery, gpii*/
/*jslint white: true, onevar: true, funcinvoke: true, forvar: true, undef: true, newcap: true, nomen: true, regexp: true, plusplus: true, bitwise: true, maxerr: 50, indent: 4 */

(function ($, fluid) {

    fluid.defaults("gpii.uiOptions.panels.contrast", {
        gradeNames: ["fluid.uiOptions.panels", "gpii.uiOptions.pmt.previewPerSettingEnhanced", "autoInit"],
        preferenceMap: {
            "http://registry.gpii.org/common/display.screenEnhancement.highContrast": {
                "model.value": "default"
            }
        },
        events: {
            onToggleContrastAdjusters: null
        },
        listeners: {
            "afterRender.bindEventPreferenceSwitchContrast": {
                "this": "{that}.dom.valueCheckbox",
                "method": "change",
                "args": ["{that}.events.onToggleContrastAdjusters.fire"]
            },
            "onToggleContrastAdjusters.showHide": {
                "this": "{that}.dom.contrastAdjusters",
                "method": "slideToggle"
            },
            "afterRender.setContrastAdjusters": {
                listener: "gpii.uiOptions.panels.contrast.setContrastAdjusters",
                args: ["{that}.dom.contrastAdjusters", "{that}.model.value"]
            },
            "afterRender.setATTRaddToMyPreferencesLabel": {
                "this": "{that}.dom.addToMyPreferencesLabel",
                "method": "attr",
                "args": [{
                    "tooltip-checked": "{that}.options.strings.tooltipChecked",
                    "tooltip-unchecked": "{that}.options.strings.tooltipUnchecked"
                }]
            }
        },
        selectors: {
            valueCheckbox: ".flc-uiOptions-constrastInput",
            headingLabel: ".flc-uiOptions-contrast-label",
            panelLabel: ".headerTitle",
            addToMyPreferencesLabel: ".addToMyPreferencesLabel",
            contrastAdjusters: ".fl-uiOptions-category"
        },
        selectorsToIgnore: ["contrastAdjusters"],
        protoTree: {
            valueCheckbox: "${value}",
            headingLabel: {messagekey: "contrast"},
            panelLabel: {messagekey: "addContrast"},
            addToMyPreferencesLabel: " "
        },
        strings: {
            tooltipChecked: {
                expander: {
                    func: "gpii.uiOptions.pmt.lookupMsg",
                    args: ["{uiOptionsLoader}.msgBundle", "tooltipChecked"]
                }
            },
            tooltipUnchecked: {
                expander: {
                    func: "gpii.uiOptions.pmt.lookupMsg",
                    args: ["{uiOptionsLoader}.msgBundle", "tooltipUnchecked"]
                }
            }
        },
        components: {
            preview: {
                type: "fluid.uiOptions.preview",
                createOnEvent: "afterRender",
                container: ".flc-uiOptions-contrast .flc-uiOptions-preview-per-setting-frame",
                options: {
                    templateUrl: "../../src/shared/preview/html/uiOptionsContrastPreview.html",
                    components: {
                        enhancer: {
                            type: "fluid.uiEnhancer",
                            container: "{preview}.enhancerContainer",
                            createOnEvent: "onReady",
                            options: {
                                selectors: {
                                    previewText: ".flc-uiOptions-preview-per-setting-label"
                                },
                                strings: {
                                    previewText: {
                                        expander: {
                                            func: "gpii.uiOptions.pmt.lookupMsg",
                                            args: ["{uiOptionsLoader}.msgBundle", "contrastPreviewText"]
                                        }
                                    }
                                },
                                listeners: {
                                    "onCreate.setText": {
                                        "this": "{that}.dom.previewText",
                                        "method": "text",
                                        "args": ["{that}.options.strings.previewText"]
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },

        distributeOptions: [{
            source: "{that}.options.outerPreviewEnhancerOptions",
            removeSource: true,
            target: "{that preview enhancer}.options"
        }, {
            source: "{that}.options.emptyComponentType",
            removeSource: true,
            target: "{that preview enhancer magnifier}.type"
        }]
    });

    gpii.uiOptions.panels.contrast.setContrastAdjusters = function (contrastAdjuster, flag) {
        contrastAdjuster[flag ? "show" : "hide"]();
    };
})(jQuery, fluid);
<commit_msg>Corrected the addToMyPreferencesLabel: " " bug.<commit_after>/*!
Cloud4all Preferences Management Tools

Copyright 2013 CERTH/HIT

Licensed under the New BSD license. You may not use this file except in
compliance with this License.

You may obtain a copy of the License at
https://github.com/GPII/prefsEditors/LICENSE.txt
*/

/*global fluid, jQuery, gpii*/
/*jslint white: true, onevar: true, funcinvoke: true, forvar: true, undef: true, newcap: true, nomen: true, regexp: true, plusplus: true, bitwise: true, maxerr: 50, indent: 4 */

(function ($, fluid) {

    fluid.defaults("gpii.uiOptions.panels.contrast", {
        gradeNames: ["fluid.uiOptions.panels", "gpii.uiOptions.pmt.previewPerSettingEnhanced", "autoInit"],
        preferenceMap: {
            "http://registry.gpii.org/common/display.screenEnhancement.highContrast": {
                "model.value": "default"
            }
        },
        events: {
            onToggleContrastAdjusters: null
        },
        listeners: {
            "afterRender.bindEventPreferenceSwitchContrast": {
                "this": "{that}.dom.valueCheckbox",
                "method": "change",
                "args": ["{that}.events.onToggleContrastAdjusters.fire"]
            },
            "onToggleContrastAdjusters.showHide": {
                "this": "{that}.dom.contrastAdjusters",
                "method": "slideToggle"
            },
            "afterRender.setContrastAdjusters": {
                listener: "gpii.uiOptions.panels.contrast.setContrastAdjusters",
                args: ["{that}.dom.contrastAdjusters", "{that}.model.value"]
            },
            "afterRender.setATTRaddToMyPreferencesLabel": {
                "this": "{that}.dom.addToMyPreferencesLabel",
                "method": "attr",
                "args": [{
                    "tooltip-checked": "{that}.options.strings.tooltipChecked",
                    "tooltip-unchecked": "{that}.options.strings.tooltipUnchecked"
                }]
            }
        },
        selectors: {
            valueCheckbox: ".flc-uiOptions-constrastInput",
            headingLabel: ".flc-uiOptions-contrast-label",
            panelLabel: ".headerTitle",
            addToMyPreferencesLabel: ".addToMyPreferencesLabel",
            contrastAdjusters: ".fl-uiOptions-category"
        },
        selectorsToIgnore: ["contrastAdjusters", "addToMyPreferencesLabel"],
        protoTree: {
            valueCheckbox: "${value}",
            headingLabel: {messagekey: "contrast"},
            panelLabel: {messagekey: "addContrast"}
        },
        strings: {
            tooltipChecked: {
                expander: {
                    func: "gpii.uiOptions.pmt.lookupMsg",
                    args: ["{uiOptionsLoader}.msgBundle", "tooltipChecked"]
                }
            },
            tooltipUnchecked: {
                expander: {
                    func: "gpii.uiOptions.pmt.lookupMsg",
                    args: ["{uiOptionsLoader}.msgBundle", "tooltipUnchecked"]
                }
            }
        },
        components: {
            preview: {
                type: "fluid.uiOptions.preview",
                createOnEvent: "afterRender",
                container: ".flc-uiOptions-contrast .flc-uiOptions-preview-per-setting-frame",
                options: {
                    templateUrl: "../../src/shared/preview/html/uiOptionsContrastPreview.html",
                    components: {
                        enhancer: {
                            type: "fluid.uiEnhancer",
                            container: "{preview}.enhancerContainer",
                            createOnEvent: "onReady",
                            options: {
                                selectors: {
                                    previewText: ".flc-uiOptions-preview-per-setting-label"
                                },
                                strings: {
                                    previewText: {
                                        expander: {
                                            func: "gpii.uiOptions.pmt.lookupMsg",
                                            args: ["{uiOptionsLoader}.msgBundle", "contrastPreviewText"]
                                        }
                                    }
                                },
                                listeners: {
                                    "onCreate.setText": {
                                        "this": "{that}.dom.previewText",
                                        "method": "text",
                                        "args": ["{that}.options.strings.previewText"]
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },

        distributeOptions: [{
            source: "{that}.options.outerPreviewEnhancerOptions",
            removeSource: true,
            target: "{that preview enhancer}.options"
        }, {
            source: "{that}.options.emptyComponentType",
            removeSource: true,
            target: "{that preview enhancer magnifier}.type"
        }]
    });

    gpii.uiOptions.panels.contrast.setContrastAdjusters = function (contrastAdjuster, flag) {
        contrastAdjuster[flag ? "show" : "hide"]();
    };
})(jQuery, fluid);
<|endoftext|>


<commit_before>import React from 'react';
import { expect } from 'chai';
import { shallow, configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });

import Header from './Header';
import t from './_lang.json';

describe('Header', () => {
  const props = {
    'lang': { id: 'en-AU', name: 'English(AU)' },
    'languages': [
      { id: 'en-AU', name: 'English(AU)' },
      { id: 'zh-CN', name: '中文（简体）' }
    ]
  };

  let wrapper;

  beforeEach(() => {
    wrapper = shallow(<Header {...props}/>);
  });

  it("should be rendered", () => {
    expect(wrapper.find('.header')).to.have.length(1);
  });
  it("should display title", () => {
    expect(wrapper.find('.header__title').text()).to.equal(t[props.lang.id].name);
  });
  it("should display language", () => {
    expect(wrapper.find('.header__lang')).to.have.length(1);
  });

  describe('Navbar', () => {
    it("should be rendered", () => {
      expect(wrapper.find('.navbar')).to.have.length(1);
    });

    describe('NavBtn', () => {
      it("should display dropdown button", () => {
        expect(wrapper.find('.navbtn')).to.have.length(1);
        expect(wrapper.find('.navbtn__line1')).to.have.length(1);
        expect(wrapper.find('.navbtn__line2')).to.have.length(1);
        expect(wrapper.find('.navbtn__line3')).to.have.length(1);
      });
      it('should toggle navbtn style after clicked', () => {

      });
    })
  })
});
<commit_msg>toggle<commit_after>import React from 'react';
import { expect } from 'chai';
import { shallow, configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });

import Header from './Header';
import t from './_lang.json';

describe('Header', () => {
  const props = {
    'lang': { id: 'en-AU', name: 'English(AU)' },
    'languages': [
      { id: 'en-AU', name: 'English(AU)' },
      { id: 'zh-CN', name: '中文（简体）' }
    ]
  };

  let wrapper;

  beforeEach(() => {
    wrapper = shallow(<Header {...props}/>);
  });

  it("should be rendered", () => {
    expect(wrapper.find('.header')).to.have.length(1);
  });
  it("should display title", () => {
    expect(wrapper.find('.header__title').text()).to.equal(t[props.lang.id].name);
  });
  it("should display language", () => {
    expect(wrapper.find('.header__lang')).to.have.length(1);
  });

  describe('Navbar', () => {
    it("should be rendered", () => {
      expect(wrapper.find('.navbar')).to.have.length(1);
    });

    describe('NavBtn', () => {
      it("should display dropdown button", () => {
        expect(wrapper.find('.navbtn')).to.have.length(1);
        expect(wrapper.find('.navbtn__line1')).to.have.length(1);
        expect(wrapper.find('.navbtn__line2')).to.have.length(1);
        expect(wrapper.find('.navbtn__line3')).to.have.length(1);
      });
      it('should toggle navbtn style after clicked', () => {

      });
    })
  })
});
<|endoftext|>