<commit_before>angular.module('uniben' , ['ui.router' ,'mgcrea.ngStrap'])

//state configuration and routing setup
.config([
    '$stateProvider' , '$urlRouterProvider'  , '$locationProvider',
    function($stateProvider , $urlRouterProvider  , $locationProvider){
          //enabling HTML5 mode
          $locationProvider.html5Mode(false).hashPrefix('!');

            //Logged in state
            $stateProvider

             .state('home' , {
                 url : '/home',
                 templateUrl : 'views/in.home.tpl.html',
                 controller : 'homeController',
                 data :{}

             });

             $urlRouterProvider.otherwise('/home');
        }
])

// cors configurations to enable consuming the rest api
.config([
    '$httpProvider' ,
    function($httpProvider){
       $httpProvider.defaults.useXDomain = true;
       $httpProvider.defaults.withCredentials = true;
       delete $httpProvider.defaults.headers.common['X-Requested-With'];
    }
])

.filter("myfilter", function ($filter) {
  return function (data, activeCategory, activeState) {
      //console.log('category:'+activeCategory+' activeState:'+activeState);
      var filtered = [];

      angular.forEach(data , function(item){
          var stateTest = item.status == activeState || activeState == '';
          var categoryTest = false;

          //Test for category
          if(activeState == 'Idle' || activeState == 'Dormant'){
              var categoryTest = true;
          }
          else{
              if(angular.isDefined(item.urlObj.selector)){
                   categoryTest = item.urlObj.selector==activeCategory || activeCategory == '';
              }
          }

          if(stateTest && categoryTest){
               filtered.push(item);
          }
      });
      return filtered;
  }
})

//======================================================FACTORY STARTS HERE
.factory('Urlservice' , function($q , $http){

       //
       function addUrl(UrlObj){
           var promise = $q.defer();

           //
           $http({
               method:'POST',
               url:'/api/urls/1',
               params:UrlObj
           })
           .success(function(data){
               promise.resolve(data);
           })
           .error(function(err){
               promise.reject(err);
           });

           return promise.promise;
       }

        //
       function updateUrl(O , token){
           var promise = $q.defer();

           //
           if(token.length<5){
              promise.reject('token not defined');
           }
           else{

             var o = angular.copy(O);
             console.log(o);

             //
             $http({
                 method:'PUT',
                 url:'/api/urls/'+token,
                 params:o
             })
             .success(function(status){
                 promise.resolve(status);
             })
             .error(function(err){
                 promise.reject(err);
             });

           }

           return promise.promise;
       }

        //
       function removeUrl(UrlObj , token){
           var promise = $q.defer();
           //
           if(!angular.isDefined(token)){
              promise.reject('token not defined');
           }
           else{

             $http({
                 method:'DELETE',
                 url:'/api/urls/'+UrlObj._id ,
                 params:{token:token}
             })
             .success(function(status){
                 promise.resolve(status);
             })
             .error(function(err){
                 promise.reject(err);
             });

           }
           return promise.promise;
       }

       //
       function getAll(){
            var promise = $q.defer();

            $http({
                method:'GET',
                url:'/api/urls/all',
            })
            .success(function(data){
               promise.resolve(data);
            })
            .error(function(err){
               promise.reject(err);
            });;

            return promise.promise;

       }

       //
       var domains = [
          'localhost:5003',
          'ghostip.herokuapp.com' ,
          'ghostip1.herokuapp.com',
          'ghostip2.herokuapp.com',
          'ghostip3.herokuapp.com',
          'ghostip4.herokuapp.com',
          'ghostip5.herokuapp.com',
          'ghostip6.herokuapp.com',
          'ghostip7.herokuapp.com',
          'ghostip8.herokuapp.com',
          'ghostip9.herokuapp.com',
          'ghostip10.herokuapp.com'
       ];

       function populateDomainMap(urlMapList){
             var domainMapArr = [];
             var promise = $q.defer();
             var counter = 0;

             console.log(urlMapList);

             function checkExit(){
                  if(counter == domains.length-1){
                      return aggregateNonAllocated();
                  }
                  else{
                      counter++;
                      doQuery(domains[counter]);
                  }
             }

             function doQuery(domain){
                    $http({
                         method:'GET',
                         url:'http://'+domain+'/stats'
                    })
                    .success(function(data){
                         if(angular.isDefined(data.urlObj.url)){
                             domainMapArr.push({
                                domain:domain,
                                stats:data.statsObj,
                                urlObj:data.urlObj,
                                status:'Active'     //process is actively handling a url
                              });

                             //remove the confirmed domain from the urlMapList
                             console.log(data.urlObj.url);
                             urlMapList[data.urlObj.url].splice(0 , 1);

                         }
                         else{
                             domainMapArr.push({
                                domain:domain,
                                stats:data.statsObj,
                                urlObj:data.urlObj,
                                status:'Idle'    //Process is waiting for a non occupied url
                             });
                         }

                         //
                         checkExit();

                    })
                    .error(function(err){
                         domainMapArr.push({
                            domain:domain ,
                            stats:{} ,
                            urlObj:{},
                            status:'Dormant'   //Process is offline due to error or change of protocol
                         });
                         checkExit();
                    });
             }
             //start the query process
             doQuery(domains[counter]);

             //This functions filters out UrlOBjects that are curently  not allocated to a process
             function aggregateNonAllocated() {
                  console.log('computing non allocated urls');
                  angular.forEach(Object.keys(urlMapList) , function(key){
                       if(urlMapList[key].length>0){
                           angular.forEach(urlMapList[key] , function(UMLObj){
                                  domainMapArr.push({
                                      domain:"no server",
                                      stats:{},
                                      urlObj:UMLObj,
                                      status:'Non Allocated'    //url not being processed at the moment
                                   });
                           });
                       }

                  });

                  //
                  promise.resolve(domainMapArr);
             }

             return promise.promise;
       }

       return {
           addUrl:addUrl,
           updateUrl:updateUrl,
           removeUrl:removeUrl,
           getAll:getAll,
           populateDomainMap:populateDomainMap
       };
})
//======================================================FACTORY ENDS HERE

//Controller controlling the logic of  the appication
.controller ('homeController' , function($rootScope , $scope , $timeout  , $http, Urlservice){

    //
    function startApp(){
      Urlservice.getAll().then(function(data){
           $scope.domainDone = false;
           $scope.Urls = data;
           computeCategories();

          //
          computeUrlMapList();

      } , function(err){
           alert(err);
      });
    }

    startApp();
   /////////////////////////////
    //
    function computeUrlMapList(){
         var urlMapList = {};
         console.log($scope.Urls.length);
         angular.forEach($scope.Urls , function(urlObj){
              if(angular.isArray(urlMapList[urlObj.url])){
                 urlMapList[urlObj.url].push(urlObj);
              }
              else {
                urlMapList[urlObj.url] = [];
                urlMapList[urlObj.url].push(urlObj);
              }

         });

         Urlservice.populateDomainMap(urlMapList).then(function(domainMapArr){
             $scope.domainMapArr = domainMapArr;
             console.log(domainMapArr);
             $scope.domainDone = true;
         });
    }

     //Functions to add a new url
     $scope.newUrl = {
         token:'',
         url:'http://www.yoururl.com',
         domain:'Server',
         selector:'none',
         account:'account email',
         username:'account name',
         dateCreated:'',
         lastVisited:''
     } //

     //
      $scope.addUrl = function(){
         $scope.processingNew = true;
         Urlservice.addUrl($scope.newUrl).then(function(data){
             $scope.processingNew = false;
             startApp();
         } , function(err){
            $scope.processingNew = false;
            alert(err);
         });
     };

     //
     $scope.saveUrl = function(urlObj){

         $scope.processing= true;
         urlObj.url = $scope.editorObj.url;
         urlObj.selector = $scope.editorObj.selector;
         Urlservice.updateUrl(urlObj , $scope.newUrl.token).then(function(status){
              $scope.processing = false;
              $scope.resetEditorSettings(-1);
              $scope.editorObj = {};
              startApp();
         },
         function(err){
              $scope.processing = false;
              console.log(err);
         });
     };

     //
     $scope.deleteUrl = function(domainMap){
         $scope.processingDel = true;
         Urlservice.removeUrl(domainMap , $scope.newUrl.token).then(function(status){
            $scope.processingDel = false;
            startApp();

         } , function(err){
            alert(err);
            $scope.processingDel = false;

         });
     }

     //
     $scope.editorIndex = -1;
     $scope.editorObj = {url:'' , selector:''}

     $scope.resetEditorSettings = function(index , url , selector){
         $scope.editorObj.url = url;
         $scope.editorObj.selector = selector
         $scope.editorIndex = index;
     };

     function computeCategories(){
         //
         console.log($scope.Urls);
         $scope.categories = ['All'];
         angular.forEach($scope.Urls , function(url){
             if($scope.categories.indexOf(url.selector)<0){
                 $scope.categories.push(url.selector);
             }
         });
     }

     $scope.activeCategory = '';
     $scope.setCategory = function(category){
         category=category=='All'?'':category;
         $scope.activeCategory = category;
     };

     //
     $scope.states = ['All' , 'Active' , 'Idle' , 'Dormant' , 'Non Allocated'];
     $scope.activeState = '';
     $scope.setState = function(state){
         state=state=='All'?'':state;
         $scope.activeState = state;
     };

     //
     $scope.activeHover = -1;
     //Scroll spy
     $scope.fixed = false;

     $rootScope.$on('my:fixed' , function(e, a){
          $timeout(function(){
              $scope.fixed = true;
          });

     });

      $rootScope.$on('my:unfixed' , function(e, a){
          $timeout(function(){
              $scope.fixed = false;
          });
     });
});<commit_msg>Signed-off-by: codemuhammed <codemuhammed@gmail.com><commit_after>angular.module('uniben' , ['ui.router' ,'mgcrea.ngStrap'])

//state configuration and routing setup
.config([
    '$stateProvider' , '$urlRouterProvider'  , '$locationProvider',
    function($stateProvider , $urlRouterProvider  , $locationProvider){
          //enabling HTML5 mode
          $locationProvider.html5Mode(false).hashPrefix('!');

            //Logged in state
            $stateProvider

             .state('home' , {
                 url : '/home',
                 templateUrl : 'views/in.home.tpl.html',
                 controller : 'homeController',
                 data :{}

             });

             $urlRouterProvider.otherwise('/home');
        }
])

// cors configurations to enable consuming the rest api
.config([
    '$httpProvider' ,
    function($httpProvider){
       $httpProvider.defaults.useXDomain = true;
       $httpProvider.defaults.withCredentials = true;
       delete $httpProvider.defaults.headers.common['X-Requested-With'];
    }
])

.filter("myfilter", function ($filter) {
  return function (data, activeCategory, activeState) {
      //console.log('category:'+activeCategory+' activeState:'+activeState);
      var filtered = [];

      angular.forEach(data , function(item){
          var stateTest = item.status == activeState || activeState == '';
          var categoryTest = false;

          //Test for category
          if(activeState == 'Idle' || activeState == 'Dormant'){
              var categoryTest = true;
          }
          else{
              if(angular.isDefined(item.urlObj.selector)){
                   categoryTest = item.urlObj.selector==activeCategory || activeCategory == '';
              }
          }

          if(stateTest && categoryTest){
               filtered.push(item);
          }
      });
      return filtered;
  }
})

//======================================================FACTORY STARTS HERE
.factory('Urlservice' , function($q , $http){

       //
       function addUrl(UrlObj){
           var promise = $q.defer();

           //
           $http({
               method:'POST',
               url:'/api/urls/1',
               params:UrlObj
           })
           .success(function(data){
               promise.resolve(data);
           })
           .error(function(err){
               promise.reject(err);
           });

           return promise.promise;
       }

        //
       function updateUrl(O , token){
           var promise = $q.defer();

           //
           if(token.length<5){
              promise.reject('token not defined');
           }
           else{

             var o = angular.copy(O);
             console.log(o);

             //
             $http({
                 method:'PUT',
                 url:'/api/urls/'+token,
                 params:o
             })
             .success(function(status){
                 promise.resolve(status);
             })
             .error(function(err){
                 promise.reject(err);
             });

           }

           return promise.promise;
       }

        //
       function removeUrl(domainMap , token){
           var promise = $q.defer();
           //
           if(!angular.isDefined(token)){
              promise.reject('token not defined');
           }
           else{

             $http({
                 method:'DELETE',
                 url:domainMap.domain+'/api/urls/'+domainMap.UrlObj._id ,
                 params:{token:token}
             })
             .success(function(status){
                 promise.resolve(status);
             })
             .error(function(err){
                 promise.reject(err);
             });

           }
           return promise.promise;
       }

       //
       function getAll(){
            var promise = $q.defer();

            $http({
                method:'GET',
                url:'/api/urls/all',
            })
            .success(function(data){
               promise.resolve(data);
            })
            .error(function(err){
               promise.reject(err);
            });;

            return promise.promise;

       }

       //
       var domains = [
          'localhost:5003',
          'ghostip.herokuapp.com' ,
          'ghostip1.herokuapp.com',
          'ghostip2.herokuapp.com',
          'ghostip3.herokuapp.com',
          'ghostip4.herokuapp.com',
          'ghostip5.herokuapp.com',
          'ghostip6.herokuapp.com',
          'ghostip7.herokuapp.com',
          'ghostip8.herokuapp.com',
          'ghostip9.herokuapp.com',
          'ghostip10.herokuapp.com'
       ];

       function populateDomainMap(urlMapList){
             var domainMapArr = [];
             var promise = $q.defer();
             var counter = 0;

             console.log(urlMapList);

             function checkExit(){
                  if(counter == domains.length-1){
                      return aggregateNonAllocated();
                  }
                  else{
                      counter++;
                      doQuery(domains[counter]);
                  }
             }

             function doQuery(domain){
                    $http({
                         method:'GET',
                         url:'http://'+domain+'/stats'
                    })
                    .success(function(data){
                         if(angular.isDefined(data.urlObj.url)){
                             domainMapArr.push({
                                domain:domain,
                                stats:data.statsObj,
                                urlObj:data.urlObj,
                                status:'Active'     //process is actively handling a url
                              });

                             //remove the confirmed domain from the urlMapList
                             console.log(data.urlObj.url);
                             urlMapList[data.urlObj.url].splice(0 , 1);

                         }
                         else{
                             domainMapArr.push({
                                domain:domain,
                                stats:data.statsObj,
                                urlObj:data.urlObj,
                                status:'Idle'    //Process is waiting for a non occupied url
                             });
                         }

                         //
                         checkExit();

                    })
                    .error(function(err){
                         domainMapArr.push({
                            domain:domain ,
                            stats:{} ,
                            urlObj:{},
                            status:'Dormant'   //Process is offline due to error or change of protocol
                         });
                         checkExit();
                    });
             }
             //start the query process
             doQuery(domains[counter]);

             //This functions filters out UrlOBjects that are curently  not allocated to a process
             function aggregateNonAllocated() {
                  console.log('computing non allocated urls');
                  angular.forEach(Object.keys(urlMapList) , function(key){
                       if(urlMapList[key].length>0){
                           angular.forEach(urlMapList[key] , function(UMLObj){
                                  domainMapArr.push({
                                      domain:"no server",
                                      stats:{},
                                      urlObj:UMLObj,
                                      status:'Non Allocated'    //url not being processed at the moment
                                   });
                           });
                       }

                  });

                  //
                  promise.resolve(domainMapArr);
             }

             return promise.promise;
       }

       return {
           addUrl:addUrl,
           updateUrl:updateUrl,
           removeUrl:removeUrl,
           getAll:getAll,
           populateDomainMap:populateDomainMap
       };
})
//======================================================FACTORY ENDS HERE

//Controller controlling the logic of  the appication
.controller ('homeController' , function($rootScope , $scope , $timeout  , $http, Urlservice){

    //
    function startApp(){
      Urlservice.getAll().then(function(data){
           $scope.domainDone = false;
           $scope.Urls = data;
           computeCategories();

          //
          computeUrlMapList();

      } , function(err){
           alert(err);
      });
    }

    startApp();
   /////////////////////////////
    //
    function computeUrlMapList(){
         var urlMapList = {};
         console.log($scope.Urls.length);
         angular.forEach($scope.Urls , function(urlObj){
              if(angular.isArray(urlMapList[urlObj.url])){
                 urlMapList[urlObj.url].push(urlObj);
              }
              else {
                urlMapList[urlObj.url] = [];
                urlMapList[urlObj.url].push(urlObj);
              }

         });

         Urlservice.populateDomainMap(urlMapList).then(function(domainMapArr){
             $scope.domainMapArr = domainMapArr;
             console.log(domainMapArr);
             $scope.domainDone = true;
         });
    }

     //Functions to add a new url
     $scope.newUrl = {
         token:'',
         url:'http://www.yoururl.com',
         domain:'Server',
         selector:'none',
         account:'account email',
         username:'account name',
         dateCreated:'',
         lastVisited:''
     } //

     //
      $scope.addUrl = function(){
         $scope.processingNew = true;
         Urlservice.addUrl($scope.newUrl).then(function(data){
             $scope.processingNew = false;
             startApp();
         } , function(err){
            $scope.processingNew = false;
            alert(err);
         });
     };

     //
     $scope.saveUrl = function(urlObj){

         $scope.processing= true;
         urlObj.url = $scope.editorObj.url;
         urlObj.selector = $scope.editorObj.selector;
         Urlservice.updateUrl(urlObj , $scope.newUrl.token).then(function(status){
              $scope.processing = false;
              $scope.resetEditorSettings(-1);
              $scope.editorObj = {};
              startApp();
         },
         function(err){
              $scope.processing = false;
              console.log(err);
         });
     };

     //
     $scope.deleteUrl = function(domainMap){
         $scope.processingDel = true;
         Urlservice.removeUrl(domainMap , $scope.newUrl.token).then(function(status){
            $scope.processingDel = false;
            startApp();

         } , function(err){
            alert(err);
            $scope.processingDel = false;

         });
     }

     //
     $scope.editorIndex = -1;
     $scope.editorObj = {url:'' , selector:''}

     $scope.resetEditorSettings = function(index , url , selector){
         $scope.editorObj.url = url;
         $scope.editorObj.selector = selector
         $scope.editorIndex = index;
     };

     function computeCategories(){
         //
         console.log($scope.Urls);
         $scope.categories = ['All'];
         angular.forEach($scope.Urls , function(url){
             if($scope.categories.indexOf(url.selector)<0){
                 $scope.categories.push(url.selector);
             }
         });
     }

     $scope.activeCategory = '';
     $scope.setCategory = function(category){
         category=category=='All'?'':category;
         $scope.activeCategory = category;
     };

     //
     $scope.states = ['All' , 'Active' , 'Idle' , 'Dormant' , 'Non Allocated'];
     $scope.activeState = '';
     $scope.setState = function(state){
         state=state=='All'?'':state;
         $scope.activeState = state;
     };

     //
     $scope.activeHover = -1;
     //Scroll spy
     $scope.fixed = false;

     $rootScope.$on('my:fixed' , function(e, a){
          $timeout(function(){
              $scope.fixed = true;
          });

     });

      $rootScope.$on('my:unfixed' , function(e, a){
          $timeout(function(){
              $scope.fixed = false;
          });
     });
});<|endoftext|>


<commit_before>var math=mathjs();

var parse_helper={};

var env = {
	'currentTab': 0,
	'tabs': [
				{
				'name': 'tab0',
				'code': '',
				}
		],

	'vars': {
		'e': {
			'type': "scalar",
			'val': math.e,
			},
		'pi': {
			'type': 'scalar',
			'val': math.pi,
			},
		'i': {
			'type': 'scalar',
			'val': math.i,
			},
		'inf': {
			'type': 'scalar',
			'val': math.Infinity,
			},
		'userfunc': {
			'type': 'function',
			'val': '[x=[1,2,3,4], y=[4,3,2,1], plot(x,y,\'.\')]',
			'varin': ['arg1', 'arg2'],
			'varout': ['x', 'y'],
			},
		},
	'runtime': {
		'code': [],
		'linenum': 0,
		},
	};

	stack = [
			/*{
				'x': {
				'type': 'scalar',
				'val': '[1,2,3,4]',
				},
			},*/
			];

function attachFunc(split_line){
	if (split_line[1]=="[") { //Function with defined outputs
		endArgs=next_semantic_block(split_line, "[")[1];
		console.log("1");
		var func=split_line[endArgs];
		env.vars[func]={{'val':[]}};
		for (var line = env.runtime.linenum+1; line<env.runtime.code.length; line++){
			token_line=tokenize(env.runtime.code[line],all_tokens);
			console.log(token_line[0]);
			if (token_line[0]=="end"){
			console.log("3");
				env.runtime.linenum=line+1;
				break;
			}
			else{
			console.log("4");
				env.vars[func].val.push(env.runtime.code[line]);
			}
		}
		var outVar=[];
		for (var i = 2; i<endArgs; i++){
			if(isBareword(split_line[i])){
				outVar.push(split_line[i]);
			}
			else if(split_line[i]==','){
				continue;
			}
			else return "That ain't valid! Arg: " + split_line[i];
		}
		endInArgs=next_semantic_block(split_line, endArgs)[1];
		var inVar=[];
		for (var i = endArgs; i<endInArgs; i++){
			if(isBareword(split_line[i])){
				inVar.push(split_line[i]);
			}
			else if(split_line[i]==','){
				continue;
			}
			else return "That ain't valid! Arg: " + split_line[i];
		}
		math[func]=evalUserFunc(func, args);
		env.vars[func].varin=inVar;
		env.vars[func].varout=outVar;
	}
}

function evalUserFunc(func, args){
		enterScope();
			args = Array.prototype.slice.call(arguments, 1);
			for (var vin in env.vars[func].varin){
				setvar(varin[vin], args[vin]);
			}
			for (var line in env.vars[func].val) {
				exec_statement(env.vars[func].val[line]);
			}
			var myRetArgs=env.vars[func].varout;
			for (var i in myRetArgs){
				myRetArgs[i]=getvar(myRetArgs[i]); //Populate return vars from current stack frame
			}
		exitScope();
		return myRetArgs;
}

function exitScope(){
	popvars=stack.pop();
	for (var v in popvars){
		if (getvar(v)!=null){
			math[v]=getvar(v).val;
		}
		else math[v]=undefined;
	}
}

function enterScope(){
	stack.push({});
}

function getvar(varname){
	for(var i=stack.length-1; i>=0; i--){
		if (stack[i][varname]!=null){
			return stack[i][varname];
		}
	}
	return env.vars[varname];
}

function setvar(varname, val){
	if(stack.length>0){
		stack[stack.length-1][varname]=val;
	}
	else env.vars[varname]=val;
}

function load_locals(){
	for (var localvar in env.vars){
		try{
		if(env.vars[localvar].val.hasOwnProperty('_data')){
			var m = math.matrix(env.vars[localvar].val._data);
			env.vars[localvar].val = m;
		}} catch(e){}
		math[localvar]=env.vars[localvar].val;
	}
}

function isBareword( word ){
	if(word.match(/^[a-zA-Z]\w*$/)) return true; else return false;
}

function isScalar( word ){
	if(word.match(/^(\w|[\.\+\-\/\*\(\)])*$/)) return true; else return false;
}

function flatten(array) {
  var result = [], self = arguments.callee;
  array.forEach(function(item) {
    Array.prototype.push.apply(
      result,
      Array.isArray(item) ? self(item) : [item]
    );
  });
  return result;
};

function next_semantic_block( obj, index ){
	//Returns the start and end index of the next semantic block [start,end]
	var start_ind;
	var blocked='';
	var depth=0;
	for(var i=index; i<obj.length; i++){
		if(blocked){
			switch(blocked)
			{
				case '[':
					if(obj[i]==']') if(--depth==0) return [start_ind, i+1];
					break;
				case '(':
					if(obj[i]==')') if(--depth==0) return [start_ind, i+1];
					break;
				case '{':
					if(obj[i]=='}') if(--depth==0) return [start_ind, i+1];
					break;
			}
		}
		else if (isBareword(obj[i])) return [i,i+1];
		//Check for blocking every pass and dive in!
		if (obj[i]=='['){ blocked='['; if(depth++==0) start_ind=i;}
		else if(obj[i]=='('){ blocked='('; if(depth++==0) start_ind=i;}
		else if(obj[i]=='{'){ blocked='{'; if(depth++==0) start_ind=i;}

	}
	return false;
}

function has_semantic_block( obj, type, index){//type can be (, [, {
	var n;
	for(var i=index; i<obj.length;){
		n=next_semantic_block(obj,i);
		if(n){
			if(obj[n[0]] == type){
				return n[0];
			}
			else i=n[1];
		}
		else i++;
	}
	return false;
}

var binary_ops = ['+', '-', '*', '/', '^', '&', '|', '&&', '||'];
var comparison_ops = ['>','<'];
var specials = [',', '=', ';', '~', ' '];
var blockers = ['[', ']', '(', ')', '{', '}'];

var all_tokens = binary_ops;
all_tokens.push(comparison_ops);
all_tokens.push(specials);
all_tokens.push(blockers);
all_tokens = flatten(all_tokens);

function preparse( str ){
	var i=0;
	var saved=0;
	var escaped_index;
	var parsed_str=str;
	var escaped='f';
	while (i<parsed_str.length){
		if (escaped=='f'){
			if(parsed_str[i]=='"'){
				escaped='"';
				escaped_index=i;
			}
			else if(parsed_str[i]=="'"){
				escaped="'";
				escaped_index=i;
			}
			else if(parsed_str[i]=='%'){
				parsed_str=parsed_str.slice(0,i);
				break;
			}
			i++;
		}
		else if(parsed_str[i]==escaped && parsed_str[i-1]!='\\'){
			parse_helper['%'+saved+'%']=parsed_str.slice(escaped_index,i+1);
			parsed_str=parsed_str.slice(0,escaped_index)+"%"+saved+"%"+parsed_str.slice(i+1,parsed_str.length);
			i=escaped_index+("%"+saved+"%").length;
			saved++;
			escaped='f';
		}
		else i++;
		}
	return parsed_str;
}

function postparse( str ){
	return str.replace(/%(\w)%/g,function(a,b){return parse_helper['%'+b+'%'];});
	}

function tokenize_str( str, token ){
	var sarr=[];
	var spl=String(str).split(token);
	for (var i=0; i<spl.length-1; i++){
		if (spl[i]!='')
		sarr.push(spl[i]);
		if(token!=' ')
		sarr.push(token);
	}
	sarr.push(spl[spl.length-1]);
	return sarr;
}

function tokenize( line, tokens ){
	var arr=tokenize_str(line, tokens[0]);
	var tmparr;
	for (var t=1; t<tokens.length; t++){
		tmparr=flatten(arr);
		arr=[];
		for (var str in tmparr){
			arr.push(tokenize_str( tmparr[str], tokens[t] ));
		}
	}
	return flatten(arr);
}

function structure_array(split_index){
	//This creates a semantic block array
	range=next_semantic_block(split_index, has_semantic_block(split_index,'[',0));
	var top=range[1]-2;
	for (var i = range[0]+1; i<top; i++){
		if (isScalar(split_index[i]) && isScalar(split_index[i+1])){
			split_index.splice(i+1,0,',');
			i++; top++;
		}
	}
	return split_index;
}

function merge_to_array(split_array){
	//Merges comma separated syntactic list into a js array
	return split_array.join('').split(',');
}

function exec_statement( line ){
	try{
		parsed_line=preparse(line);
		split_line = tokenize(parsed_line, all_tokens);

		for(var i in split_line){
			split_line[i]=postparse(split_line[i]);
		}
		if(split_line[0]=="for"){

		}

		//User defined functions
		else if(split_line[0]=="function"){
			console.log("Found a function");
			attachFunc(split_line);

		}

		//Temporary plotting function for demo
		else if(split_line[0]=="plot"){
			$('#chart-modal').modal('toggle');
			var i=1;
			var data={};
			var type='line';
			for(;i<split_line.length; i++){
				if (split_line[i]=='(') break;
			}
			for(;i<split_line.length; i++){
				if (isBareword(split_line[i])){
					data['x']=math[split_line[i]]._data;
					i++;
					break;}
			}
			for(;i<split_line.length; i++){
				if(isBareword(split_line[i])){
				data['y']=math[split_line[i]]._data;
					break;}
			}
			for(;i<split_line.length; i++){
				if(typeof split_line[i] == 'string'){
					if (split_line[i]=='.') type='scatter';
				}
			}
			if(data['x'].hasOwnProperty('_data')){
				data['x'] = data['x']._data;
				}
			if(data['y'].hasOwnProperty('_data')){
				data['y'] = data['y']._data;
				console.log("I did something");
				}
			console.log(data);
			d3_plot(data,type);
		}
		else if(split_line[0]=="plot"){
			args = next_semantic_block(split_line, has_semantic_block(split_line, '(', 0));
			datas=[]; styles=[];
			data_num=0;
			for( var i=args[0]; i<args[1]-1; i++){
				if (datas[0]){
					if (datas['x']){
						if(datas['y']){}}}}
			chart = d3_plot(data,style);
			setTimeout(10000, chart.update());
		}

		else if (split_line.indexOf('=')>0 && split_line[split_line.indexOf('=')+1]!='=' && split_line[split_line.indexOf('=')-1]!='<' && split_line[split_line.indexOf('=')-1]!='>' && split_line[split_line.indexOf('=')-1]!='~'){
			//Yay! We've found an assignment!
			if( 1==1 ){
			varname=split_line.slice(0,split_line.indexOf('=')).join('');
			tmpvar={};
			expr=split_line.slice(split_line.indexOf('=')+1);
			if(has_semantic_block(split_line,'[',0)){
				expr=structure_array(expr);
			}
			tmpvar['val'] = eval_expr( expr.join('') );
			tmpvar['type']='scalar';
			setvar(varname,tmpvar);
			math[varname]=tmpvar.val;
			return getvar(varname)['val'];
			}
			//else if( /*obj_prop*/ ){

			//}
			//else if( /*matrix*/ ){

			//}

		}
		return eval_expr(line);

	}
	catch(err){
	return err;
	}
	//math.eval(line);
}

function eval_expr( expr ){
	try{
		return math.eval(expr);
	}
	catch(err){ return expr };
}

function set_tab(tab){
	env.currentTab=tab;
}

function run_file(tab){//tab is an int
	mycode=env.tabs[env.currentTab].code;
	env.runtime.code=mycode.split('\n');
	env.runtime.linenum=0;
	for (; env.runtime.linenum<env.runtime.code.length; env.runtime.linenum++){
		exec_statement(env.runtime.code[env.runtime.linenum]);
	}
}<commit_msg>debugging logs<commit_after>var math=mathjs();

var parse_helper={};

var env = {
	'currentTab': 0,
	'tabs': [
				{
				'name': 'tab0',
				'code': '',
				}
		],

	'vars': {
		'e': {
			'type': "scalar",
			'val': math.e,
			},
		'pi': {
			'type': 'scalar',
			'val': math.pi,
			},
		'i': {
			'type': 'scalar',
			'val': math.i,
			},
		'inf': {
			'type': 'scalar',
			'val': math.Infinity,
			},
		'userfunc': {
			'type': 'function',
			'val': '[x=[1,2,3,4], y=[4,3,2,1], plot(x,y,\'.\')]',
			'varin': ['arg1', 'arg2'],
			'varout': ['x', 'y'],
			},
		},
	'runtime': {
		'code': [],
		'linenum': 0,
		},
	};

	stack = [
			/*{
				'x': {
				'type': 'scalar',
				'val': '[1,2,3,4]',
				},
			},*/
			];

function attachFunc(split_line){
	if (split_line[1]=="[") { //Function with defined outputs
		endArgs=next_semantic_block(split_line, "[")[1];
		console.log("1");
		var func=split_line[endArgs];
		env.vars[func]={'val':[]};
		for (var line = env.runtime.linenum+1; line<env.runtime.code.length; line++){
			token_line=tokenize(env.runtime.code[line],all_tokens);
			console.log(token_line[0]);
			if (token_line[0]=="end"){
			console.log("3");
				env.runtime.linenum=line+1;
				break;
			}
			else{
			console.log("4");
				env.vars[func].val.push(env.runtime.code[line]);
			}
		}
		var outVar=[];
		for (var i = 2; i<endArgs; i++){
			if(isBareword(split_line[i])){
				outVar.push(split_line[i]);
			}
			else if(split_line[i]==','){
				continue;
			}
			else return "That ain't valid! Arg: " + split_line[i];
		}
		endInArgs=next_semantic_block(split_line, endArgs)[1];
		var inVar=[];
		for (var i = endArgs; i<endInArgs; i++){
			if(isBareword(split_line[i])){
				inVar.push(split_line[i]);
			}
			else if(split_line[i]==','){
				continue;
			}
			else return "That ain't valid! Arg: " + split_line[i];
		}
		math[func]=evalUserFunc(func, args);
		env.vars[func].varin=inVar;
		env.vars[func].varout=outVar;
	}
}

function evalUserFunc(func, args){
		enterScope();
			args = Array.prototype.slice.call(arguments, 1);
			for (var vin in env.vars[func].varin){
				setvar(varin[vin], args[vin]);
			}
			for (var line in env.vars[func].val) {
				exec_statement(env.vars[func].val[line]);
			}
			var myRetArgs=env.vars[func].varout;
			for (var i in myRetArgs){
				myRetArgs[i]=getvar(myRetArgs[i]); //Populate return vars from current stack frame
			}
		exitScope();
		return myRetArgs;
}

function exitScope(){
	popvars=stack.pop();
	for (var v in popvars){
		if (getvar(v)!=null){
			math[v]=getvar(v).val;
		}
		else math[v]=undefined;
	}
}

function enterScope(){
	stack.push({});
}

function getvar(varname){
	for(var i=stack.length-1; i>=0; i--){
		if (stack[i][varname]!=null){
			return stack[i][varname];
		}
	}
	return env.vars[varname];
}

function setvar(varname, val){
	if(stack.length>0){
		stack[stack.length-1][varname]=val;
	}
	else env.vars[varname]=val;
}

function load_locals(){
	for (var localvar in env.vars){
		try{
		if(env.vars[localvar].val.hasOwnProperty('_data')){
			var m = math.matrix(env.vars[localvar].val._data);
			env.vars[localvar].val = m;
		}} catch(e){}
		math[localvar]=env.vars[localvar].val;
	}
}

function isBareword( word ){
	if(word.match(/^[a-zA-Z]\w*$/)) return true; else return false;
}

function isScalar( word ){
	if(word.match(/^(\w|[\.\+\-\/\*\(\)])*$/)) return true; else return false;
}

function flatten(array) {
  var result = [], self = arguments.callee;
  array.forEach(function(item) {
    Array.prototype.push.apply(
      result,
      Array.isArray(item) ? self(item) : [item]
    );
  });
  return result;
};

function next_semantic_block( obj, index ){
	//Returns the start and end index of the next semantic block [start,end]
	var start_ind;
	var blocked='';
	var depth=0;
	for(var i=index; i<obj.length; i++){
		if(blocked){
			switch(blocked)
			{
				case '[':
					if(obj[i]==']') if(--depth==0) return [start_ind, i+1];
					break;
				case '(':
					if(obj[i]==')') if(--depth==0) return [start_ind, i+1];
					break;
				case '{':
					if(obj[i]=='}') if(--depth==0) return [start_ind, i+1];
					break;
			}
		}
		else if (isBareword(obj[i])) return [i,i+1];
		//Check for blocking every pass and dive in!
		if (obj[i]=='['){ blocked='['; if(depth++==0) start_ind=i;}
		else if(obj[i]=='('){ blocked='('; if(depth++==0) start_ind=i;}
		else if(obj[i]=='{'){ blocked='{'; if(depth++==0) start_ind=i;}

	}
	return false;
}

function has_semantic_block( obj, type, index){//type can be (, [, {
	var n;
	for(var i=index; i<obj.length;){
		n=next_semantic_block(obj,i);
		if(n){
			if(obj[n[0]] == type){
				return n[0];
			}
			else i=n[1];
		}
		else i++;
	}
	return false;
}

var binary_ops = ['+', '-', '*', '/', '^', '&', '|', '&&', '||'];
var comparison_ops = ['>','<'];
var specials = [',', '=', ';', '~', ' '];
var blockers = ['[', ']', '(', ')', '{', '}'];

var all_tokens = binary_ops;
all_tokens.push(comparison_ops);
all_tokens.push(specials);
all_tokens.push(blockers);
all_tokens = flatten(all_tokens);

function preparse( str ){
	var i=0;
	var saved=0;
	var escaped_index;
	var parsed_str=str;
	var escaped='f';
	while (i<parsed_str.length){
		if (escaped=='f'){
			if(parsed_str[i]=='"'){
				escaped='"';
				escaped_index=i;
			}
			else if(parsed_str[i]=="'"){
				escaped="'";
				escaped_index=i;
			}
			else if(parsed_str[i]=='%'){
				parsed_str=parsed_str.slice(0,i);
				break;
			}
			i++;
		}
		else if(parsed_str[i]==escaped && parsed_str[i-1]!='\\'){
			parse_helper['%'+saved+'%']=parsed_str.slice(escaped_index,i+1);
			parsed_str=parsed_str.slice(0,escaped_index)+"%"+saved+"%"+parsed_str.slice(i+1,parsed_str.length);
			i=escaped_index+("%"+saved+"%").length;
			saved++;
			escaped='f';
		}
		else i++;
		}
	return parsed_str;
}

function postparse( str ){
	return str.replace(/%(\w)%/g,function(a,b){return parse_helper['%'+b+'%'];});
	}

function tokenize_str( str, token ){
	var sarr=[];
	var spl=String(str).split(token);
	for (var i=0; i<spl.length-1; i++){
		if (spl[i]!='')
		sarr.push(spl[i]);
		if(token!=' ')
		sarr.push(token);
	}
	sarr.push(spl[spl.length-1]);
	return sarr;
}

function tokenize( line, tokens ){
	var arr=tokenize_str(line, tokens[0]);
	var tmparr;
	for (var t=1; t<tokens.length; t++){
		tmparr=flatten(arr);
		arr=[];
		for (var str in tmparr){
			arr.push(tokenize_str( tmparr[str], tokens[t] ));
		}
	}
	return flatten(arr);
}

function structure_array(split_index){
	//This creates a semantic block array
	range=next_semantic_block(split_index, has_semantic_block(split_index,'[',0));
	var top=range[1]-2;
	for (var i = range[0]+1; i<top; i++){
		if (isScalar(split_index[i]) && isScalar(split_index[i+1])){
			split_index.splice(i+1,0,',');
			i++; top++;
		}
	}
	return split_index;
}

function merge_to_array(split_array){
	//Merges comma separated syntactic list into a js array
	return split_array.join('').split(',');
}

function exec_statement( line ){
	try{
		parsed_line=preparse(line);
		split_line = tokenize(parsed_line, all_tokens);

		for(var i in split_line){
			split_line[i]=postparse(split_line[i]);
		}
		if(split_line[0]=="for"){

		}

		//User defined functions
		else if(split_line[0]=="function"){
			console.log("Found a function");
			attachFunc(split_line);

		}

		//Temporary plotting function for demo
		else if(split_line[0]=="plot"){
			$('#chart-modal').modal('toggle');
			var i=1;
			var data={};
			var type='line';
			for(;i<split_line.length; i++){
				if (split_line[i]=='(') break;
			}
			for(;i<split_line.length; i++){
				if (isBareword(split_line[i])){
					data['x']=math[split_line[i]]._data;
					i++;
					break;}
			}
			for(;i<split_line.length; i++){
				if(isBareword(split_line[i])){
				data['y']=math[split_line[i]]._data;
					break;}
			}
			for(;i<split_line.length; i++){
				if(typeof split_line[i] == 'string'){
					if (split_line[i]=='.') type='scatter';
				}
			}
			if(data['x'].hasOwnProperty('_data')){
				data['x'] = data['x']._data;
				}
			if(data['y'].hasOwnProperty('_data')){
				data['y'] = data['y']._data;
				console.log("I did something");
				}
			console.log(data);
			d3_plot(data,type);
		}
		else if(split_line[0]=="plot"){
			args = next_semantic_block(split_line, has_semantic_block(split_line, '(', 0));
			datas=[]; styles=[];
			data_num=0;
			for( var i=args[0]; i<args[1]-1; i++){
				if (datas[0]){
					if (datas['x']){
						if(datas['y']){}}}}
			chart = d3_plot(data,style);
			setTimeout(10000, chart.update());
		}

		else if (split_line.indexOf('=')>0 && split_line[split_line.indexOf('=')+1]!='=' && split_line[split_line.indexOf('=')-1]!='<' && split_line[split_line.indexOf('=')-1]!='>' && split_line[split_line.indexOf('=')-1]!='~'){
			//Yay! We've found an assignment!
			if( 1==1 ){
			varname=split_line.slice(0,split_line.indexOf('=')).join('');
			tmpvar={};
			expr=split_line.slice(split_line.indexOf('=')+1);
			if(has_semantic_block(split_line,'[',0)){
				expr=structure_array(expr);
			}
			tmpvar['val'] = eval_expr( expr.join('') );
			tmpvar['type']='scalar';
			setvar(varname,tmpvar);
			math[varname]=tmpvar.val;
			return getvar(varname)['val'];
			}
			//else if( /*obj_prop*/ ){

			//}
			//else if( /*matrix*/ ){

			//}

		}
		return eval_expr(line);

	}
	catch(err){
	return err;
	}
	//math.eval(line);
}

function eval_expr( expr ){
	try{
		return math.eval(expr);
	}
	catch(err){ return expr };
}

function set_tab(tab){
	env.currentTab=tab;
}

function run_file(tab){//tab is an int
	mycode=env.tabs[env.currentTab].code;
	env.runtime.code=mycode.split('\n');
	env.runtime.linenum=0;
	for (; env.runtime.linenum<env.runtime.code.length; env.runtime.linenum++){
		exec_statement(env.runtime.code[env.runtime.linenum]);
	}
}<|endoftext|>


<commit_before>import {getField} from "./getField";

/**
 * Creates a new object whose fields are either equal to obj[field]
 * or defaultValue.
 * Useful for extracting a subset of fields from an object.
 *
 * @param obj the object to query the fields for.
 * @param fields an array of the target fields, in string form.
 * @param defaultValue the value to be used if obj[field] === undefined.
 * @deprecated extracting values with destructuring instead.
 * @see {@link https://github.com/googleinterns/step240-2020/pull/139|GitHub}
 */
export const getFields = (obj, fields, defaultValue) => {
  const res = {};
  for (const field of fields) {
    res[field] = getField(obj, field, defaultValue);
  }
  return res;
}
<commit_msg>Update PR reference<commit_after>import {getField} from "./getField";

/**
 * Creates a new object whose fields are either equal to obj[field]
 * or defaultValue.
 * Useful for extracting a subset of fields from an object.
 *
 * @param obj the object to query the fields for.
 * @param fields an array of the target fields, in string form.
 * @param defaultValue the value to be used if obj[field] === undefined.
 * @deprecated extracting values with destructuring instead.
 * @see {@link https://github.com/googleinterns/step240-2020/pull/176|GitHub}
 */
export const getFields = (obj, fields, defaultValue) => {
  const res = {};
  for (const field of fields) {
    res[field] = getField(obj, field, defaultValue);
  }
  return res;
}
<|endoftext|>


<commit_before>/*jslint sloppy:true */
/*global $, Backbone, console, EventsView, EditEventView, CreateEventView, ControlsView */

var AppRouter = Backbone.Router.extend({
    initialize: function (options) {
        this.main = options.main;
        this.events = options.events;
    },
    routes: {
        '': 'index',
        'create': 'create',
        'edit/:id': 'edit'
    },
    index: function () {
        var cv = new ControlsView({
            nav: this.navigate.bind(this)
        }),
            av = new EventsView({
                collection: this.events,
                nav: this.navigate.bind(this)
            });
        this.main.html(cv.render().el);
        this.main.append(av.render().el);
    },
    create: function () {
        var cv = new CreateEventView({
            collection: this.events,
            nav: this.navigate.bind(this)
        });
        if ($("table").length === 0) {
            this.index();
        }
        this.main.prepend(cv.render().el);
    },
    edit: function (id) {
        var ev = new EditEventView({
            model: this.events.get(parseInt(id, 10)),
            nav: this.navigate.bind(this)
        });
        if ($("table").length === 0) {
            this.index();
        }
        this.main.prepend(ev.render().el);
    }
});<commit_msg>refactored router<commit_after>/*jslint sloppy:true */
/*global $, Backbone, console, EventsView, EditEventView, CreateEventView, ControlsView */

var AppRouter = Backbone.Router.extend({
    initialize: function (options) {
        this.main = options.main;
        this.events = options.events;
        this.nav = this.navigate.bind(this);
    },
    routes: {
        '': 'index',
        'create': 'create',
        'edit/:id': 'edit'
    },
    index: function () {
        var cv = new ControlsView({
            nav: this.nav
        }),
            av = new EventsView({
                collection: this.events,
                nav: this.nav
            });
        this.main.html(cv.render().el);
        this.main.append(av.render().el);
    },
    create: function () {
        var cv = new CreateEventView({
            collection: this.events,
            nav: this.nav
        });
        this.modal(cv);
    },
    edit: function (id) {
        var ev = new EditEventView({
            model: this.events.get(parseInt(id, 10)),
            nav: this.nav
        });
        this.modal(ev);
    },
    modal: function (view) {
        if ($("table").length === 0) {
            this.index();
        }
        this.main.prepend(view.render().el);
    }
});<|endoftext|>


<commit_before>(function (Backbone, _, $, undefined) {
"use strict";

Backbone.$ = $;

window.Daybed = window.Daybed || {};

/**
 * Default settings
 */
Daybed.SETTINGS = {
    SERVER: "localhost:8000"
};

//
//  Item : a record
//
Daybed.Item = Backbone.Model.extend({
    url: function () {
        return URI.build({hostname: Daybed.SETTINGS.SERVER,
                          path: '/data/' + this.definition.id});
    },

    /**
     * Fields values
     */
    fieldsValues: function () {
        var columns = this.definition.fieldsNames(),
            fields = _.pick.apply(_, ([this.attributes]).concat(columns));
        return _.values(fields);
    }
});

Daybed.ItemList = Backbone.Collection.extend({
    model: Daybed.Item,

    initialize: function (definition) {
        this.definition = definition;
    },

    url: function () {
        return URI.build({hostname: Daybed.SETTINGS.SERVER,
                          path: '/data/' + this.definition.id});
    },

    parse: function (response) {
        return response.data;
    },

    /**
     * Fetch only once Definition is ready.
     */
    fetch: function () {
        var args = Array.prototype.slice.call(arguments);
        this.definition.whenReady((function () {
            Backbone.Collection.prototype.fetch.apply(this, args);
        }).bind(this));
    },

    /**
     * Override instanciation to link with Definition instance.
     */
    _prepareModel: function () {
        var m = Backbone.Collection.prototype._prepareModel.apply(this, arguments);
        m.definition = this.definition;
        return m;
    }
});

//
//  Definition : a model
//
Daybed.Definition = Backbone.Model.extend({
    /**
     * Backbone.forms schema for Definition forms
     */
    schema: {
        id:  { type: 'Hidden', title: '' },
        title: 'Text',
        description: 'Text',
        fields: { type: 'List', itemType: 'Object', subSchema: {
            name: { validators: ['required'] },
            description: 'Text',
            required: { type: 'Checkbox', editorAttrs: { 'checked' : 'checked' } },
            type: { type: 'Select', options: ['int', 'string', 'decimal', 'boolean',
                                              'email', 'url', 'point', 'line', 'polygon'] }
        }}
    },

    /**
     * Meta-types are fake types. Daybed does not know them.
     */
    metaTypes: {
        'text': 'string'
    },

    initialize: function () {
        // Add meta types to schema choice list
        var choices = this.schema.fields.subSchema.type.options;
        for (var metatype in this.metaTypes) {
            if (!_.contains(choices, metatype))
                choices.push(metatype);
        }
    },

    save: function () {
        // Substitute meta types by daybed types
        $(this.attributes.fields).each((function (i, field) {
            var meta = this.metaTypes[field.type];
            if (meta) {
                field.meta = field.type;
                field.type = meta;
            }
        }).bind(this));
        Backbone.Model.prototype.save.apply(this, arguments);
    },

    url: function () {
        return URI.build({hostname: Daybed.SETTINGS.SERVER,
                          path: 'definitions/' + this.id});
    },

    /**
     * @returns {boolean} True if *Definition* is initialized (fetched from server)
     */
    isReady: function () {
        return this.attributes.fields && this.attributes.fields.length > 0;
    },

    /**
     * Calls ``cb`` when *Definition* was fetched from server.
     * @param {function} cb
     */
    whenReady: function (cb) {
        if (this.isReady())
            cb();
        else {
            this.once('change', function () {
                this.whenReady(cb);
            }, this);
        }
    },

    /**
     * Fields names
     */
    fieldsNames: function () {
        return _.pluck(this.attributes.fields, 'name');
    },

    /**
     * Builds a Backbone.forms schema from the *Definition* record,
     * for {Item} forms.
     * For each model field, add a Backbone.forms declaration.
     * @returns {Object}
     */
    itemSchema: function () {
        if (!this.isReady())
            throw "Definition is not ready. Fetch it first.";
        var typeMapping = {
            'int': 'Number',
            'string': 'Text',
            'boolean': 'Checkbox'
        };
        var fieldMapping = {
            'default': function (f) {
                var d = {help: f.description},
                    t = typeMapping[f.type];
                if (t) d.type = t;
                return d;
            },
            'text': function () {
                return { type: 'TextArea' };
            },
            'decimal': function (f) {
                var d = fieldMapping['default'](f);
                d.editorAttrs = {pattern: '[-+]?[0-9]*\\.?[0-9]+'};
                return d;
            },
            'email': function (f) {
                var d = fieldMapping['default'](f);
                d.validators = ['required', 'email'];
                return d;
            },
            'url': function (f) {
                var d = fieldMapping['default'](f);
                d.validators = ['required', 'url'];
                return d;
            }
        };
        var schema = {};
        // Backbone.Forms fields from this Daybed definition
        $(this.attributes.fields).each(function (i, field) {
            var build = fieldMapping[field.meta || field.type];
            schema[field.name] = (build ?
                                  build(field) : fieldMapping['default'](field));
        });
        return schema;
    }
});

//
// FormView : Generic Backbone form
//
Daybed.FormView = Backbone.View.extend({
    model: Daybed.Item,
    tagName: "div",
    className: "well",

    template: Mustache.compile('
{{ title }}
' +
                               '

' +
                               'Cancel ' +
                               'Save'),
    templateError: Mustache.compile('{{ msg }}'),

    events: {
        "click .submit": "submit",
        "click .cancel": "cancel"
    },

    initialize: function () {
        this.definition = this.options.definition || this.options.instance.definition;
        this.definition.whenReady(this.setup.bind(this));
    },

    setup: function (instance) {
        this.instance = instance || this.options.instance || new this.model({});
        this.instance.definition = this.instance.definition || this.definition;
        this.instance.schema = this.instance.schema || this.definition.itemSchema();

        this.instance.on('change', this.refresh.bind(this));
        this.instance.on('sync', this.success.bind(this));
        this.instance.on('error', this.error.bind(this));

        this.creation = this.instance.attributes.id === undefined;

        this.title = this.options.title ||
                     (this.creation ? "Create " : "Edit ") + this.definition.attributes.title;

        // Underlying backbone-forms object
        this.form = new Backbone.Form({
            model: this.instance
        });

        this.refresh();
    },

    render: function () {
        this.$el.html(this.template(this));
        this.$('.form').html(this.form.render().el);
        this.delegateEvents();
        return this;
    },

    cancel: function (e) {
        e.preventDefault();
        this.$('form')[0].reset();
        return false;
    },

    submit: function(e) {
        e.preventDefault();
        // Hide previous validation errors (if any)
        this.$('.field-error').remove();
        // Serialize form fields
        var data = this.form.getValue();
        this.trigger('submit', data);
        // Store form data into instance, and save it
        this.form.commit();
        this.instance.save();
        return false;
    },

    success: function (model, response, options) {
        this.trigger((this.creation ? 'created' : 'saved'), model);
        return false;
    },

    error: function (model, response, options) {
        try {
            this.showErrors(JSON.parse(response.responseText));
        }
        catch (e) {
            this.$el.html(this.templateError({msg: response.responseText}));
        }

        this.trigger('error', model);
        return false;
    },

    /**
     * Show each error along its field
     */
    showErrors: function (descriptions) {
        $(descriptions.errors).each((function (i, e) {
            var name = e.name.split('.')[0];
            this.$("[name='" + name + "']")
                .after(this.templateError({msg: e.description}));
        }).bind(this));
    },

    /**
     * Refresh field values from instance attributes.
     */
    refresh: function () {
        for (var f in this.instance.changed) {
            if (f == 'id') continue;
            var formfield = this.$("[name='"+ f + "']");
            if (formfield.length === 0)
                console.warn("Could not find form field '" + f + "'");
            formfield.val(this.instance.get(f));
        }
    }
});

/**
 * Form rendering helper
 */
Daybed.renderForm = function (selector, options) {
    var definition = new Daybed.Definition(options),
        formView = new Daybed.FormView({definition: definition});

    definition.whenReady(function () {
        $(selector).html(formView.render().el);
    });

    definition.fetch();
    return formView;
};

})(Backbone,  _, jQuery);<commit_msg>Explicit save and reset methods<commit_after>(function (Backbone, _, $, undefined) {
"use strict";

Backbone.$ = $;

window.Daybed = window.Daybed || {};

/**
 * Default settings
 */
Daybed.SETTINGS = {
    SERVER: "localhost:8000"
};

//
//  Item : a record
//
Daybed.Item = Backbone.Model.extend({
    url: function () {
        return URI.build({hostname: Daybed.SETTINGS.SERVER,
                          path: '/data/' + this.definition.id});
    },

    /**
     * Fields values
     */
    fieldsValues: function () {
        var columns = this.definition.fieldsNames(),
            fields = _.pick.apply(_, ([this.attributes]).concat(columns));
        return _.values(fields);
    }
});

Daybed.ItemList = Backbone.Collection.extend({
    model: Daybed.Item,

    initialize: function (definition) {
        this.definition = definition;
    },

    url: function () {
        return URI.build({hostname: Daybed.SETTINGS.SERVER,
                          path: '/data/' + this.definition.id});
    },

    parse: function (response) {
        return response.data;
    },

    /**
     * Fetch only once Definition is ready.
     */
    fetch: function () {
        var args = Array.prototype.slice.call(arguments);
        this.definition.whenReady((function () {
            Backbone.Collection.prototype.fetch.apply(this, args);
        }).bind(this));
    },

    /**
     * Override instanciation to link with Definition instance.
     */
    _prepareModel: function () {
        var m = Backbone.Collection.prototype._prepareModel.apply(this, arguments);
        m.definition = this.definition;
        return m;
    }
});

//
//  Definition : a model
//
Daybed.Definition = Backbone.Model.extend({
    /**
     * Backbone.forms schema for Definition forms
     */
    schema: {
        id:  { type: 'Hidden', title: '' },
        title: 'Text',
        description: 'Text',
        fields: { type: 'List', itemType: 'Object', subSchema: {
            name: { validators: ['required'] },
            description: 'Text',
            required: { type: 'Checkbox', editorAttrs: { 'checked' : 'checked' } },
            type: { type: 'Select', options: ['int', 'string', 'decimal', 'boolean',
                                              'email', 'url', 'point', 'line', 'polygon'] }
        }}
    },

    /**
     * Meta-types are fake types. Daybed does not know them.
     */
    metaTypes: {
        'text': 'string'
    },

    initialize: function () {
        // Add meta types to schema choice list
        var choices = this.schema.fields.subSchema.type.options;
        for (var metatype in this.metaTypes) {
            if (!_.contains(choices, metatype))
                choices.push(metatype);
        }
    },

    save: function () {
        // Substitute meta types by daybed types
        $(this.attributes.fields).each((function (i, field) {
            var meta = this.metaTypes[field.type];
            if (meta) {
                field.meta = field.type;
                field.type = meta;
            }
        }).bind(this));
        Backbone.Model.prototype.save.apply(this, arguments);
    },

    url: function () {
        return URI.build({hostname: Daybed.SETTINGS.SERVER,
                          path: 'definitions/' + this.id});
    },

    /**
     * @returns {boolean} True if *Definition* is initialized (fetched from server)
     */
    isReady: function () {
        return this.attributes.fields && this.attributes.fields.length > 0;
    },

    /**
     * Calls ``cb`` when *Definition* was fetched from server.
     * @param {function} cb
     */
    whenReady: function (cb) {
        if (this.isReady())
            cb();
        else {
            this.once('change', function () {
                this.whenReady(cb);
            }, this);
        }
    },

    /**
     * Fields names
     */
    fieldsNames: function () {
        return _.pluck(this.attributes.fields, 'name');
    },

    /**
     * Builds a Backbone.forms schema from the *Definition* record,
     * for {Item} forms.
     * For each model field, add a Backbone.forms declaration.
     * @returns {Object}
     */
    itemSchema: function () {
        if (!this.isReady())
            throw "Definition is not ready. Fetch it first.";
        var typeMapping = {
            'int': 'Number',
            'string': 'Text',
            'boolean': 'Checkbox'
        };
        var fieldMapping = {
            'default': function (f) {
                var d = {help: f.description},
                    t = typeMapping[f.type];
                if (t) d.type = t;
                return d;
            },
            'text': function () {
                return { type: 'TextArea' };
            },
            'decimal': function (f) {
                var d = fieldMapping['default'](f);
                d.editorAttrs = {pattern: '[-+]?[0-9]*\\.?[0-9]+'};
                return d;
            },
            'email': function (f) {
                var d = fieldMapping['default'](f);
                d.validators = ['required', 'email'];
                return d;
            },
            'url': function (f) {
                var d = fieldMapping['default'](f);
                d.validators = ['required', 'url'];
                return d;
            }
        };
        var schema = {};
        // Backbone.Forms fields from this Daybed definition
        $(this.attributes.fields).each(function (i, field) {
            var build = fieldMapping[field.meta || field.type];
            schema[field.name] = (build ?
                                  build(field) : fieldMapping['default'](field));
        });
        return schema;
    }
});

//
// FormView : Generic Backbone form
//
Daybed.FormView = Backbone.View.extend({
    model: Daybed.Item,
    tagName: "div",
    className: "well",

    template: Mustache.compile('
{{ title }}
' +
                               '

' +
                               'Cancel ' +
                               'Save'),
    templateError: Mustache.compile('{{ msg }}'),

    events: {
        "click .submit": "submit",
        "click .cancel": "cancel"
    },

    initialize: function () {
        this.definition = this.options.definition || this.options.instance.definition;
        this.definition.whenReady(this.setup.bind(this));
    },

    setup: function (instance) {
        this.instance = instance || this.options.instance || new this.model({});
        this.instance.definition = this.instance.definition || this.definition;
        this.instance.schema = this.instance.schema || this.definition.itemSchema();

        this.instance.on('change', this.refresh.bind(this));
        this.instance.on('sync', this.success.bind(this));
        this.instance.on('error', this.error.bind(this));

        this.creation = this.instance.attributes.id === undefined;

        this.title = this.options.title ||
                     (this.creation ? "Create " : "Edit ") + this.definition.attributes.title;

        // Underlying backbone-forms object
        this.form = new Backbone.Form({
            model: this.instance
        });

        this.refresh();
    },

    render: function () {
        this.$el.html(this.template(this));
        this.$('.form').html(this.form.render().el);
        this.delegateEvents();
        return this;
    },

    cancel: function (e) {
        e.preventDefault();
        this.trigger('cancel');
        this.reset();
        return false;
    },

    reset: function () {
        this.$('form')[0].reset();
    },

    submit: function(e) {
        e.preventDefault();
        // Serialize form fields
        var data = this.form.getValue();
        this.trigger('submit', data);
        this.save();
        return false;
    },

    save: function () {
        // Hide previous validation errors (if any)
        this.$('.field-error').remove();
        // Store form data into instance, and save it
        this.form.commit();
        this.instance.save();
    },

    success: function (model, response, options) {
        this.trigger((this.creation ? 'created' : 'saved'), model);
        return false;
    },

    error: function (model, response, options) {
        var descriptions = [];
        try {
            descriptions = JSON.parse(response.responseText);
            this.showErrors(descriptions);
        }
        catch (e) {
            this.$el.html(this.templateError({msg: response.responseText}));
        }
        this.trigger('error', {model: model,
                               errors: descriptions});
        return false;
    },

    /**
     * Show each error along its field
     */
    showErrors: function (descriptions) {
        $(descriptions.errors).each((function (i, e) {
            var name = e.name.split('.')[0];
            this.$("[name='" + name + "']")
                .after(this.templateError({msg: e.description}));
        }).bind(this));
    },

    /**
     * Refresh field values from instance attributes.
     */
    refresh: function () {
        for (var f in this.instance.changed) {
            if (f == 'id') continue;
            var formfield = this.$("[name='"+ f + "']");
            if (formfield.length === 0)
                console.warn("Could not find form field '" + f + "'");
            formfield.val(this.instance.get(f));
        }
    }
});

/**
 * Form rendering helper
 */
Daybed.renderForm = function (selector, options) {
    var definition = new Daybed.Definition(options),
        formView = new Daybed.FormView({definition: definition});

    definition.whenReady(function () {
        $(selector).html(formView.render().el);
    });

    definition.fetch();
    return formView;
};

})(Backbone,  _, jQuery);<|endoftext|>


<commit_before>$.get("/get/username", function(data) {
    parsedData = JSON.parse(data);
    $("#loggedIn").html("Welcome " + data.username + "");
    $("#login").hide();
    $("#signup").hide();
    $("#loggedIn").show();
});

window.onload = function() {

  // Get references to elements on the page.
  var form = document.getElementById('message-form');
  var messageField = document.getElementById('message');
  var messagesList = document.getElementById('messages');
  //var socketStatus = document.getElementById('status');

  // Create a new WebSocket.
  var socket = new WebSocket('ws://ipp.chtr.us');

  // // Handle any errors that occur.
  // socket.onerror = function(error) {
  //   console.log('WebSocket Error: ' + error);
  // };

  // // Show a connected message when the WebSocket is opened.
  // socket.onopen = function(event) {
  //   socketStatus.innerHTML = 'Connected to: ws://ipp.chtr.us';
  //   socketStatus.className = 'open';
  // };

  // Handle messages sent by the server.
  socket.onmessage = function(event) {
    var value = JSON.parse(event.data);
    messagesList.innerHTML += '

' +
                               value.message + '
'+value.username+'| 23rd June at 5:00pm

';
  };

  // // Show a disconnected message when the WebSocket is closed.
  // socket.onclose = function(event) {
  //   socketStatus.innerHTML = 'Disconnected from WebSocket.';
  //   socketStatus.className = 'closed';
  // };

  // Send a message when the form is submitted.
  form.onsubmit = function(e) {
    e.preventDefault();

    // Retrieve the message from the textarea.
    var json = {
        "message": messageField.value,
        "username": "yogert96"
    };
    var message = JSON.stringify(json);

    // Send the message through the WebSocket.
    socket.send(message);

    // Add the message to the messages list.
    //messagesList.innerHTML += '
Sent:' + message +
                              //'
';

    // Clear out the message field.
    messageField.value = '';

    return false;
  };

};
<commit_msg>idk whats wrong<commit_after>$.get("/get/username", function(data) {
    parsedData = JSON.stringify(data);
    $("#loggedIn").html("Welcome " + data.username + "");
    $("#login").hide();
    $("#signup").hide();
    $("#loggedIn").show();
});

window.onload = function() {

  // Get references to elements on the page.
  var form = document.getElementById('message-form');
  var messageField = document.getElementById('message');
  var messagesList = document.getElementById('messages');
  //var socketStatus = document.getElementById('status');

  // Create a new WebSocket.
  var socket = new WebSocket('ws://ipp.chtr.us');

  // // Handle any errors that occur.
  // socket.onerror = function(error) {
  //   console.log('WebSocket Error: ' + error);
  // };

  // // Show a connected message when the WebSocket is opened.
  // socket.onopen = function(event) {
  //   socketStatus.innerHTML = 'Connected to: ws://ipp.chtr.us';
  //   socketStatus.className = 'open';
  // };

  // Handle messages sent by the server.
  socket.onmessage = function(event) {
    var value = JSON.parse(event.data);
    messagesList.innerHTML += '

' +
                               value.message + '
'+value.username+'| 23rd June at 5:00pm

';
  };

  // // Show a disconnected message when the WebSocket is closed.
  // socket.onclose = function(event) {
  //   socketStatus.innerHTML = 'Disconnected from WebSocket.';
  //   socketStatus.className = 'closed';
  // };

  // Send a message when the form is submitted.
  form.onsubmit = function(e) {
    e.preventDefault();

    // Retrieve the message from the textarea.
    var json = {
        "message": messageField.value,
        "username": "yogert96"
    };
    var message = JSON.stringify(json);

    // Send the message through the WebSocket.
    socket.send(message);

    // Add the message to the messages list.
    //messagesList.innerHTML += '
Sent:' + message +
                              //'
';

    // Clear out the message field.
    messageField.value = '';

    return false;
  };

};
<|endoftext|>


<commit_before>;(function (root, factory) {
    // https://github.com/umdjs/umd/blob/master/returnExports.js
    if (typeof exports === 'object') {
        // Node
        module.exports = factory(require('jquery'), require('underscore'), require('backbone'), require('backbone.marionette'));
    } else if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery', 'underscore', 'backbone', 'backbone.marionette'], factory);
    } else {
        // Browser globals (root is window)
        factory(root.$, root._, root.Backbone, root.Backbone.Marionette, root);
    }
})(this, function ($, _, Backbone, Marionette, root) {
    'use strict';

    Backbone.Blazer = {};

    Backbone.Blazer.Route = Backbone.Marionette.Object.extend({
        prepare: function() { return $.Deferred().resolve(); },
        execute: function() { }
    });

    Backbone.Blazer.Router = Backbone.Router.extend({
        route: function(route, config) {
            if (!_.isRegExp(route)) {
                route = this._routeToRegExp(route);
            }

            var routeData = {
                handler: config
            };

            var router = this;
            Backbone.history.route(route, function(fragment) {
                routeData.params = router._extractParameters(route, fragment);
                router.handleRoute(routeData);
            });
            return this;
        },

        handleRoute: function(routeData) {
            var handler = routeData.handler;

            if (_.isString(handler)) {
                if (_.isFunction(this[handler])) {
                    this[handler].apply(this, routeData.params);
                }
            } else if (handler instanceof Backbone.Blazer.Route) {
                this._handleBlazerRoute(handler, routeData);
            } else if (_.isFunction(handler)) {
                handler.apply(this, routeData);
            } else {
                throw new Error('Incorrectly configured route');
            }
        },

        _handleBlazerRoute: function(route, routeData) {
            var router = this;

            this.currentRoute = route;

            route.trigger('before:execute');

            route.prepare(routeData).then(function() {
                if (router.currentRoute !== route) {
                    return;
                }
                route.execute(routeData);
                route.trigger('after:execute');
            }).fail(function() {
                if (router.currentRoute !== route) {
                    return;
                }
                if (_.isFunction(route.error)) {
                    var errorHandled = route.error.apply(route, arguments) === false;
                    if (!errorHandled) {
                        router.trigger('error', arguments);
                    }
                }
            });
        }
    });

    return Backbone.Blazer;
});
<commit_msg>include route data in error method calls<commit_after>;(function (root, factory) {
    // https://github.com/umdjs/umd/blob/master/returnExports.js
    if (typeof exports === 'object') {
        // Node
        module.exports = factory(require('jquery'), require('underscore'), require('backbone'), require('backbone.marionette'));
    } else if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery', 'underscore', 'backbone', 'backbone.marionette'], factory);
    } else {
        // Browser globals (root is window)
        factory(root.$, root._, root.Backbone, root.Backbone.Marionette, root);
    }
})(this, function ($, _, Backbone, Marionette, root) {
    'use strict';

    Backbone.Blazer = {};

    Backbone.Blazer.Route = Backbone.Marionette.Object.extend({
        prepare: function() { return $.Deferred().resolve(); },
        execute: function() { }
    });

    Backbone.Blazer.Router = Backbone.Router.extend({
        route: function(route, config) {
            if (!_.isRegExp(route)) {
                route = this._routeToRegExp(route);
            }

            var routeData = {
                handler: config
            };

            var router = this;
            Backbone.history.route(route, function(fragment) {
                routeData.params = router._extractParameters(route, fragment);
                router.handleRoute(routeData);
            });
            return this;
        },

        handleRoute: function(routeData) {
            var handler = routeData.handler;

            if (_.isString(handler)) {
                if (_.isFunction(this[handler])) {
                    this[handler].apply(this, routeData.params);
                }
            } else if (handler instanceof Backbone.Blazer.Route) {
                this._handleBlazerRoute(handler, routeData);
            } else if (_.isFunction(handler)) {
                handler.apply(this, routeData);
            } else {
                throw new Error('Incorrectly configured route');
            }
        },

        _handleBlazerRoute: function(route, routeData) {
            var router = this;

            this.currentRoute = route;

            route.trigger('before:execute');

            route.prepare(routeData).then(function() {
                if (router.currentRoute !== route) {
                    return;
                }
                route.execute(routeData);
                route.trigger('after:execute');
            }).fail(function() {
                var args = Array.prototype.slice.call(arguments);
                args = args.unshift(routeData);
                if (router.currentRoute !== route) {
                    return;
                }
                if (_.isFunction(route.error)) {
                    var errorHandled = route.error.call(route, args) === false;
                    if (!errorHandled) {
                        router.trigger('error', args);
                    }
                }
            });
        }
    });

    return Backbone.Blazer;
});
<|endoftext|>


<commit_before>"use strict";

class ImpossiblePromise {

    constructor (fn){
        this._stack = [];
        this._data  = [];
        this._done = false;
        this._ups = function(){/* noop! */};

        if(!fn){
          throw new Error("ImpossiblePromise(:Function) requires a function to start a sequence");
        }

        process.nextTick(function() {
            this._promise = new Promise(fn).catch(this._ups);
        }.bind(this));
    }

    then (fn){
        if(this._done===true){
            return new ImpossiblePromise(fn);
        }

        process.nextTick(function() {
            this._promise = this._promise.then((value) => {
                this._data.push(value);
                return new Promise((done,err) => fn.apply(null, [done, err, value])).catch(this._ups);
            });
            this._stack.push(this._promise);
        }.bind(this));
        return this;
    }

    done (fn){
        this.then((done,err) => {
            fn.apply(null, this._data);
        });

        this._done = true;
        return this;
    }

    error (fn){
        this._ups = fn;
        return this;
    }
}

module.exports = ImpossiblePromise;

<commit_msg>.done() should finish the chain<commit_after>"use strict";

class ImpossiblePromise {

    constructor (fn){
        this._stack = [];
        this._data  = [];
        this._done = false;
        this._ups = function(){/* noop! */};

        if(!fn){
          throw new Error("ImpossiblePromise(:Function) requires a function to start a sequence");
        }

        process.nextTick(function() {
            this._promise = new Promise(fn).catch(this._ups);
        }.bind(this));
    }

    then (fn){
        if(this._done===true){
            return new ImpossiblePromise(fn);
        }

        process.nextTick(function() {
            this._promise = this._promise.then((value) => {
                this._data.push(value);
                return new Promise((done,err) => fn.apply(null, [done, err, value])).catch(this._ups);
            });
            this._stack.push(this._promise);
        }.bind(this));
        return this;
    }

    done (fn){
        this.then((done) => {
            fn.apply(null, this._data);
            done();
        });

        this._done = true;
        return this;
    }

    error (fn){
        this._ups = fn;
        return this;
    }
}

module.exports = ImpossiblePromise;

<|endoftext|>


<commit_before>var socket = io.connect('http://localhost');

function getTeamID (id, callback) {
  socket.emit('getID', id);
  socket.on('receiveID', function (exists, newID) {
    if (exists)
    callback(newID);
  });
}
<commit_msg>Adding sockets<commit_after>var socket = io.connect('http://localhost');

function getTeamID (id, callback) {
  socket.emit('getID', id);
  socket.on('receiveID', function (exists, newID) {
    if (exists) {
      alert('Already exists');
    } else {
      callback(newID);
    }
  });
}
<|endoftext|>


<commit_before>'use strict'

const mongoose = require('mongoose')
const MONGODB_URL = MONGO_DB_URL || 'mongodb://localhost:27017/fake-reddit'

mongoose.Promise = Promise

module.exports.connect = () => mongoose.connect(MONGODB_URL)
<commit_msg>added node engine<commit_after>'use strict'

const mongoose = require('mongoose')

const MONGODB_URL = process.env.MONGO_DB_URL || 'mongodb://localhost:27017/fake-reddit'

mongoose.Promise = Promise

module.exports.connect = () => mongoose.connect(MONGODB_URL)
<|endoftext|>


<commit_before>var redis = require("redis"),
    url = require("url"),
    client;

function setUp(app, options) {
  app.get('/priorities', retrieve);
  app.put('/priorities', update);
  app.post('/priorities', update);

  var redisUrl = url.parse(options.url);
  client = redis.createClient(redisUrl.port, redisUrl.hostname);
  if(redisUrl.auth) {
    client.auth(redisUrl.auth.split(":")[1]);
  }
}

function retrieve(req, res) {
  var query = req.query;
  console.log(query.track)
  client.get("priority:" + query.track, function(err, reply) {
    if(err) {
      console.log(err);
    }
    console.log(reply)
    res
      .send({issues: JSON.parse(reply)})
      .status(200);
  });
}

function update(req, res) {
  var body = req.body;
  console.log(req.body);
  var priorities = body.issues || [];
  client.set("priority:" + body.track, JSON.stringify(priorities));
  res
    .send({})
    .status(201);
}

module.exports = setUp;<commit_msg> fixing behaviour when there is no redistogo configuration<commit_after>var redis = require("redis"),
url = require("url"),
client;

function setUp(app, options) {
  app.get('/priorities', retrieve);
  app.put('/priorities', update);
  app.post('/priorities', update);

    var redisUrl = url.parse(options.url);
    client = redis.createClient(redisUrl.port, redisUrl.hostname);

    client.on('error', function(event) {

      console.log('fail in connect with redis');
      client = undefined;

    });

    if(redisUrl.auth) {
      client.auth(redisUrl.auth.split(":")[1]);
    }

}

function retrieve(req, res) {
  var query = req.query;
  console.log(query.track)
  if(client){
    client.get("priority:" + query.track, function(err, reply) {
      if(err) {
        console.log(err);
      }
      console.log(reply)
      res
      .send({issues: JSON.parse(reply)})
      .status(200);
    });
  }
  else{
    res.send({}).status(503);
  }

}

function update(req, res) {
  var body = req.body;
  console.log(req.body);
  var priorities = body.issues || [];
  if(client){
    client.set("priority:" + body.track, JSON.stringify(priorities));
    res
    .send({})
    .status(201);
  } else {
    res.send({})
    .status(503);
  }
}

module.exports = setUp;<|endoftext|>


<commit_before>var config = require('./config.js');
var pg = require('pg');
var fs = require('fs');
var path = require('path');

var cfg = config.pg;

pg.on('notice', function(msg) {
  console.log("notice: %j", msg);
});

pg.on('error', function(msg) {
  console.log("error: %j", msg);
});

var getCurrentRound = function(next) {
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }

    var query = 'select * from "round" where is_current = TRUE order by id desc limit 1';
    client.query({text: query}, function(err, result) {
      next(err, result.rows[0]);
      done();
    });
  });
};

var incrementCurrentRound = function (next) {
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    var query = 'update round set is_current=FALSE;\n' +
                'insert into round(is_current) VALUES(TRUE) returning id;';
    client.query({text: query}, function(err, result){
      next(err, result != null ? result.rows[0] : {});
      done();
    });
  });
};

var getChoicesForRoundQuery = fs.readFileSync(path.join(__dirname, 'database/getChoicesForRound.sql'), 'utf-8');
var getChoicesForRound = function(round, next) {
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    var values = [round];
    	client.query({text: getChoicesForRoundQuery, values: values}, function(err, result){
		    next(err, result.rows);
        done();
  	});
  });
};

var getVotesByRoundQuery = fs.readFileSync(path.join(__dirname, 'database/getVotesByRound.sql'), 'utf-8');
var getVotesByRound = function(round, next) {
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    var values = [round];
      client.query({text: getVotesByRoundQuery, values: values}, function(err, result){
        next(err, result.rows);
        done();
    });
  });
};

var getVotesQuery = fs.readFileSync(path.join(__dirname, 'database/getVotes.sql'), 'utf-8');
var getVotes = function (next) {
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    client.query({text: getVotesQuery}, function(err, result){
      next(err, result != null ? result.rows : []);
      done();
    });
  });
};

var hasVotedInRound = function(user, roundId, next) {
  if(!user) {
    next(null, false);
    return;
  }
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    var hasVotedQuery = 'select count(1) from "vote" where user_id = $1 and round_id = $2';
    client.query({text: hasVotedQuery, values: [user.id, roundId]}, function(err, result){
      next(err, result != null ? result.rows[0].count > 0 : false);
      done();
    });
  });
}

var addVote = function (vote, next) {
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    getCurrentRound(function(err, round){
      if(err) { done(); return next(err); }
      var query = 'insert into vote(round_id, choice_id, user_id) values($1, $2, $3)\n '+
                  'on conflict on constraint vote_round_id_user_id_key do update set choice_id = $2\n '+
                  'RETURNING *';
      var values = [round.id, vote.choice_id, vote.user_id];
      client.query({text: query, values: values}, function(err, result){
        next(err, result != null ? result.rows[0] : {});
        done();
      });
    });
  });
};

var setWinner = function (winner, next) {
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    getCurrentRound(function(err, round){
      if(err) { done(); return next(err); }
      var query = 'update round set winning_vote_id = $1, winning_choice_id = $2 where id = $3';
      var values = [winner.vote_id, winner.choice_id, round.id];
      client.query({text: query, values: values}, function(err, result){
        next(err, {});
        done();
      });
    })
  });
};

var getFavouriteByRoundQuery = fs.readFileSync(path.join(__dirname, 'database/getFavouriteByRound.sql'), 'utf-8');
var getFavouriteByRound = function (round, next) {
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    var values = [round];
    client.query({text: getFavouriteByRoundQuery, values: values}, function(err, result){
      next(err, result.rows[0]);
      done();
  	});
  });
}

var getWinnerByRoundQuery = fs.readFileSync(path.join(__dirname, 'database/getWinnerByRound.sql'), 'utf-8');
var getWinnerByRound = function (round, next) {
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    var values = [round];
    client.query({text: getWinnerByRoundQuery, values: values}, function(err, result){
      next(err, result.rows[0]);
      done();
  	});
  });
}

var getWinnerQuery = fs.readFileSync(path.join(__dirname, 'database/getWinner.sql'), 'utf-8');
var getWinner = function (next) {
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    client.query({text: getWinnerQuery}, function(err, result){
      next(err, result.rows[0].winning_choice_id);
      done();
  	});
  });
}

var getUserByToken = function(token, next){
  if(!token) {
    next('No token specified', null);
    return;
  }
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    var query = 'select * from "user" where token = $1 limit 1';
    var values = [token];
    client.query({text: query, values: values}, function(err, result){
      next(err, result.rows[0]);
      done();
  	});
  });
};

var getUserByName = function(name, next){
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    var query = 'select * from "user" where name = $1 limit 1';
    var values = [name];
    client.query({text: query, values: values}, function(err, result){
      next(err, result.rows[0]);
      done();
  	});
  });
};

var getWinsForEachUserQuery = fs.readFileSync(path.join(__dirname, 'database/getWinsForEachUser.sql'), 'utf-8');
var getWinsForEachUser = function(next){
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    client.query({text: getWinsForEachUserQuery}, function(err, result){
      next(err, result.rows);
      done();
  	});
  });
};

var getStatsForRoundQuery = fs.readFileSync(path.join(__dirname, 'database/getStatsForRound.sql'), 'utf-8');
var getStatsForRound = function(round, next){
  pg.connect(cfg, function queryStats(err, client, done) {
    if(err) { done(); return next(err); }
    var values = [round];
    client.query({text: getStatsForRoundQuery, values: values}, function(err, result){
      if (err) { done(); return next(err); }
      var stats = result.rows;

      getWinnerByRound(round, function(err, winner) {
        if (err) { done(); return next(err); }
        else {
          getFavouriteByRound(round, function(err, favourite){
            if (err) { done(); return next(err); }

            var winnerName = winner ? winner.name : "";
            var favName = favourite ? favourite.name : "";
            next(null, {users: stats, round: round, winner: winnerName, popular: favName});
            done();
          });
        }
      });
  	});
  });
};

var getChoice = function (choice, next) {
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    var query = 'select * from choice where id = $1 limit 1;';
    var values = [choice];
    client.query({text: query, values: values}, function(err, result){
      next(err, result.rows[0]);
      done();
  	});
  });
}

module.exports = {
  getStatsForRound: getStatsForRound,
  getChoice: getChoice,
  getWinsForEachUser: getWinsForEachUser,
  getUserByToken: getUserByToken,
  getChoicesForRound: getChoicesForRound,
  getVotes: getVotes,
  getVotesByRound: getVotesByRound,
  addVote: addVote,
  setWinner: setWinner,
  getWinner: getWinner,
  getWinnerByRound: getWinnerByRound,
  getCurrentRound: getCurrentRound,
  incrementCurrentRound: incrementCurrentRound,
  hasVotedInRound: hasVotedInRound
}<commit_msg>Add getUserByName to database module exports<commit_after>var config = require('./config.js');
var pg = require('pg');
var fs = require('fs');
var path = require('path');

var cfg = config.pg;

pg.on('notice', function(msg) {
  console.log("notice: %j", msg);
});

pg.on('error', function(msg) {
  console.log("error: %j", msg);
});

var getCurrentRound = function(next) {
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }

    var query = 'select * from "round" where is_current = TRUE order by id desc limit 1';
    client.query({text: query}, function(err, result) {
      next(err, result.rows[0]);
      done();
    });
  });
};

var incrementCurrentRound = function (next) {
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    var query = 'update round set is_current=FALSE;\n' +
                'insert into round(is_current) VALUES(TRUE) returning id;';
    client.query({text: query}, function(err, result){
      next(err, result != null ? result.rows[0] : {});
      done();
    });
  });
};

var getChoicesForRoundQuery = fs.readFileSync(path.join(__dirname, 'database/getChoicesForRound.sql'), 'utf-8');
var getChoicesForRound = function(round, next) {
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    var values = [round];
    	client.query({text: getChoicesForRoundQuery, values: values}, function(err, result){
		    next(err, result.rows);
        done();
  	});
  });
};

var getVotesByRoundQuery = fs.readFileSync(path.join(__dirname, 'database/getVotesByRound.sql'), 'utf-8');
var getVotesByRound = function(round, next) {
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    var values = [round];
      client.query({text: getVotesByRoundQuery, values: values}, function(err, result){
        next(err, result.rows);
        done();
    });
  });
};

var getVotesQuery = fs.readFileSync(path.join(__dirname, 'database/getVotes.sql'), 'utf-8');
var getVotes = function (next) {
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    client.query({text: getVotesQuery}, function(err, result){
      next(err, result != null ? result.rows : []);
      done();
    });
  });
};

var hasVotedInRound = function(user, roundId, next) {
  if(!user) {
    next(null, false);
    return;
  }
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    var hasVotedQuery = 'select count(1) from "vote" where user_id = $1 and round_id = $2';
    client.query({text: hasVotedQuery, values: [user.id, roundId]}, function(err, result){
      next(err, result != null ? result.rows[0].count > 0 : false);
      done();
    });
  });
}

var addVote = function (vote, next) {
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    getCurrentRound(function(err, round){
      if(err) { done(); return next(err); }
      var query = 'insert into vote(round_id, choice_id, user_id) values($1, $2, $3)\n '+
                  'on conflict on constraint vote_round_id_user_id_key do update set choice_id = $2\n '+
                  'RETURNING *';
      var values = [round.id, vote.choice_id, vote.user_id];
      client.query({text: query, values: values}, function(err, result){
        next(err, result != null ? result.rows[0] : {});
        done();
      });
    });
  });
};

var setWinner = function (winner, next) {
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    getCurrentRound(function(err, round){
      if(err) { done(); return next(err); }
      var query = 'update round set winning_vote_id = $1, winning_choice_id = $2 where id = $3';
      var values = [winner.vote_id, winner.choice_id, round.id];
      client.query({text: query, values: values}, function(err, result){
        next(err, {});
        done();
      });
    })
  });
};

var getFavouriteByRoundQuery = fs.readFileSync(path.join(__dirname, 'database/getFavouriteByRound.sql'), 'utf-8');
var getFavouriteByRound = function (round, next) {
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    var values = [round];
    client.query({text: getFavouriteByRoundQuery, values: values}, function(err, result){
      next(err, result.rows[0]);
      done();
  	});
  });
}

var getWinnerByRoundQuery = fs.readFileSync(path.join(__dirname, 'database/getWinnerByRound.sql'), 'utf-8');
var getWinnerByRound = function (round, next) {
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    var values = [round];
    client.query({text: getWinnerByRoundQuery, values: values}, function(err, result){
      next(err, result.rows[0]);
      done();
  	});
  });
}

var getWinnerQuery = fs.readFileSync(path.join(__dirname, 'database/getWinner.sql'), 'utf-8');
var getWinner = function (next) {
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    client.query({text: getWinnerQuery}, function(err, result){
      next(err, result.rows[0].winning_choice_id);
      done();
  	});
  });
}

var getUserByToken = function(token, next){
  if(!token) {
    next('No token specified', null);
    return;
  }
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    var query = 'select * from "user" where token = $1 limit 1';
    var values = [token];
    client.query({text: query, values: values}, function(err, result){
      next(err, result.rows[0]);
      done();
  	});
  });
};

var getUserByName = function(name, next){
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    var query = 'select * from "user" where name = $1 limit 1';
    var values = [name];
    client.query({text: query, values: values}, function(err, result){
      next(err, result.rows[0]);
      done();
  	});
  });
};

var getWinsForEachUserQuery = fs.readFileSync(path.join(__dirname, 'database/getWinsForEachUser.sql'), 'utf-8');
var getWinsForEachUser = function(next){
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    client.query({text: getWinsForEachUserQuery}, function(err, result){
      next(err, result.rows);
      done();
  	});
  });
};

var getStatsForRoundQuery = fs.readFileSync(path.join(__dirname, 'database/getStatsForRound.sql'), 'utf-8');
var getStatsForRound = function(round, next){
  pg.connect(cfg, function queryStats(err, client, done) {
    if(err) { done(); return next(err); }
    var values = [round];
    client.query({text: getStatsForRoundQuery, values: values}, function(err, result){
      if (err) { done(); return next(err); }
      var stats = result.rows;

      getWinnerByRound(round, function(err, winner) {
        if (err) { done(); return next(err); }
        else {
          getFavouriteByRound(round, function(err, favourite){
            if (err) { done(); return next(err); }

            var winnerName = winner ? winner.name : "";
            var favName = favourite ? favourite.name : "";
            next(null, {users: stats, round: round, winner: winnerName, popular: favName});
            done();
          });
        }
      });
  	});
  });
};

var getChoice = function (choice, next) {
  pg.connect(cfg, function(err, client, done) {
    if(err) { done(); return next(err); }
    var query = 'select * from choice where id = $1 limit 1;';
    var values = [choice];
    client.query({text: query, values: values}, function(err, result){
      next(err, result.rows[0]);
      done();
  	});
  });
}

module.exports = {
  getStatsForRound: getStatsForRound,
  getChoice: getChoice,
  getWinsForEachUser: getWinsForEachUser,
  getUserByToken: getUserByToken,
  getUserByName: getUserByName,
  getChoicesForRound: getChoicesForRound,
  getVotes: getVotes,
  getVotesByRound: getVotesByRound,
  addVote: addVote,
  setWinner: setWinner,
  getWinner: getWinner,
  getWinnerByRound: getWinnerByRound,
  getCurrentRound: getCurrentRound,
  incrementCurrentRound: incrementCurrentRound,
  hasVotedInRound: hasVotedInRound
}<|endoftext|>