<commit_before>"use strict";
var __version__='1.0.1';
function isChainable(name){
	name=name[0]=='.'?name.slice(1).split("(")[0]:name.split("(")[0];//remove '.' and "(" and ")"
	var tools={"activateGenerator":true,"deactivateGenerator":true,"setAxisValues":true,"resetGenerator":true,"addToFavourites":true,"removeFavourites":true,"getId":false,"getFavourites":false,
	"getBackup":false,"restoreBackup":false};
	return tools[name] != undefined ?tools[name]:false;//if the key does not exist in the above dictionary return  false else return its value
}
function TextShadow(args){
	function val(o){return $(o).val();}
	function abs(a){return Math.abs(a);}
	function bind(container,evnt,item,fn){
		$(function(){
			if(item)
				$(container).on(evnt,item,fn);
			else
				$(container).on(evnt,fn);
		});
	}
	var self=this;
	var host=null;
	self.generator_markup=""+
	"
 "+
		"
"+
			"
Text shadow Generator
"+
			"
"+
			"
 "+
				"
 "+
					"
X-axis
 "+
					"<input type='range' class='text-shadow-sliders x-axis' min='-100' max='150' value=0>"+
				"
 "+
				"
"+
					"
Y-axis
 "+
					"<input type='range' class='text-shadow-sliders y-axis' min='-100' max='150' value=0> "
				+"
"
				+"
"+
					"
Blur
"+
					"<input type='range' class='text-shadow-sliders blur' min='0' max='10' step='0.1' value='0'> "+
				"
"+
			"
"+
			"

Shadow is applied here

 "+
			"
 "+
			"
"+
				"
Red
 "+
				"<input type='range' class='text-shadow-color-sliders' min='0' max='255' step='1' value='0'> "+
			"
"+
			"
 "+
				"
Green
 "+
				" <input type='range' class='text-shadow-color-sliders' min='0' max='255' step='1' value='0'>"+
			"
 "+
			"
 "+
				"
Blue
 "+
				" <input type='range' class='text-shadow-color-sliders' min='0' max='255' step='1' value='0'> "+
			"
 "+
			"
 "+
				"
Opacity
 "+
				"<input type='range' class='text-shadow-color-sliders opacity' min='0' max='1' step='0.1' value='1'> "+
			"
"+
			"
"+
		"
  "+
			"
text-shadow:0px 0px rgb(0,0,0);
  "+
		"
"+
	"
 ";
	self.host_id=null;
	if(typeof args != 'string' || !args || args[0]=='.' || !args[0]=="#"){
		throw new Error("Invalid id!!!"+args);
	}
	else
		self.host_id=host=args;
	self.shadow_code="none";
	self.content_backup=null;
	self.favourites=[];
	for(var i=1;i<=30;i++)self.favourites.push(i);
	self.getId=function(){
		return self.host_id;
	};
	var render=function(){
		if(host != null && host[0]=='#')
			bind(document,"ready",null,function(){
				self.content_backup=$(host).html();
				$(host).html(self.generator_markup);
			});
		return self;
	};
	self.getBackup=function(){
		return self.content_backup;
	}
	self.restoreBackup=function(destination){
		var backup=self.getBackup();
		if(!destination)
			throw new Error("Wrong destination");
		var isClass=destination[0]=='.';
		if(isClass){
			var answer=confirm("You are going to create duplicates of your backed content.Are you sure you want to continue");
			if(answer)
				$(destination).html(backup);
		}
		else
			$(destination).html(backup);
		return self;
	};
	self.getCode=function(){
		return self.shadow_code;
	};
	self.activateGenerator=function(){
		var code=self.getCode();
		bind(host,"mousemove touchmove",null,function(){
			var sliders=$(host+" .panel-body .text-shadow-sliders");
			var color_sliders=$(host+" .panel-body .text-shadow-color-sliders");
			var color=val(color_sliders[3]) != '1'?"rgba("+val(color_sliders[0])+","+val(color_sliders[1])+","+val(color_sliders[2])+","+val(color_sliders[3])+")":"rgb("+val(color_sliders[0])+","+val(color_sliders[1])+","+val(color_sliders[2])+")";
			self.shadow_code=val(sliders[0])+"px "+val(sliders[1])+"px ";
			if(val(sliders[2])!= '0')
				self.shadow_code+=val(sliders[2])+"px ";
			self.shadow_code+=color;
			$(host+ " .text-shadow-code-output").text("text-shadow:"+self.shadow_code+";");
			$(host+ " .panel .text-shadow-output").css("text-shadow",self.shadow_code);
		});
		return self;
	};
	self.deactivateGenerator=function(){
		$(host).off();
		return self;
	};
	self.setAxisValues=function(limit,value){
		//more validations to come here
		var sliders=$(host+" .text-shadow-sliders");
		if(isNaN(value) || !value || !limit)
			throw new Error("An error occured.");
		var value=abs(value);
		switch(limit.toUpperCase()){
			//we use for loop because we do not want to target every single slider
			case "MIN":
				for(var i=0;i<sliders.length-1;i++)
					$(sliders[i]).prop("min",value * -1);
				break;
			default:
				for(var i=0;i<sliders.length-1;i++)
					$(sliders[i]).prop("max",value);
		}//switch
		return self;
	};
	self.resetGenerator=function(){
		$(host+" .text-shadow-sliders").val(0);
		$(host+" .text-shadow-color-sliders").val(0);
		$(host+" .opacity").val(1);
		self.shadow_code="0px 0px rgb(0,0,0)";
		$(host+ " .text-shadow-code-output").text("text-shadow:"+self.shadow_code+";");
		$(host+ " .panel .text-shadow-output").css("text-shadow","none");
		return self;
	};
	self.addToFavourites=function(append){
		var code=self.getCode();
		if(self.favourites.indexOf(code)== -1 && code != "none")
			self.favourites.push(code);
		return self;
	};
	self.getFavourites=function(){
		return self.favourites;
	};
	self.removeFavourites=function(){
		var del;
		if( del=confirm("Are you sure you want to erase your favourites?"))
			self.favourites.length=0;
		return self;
	};
	self.showFavourites=function(){
		var error="Function has not been implemented yet and it is not part of the public API!!!!";
		var index=10;
		/*try{
			bootbox.alert("
"+error+"
");
		}
		catch(e){
			setTimeout(function(){
				console.warning(error);
			},3000);
		}*/
		var favourites=self.getFavourites();
		var total=favourites.length;
		if(favourites.length<1)
			bootbox.alert("No favourites  to show!!!");
		else{
			var list_items;
			function renderlist(){
				var ul="
";
				var carrets="

"
				+"

";
				for(var i=0;i<10;i++)
					ul+="
text-shadow:"+favourites[i]+";
";
				ul+="
"+carrets;
				list_items=$(".favourite_item");
				return ul;
			}
			bootbox.alert(renderlist());
			bind(".list-group","click",".list-group-item",function(){
				$(".list-group li").removeClass('active');
				$(this).addClass('active');
			});
			bind(".show_less","click",null,function(){
				if(index==0)
					return;//there are no previous favourites when we hit 0
				var min_value=index>9?index-10:0;
				var list="";
				console.log(min_value);
				for(var i=min_value;i<index;i++)
					//console.log(i);
					list+="
text-shadow:"+favourites[i]+";
";
				index=min_value;
				$(".fix").html(list);

			});
			bind(".show_more","click",null,function(){
				if(index>=favourites.length)
					return;//max items displayed so exit the function
				var current_list="";
				var total=favourites.length;
				var diff=total-index;
				var end;
				if(diff > 9)
					end=index+10;
				else
					end=index+diff;
				for(var i=index;i<end;i++)
					current_list+="
text-shadow:"+favourites[i]+";
";
				if(diff>9)
					index+=10
				else
					index+=diff
				$(".fix").html(current_list).animate({
					"top":"12px",
					"box-shadow":"0 0 3px 4px dodgerblue"
				},1200);
				//$(".fix").html(current_list);
				//console.log(current_list);
			});
		}
		return self;
	};
	self.downloadFavourites=function(){
		var file="/********\n";
		var items=self.getFavourites();
		if(items.length<1)
			return "No favourites found";
		for(var i=0;i<items.length;i++)
			file+="text-shadow:"+items[i]+";\n";
		file+="**************\n";
		try{
			saveAs(new Blob([file], {type: "text/plain;charset=utf-8"}),"favourites.css");
		}
		catch(e){
			alert("Filesaver is missing!!!");
		}
	};
	render();
}<commit_msg>replaced glyphicons with buttons when showing favourites<commit_after>"use strict";
var __version__='1.0.1';
function isChainable(name){
	name=name[0]=='.'?name.slice(1).split("(")[0]:name.split("(")[0];//remove '.' and "(" and ")"
	var tools={"activateGenerator":true,"deactivateGenerator":true,"setAxisValues":true,"resetGenerator":true,"addToFavourites":true,"removeFavourites":true,"getId":false,"getFavourites":false,
	"getBackup":false,"restoreBackup":false};
	return tools[name] != undefined ?tools[name]:false;//if the key does not exist in the above dictionary return  false else return its value
}
function TextShadow(args){
	function val(o){return $(o).val();}
	function abs(a){return Math.abs(a);}
	function bind(container,evnt,item,fn){
		$(function(){
			if(item)
				$(container).on(evnt,item,fn);
			else
				$(container).on(evnt,fn);
		});
	}
	var self=this;
	var host=null;
	self.generator_markup=""+
	"
 "+
		"
"+
			"
Text shadow Generator
"+
			"
"+
			"
 "+
				"
 "+
					"
X-axis
 "+
					"<input type='range' class='text-shadow-sliders x-axis' min='-100' max='150' value=0>"+
				"
 "+
				"
"+
					"
Y-axis
 "+
					"<input type='range' class='text-shadow-sliders y-axis' min='-100' max='150' value=0> "
				+"
"
				+"
"+
					"
Blur
"+
					"<input type='range' class='text-shadow-sliders blur' min='0' max='10' step='0.1' value='0'> "+
				"
"+
			"
"+
			"

Shadow is applied here

 "+
			"
 "+
			"
"+
				"
Red
 "+
				"<input type='range' class='text-shadow-color-sliders' min='0' max='255' step='1' value='0'> "+
			"
"+
			"
 "+
				"
Green
 "+
				" <input type='range' class='text-shadow-color-sliders' min='0' max='255' step='1' value='0'>"+
			"
 "+
			"
 "+
				"
Blue
 "+
				" <input type='range' class='text-shadow-color-sliders' min='0' max='255' step='1' value='0'> "+
			"
 "+
			"
 "+
				"
Opacity
 "+
				"<input type='range' class='text-shadow-color-sliders opacity' min='0' max='1' step='0.1' value='1'> "+
			"
"+
			"
"+
		"
  "+
			"
text-shadow:0px 0px rgb(0,0,0);
  "+
		"
"+
	"
 ";
	self.host_id=null;
	if(typeof args != 'string' || !args || args[0]=='.' || !args[0]=="#"){
		throw new Error("Invalid id!!!"+args);
	}
	else
		self.host_id=host=args;
	self.shadow_code="none";
	self.content_backup=null;
	self.favourites=[];
	for(var i=1;i<=30;i++)self.favourites.push(i);
	self.getId=function(){
		return self.host_id;
	};
	var render=function(){
		if(host != null && host[0]=='#')
			bind(document,"ready",null,function(){
				self.content_backup=$(host).html();
				$(host).html(self.generator_markup);
			});
		return self;
	};
	self.getBackup=function(){
		return self.content_backup;
	}
	self.restoreBackup=function(destination){
		var backup=self.getBackup();
		if(!destination)
			throw new Error("Wrong destination");
		var isClass=destination[0]=='.';
		if(isClass){
			var answer=confirm("You are going to create duplicates of your backed content.Are you sure you want to continue");
			if(answer)
				$(destination).html(backup);
		}
		else
			$(destination).html(backup);
		return self;
	};
	self.getCode=function(){
		return self.shadow_code;
	};
	self.activateGenerator=function(){
		var code=self.getCode();
		bind(host,"mousemove touchmove",null,function(){
			var sliders=$(host+" .panel-body .text-shadow-sliders");
			var color_sliders=$(host+" .panel-body .text-shadow-color-sliders");
			var color=val(color_sliders[3]) != '1'?"rgba("+val(color_sliders[0])+","+val(color_sliders[1])+","+val(color_sliders[2])+","+val(color_sliders[3])+")":"rgb("+val(color_sliders[0])+","+val(color_sliders[1])+","+val(color_sliders[2])+")";
			self.shadow_code=val(sliders[0])+"px "+val(sliders[1])+"px ";
			if(val(sliders[2])!= '0')
				self.shadow_code+=val(sliders[2])+"px ";
			self.shadow_code+=color;
			$(host+ " .text-shadow-code-output").text("text-shadow:"+self.shadow_code+";");
			$(host+ " .panel .text-shadow-output").css("text-shadow",self.shadow_code);
		});
		return self;
	};
	self.deactivateGenerator=function(){
		$(host).off();
		return self;
	};
	self.setAxisValues=function(limit,value){
		//more validations to come here
		var sliders=$(host+" .text-shadow-sliders");
		if(isNaN(value) || !value || !limit)
			throw new Error("An error occured.");
		var value=abs(value);
		switch(limit.toUpperCase()){
			//we use for loop because we do not want to target every single slider
			case "MIN":
				for(var i=0;i<sliders.length-1;i++)
					$(sliders[i]).prop("min",value * -1);
				break;
			default:
				for(var i=0;i<sliders.length-1;i++)
					$(sliders[i]).prop("max",value);
		}//switch
		return self;
	};
	self.resetGenerator=function(){
		$(host+" .text-shadow-sliders").val(0);
		$(host+" .text-shadow-color-sliders").val(0);
		$(host+" .opacity").val(1);
		self.shadow_code="0px 0px rgb(0,0,0)";
		$(host+ " .text-shadow-code-output").text("text-shadow:"+self.shadow_code+";");
		$(host+ " .panel .text-shadow-output").css("text-shadow","none");
		return self;
	};
	self.addToFavourites=function(append){
		var code=self.getCode();
		if(self.favourites.indexOf(code)== -1 && code != "none")
			self.favourites.push(code);
		return self;
	};
	self.getFavourites=function(){
		return self.favourites;
	};
	self.removeFavourites=function(){
		var del;
		if( del=confirm("Are you sure you want to erase your favourites?"))
			self.favourites.length=0;
		return self;
	};
	self.showFavourites=function(){
		var error="Function has not been implemented yet and it is not part of the public API!!!!";
		var index=10;
		var favourites=self.getFavourites();
		var total=favourites.length;
		if(favourites.length<1)
			bootbox.alert("No favourites  to show!!!");
		else{
			var list_items;
			function renderlist(){
				var ul="
";
				var carrets="

Show less
"
				+"
Show more

";
				for(var i=0;i<10;i++)
					ul+="
text-shadow:"+favourites[i]+";
";
				ul+="
"+carrets;
				list_items=$(".favourite_item");
				return ul;
			}
			bootbox.alert(renderlist());
			bind(".list-group","click",".list-group-item",function(){
				$(".list-group li").removeClass('active');
				$(this).addClass('active');
			});
			bind(".show_less","click",null,function(){
				if(index==0)
					return;//there are no previous favourites when we hit 0
				var min_value=index>9?index-10:0;
				var list="";
				for(var i=min_value;i<index;i++)
					//console.log(i);
					list+="
text-shadow:"+favourites[i]+";
";
				index=min_value;
				$(".fix").html(list);
			});
			bind(".show_more","click",null,function(){
				if(index>=favourites.length)
					return;//max items displayed so exit the function
				var current_list="";
				var total=favourites.length;
				var diff=total-index;
				var end;
				if(diff > 9)
					end=index+10;
				else
					end=index+diff;
				for(var i=index;i<end;i++)
					current_list+="
text-shadow:"+favourites[i]+";
";
				if(diff>9)
					index+=10
				else
					index+=diff
				$(".fix").html(current_list).animate({
					"top":"12px",
					"box-shadow":"0 0 3px 4px dodgerblue"
				},1200);
				//$(".fix").html(current_list);
				//console.log(current_list);
			});
		}
		return self;
	};
	self.downloadFavourites=function(){
		var file="/********\n";
		var items=self.getFavourites();
		if(items.length<1)
			return "No favourites found";
		for(var i=0;i<items.length;i++)
			file+="text-shadow:"+items[i]+";\n";
		file+="**************\n";
		try{
			saveAs(new Blob([file], {type: "text/plain;charset=utf-8"}),"favourites.css");
		}
		catch(e){
			alert("Filesaver is missing!!!");
		}
	};
	render();
}<|endoftext|>


<commit_before>'use strict';

// import numpy.random as random
// print(random.normal(100.0,15,10))
//
// [  89.07511089  102.23344158   99.40623555  101.12356061  117.28880854
//    125.3285453    89.50526668   72.32998573   96.34697385  107.97372603]

var clapDelays = [89.07511089,  102.23344158,   99.40623555,  101.12356061,  117.28880854,
    125.3285453,    89.50526668,   72.32998573,   96.34697385,  107.97372603];
var volumes = [0.3223254,   0.75143339,  0.47993786, 0.9172416,   0.58518288,0.3223254,   0.75143339,  0.47993786, 0.9172416,   0.58518288];
angular.module('myApp.claps', ['ngRoute'])

    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/view1', {
            templateUrl: 'claps/claps.html',
            controller: 'ClapsCtrl'
        });
    }])

    //ok, now use ideas from https://github.com/danielstern/ngAudio to finish.
    .controller('ClapsCtrl', ['$scope', function ($scope) {
        $scope.claps = [];
        $scope.playing = false;
        for(var i = 0; i < clapDelays.length;i++){
            $scope.claps[i] = document.createElement('audio');
            $scope.claps[i].src = 'media/clap-hall-01.mp3';
            $scope.claps[i].volume = volumes[i];
        }

        $scope.play = function () {
            for(var i = 0; i < clapDelays.length;i++){
                (function(_i){setTimeout(function(){
                    if($scope.claps[_i]) {
                        $scope.claps[_i].play();
                    }
                },clapDelays[_i]);})(i);

            }

            setTimeout($scope.play, 600);

            $scope.playing = true;
        };
        $scope.stop = function () {
            for(var i = 0; i < clapDelays.length;i++){
                $scope.claps[i].pause();
            }
            $scope.playing = false;
        };
        /*$scope.claps[0].addEventListener('ended', function () {
            console.log("got an ended event");
            $scope.$apply(function () {
                $scope.stop()
            });
        });*/

    }]);
<commit_msg>figuring out a high resolution timer for claps<commit_after>'use strict';

// import numpy.random as random
// print(random.normal(100.0,15,10))
//
// [  89.07511089  102.23344158   99.40623555  101.12356061  117.28880854
//    125.3285453    89.50526668   72.32998573   96.34697385  107.97372603]

var clapDelays = [89.07511089,  102.23344158,   99.40623555,  101.12356061,  117.28880854,
    125.3285453,    89.50526668,   72.32998573,   96.34697385,  107.97372603];
var volumes = [0.3223254,   0.75143339,  0.47993786, 0.9172416,   0.58518288,0.3223254,   0.75143339,  0.47993786, 0.9172416,   0.58518288];

//from https://gist.github.com/manast/1185904
function interval(duration, fn){
    this.baseline = undefined

    this.run = function(){
        if(this.baseline === undefined){
            this.baseline = new Date().getTime()
        }
        fn()
        var end = new Date().getTime()
        this.baseline += duration

        var nextTick = duration - (end - this.baseline)
        if(nextTick<0){
            nextTick = 0
        }
        (function(i){
            i.timer = setTimeout(function(){
                i.run(end)
            }, nextTick)
        }(this))
    }

    this.stop = function(){
        clearTimeout(this.timer)
    }
}

angular.module('myApp.claps', ['ngRoute'])

    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/view1', {
            templateUrl: 'claps/claps.html',
            controller: 'ClapsCtrl'
        });
    }])

    //ok, now use ideas from https://github.com/danielstern/ngAudio to finish.
    .controller('ClapsCtrl', ['$scope', function ($scope) {

        $scope.timer = new interval(50, function(){
            console.log(new Date().getTime())
        })
        //$scope.timer.run()

        $scope.claps = [];
        $scope.playing = false;
        for(var i = 0; i < clapDelays.length;i++){
            $scope.claps[i] = document.createElement('audio');
            $scope.claps[i].src = 'media/clap-hall-01.mp3';
            $scope.claps[i].volume = volumes[i];
        }

        $scope.play = function () {
            for(var i = 0; i < clapDelays.length;i++){
                (function(_i){setTimeout(function(){
                    if($scope.claps[_i]) {
                        $scope.claps[_i].play();
                    }
                },clapDelays[_i]);})(i);

            }

            setTimeout($scope.play, 600);

            $scope.playing = true;
        };
        $scope.stop = function () {
            for(var i = 0; i < clapDelays.length;i++){
                $scope.claps[i].pause();
            }
            $scope.playing = false;
        };
        /*$scope.claps[0].addEventListener('ended', function () {
            console.log("got an ended event");
            $scope.$apply(function () {
                $scope.stop()
            });
        });*/

    }]);
<|endoftext|>


<commit_before>
// ---------------------------------------------------------

Template.mobile.helpers({
    clipboard: function() {
        return Clipboard.find();
    },
    host: function() {
        // find the other computer in the connection list by
        // eliminating ourselves
        return _.find(this.connections, function(conn) {
            return conn.clientAddress != device.clientAddress;
        });
    }
});

var sessions = [];

Template.mobile.onRendered(function() {
    console.log("onRendered " + JSON.stringify(device));
    if (Meteor.isCordova) {
        if (Meteor.userId()) {
            subscribeUser();
        } else {
            Accounts.onLogin(function() {
                subscribeUser();
            });
        }

        if (cordova.InAppBrowser) {
            window.open = cordova.InAppBrowser.open;
        }
        console.log("this: " + JSON.stringify(_.keys(this)));
        console.log("Oauth: " + JSON.stringify(_.keys(Oauth)));
        console.log("cordova: " + JSON.stringify(_.keys(cordova)));
        console.log("plugins: " + JSON.stringify(_.keys(cordova.plugins)));
        console.log("navigator: " + JSON.stringify(navigator));
        console.log("querying");
        var query = Clipboard.find();
        query.observe({
            changed: function(newDoc, oldDoc) {
                console.log("change: " + JSON.stringify(newDoc));

                if (newDoc.connections.length < 2) {
                    // Router.go('/');
                    // TODO: add a flash message or something?
                    // stop this subscription
                    Clipboard.remove(newDoc._id);
                } else {

                    if (newDoc.cmd == "clipboard") {
                        cordova.plugins.clipboard.copy(newDoc.text);

                    } else if (newDoc.cmd == "maps") {
                        window.open("geo:0,0?q=" + newDoc.text,
                                    '_system', 'location=yes');

                    } else if (newDoc.cmd == "url") {
                        window.open(newDoc.text, '_system');

                    } else if (newDoc.cmd == "tel") {
                        window.open("tel:" + newDoc.number,
                                    '_system', 'location=yes');

                    } else if (newDoc.cmd == "sms") {
                        console.log("sending sms");
                        sms.send(newDoc.number, newDoc.message, {},
                                 function() {
                                     console.log("sms sent");
                                 },
                                 function(e) {
                                     console.log("sms not sent: " + e);
                                 });
                    }
                    if (newDoc.callerCandidate) {
                        // TODO: only if new
                        console.log("adding ice candidate: " + newDoc.callerCandidate);
                        pc.addIceCandidate(new RTCIceCandidate(JSON.parse(newDoc.callerCandidate)));
                    }

                    if (newDoc.offer && !offer) {
                        console.log("got offer:" + newDoc.offer);
                        offer = newDoc.offer;
                        console.log(JSON.parse(newDoc.offer));
                        console.log(pc.setRemoteDescription);
                        var rsd = new sessionDescription(JSON.parse(newDoc.offer));
                        console.log(rsd);
                        pc.setRemoteDescription(rsd, function() {
                            console.log("set remote description");
                            pc.createAnswer(function(description) {
                                console.log("answer: " + JSON.stringify(description));
                                answer = description;
                                pc.setLocalDescription(description, function() {
                                    console.log("set local description");
                                    var data = {
                                        answer: JSON.stringify(description),
                                    };
                                    console.log(sessions);
                                    _.each(sessions, function(id) {
                                        console.log(id);
                                        Clipboard.update(id, {$set: data});
                                    });
                                }, function() {
                                    console.log("couldn't set local description");
                                });
                            }, function() {
                                console.log("couldn't create answer");
                            });
                        }, function(err) {
                            console.log("couldn't set remote description");
                        });
                    }
                }
            }
        });

        startRTC(false);
    }
});

Template.mobile.events({
    'click .qr': function() {
        cordova.plugins.barcodeScanner.scan(
            function (result) {
                // console.log("We got a barcode\n" +
                //             "Result: " + result.text + "\n" +
                //             "Format: " + result.format + "\n" +
                //             "Cancelled: " + result.cancelled);
                // Router.go("/page/"+ result.text);
                sessions.push(result.text);
                Meteor.subscribe('clipboard', result.text, device);
            },
            function (error) {
                console.log("Scanning failed: " + error);
            }
        );
    },
    'click .remove': function() {
        console.log("remove " + JSON.stringify(this));
        Clipboard.remove(this._id);
    }
});

// Template.mobile.helpers({
//     peers: function() {
//         var data = Clipboard.findOne();
//         if (data) {
//             return data.connections.length;
//         }
//     }
// });

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

function subscribeUser() {
    var id = Meteor.userId();
    console.log("subscribing to user collection", id);
    sessions.push(id);
    Meteor.subscribe('clipboard', id);
}

Template.web.onRendered(function() {
    // TODO: this creates too many collection (on per page load;
    // change that to once per established connection between
    // web+mobile)
    Clipboard.insert({ text: "type here" }, function(err, id) {
        sessions.push(id);
        $('#qrcode').qrcode( {
            text: id,
            render: 'canvas',
            size: 60,
            ecLevel: 'H',
            fill: "#000",
            // background: "#ffffff",
            radius: 2.0,
        });
        Meteor.subscribe('clipboard', id);

        if (Meteor.userId()) {
            subscribeUser();
        } else {
            Accounts.onLogin(function() {
                subscribeUser();
            });
        }
    });

    startRTC(true);

    $("body").addClass("web");
});

Template.web.events({
    // 'keydown input': function(event, template) {
    //     if (event.keyCode == 13) {
    //         var val = template.$(event.target).val();
    //         Clipboard.update(Session.get('id'), {$set: {
    //             text: val,
    //             cmd: event.target.dataset.cmd
    //         }});
    //         return false;
    //     }
    // },
    'keydown .action': function(event, template) {
        if (event.keyCode == 13) {
            var form = template.$(event.target).closest('.form');
            var data = {cmd: event.target.dataset.cmd};
            form.find('[data-field]').each(function(index) {
                data[this.dataset.field] = $(this).val();
            });
            console.log(data);
            _.each(sessions, function(id) {
                Clipboard.update(id, {$set: data});
            });
            return false;
        }
    }

});

Template.web.helpers({
    connections: function() {
        var data = Clipboard.findOne();
        console.log("data", data);
        if (data) {
            if (offer == null
                && data.connections
                && data.connections.length > 1) {
                makeOffer();
            }
            if (answer == null
                && data.answer) {
                pc.setRemoteDescription(
                    new sessionDescription(JSON.parse(data.answer)),
                    function() {
                        console.log("RTC: we are ready!");
                    }, function(err) {
                        console.log("couldn't set remote description");
                    });
            }
            if (data.responderCandidate) {
                // TODO: only if new
                pc.addIceCandidate(new RTCIceCandidate(JSON.parse(data.responderCandidate)));
            }
            return _.map(data.connections, function(conn) {
                return { ip: conn.clientAddress,
                         agent: conn.httpHeaders["user-agent"],
                         device: conn.device };
            });
        }
    }
});

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

var peerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection ||
    window.webkitRTCPeerConnection || window.msRTCPeerConnection;
var sessionDescription = window.RTCSessionDescription ||
    window.mozRTCSessionDescription ||
    window.webkitRTCSessionDescription || window.msRTCSessionDescription;
navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia ||
    navigator.webkitGetUserMedia || navigator.msGetUserMedia;

sendChannel = null;
pc = null;
var configuration = {};
offer = null;
answer = null;

// run start(true) to initiate a call
startRTC = function(isCaller) {
    console.log("starting RTC");
    pc = new peerConnection(
        // configuration,
        {"iceServers": [{"url": "stun:stun.l.google.com:19302"}]},
        // {optional: [{RtpDataChannels: true}]}
        null
    );
    console.log(pc);

    // send any ice candidates to the other peer
    pc.onicecandidate = function (evt) {
        if (evt.candidate) {
            console.log("onICECandidate", evt);
            // signalingChannel.send(JSON.stringify({ "candidate": evt.candidate }));
            var data = {};
            if (isCaller) {
                data.callerCandidate = JSON.stringify(evt.candidate);
            } else {
                data.responderCandidate = JSON.stringify(evt.candidate);
            };
            console.log("setting callerCandidate", data);
            _.each(sessions, function(id) {
                Clipboard.update(id, {$set: data});
            });
        }
    };

    // once remote stream arrives, show it in the remote video element
    // pc.onaddstream = function (evt) {
    //     remoteView.src = URL.createObjectURL(evt.stream);
    // };

    // get the local stream, show it in the local video element and send it
    // navigator.getUserMedia({ "audio": true, "video": true }, function (stream) {
    //     selfView.src = URL.createObjectURL(stream);
    //     pc.addStream(stream);

    //     if (isCaller)
    //         pc.createOffer(gotDescription);
    //     else
    //         pc.createAnswer(pc.remoteDescription, gotDescription);

    //     function gotDescription(desc) {
    //         pc.setLocalDescription(desc);
    //         signalingChannel.send(JSON.stringify({ "sdp": desc }));
    //     }
    // });

    pc.ondatachannel = function(event) {
        console.log("got data channel");
        receiveChannel = event.channel;
        receiveChannel.onmessage = function(event){
            console.log(event, event.data);
        };
    };

    sendChannel = pc.createDataChannel("sendDataChannel", {reliable: false});
    // sendChannel.binaryType = 'arraybuffer';

    // document.querySelector("button#send").onclick = function (){
    //     var data = document.querySelector("textarea#send").value;
    //     sendChannel.send(data);
    // };
}

makeOffer = function() {
    pc.createOffer(function(description) {
        offer = description;
        console.log("createOffer", description, JSON.stringify(description));
        pc.setLocalDescription(description, function() {
            // pc2.setRemoteDescription(offer, onPc2RemoteDescriptionSet, onError);
            var data = {
                offer: JSON.stringify(description),
            };
            _.each(sessions, function(id) {
                Clipboard.update(id, {$set: data});
            });
        }, function(err) {
            console.log("couldn't set local description", err);
        });
    }, function(err) {
        console.log(err);
    });
}
<commit_msg>Tidying up unnecessary JSON.stringify + JSON.parse pairs.<commit_after>
// ---------------------------------------------------------

Template.mobile.helpers({
    clipboard: function() {
        return Clipboard.find();
    },
    host: function() {
        // find the other computer in the connection list by
        // eliminating ourselves
        return _.find(this.connections, function(conn) {
            return conn.clientAddress != device.clientAddress;
        });
    }
});

var sessions = [];

Template.mobile.onRendered(function() {
    console.log("onRendered " + JSON.stringify(device));
    if (Meteor.isCordova) {
        if (Meteor.userId()) {
            subscribeUser();
        } else {
            Accounts.onLogin(function() {
                subscribeUser();
            });
        }

        if (cordova.InAppBrowser) {
            window.open = cordova.InAppBrowser.open;
        }
        console.log("this: " + JSON.stringify(_.keys(this)));
        console.log("Oauth: " + JSON.stringify(_.keys(Oauth)));
        console.log("cordova: " + JSON.stringify(_.keys(cordova)));
        console.log("plugins: " + JSON.stringify(_.keys(cordova.plugins)));
        console.log("navigator: " + JSON.stringify(navigator));
        console.log("querying");
        var query = Clipboard.find();
        query.observe({
            changed: function(newDoc, oldDoc) {
                console.log("change: " + JSON.stringify(newDoc));

                if (newDoc.connections.length < 2) {
                    // Router.go('/');
                    // TODO: add a flash message or something?
                    // stop this subscription
                    Clipboard.remove(newDoc._id);
                } else {

                    if (newDoc.cmd == "clipboard") {
                        cordova.plugins.clipboard.copy(newDoc.text);

                    } else if (newDoc.cmd == "maps") {
                        window.open("geo:0,0?q=" + newDoc.text,
                                    '_system', 'location=yes');

                    } else if (newDoc.cmd == "url") {
                        window.open(newDoc.text, '_system');

                    } else if (newDoc.cmd == "tel") {
                        window.open("tel:" + newDoc.number,
                                    '_system', 'location=yes');

                    } else if (newDoc.cmd == "sms") {
                        console.log("sending sms");
                        sms.send(newDoc.number, newDoc.message, {},
                                 function() {
                                     console.log("sms sent");
                                 },
                                 function(e) {
                                     console.log("sms not sent: " + e);
                                 });
                    }
                    if (newDoc.callerCandidate) {
                        // TODO: only if new
                        console.log("adding ice candidate: " + newDoc.callerCandidate);
                        pc.addIceCandidate(new RTCIceCandidate(newDoc.callerCandidate));
                    }

                    if (newDoc.offer && !offer) {
                        console.log("got offer:" + newDoc.offer);
                        offer = newDoc.offer;
                        console.log(newDoc.offer);
                        console.log(pc.setRemoteDescription);
                        var rsd = new sessionDescription(newDoc.offer);
                        console.log(rsd);
                        pc.setRemoteDescription(rsd, function() {
                            console.log("set remote description");
                            pc.createAnswer(function(description) {
                                console.log("answer: " + JSON.stringify(description));
                                answer = description;
                                pc.setLocalDescription(description, function() {
                                    console.log("set local description");
                                    var data = {
                                        answer: description.toJSON(),
                                    };
                                    console.log(sessions);
                                    _.each(sessions, function(id) {
                                        console.log(id);
                                        Clipboard.update(id, {$set: data});
                                    });
                                }, function() {
                                    console.log("couldn't set local description");
                                });
                            }, function() {
                                console.log("couldn't create answer");
                            });
                        }, function(err) {
                            console.log("couldn't set remote description");
                        });
                    }
                }
            }
        });

        startRTC(false);
    }
});

Template.mobile.events({
    'click .qr': function() {
        cordova.plugins.barcodeScanner.scan(
            function (result) {
                // console.log("We got a barcode\n" +
                //             "Result: " + result.text + "\n" +
                //             "Format: " + result.format + "\n" +
                //             "Cancelled: " + result.cancelled);
                // Router.go("/page/"+ result.text);
                sessions.push(result.text);
                Meteor.subscribe('clipboard', result.text, device);
            },
            function (error) {
                console.log("Scanning failed: " + error);
            }
        );
    },
    'click .remove': function() {
        console.log("remove " + JSON.stringify(this));
        Clipboard.remove(this._id);
    }
});

// Template.mobile.helpers({
//     peers: function() {
//         var data = Clipboard.findOne();
//         if (data) {
//             return data.connections.length;
//         }
//     }
// });

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

function subscribeUser() {
    var id = Meteor.userId();
    console.log("subscribing to user collection", id);
    sessions.push(id);
    Meteor.subscribe('clipboard', id);
}

Template.web.onRendered(function() {
    // TODO: this creates too many collection (on per page load;
    // change that to once per established connection between
    // web+mobile)
    Clipboard.insert({ text: "type here" }, function(err, id) {
        sessions.push(id);
        $('#qrcode').qrcode( {
            text: id,
            render: 'canvas',
            size: 60,
            ecLevel: 'H',
            fill: "#000",
            // background: "#ffffff",
            radius: 2.0,
        });
        Meteor.subscribe('clipboard', id);

        if (Meteor.userId()) {
            subscribeUser();
        } else {
            Accounts.onLogin(function() {
                subscribeUser();
            });
        }
    });

    startRTC(true);

    $("body").addClass("web");
});

Template.web.events({
    // 'keydown input': function(event, template) {
    //     if (event.keyCode == 13) {
    //         var val = template.$(event.target).val();
    //         Clipboard.update(Session.get('id'), {$set: {
    //             text: val,
    //             cmd: event.target.dataset.cmd
    //         }});
    //         return false;
    //     }
    // },
    'keydown .action': function(event, template) {
        if (event.keyCode == 13) {
            var form = template.$(event.target).closest('.form');
            var data = {cmd: event.target.dataset.cmd};
            form.find('[data-field]').each(function(index) {
                data[this.dataset.field] = $(this).val();
            });
            console.log(data);
            _.each(sessions, function(id) {
                Clipboard.update(id, {$set: data});
            });
            return false;
        }
    }

});

Template.web.helpers({
    connections: function() {
        var data = Clipboard.findOne();
        console.log("data", data);
        if (data) {
            if (offer == null
                && data.connections
                && data.connections.length > 1) {
                makeOffer();
            }
            if (answer == null
                && data.answer) {
                pc.setRemoteDescription(
                    new sessionDescription(data.answer),
                    function() {
                        console.log("RTC: we are ready!");
                    }, function(err) {
                        console.log("couldn't set remote description");
                    });
            }
            if (data.responderCandidate) {
                // TODO: only if new
                pc.addIceCandidate(new RTCIceCandidate(data.responderCandidate));
            }
            return _.map(data.connections, function(conn) {
                return { ip: conn.clientAddress,
                         agent: conn.httpHeaders["user-agent"],
                         device: conn.device };
            });
        }
    }
});

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

var peerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection ||
    window.webkitRTCPeerConnection || window.msRTCPeerConnection;
var sessionDescription = window.RTCSessionDescription ||
    window.mozRTCSessionDescription ||
    window.webkitRTCSessionDescription || window.msRTCSessionDescription;
navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia ||
    navigator.webkitGetUserMedia || navigator.msGetUserMedia;

sendChannel = null;
pc = null;
var configuration = {};
offer = null;
answer = null;

// run start(true) to initiate a call
startRTC = function(isCaller) {
    console.log("starting RTC");
    pc = new peerConnection(
        // configuration,
        {"iceServers": [{"url": "stun:stun.l.google.com:19302"}]},
        // {optional: [{RtpDataChannels: true}]}
        null
    );
    console.log(pc);

    // send any ice candidates to the other peer
    pc.onicecandidate = function (evt) {
        if (evt.candidate) {
            console.log("onICECandidate", evt);
            // signalingChannel.send(JSON.stringify({ "candidate": evt.candidate }));
            var data = {};
            if (isCaller) {
                data.callerCandidate = evt.candidate.toJSON();
            } else {
                data.responderCandidate = evt.candidate.toJSON();
            };
            console.log("setting callerCandidate", data);
            _.each(sessions, function(id) {
                Clipboard.update(id, {$set: data});
            });
        }
    };

    // once remote stream arrives, show it in the remote video element
    // pc.onaddstream = function (evt) {
    //     remoteView.src = URL.createObjectURL(evt.stream);
    // };

    // get the local stream, show it in the local video element and send it
    // navigator.getUserMedia({ "audio": true, "video": true }, function (stream) {
    //     selfView.src = URL.createObjectURL(stream);
    //     pc.addStream(stream);

    //     if (isCaller)
    //         pc.createOffer(gotDescription);
    //     else
    //         pc.createAnswer(pc.remoteDescription, gotDescription);

    //     function gotDescription(desc) {
    //         pc.setLocalDescription(desc);
    //         signalingChannel.send(JSON.stringify({ "sdp": desc }));
    //     }
    // });

    pc.ondatachannel = function(event) {
        console.log("got data channel");
        receiveChannel = event.channel;
        receiveChannel.onmessage = function(event){
            console.log(event, event.data);
        };
    };

    sendChannel = pc.createDataChannel("sendDataChannel", {reliable: false});
    // sendChannel.binaryType = 'arraybuffer';

    // document.querySelector("button#send").onclick = function (){
    //     var data = document.querySelector("textarea#send").value;
    //     sendChannel.send(data);
    // };
}

makeOffer = function() {
    pc.createOffer(function(description) {
        offer = description;
        console.log("createOffer", description, description);
        pc.setLocalDescription(description, function() {
            // pc2.setRemoteDescription(offer, onPc2RemoteDescriptionSet, onError);
            var data = {
                offer: description.toJSON(),
            };
            _.each(sessions, function(id) {
                Clipboard.update(id, {$set: data});
            });
        }, function(err) {
            console.log("couldn't set local description", err);
        });
    }, function(err) {
        console.log(err);
    });
}
<|endoftext|>


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

		var _filter = {};
		var undefined;

		var _add = function(name, code){
			_filter[name] = code;
		}

		var _get = function(name){
			return _filter[name] || false;
		}

		_add("currency", function(value){
			value = +value;
			value = value.toFixed(2).replace(".", ",");
			value = value.substring(0, value.lastIndexOf(",") - 3)
					+ "." + value.substring(value.lastIndexOf(",") - 3, value.lastIndexOf(","))
					+ value.substring(value.lastIndexOf(","))

			return value;
		});

		_add("maxlen", function(data, conf){
			if(Mold.isArray(data)){
				data = data.splice(0, conf.len);
			}
			return data;
		})

		_add("topath", function(data, conf){
			var target = (conf.prefix) ? conf.prefix : "" + data.replace(/./g, "/");
			return target + (conf.ending) ? conf.ending : '.js';
		})

		_add("sort", function(data, conf){
			if(Mold.isArray(data)){
				if(conf.value){
					data.sort(function (a, b) {
						a = a[conf.value];
						b = b[conf.value];

						if (a > b) {
							return 1;
						}
						if (a < b) {
							return -1;
						}
						return 0;
					});
				}

				if(conf.desc){
					data.reverse();
				}
			}
			return data;
		});

		_add("exists", function(data, conf){

			if(Mold.isArray(data) && !data.length){
				return false;
			}

			if(Mold.isObject(data)){
				var test = 0;
				for(var prop in data){
					test++;
					if(data.hasProperty(prop)){

					}
				}
				if(test === 0){
					return false;
				}
			}

			if(data == undefined && data == null && data == false){
				return false;
			}

			return true;
		})

		_add("case", function(data, conf){
			for(var prop in conf){
				break;
			}
			if(data === prop){

				return true;
			}else{
				return false;
			}
		})

		_add("if", function(data, conf){
			if(conf.expression){
				conf.expression = conf.expression.replace(/this/g, "data");
				if(eval(conf.expression)){
					return data;
				}
				return false;
			}else{
				return true;
			}
		});

		return {
			add : _add,
			get : _get
		}
	}
)<commit_msg>unused code removed<commit_after>Seed({
		name : "Mold.Lib.Filter",
		dna : "static"
	},
	function(){

		var _filter = {};
		var undefined;

		var _add = function(name, code){
			_filter[name] = code;
		}

		var _get = function(name){
			return _filter[name] || false;
		}

		_add("currency", function(value){
			value = +value;
			value = value.toFixed(2).replace(".", ",");
			value = value.substring(0, value.lastIndexOf(",") - 3)
					+ "." + value.substring(value.lastIndexOf(",") - 3, value.lastIndexOf(","))
					+ value.substring(value.lastIndexOf(","))

			return value;
		});

		_add("maxlen", function(data, conf){
			if(Mold.isArray(data)){
				data = data.splice(0, conf.len);
			}
			return data;
		})

		_add("topath", function(data, conf){
			var target = (conf.prefix) ? conf.prefix : "" + data.replace(/./g, "/");
			return target + (conf.ending) ? conf.ending : '.js';
		})

		_add("sort", function(data, conf){
			if(Mold.isArray(data)){
				if(conf.value){
					data.sort(function (a, b) {
						a = a[conf.value];
						b = b[conf.value];

						if (a > b) {
							return 1;
						}
						if (a < b) {
							return -1;
						}
						return 0;
					});
				}

				if(conf.desc){
					data.reverse();
				}
			}
			return data;
		});

		_add("exists", function(data, conf){
			if(Mold.isArray(data) && !data.length){
				return false;
			}

			if(Mold.isObject(data)){
				var test = 0;
				for(var prop in data){
					test++;
				}
				if(test === 0){
					return false;
				}
			}

			if(data == undefined && data == null && data == false){
				return false;
			}

			return true;
		})

		_add("case", function(data, conf){
			for(var prop in conf){
				break;
			}
			if(data === prop){

				return true;
			}else{
				return false;
			}
		})

		_add("if", function(data, conf){
			if(conf.expression){
				conf.expression = conf.expression.replace(/this/g, "data");
				if(eval(conf.expression)){
					return data;
				}
				return false;
			}else{
				return true;
			}
		});

		return {
			add : _add,
			get : _get
		}
	}
)<|endoftext|>


<commit_before>var tileMath = require('../tools/tileMath');

exports.process = function process (req, res, config) {
    var z,
        x,
        y,
        urlParams = req.url.replace(/[^0-9a-zA-Z]/g, "/").split('/'),
        tileObject = {
            "tileUrl": null,
            "cachePath": null,
            "cacheTile": false,
            "returnTile": false,
            "res": res,
            "stream": res,
            "imageFormat": config.imageFormat
        };

    if (urlParams.length > 4) {
        // We have enough params
        z = parseInt(urlParams[2],10);
        x = parseInt(urlParams[3],10);
        y = parseInt(urlParams[4],10);

        // Set default wmsSettings
        var wmsSettings = {
            "dpi": "92",
            "transparent":  true,
            "layers": "show:0",
            "size": "256,256",
            "f": "image",
            "format": config.imageFormat,
            "bboxSR": "4326",
            "imageSR": "102113"
        };

        var bounds = {
            'left': tileMath.tile2long(x,z),
            'top': tileMath.tile2lat(y,z),
            'right': tileMath.tile2long((x+1), z),
            'bottom': tileMath.tile2lat((y+1),z)
        };

        wmsSettings.bbox = [bounds.left, bounds.top, bounds.right, bounds.bottom].join(",");

        // Add in params from the config (not ready yet!)
        if (config.wms) {
            for (var setting in config.wms) {
                if (config.wms.hasOwnProperty(setting)){
                    wmsSettings[setting] = config.wms[setting];
                }
            }
        }
        tileObject.tileUrl = config.url;
        for (var key in wmsSettings) {
            if (wmsSettings.hasOwnProperty(key)){
                tileObject.tileUrl += key + "=" + encodeURIComponent(wmsSettings[key]) + "&";
            }
        }
        // Remove last character and URL encode the url
        tileObject.tileUrl = tileObject.tileUrl.substring(0,tileObject.tileUrl.length-1);
        console.log("displayable URL ", tileObject.tileUrl);
        tileObject.cachePath = urlParams.splice(1,5).join("/");

        // If we're not in the right zoom, return false for the tileUrl
        if (z >= parseInt(config.minZoom,10) && z <= parseInt(config.maxZoom, 10)) {
            tileObject.cacheTile = config.cacheTiles;
            tileObject.returnTile = true;
        } else {
            tileObject.errorDescription = [
                "The zoom level of (",
                z,
                ") is not between the minZoom (",
                config.minZoom,
                ") and the maxZoom (",
                config.maxZoom,
                ")."
            ].join('');
            tileObject.errorNum = 400;
        }
    } else {
        tileObject.errorDescription = "Too few parameters, this requires parameters in z/x/y format";
        tileObject.errorNum = 400;
    }
    return tileObject;
};
<commit_msg>Clean up code: Update src/types/wms.js<commit_after>var tileMath = require('../tools/tileMath');

exports.process = function process(req, res, config) {
  var z,
    x,
    y,
    urlParams = req.url.replace(/[^0-9a-zA-Z]/g, '/').split('/'),
    tileObject = {
      'tileUrl': null,
      'cachePath': null,
      'cacheTile': false,
      'returnTile': false,
      'res': res,
      'stream': res,
      'imageFormat': config.imageFormat
    };

  if (urlParams.length > 4) {
    // We have enough params
    z = parseInt(urlParams[2], 10);
    x = parseInt(urlParams[3], 10);
    y = parseInt(urlParams[4], 10);

    // Set default wmsSettings
    var wmsSettings = {
      'dpi': '92',
      'transparent': true,
      'layers': 'show:0',
      'size': '256,256',
      'f': 'image',
      'format': config.imageFormat,
      'bboxSR': '4326',
      'imageSR': '102113'
    };

    var bounds = {
      'left': tileMath.tile2long(x, z),
      'top': tileMath.tile2lat(y, z),
      'right': tileMath.tile2long((x + 1), z),
      'bottom': tileMath.tile2lat((y + 1), z)
    };

    wmsSettings.bbox = [bounds.left, bounds.top, bounds.right, bounds.bottom].join(',');

    // Add in params from the config (not ready yet!)
    if (config.wms) {
      for (var setting in config.wms) {
        if (config.wms.hasOwnProperty(setting)) {
          wmsSettings[setting] = config.wms[setting];
        }
      }
    }
    tileObject.tileUrl = config.url;
    for (var key in wmsSettings) {
      if (wmsSettings.hasOwnProperty(key)) {
        tileObject.tileUrl += key + '=' + encodeURIComponent(wmsSettings[key]) + '&';
      }
    }
    // Remove last character and URL encode the url
    tileObject.tileUrl = tileObject.tileUrl.substring(0, tileObject.tileUrl.length - 1);
    console.log('displayable URL ', tileObject.tileUrl);
    tileObject.cachePath = urlParams.splice(1, 5).join('/');

    // If we're not in the right zoom, return false for the tileUrl
    if (z >= parseInt(config.minZoom, 10) && z <= parseInt(config.maxZoom, 10)) {
      tileObject.cacheTile = config.cacheTiles;
      tileObject.returnTile = true;
    } else {
      tileObject.errorDescription = [
        'The zoom level of (',
        z,
        ') is not between the minZoom (',
        config.minZoom,
        ') and the maxZoom (',
        config.maxZoom,
        ').'
      ].join('');
      tileObject.errorNum = 400;
    }
  } else {
    tileObject.errorDescription = 'Too few parameters, this requires parameters in z/x/y format';
    tileObject.errorNum = 400;
  }
  return tileObject;
};
<|endoftext|>


<commit_before>define( [ "dialog/iframe-dialog" ], function( IFrameDialog ){

  var DEFAULT_AUTH_BUTTON_TEXT = "Login / Sign Up";

  return function( butter, options ){

    options = options || {};

    var _rootElement = document.createElement( "div" ),
        _newButton,
        _saveButton,
        _loadButton,
        _shareButton,
        _authButton,
        _logoutButton;

    var title = options.title || "Butter";

    _rootElement.innerHTML = '' +
      '

' + title + '
' +
      '
' +
      '    <button id="butter-header-new">New</button>' +
      '    <button id="butter-header-save">Save</button>' +
      '    <button id="butter-header-load">Load</button>' +
      '    <button id="butter-header-share">Share</button>' +
      '    <button id="butter-header-auth">' + DEFAULT_AUTH_BUTTON_TEXT + '</button>' +
      '    <button id="butter-header-auth-out">Logout</button>' +
      '
';

    _rootElement.setAttribute( "data-butter-exclude", true );
    _rootElement.id = "butter-header";

    document.body.insertBefore( _rootElement, document.body.firstChild );

    _newButton = document.getElementById( "butter-header-new" ),
    _saveButton = document.getElementById( "butter-header-save" ),
    _loadButton = document.getElementById( "butter-header-load" ),
    _shareButton = document.getElementById( "butter-header-share" ),
    _authButton = document.getElementById( "butter-header-auth" ),
    _logoutButton = document.getElementById( "butter-header-auth-out" );

    var _oldDisplayProperty = _logoutButton.style.display;
    _logoutButton.style.display = "none";

    function doAuth( successCallback, errorCallback ){
      butter.cornfield.login(function( response ){
        if( response.status === "okay" ){
          var email = response.email;
          butter.cornfield.list(function( listResponse ) {
            _authButton.innerHTML = email;
            _logoutButton.style.display = _oldDisplayProperty;
            if( successCallback ){
              successCallback();
            }
          });
        }
        else{
          showErrorDialog( "There was an error logging in. Please try again." );
          if( errorCallback ){
            errorCallback();
          }
        }
      });
    }

    _newButton.addEventListener( "click", function( e ){
      var dialog = new IFrameDialog({
        type: "iframe",
        modal: true,
        url: "../dialogs/quit-confirmation.html",
        events: {
          submit: function( e ){
            dialog.close();
            window.location.reload();
          },
          cancel: function( e ){
            dialog.close();
          }
        }
      });
      dialog.open();
    }, false );

    _authButton.addEventListener( "click", function( e ){
      if( !butter.cornfield.user() ){
        doAuth();
      }
    }, false );

    _logoutButton.addEventListener( "click", function( e ){
      if( butter.cornfield.user() ){
        butter.cornfield.logout(function( response ){
          _logoutButton.style.display = "none";
          _authButton.innerHTML = DEFAULT_AUTH_BUTTON_TEXT;
        });
      }
    });

    function showErrorDialog( message, callback ){
      var dialog = new IFrameDialog({
        type: "iframe",
        modal: true,
        url: "../dialogs/error-message.html",
        events: {
          open: function( e ){
            dialog.send( "message", message );
          },
          cancel: function( e ){
            dialog.close();
            if( callback ){
              callback();
            }
          }
        }
      });
      dialog.open();
    }

    _shareButton.addEventListener( "click", function( e ){
      function prepare(){

      }

      if( !butter.cornfield.user() ){
        doAuth( prepare );
      }
      else{
        prepare();
      }
    }, false );

    _saveButton.addEventListener( "click", function( e ){

      function doSave(){
        butter.project.html = butter.getHTML();
        butter.project.data = butter.exportProject();
        var saveString = JSON.stringify( butter.project );
        butter.cornfield.saveas( butter.project._id, saveString, function( e ){
          if( e.error !== "okay" || !e.project || !e.project._id ){
            showErrorDialog( "There was a problem saving your project. Please try again." );
            return;
          }
          butter.project.id = e.project._id;
        });
      }

      function prepare() {
        if( !butter.project.name ){
          var dialog = new IFrameDialog({
            type: "iframe",
            modal: true,
            url: "../dialogs/save-as.html",
            events: {
              open: function( e ){
                dialog.send( "name", null );
              },
              submit: function( e ){
                butter.project.name = e.data;
                dialog.close();
                doSave();
              },
              cancel: function( e ){
                dialog.close();
              }
            }
          });
          dialog.open();
        }
        else{
          doSave();
        }
      }

      if( !butter.cornfield.user() ){
        doAuth( prepare );
      }
      else{
        prepare();
      }
    }, false );

    _loadButton.addEventListener( "click", function( e ){
      function prepare(){
        butter.cornfield.list(function( listResponse ) {
          if( listResponse.error !== "okay" ){
            showErrorDialog( "There was an error loading your projects. Please try again." );
            return;
          }
          else{
            var dialog = new IFrameDialog({
              type: "iframe",
              modal: true,
              url: "../dialogs/load-project.html",
              events: {
                open: function( e ){
                  dialog.send( "list", listResponse.projects );
                },
                submit: function( e ){
                  dialog.close();
                  butter.cornfield.load( e.data, function( e ){
                    if( e.error === "okay" ){
                      var projectData;
                      try{
                        projectData = JSON.parse( e.project );
                      }
                      catch( e ){
                        showErrorDialog( "Your project could not be loaded. Please try another." );
                        return;
                      }
                      butter.clearProject();
                      butter.importProject( projectData );
                    }
                    else{
                      showErrorDialog( "Your project could not be loaded. Please try another." );
                    }
                  });
                },
                cancel: function( e ){
                  dialog.close();
                }
              }
            });
            dialog.open();
          }
        });
      }

      if( !butter.cornfield.user() ){
        doAuth( prepare );
      }
      else{
        prepare();
      }
    }, false );

    function setup(){
      _rootElement.style.width = window.innerWidth + "px";
    }

    window.addEventListener( "resize", setup, false );
    setup();

  };

});<commit_msg>[t537-server] - review changes<commit_after>define( [ "dialog/iframe-dialog" ], function( IFrameDialog ){

  var DEFAULT_AUTH_BUTTON_TEXT = "Login / Sign Up";

  return function( butter, options ){

    options = options || {};

    var _rootElement = document.createElement( "div" ),
        _newButton,
        _saveButton,
        _loadButton,
        _shareButton,
        _authButton,
        _logoutButton;

    var title = options.title || "Butter";

    _rootElement.innerHTML = '' +
      '

' + title + '
' +
      '
' +
      '    <button id="butter-header-new">New</button>' +
      '    <button id="butter-header-save">Save</button>' +
      '    <button id="butter-header-load">Load</button>' +
      '    <button id="butter-header-share">Share</button>' +
      '    <button id="butter-header-auth">' + DEFAULT_AUTH_BUTTON_TEXT + '</button>' +
      '    <button id="butter-header-auth-out">Logout</button>' +
      '
';

    _rootElement.setAttribute( "data-butter-exclude", true );
    _rootElement.id = "butter-header";

    document.body.insertBefore( _rootElement, document.body.firstChild );

    _newButton = document.getElementById( "butter-header-new" );
    _saveButton = document.getElementById( "butter-header-save" );
    _loadButton = document.getElementById( "butter-header-load" );
    _shareButton = document.getElementById( "butter-header-share" );
    _authButton = document.getElementById( "butter-header-auth" );
    _logoutButton = document.getElementById( "butter-header-auth-out" );

    var _oldDisplayProperty = _logoutButton.style.display;
    _logoutButton.style.display = "none";

    function doAuth( successCallback, errorCallback ){
      butter.cornfield.login(function( response ){
        if( response.status === "okay" ){
          var email = response.email;
          butter.cornfield.list(function( listResponse ) {
            _authButton.innerHTML = email;
            _logoutButton.style.display = _oldDisplayProperty;
            if( successCallback ){
              successCallback();
            }
          });
        }
        else{
          showErrorDialog( "There was an error logging in. Please try again." );
          if( errorCallback ){
            errorCallback();
          }
        }
      });
    }

    _newButton.addEventListener( "click", function( e ){
      var dialog = new IFrameDialog({
        type: "iframe",
        modal: true,
        url: "../dialogs/quit-confirmation.html",
        events: {
          submit: function( e ){
            dialog.close();
            window.location.reload();
          },
          cancel: function( e ){
            dialog.close();
          }
        }
      });
      dialog.open();
    }, false );

    _authButton.addEventListener( "click", function( e ){
      if( !butter.cornfield.user() ){
        doAuth();
      }
    }, false );

    _logoutButton.addEventListener( "click", function( e ){
      if( butter.cornfield.user() ){
        butter.cornfield.logout(function( response ){
          _logoutButton.style.display = "none";
          _authButton.innerHTML = DEFAULT_AUTH_BUTTON_TEXT;
        });
      }
    });

    function showErrorDialog( message, callback ){
      var dialog = new IFrameDialog({
        type: "iframe",
        modal: true,
        url: "../dialogs/error-message.html",
        events: {
          open: function( e ){
            dialog.send( "message", message );
          },
          cancel: function( e ){
            dialog.close();
            if( callback ){
              callback();
            }
          }
        }
      });
      dialog.open();
    }

    _shareButton.addEventListener( "click", function( e ){
      function prepare(){

      }

      if( !butter.cornfield.user() ){
        doAuth( prepare );
      }
      else{
        prepare();
      }
    }, false );

    _saveButton.addEventListener( "click", function( e ){

      function doSave(){
        butter.project.html = butter.getHTML();
        butter.project.data = butter.exportProject();
        var saveString = JSON.stringify( butter.project );
        butter.cornfield.saveas( butter.project._id, saveString, function( e ){
          if( e.error !== "okay" || !e.project || !e.project._id ){
            showErrorDialog( "There was a problem saving your project. Please try again." );
            return;
          }
          butter.project.id = e.project._id;
        });
      }

      function prepare() {
        if( !butter.project.name ){
          var dialog = new IFrameDialog({
            type: "iframe",
            modal: true,
            url: "../dialogs/save-as.html",
            events: {
              open: function( e ){
                dialog.send( "name", null );
              },
              submit: function( e ){
                butter.project.name = e.data;
                dialog.close();
                doSave();
              },
              cancel: function( e ){
                dialog.close();
              }
            }
          });
          dialog.open();
        }
        else{
          doSave();
        }
      }

      if( !butter.cornfield.user() ){
        doAuth( prepare );
      }
      else{
        prepare();
      }
    }, false );

    _loadButton.addEventListener( "click", function( e ){
      function prepare(){
        butter.cornfield.list(function( listResponse ) {
          if( listResponse.error !== "okay" ){
            showErrorDialog( "There was an error loading your projects. Please try again." );
            return;
          }
          else{
            var dialog = new IFrameDialog({
              type: "iframe",
              modal: true,
              url: "../dialogs/load-project.html",
              events: {
                open: function( e ){
                  dialog.send( "list", listResponse.projects );
                },
                submit: function( e ){
                  dialog.close();
                  butter.cornfield.load( e.data, function( e ){
                    if( e.error === "okay" ){
                      var projectData;
                      try{
                        projectData = JSON.parse( e.project );
                      }
                      catch( e ){
                        showErrorDialog( "Your project could not be loaded. Please try another." );
                        return;
                      }
                      butter.clearProject();
                      butter.importProject( projectData );
                    }
                    else{
                      showErrorDialog( "Your project could not be loaded. Please try another." );
                    }
                  });
                },
                cancel: function( e ){
                  dialog.close();
                }
              }
            });
            dialog.open();
          }
        });
      }

      if( !butter.cornfield.user() ){
        doAuth( prepare );
      }
      else{
        prepare();
      }
    }, false );

    function setup(){
      _rootElement.style.width = window.innerWidth + "px";
    }

    window.addEventListener( "resize", setup, false );
    setup();

  };

});<|endoftext|>


<commit_before>/**
 * @file TouchRipple component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import classNames from 'classnames';
import TransitionGroup from 'react-transition-group/TransitionGroup';

import Ripple from '../_Ripple';

import Util from '../_vendors/Util';
import Dom from '../_vendors/Dom';

class TouchRipple extends Component {

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.ignoreNextMouseDown = false;
        this.nextKey = 0;

        this.state = {
            ripples: []
        };

        this.getRippleStyle = ::this.getRippleStyle;
        this.addRipple = ::this.addRipple;
        this.removeRipple = ::this.removeRipple;
        this.mouseDownHandle = ::this.mouseDownHandle;

    }

    getRippleStyle(e) {

        const {displayCenter} = this.props,

            el = ReactDOM.findDOMNode(this),

            elWidth = el.offsetWidth,
            elHeight = el.offsetHeight;

        // get pointer offset of el
        let pointerX, pointerY;
        if (displayCenter) {
            pointerX = elWidth / 2;
            pointerY = elHeight / 2;
        } else {
            const {top, left} = Dom.getOffset(el);
            pointerX = e.pageX - left;
            pointerY = e.pageY - top;
        }

        // radius is the max distence
        const rippleRadius = Math.max(
            Util.getDiag(pointerX, pointerY),
            Util.getDiag(elWidth - pointerX, pointerY),
            Util.getDiag(elWidth - pointerX, elHeight - pointerY),
            Util.getDiag(pointerX, elHeight - pointerY)
        );
        const rippleSize = rippleRadius * 2;

        // calculate offset
        const left = pointerX - rippleRadius;
        const top = pointerY - rippleRadius;

        return {
            height: rippleSize,
            width: rippleSize,
            top: top,
            left: left
        };

    }

    addRipple(e) {

        if (this.ignoreNextMouseDown) {
            return;
        }

        this.ignoreNextMouseDown = true;
        let {ripples} = this.state;

        ripples.push({
            key: this.nextKey++,
            style: this.getRippleStyle(e)
        });

        this.setState({
            ripples
        }, () => {
            this.ignoreNextMouseDown = false;
        });

    }

    removeRipple() {
        this.setState({
            ripples: []
        });
    }

    mouseDownHandle(e) {
        this.addRipple(e);
    }

    render() {

        const {className, style, duration} = this.props,
            {ripples} = this.state,

            wrapperClassName = classNames('touch-ripple', {
                [className]: className
            });

        return (
            <TransitionGroup className={wrapperClassName}
                             style={style}
                             onMouseDown={this.mouseDownHandle}
                             onMouseUp={this.removeRipple}
                             onMouseLeave={this.removeRipple}>
                {
                    ripples && ripples.map(item =>
                        <Ripple {...item}
                                duration={duration}/>
                    )
                }
            </TransitionGroup>
        );

    }
}

TouchRipple.propTypes = {

    className: PropTypes.string,
    style: PropTypes.object,

    duration: PropTypes.number,
    displayCenter: PropTypes.bool

};

TouchRipple.defaultProps = {
    duration: 500,
    displayCenter: false
};

export default TouchRipple;<commit_msg>update TouchRipple<commit_after>/**
 * @file TouchRipple component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import classNames from 'classnames';
import TransitionGroup from 'react-transition-group/TransitionGroup';

import Ripple from '../_Ripple';

import Util from '../_vendors/Util';
import Dom from '../_vendors/Dom';

class TouchRipple extends Component {

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.ignoreNextMouseDown = false;
        this.nextKey = 0;

        this.state = {
            ripples: []
        };

        this.getRippleStyle = ::this.getRippleStyle;
        this.addRipple = ::this.addRipple;
        this.removeRipple = ::this.removeRipple;
        this.mouseDownHandler = ::this.mouseDownHandler;

    }

    getRippleStyle(e) {

        const {displayCenter} = this.props,

            el = ReactDOM.findDOMNode(this),

            elWidth = el.offsetWidth,
            elHeight = el.offsetHeight;

        // get pointer offset of el
        let pointerX, pointerY;
        if (displayCenter) {
            pointerX = elWidth / 2;
            pointerY = elHeight / 2;
        } else {
            const {top, left} = Dom.getOffset(el);
            pointerX = e.pageX - left;
            pointerY = e.pageY - top;
        }

        // radius is the max distence
        const rippleRadius = Math.max(
            Util.getDiag(pointerX, pointerY),
            Util.getDiag(elWidth - pointerX, pointerY),
            Util.getDiag(elWidth - pointerX, elHeight - pointerY),
            Util.getDiag(pointerX, elHeight - pointerY)
        );
        const rippleSize = rippleRadius * 2;

        // calculate offset
        const left = pointerX - rippleRadius;
        const top = pointerY - rippleRadius;

        return {
            height: rippleSize,
            width: rippleSize,
            top: top,
            left: left
        };

    }

    addRipple(e) {

        if (this.ignoreNextMouseDown) {
            return;
        }

        this.ignoreNextMouseDown = true;
        let {ripples} = this.state;

        ripples.push({
            key: this.nextKey++,
            style: this.getRippleStyle(e)
        });

        this.setState({
            ripples
        }, () => {
            this.ignoreNextMouseDown = false;
        });

    }

    removeRipple() {
        this.setState({
            ripples: []
        });
    }

    mouseDownHandler(e) {
        this.addRipple(e);
    }

    render() {

        const {className, style, duration} = this.props,
            {ripples} = this.state,

            wrapperClassName = classNames('touch-ripple', {
                [className]: className
            });

        return (
            <TransitionGroup className={wrapperClassName}
                             style={style}
                             onMouseDown={this.mouseDownHandler}
                             onMouseUp={this.removeRipple}
                             onMouseLeave={this.removeRipple}>
                {
                    ripples && ripples.map(item =>
                        <Ripple {...item}
                                duration={duration}/>
                    )
                }
            </TransitionGroup>
        );

    }
}

TouchRipple.propTypes = {

    className: PropTypes.string,
    style: PropTypes.object,

    duration: PropTypes.number,
    displayCenter: PropTypes.bool

};

TouchRipple.defaultProps = {
    duration: 500,
    displayCenter: false
};

export default TouchRipple;<|endoftext|>


<commit_before>"use strict";

let bus = require("./service-bus");
let BalancedList = require("./balanced-list");
let Context = require("./context");
let errors = require("./errors");
let utils = require("./utils");
let _ = require("lodash");

class ServiceBroker {

	constructor(options) {
		this.options = options || {};
		this.nodes = new Map();
		this.services = new Map();
		this.actions = new Map();
		this.subscriptions = new Map();
		this.transporter = this.options.transporter;

		this.nodeID = this.options.nodeID || utils.getNodeID();

		if (this.transporter) {
			this.transporter.init(this);
		}
	}

	start() {
		if (this.transporter) {
			this.transporter.connect();
		}
	}

	/**
	 * Register a local service
	 *
	 * @param {any} service
	 *
	 * @memberOf ServiceBroker
	 */
	registerService(service) {
		// Append service by name
		let item = this.services.get(service.name);
		if (!item) {
			item = new BalancedList();
			this.services.set(service.name, item);
		}
		item.add(service);

		bus.emit(`register.service.${service.name}`, service);
	}

	/**
	 * Register an action in a local server
	 *
	 * @param {any} service
	 * @param {any} action
	 *
	 * @memberOf ServiceBroker
	 */
	registerAction(service, action) {
		// Append action by name
		let item = this.actions.get(action.name);
		if (!item) {
			item = new BalancedList();
			this.actions.set(action.name, item);
		}
		item.add(action);
		bus.emit(`register.action.${action.name}`, service, action);
	}

	subscribeEvent(service, event) {
		// Append event subscriptions
		let item = this.subscriptions.get(event.name);
		if (!item) {
			item = new BalancedList();
			this.subscriptions.set(event.name, item);
		}
		item.add(event);
		bus.on(event.name, event.handler.bind(service));
	}

	getService(serviceName) {
		let service = this.services.get(serviceName);
		if (service) {
			return service.get();
		}
	}

	hasService(serviceName) {
		return this.services.has(serviceName);
	}

	hasAction(actionName) {
		return this.actions.has(actionName);
	}

	call(actionName, params, parentCtx) {
		let actions = this.actions.get(actionName);
		if (!actions)
			throw new errors.ServiceNotFoundError(`Missing action '${actionName}'!`);

		let action = actions.get();
		/* istanbul ignore next */
		if (!action)
			throw new Error(`Missing action handler '${actionName}'!`);

		let service = action.service;
		// Create a new context
		let ctx;
		if (parentCtx)
			ctx = parentCtx.createSubContext(service, action, params);
		else
			ctx = new Context({ service, action, params });

		return action.handler(ctx);
	}

	emit(eventName, data) {
		if (this.transporter)
			this.transporter.emit(eventName, data);
		return this.emitLocal(eventName, data);
	}

	emitLocal(eventName, data) {
		let d;
		if (_.isObject(data))
			d = Object.freeze(Object.assign({}, data));
		else
			d = data;

		return bus.emit(eventName, d);
	}

	getLocalActionList() {
		let res = [];
		for (let entry of this.actions.entries()) {
			if (entry[1].hasLocal())
				res.push(entry[0]);
		}
		return res;
	}
	/*
	publishActionList() {
		if (this.transporter) {
			this.transporter.publishActionList();
		}
	}*/
}

module.exports = ServiceBroker;<commit_msg>change direct bus emit call<commit_after>"use strict";

let bus = require("./service-bus");
let BalancedList = require("./balanced-list");
let Context = require("./context");
let errors = require("./errors");
let utils = require("./utils");
let _ = require("lodash");

class ServiceBroker {

	constructor(options) {
		this.options = options || {};
		this.nodes = new Map();
		this.services = new Map();
		this.actions = new Map();
		this.subscriptions = new Map();
		this.transporter = this.options.transporter;

		this.nodeID = this.options.nodeID || utils.getNodeID();

		if (this.transporter) {
			this.transporter.init(this);
		}
	}

	start() {
		if (this.transporter) {
			this.transporter.connect();
		}
	}

	/**
	 * Register a local service
	 *
	 * @param {any} service
	 *
	 * @memberOf ServiceBroker
	 */
	registerService(service) {
		// Append service by name
		let item = this.services.get(service.name);
		if (!item) {
			item = new BalancedList();
			this.services.set(service.name, item);
		}
		item.add(service);

		this.emitLocal(`register.service.${service.name}`, { service });
	}

	/**
	 * Register an action in a local server
	 *
	 * @param {any} service
	 * @param {any} action
	 *
	 * @memberOf ServiceBroker
	 */
	registerAction(service, action) {
		// Append action by name
		let item = this.actions.get(action.name);
		if (!item) {
			item = new BalancedList();
			this.actions.set(action.name, item);
		}
		item.add(action);
		this.emitLocal(`register.action.${action.name}`, { service, action });
	}

	subscribeEvent(service, event) {
		// Append event subscriptions
		let item = this.subscriptions.get(event.name);
		if (!item) {
			item = new BalancedList();
			this.subscriptions.set(event.name, item);
		}
		item.add(event);
		bus.on(event.name, event.handler.bind(service));
	}

	getService(serviceName) {
		let service = this.services.get(serviceName);
		if (service) {
			return service.get();
		}
	}

	hasService(serviceName) {
		return this.services.has(serviceName);
	}

	hasAction(actionName) {
		return this.actions.has(actionName);
	}

	call(actionName, params, parentCtx) {
		let actions = this.actions.get(actionName);
		if (!actions)
			throw new errors.ServiceNotFoundError(`Missing action '${actionName}'!`);

		let action = actions.get();
		/* istanbul ignore next */
		if (!action)
			throw new Error(`Missing action handler '${actionName}'!`);

		let service = action.service;
		// Create a new context
		let ctx;
		if (parentCtx)
			ctx = parentCtx.createSubContext(service, action, params);
		else
			ctx = new Context({ service, action, params });

		return action.handler(ctx);
	}

	emit(eventName, data) {
		if (this.transporter)
			this.transporter.emit(eventName, data);
		return this.emitLocal(eventName, data);
	}

	emitLocal(eventName, data) {
		return bus.emit(eventName, data);
	}

	getLocalActionList() {
		let res = [];
		for (let entry of this.actions.entries()) {
			if (entry[1].hasLocal())
				res.push(entry[0]);
		}
		return res;
	}
	/*
	publishActionList() {
		if (this.transporter) {
			this.transporter.publishActionList();
		}
	}*/
}

module.exports = ServiceBroker;<|endoftext|>


<commit_before>var _, Backbone, Data, AddDeviceValue;

_ =        require('underscore');
Backbone = require('backbone');
Data =     require('data');
Dict =     require('dict');

// AddDeviceValue = require('addDeviceValue.pl');

module.exports = Backbone.View.extend({

  el: "[data-view=\"dict\"]",

  initialize: function() {
    var model,
      _this = this;

    this.$worksheet =  this.$el.find('tbody');

    this.sid =         this.options.sid  || this.$el.data("dict-sid")  || '';
    this.type =        this.options.type || this.$el.data("dict-type") || '';
    this.limit =       50;
    this.step =        20;
    this.query =       '';
    this.keys =        {};
    this.vals =        {};

    this.dict =        new Dict(window[this.sid + '_data']);
    this.columns =     this.dict.get('columns');
    this.fields =      this.dict.get('fields');

    this.data = new Data();
    this.data.reset(this.dict.get('data'));

    this.selectRowUUID = this.dict.get('selectRowUUID') || this.getUUIDbyFirstRecord();

    this.colorActiveLine();

    this.vals = this.cleanVals();

    if (this.type === 'parent') {
      this.child = this.$el.data("dict-child");
      // console.log(this.conf);
    }

    if (this.type === 'child') {
      this.keys = this.dict.get('keys');
      this.vals = this.dict.get('vals');
    }

    this.on('update', function(vals) {
      if (_this.type === 'child') {
        _this.limit = 50;
        _this.vals = _this.cleanVals(vals);
        _this.$el.trigger('start.update');
        _this.sendRequest('update');
      }
    });

    this.on('clear', function() {
      if (_this.type === 'child') {
        _this.showInformationNotFound();
      }
    });

    this.on('search', function(query) {
      if (_this.type === 'parent') {
        _this.limit = 50;
        _this.query = query;
        _this.$el.trigger('start.search');
        _this.sendRequest('search');
      }
    });

    this.on('update.childs', function() {
      var _this = this,
        childs = _this.dict.get('childs'),
        line = _this.data.findWhere({'d$uuid': _this.selectRowUUID});
      // if ((_this.child != null) && (_this.data != null)) {
      //   if (window[_this.child] != null) {
      //     if (line != null) {
      //       window[_this.child].trigger('update', line.toJSON() || {});
      //     } else {
      //       window[_this.child].trigger('clear');
      //     }
      //   }
      // }
      if (_this.data !== null) {
        _.each(childs, function(child) {
          if (window[child.sid] !== null) {
            if (line != null) {
              window[child.sid].trigger('update', line.toJSON() || {});
            } else {
              window[child.sid].trigger('clear');
            }
          }
        });
      }
    });

    this.$el.on('scroll', function() {
      if (_this.$el.scrollTop() + _this.$el.height() === _this.$el.find('.container').height()) {
        _this.limit = _this.data.length + _this.step;
        _this.$el.trigger('start.scroll');
        _this.sendRequest('scroll');
      }
    });

    setTimeout(function() {
      if (_this.type === 'parent') {
        _this.sendRequest('update');
      }
    }, 1);

    this.$el.on('mouseover', function() {
      $(this).css({
        'cursor': 'pointer'
      });
    });

    this.$el.on('click', 'td', function() {
      var $tr = $(this).parent();
      _this.selectRowUUID = $tr.data('uuid');
      _this.colorActiveLine();
      _this.trigger('update.childs');
    });

    this.data.on('add', function(line) {
      _this.$worksheet.append(jade.templates.line_data({
        columns: _this.columns,
        fields:  _this.fields,
        line:    line.toJSON()
      }));
      _this.$el.trigger('add.line', line.toJSON());
    });

    this.data.on('remove', function(line) {
      _this.$worksheet.find("[data-uuid=\"" + line.get('d$uuid') + "\"]").remove();
      _this.$el.trigger('add.line', line.toJSON());
    });

    // if (this.sid == 'WEB$DEVICE_DATA') {
    //   window.addDeviceValue = new AddDeviceValue({
    //     el:  this.el,
    //     sid: this.sid
    //   });
    // }

  },

  setValsToLowerCase: function(ms) {
    var tmp = {};
    _.each(ms || {}, function(value, key) {
      tmp[key] = value.toLowerCase();
    });
    return tmp;
  },

  setKeysToLowerCase: function(ms) {
    var tmp = {};
    _.each(ms || {}, function(value, key) {
      tmp[key.toLowerCase()] = value;
    });
    return tmp;
  },

  cleanVals: function(new_vals) {
    var keys, vals,
      tmp = {};

    keys = this.keys || {};
    vals = this.vals || {};

    if ((new_vals != null) && (typeof new_vals === 'object')) {
      vals = _.extend({}, vals, new_vals);
    }

    keys =  this.setValsToLowerCase(keys);
    vals =  this.setKeysToLowerCase(vals);

    _.each(keys, function(value, key) {
      if (vals[value] != null) {
        if (typeof vals[value] === 'string') {
          tmp[value] = vals[value].trim();
        } else {
          tmp[value] = vals[value];
        }
      }
    });

    return tmp;
  },

  getUUIDbyFirstRecord: function() {
    return this.$worksheet.find('tr:first').data('uuid') || '';
  },

  colorActiveLine: function(classname) {

    if (classname == null) {
      classname = 'active';
    }

    this.$worksheet.find('tr').removeClass(classname);
    this.$activeLine = this.$worksheet.find("[data-uuid=\"" + this.selectRowUUID + "\"]");
    if (this.$activeLine != null) {
      this.$activeLine.addClass(classname);
    }
  },

  showInformationNotFound: function() {
    this.$worksheet.html(jade.templates.line_nothing({
      columns: this.columns || {}
    }));
  },

  hideInformationNotFound: function() {
    this.$worksheet.find("[data-type=\"nothing\"]").remove();
  },

  showErrorOnServer: function() {
    this.$worksheet.html(jade.templates.line_error({
      columns: this.columns || {}
    }));
  },

  hideErrorOnServer: function() {
    this.$worksheet.find("[data-type=\"error\"]").remove();
  },

  showLoading: function(type) {

    if (type == null) {
      type = 'before';
    }

    if (!this.$worksheet.find("[data-type=\"loading\"]").length) {
      switch (type) {
        case 'replace':
          this.$worksheet.html(jade.templates.line_loading({
            columns: this.columns || {}
          }));
        break;
        case 'after':
          this.$worksheet.append(jade.templates.line_loading({
            columns: this.columns || {}
          }));
        break;
        case 'before':
          this.$worksheet.prepend(jade.templates.line_loading({
            columns: this.columns || {}
          }));
        break;
      }
    }

  },

  hideLoading: function() {
    this.$worksheet.find("[data-type=\"loading\"]").remove();
  },

  sendRequest: function(type) {
    var _this = this;

    if (type == null) {
      type = 'scroll';
    }

    switch (type) {
      case 'update':
        this.$worksheet.empty();
        this.data.reset();
        this.showLoading();
      break;
      case 'search':
        this.$worksheet.empty();
        this.data.reset();
        this.showLoading();
      break;
      case 'scroll':
        this.showLoading('after');
      break;
    }

    this.$el.trigger('request:' + type);

    this.data.fetch({
      url:     '/api/dict/' + this.sid,
      timeout: 10000,
      data: {
        limit: this.limit  || null,
        query: this.query  || '',
        keys:  this.keys   || {},
        vals:  this.vals   || {}
      },
      success: function() {
        _this.hideLoading();
        _this.hideErrorOnServer();
        _this.hideInformationNotFound();
        _this.checkResponse(type);
      },
      error: function() {
        _this.hideLoading();
        _this.showErrorOnServer();
      }
    });
  },

  checkResponse: function(type) {

    if (type == null) {
      type = "scroll";
    }

    switch (type) {
      case 'update':
        this.selectRowUUID = this.getUUIDbyFirstRecord();
        this.colorActiveLine();
      break;
      case 'search':
        this.selectRowUUID = this.getUUIDbyFirstRecord();
        this.colorActiveLine();
        this.trigger('update.childs');
      break;
    }

    if (this.data.length < 1) {
      this.showInformationNotFound();
    }

    this.$el.trigger('response:' + type);

  }

});
<commit_msg>рефракторинг<commit_after>var _, Backbone, Data, AddDeviceValue, Gsender;

_ =        require('underscore');
Backbone = require('backbone');
Data =     require('data');
Dict =     require('dict');

// AddDeviceValue = require('addDeviceValue.pl');

Gsender = Backbone.View.extend({

  el: "[data-view=\"dict\"]",

  initialize: function() {
    var model,
      _this = this;

    this.$worksheet =  this.$el.find('tbody');

    this.sid =         this.options.sid  || this.$el.data("dict-sid")  || '';
    this.type =        this.options.type || this.$el.data("dict-type") || '';
    this.limit =       50;
    this.step =        20;
    this.query =       '';
    this.keys =        {};
    this.vals =        {};

    this.dict =        new Dict(window[this.sid + '_data']);
    this.columns =     this.dict.get('columns');
    this.fields =      this.dict.get('fields');

    this.data = new Data();
    this.data.reset(this.dict.get('data'));

    this.selectRowUUID = this.dict.get('selectRowUUID') || this.getUUIDbyFirstRecord();

    this.colorActiveLine();

    this.vals = this.cleanVals();

    if (this.type === 'parent') {
      this.child = this.$el.data("dict-child");
      // console.log(this.conf);
    }

    if (this.type === 'child') {
      this.keys = this.dict.get('keys');
      this.vals = this.dict.get('vals');
    }

    this.on('update', function(vals) {
      if (_this.type === 'child') {
        _this.limit = 50;
        _this.vals = _this.cleanVals(vals);
        _this.$el.trigger('start.update');
        _this.sendRequest('update');
      }
    });

    this.on('clear', function() {
      if (_this.type === 'child') {
        _this.showInformationNotFound();
      }
    });

    this.on('search', function(query) {
      if (_this.type === 'parent') {
        _this.limit = 50;
        _this.query = query;
        _this.$el.trigger('start.search');
        _this.sendRequest('search');
      }
    });

    this.on('update.childs', function() {
      var _this = this,
        childs = _this.dict.get('childs'),
        line = _this.data.findWhere({'d$uuid': _this.selectRowUUID});
      if (_this.data !== null) {
        _.each(childs, function(child) {
          if (window[child.sid] !== null) {
            if (line != null) {
              window[child.sid].trigger('update', line.toJSON() || {});
            } else {
              window[child.sid].trigger('clear');
            }
          }
        });
      }
    });

    this.$el.on('scroll', function() {
      if (_this.$el.scrollTop() + _this.$el.height() === _this.$el.find('.container').height()) {
        _this.limit = _this.data.length + _this.step;
        _this.$el.trigger('start.scroll');
        _this.sendRequest('scroll');
      }
    });

    setTimeout(function() {
      if (_this.type === 'parent') {
        _this.sendRequest('update');
      }
    }, 1);

    this.$el.on('mouseover', function() {
      $(this).css({
        'cursor': 'pointer'
      });
    });

    this.$el.on('click', 'td', function() {
      var $tr = $(this).parent();
      _this.selectRowUUID = $tr.data('uuid');
      _this.colorActiveLine();
      _this.trigger('update.childs');
    });

    this.data.on('add', function(line) {
      _this.$worksheet.append(jade.templates.line_data({
        columns: _this.columns,
        fields:  _this.fields,
        line:    line.toJSON()
      }));
      _this.$el.trigger('add.line', line.toJSON());
    });

    this.data.on('remove', function(line) {
      _this.$worksheet.find("[data-uuid=\"" + line.get('d$uuid') + "\"]").remove();
      _this.$el.trigger('add.line', line.toJSON());
    });

    // if (this.sid == 'WEB$DEVICE_DATA') {
    //   window.addDeviceValue = new AddDeviceValue({
    //     el:  this.el,
    //     sid: this.sid
    //   });
    // }

  }

});

Gsender.prototype.setValsToLowerCase = function(ms) {
  var tmp = {};
  _.each(ms || {}, function(value, key) {
    tmp[key] = value.toLowerCase();
  });
  return tmp;
};

Gsender.prototype.setKeysToLowerCase = function(ms) {
  var tmp = {};
  _.each(ms || {}, function(value, key) {
    tmp[key.toLowerCase()] = value;
  });
  return tmp;
};

Gsender.prototype.cleanVals = function(new_vals) {
  var keys, vals,
    tmp = {};

  keys = this.keys || {};
  vals = this.vals || {};

  if ((new_vals != null) && (typeof new_vals === 'object')) {
    vals = _.extend({}, vals, new_vals);
  }

  keys =  this.setValsToLowerCase(keys);
  vals =  this.setKeysToLowerCase(vals);

  _.each(keys, function(value, key) {
    if (vals[value] != null) {
      if (typeof vals[value] === 'string') {
        tmp[value] = vals[value].trim();
      } else {
        tmp[value] = vals[value];
      }
    }
  });

  return tmp;
};

Gsender.prototype.getUUIDbyFirstRecord = function() {
  return this.$worksheet.find('tr:first').data('uuid') || '';
};

Gsender.prototype.colorActiveLine = function(classname) {

  if (classname == null) {
    classname = 'active';
  }

  this.$worksheet.find('tr').removeClass(classname);
  this.$activeLine = this.$worksheet.find("[data-uuid=\"" + this.selectRowUUID + "\"]");
  if (this.$activeLine != null) {
    this.$activeLine.addClass(classname);
  }
};

Gsender.prototype.showInformationNotFound = function() {
  this.$worksheet.html(jade.templates.line_nothing({
    columns: this.columns || {}
  }));
};

Gsender.prototype.hideInformationNotFound = function() {
  this.$worksheet.find("[data-type=\"nothing\"]").remove();
};

Gsender.prototype.showErrorOnServer = function() {
  this.$worksheet.html(jade.templates.line_error({
    columns: this.columns || {}
  }));
};

Gsender.prototype.hideErrorOnServer = function() {
  this.$worksheet.find("[data-type=\"error\"]").remove();
};

Gsender.prototype.showLoading = function(type) {

  if (type == null) {
    type = 'before';
  }

  if (!this.$worksheet.find("[data-type=\"loading\"]").length) {
    switch (type) {
      case 'replace':
        this.$worksheet.html(jade.templates.line_loading({
          columns: this.columns || {}
        }));
      break;
      case 'after':
        this.$worksheet.append(jade.templates.line_loading({
          columns: this.columns || {}
        }));
      break;
      case 'before':
        this.$worksheet.prepend(jade.templates.line_loading({
          columns: this.columns || {}
        }));
      break;
    }
  }

};

Gsender.prototype.hideLoading = function() {
  this.$worksheet.find("[data-type=\"loading\"]").remove();
};

Gsender.prototype.sendRequest = function(type) {
  var _this = this;

  if (type == null) {
    type = 'scroll';
  }

  switch (type) {
    case 'update':
      this.$worksheet.empty();
      this.data.reset();
      this.showLoading();
    break;
    case 'search':
      this.$worksheet.empty();
      this.data.reset();
      this.showLoading();
    break;
    case 'scroll':
      this.showLoading('after');
    break;
  }

  this.$el.trigger('request:' + type);

  this.data.fetch({
    url:     '/api/dict/' + this.sid,
    timeout: 10000,
    data: {
      limit: this.limit  || null,
      query: this.query  || '',
      keys:  this.keys   || {},
      vals:  this.vals   || {}
    },
    success: function() {
      _this.hideLoading();
      _this.hideErrorOnServer();
      _this.hideInformationNotFound();
      _this.checkResponse(type);
    },
    error: function() {
      _this.hideLoading();
      _this.showErrorOnServer();
    }
  });
};

Gsender.prototype.checkResponse = function(type) {

  if (type == null) {
    type = "scroll";
  }

  switch (type) {
    case 'update':
      this.selectRowUUID = this.getUUIDbyFirstRecord();
      this.colorActiveLine();
    break;
    case 'search':
      this.selectRowUUID = this.getUUIDbyFirstRecord();
      this.colorActiveLine();
      this.trigger('update.childs');
    break;
  }

  if (this.data.length < 1) {
    this.showInformationNotFound();
  }

  this.$el.trigger('response:' + type);
};

module.exports = Gsender;
<|endoftext|>