<commit_before>"use strict";
app.controller("userListController", function(
  $scope,
  $state,
  $interval,
  $stateParams,
  RESTService
) {
  $scope.selectedUser = null;

  RESTService.getUsers().then(
    function(response) {
      $scope.users = response.data.users;
    },
    function(err) {
      console.log("Error to retrieve users", err);
    }
  );

  updateCalls();

  $interval(function() {
    updateCalls();
  }, 2000);

  function updateCalls() {
    RESTService.getCallList().then(function(response) {
      $scope.calls = response.data;
      RESTService.getConferenceList().then(
        function(response) {
          $scope.conferences = response.data;
          let selectedUserTmp = {};
          $scope.msg = undefined;
          angular.forEach($scope.users, function(usersVal) {
            usersVal.status = "free";
            if ($stateParams.user === usersVal.text) {
              selectedUserTmp = usersVal;
              if(selectedUserTmp.hasOwnProperty('conferenceSid')){
                delete selectedUserTmp.conferenceSid;
              }
              if(selectedUserTmp.hasOwnProperty('friendlyName')){
                delete selectedUserTmp.friendlyName;
              }
            }
            if(usersVal.hasOwnProperty('conferenceSid')){
              delete usersVal.conferenceSid;
            }
            if(usersVal.hasOwnProperty('friendlyName')){
              delete usersVal.friendlyName;
            }
            if(usersVal.hasOwnProperty('callSid')){
              delete usersVal.callSid;
            }
            angular.forEach($scope.conferences, function(confVal, confKey) {
              angular.forEach(confVal.participants, function(participant) {
                if(selectedUserTmp.hasOwnProperty('number')){
                  if(selectedUserTmp.number === participant.to){
                    selectedUserTmp.conferenceSid = confVal.sid;
                    selectedUserTmp.friendlyName = confVal.friendlyName;
                  }
                }
                if(usersVal.number === participant.to){
                  usersVal.conferenceSid = confVal.sid;
                  usersVal.friendlyName = confVal.friendlyName;
                  usersVal.callSid = participant.callSid;
                }
              });
            });
          });
          angular.forEach($scope.calls, function(callVal, callKey) {
            angular.forEach($scope.users, function(usersVal) {
              if (usersVal.number === callVal.to) {
                usersVal.status = "busy";
              }
              if ($stateParams.user === usersVal.text) {
                selectedUserTmp = usersVal;
                selectedUserTmp.callSid = callVal.sid;
              }
            });
          });
          if(!selectedUserTmp.hasOwnProperty('number')){
            $scope.msg = "There is no user selected";
          }
          $scope.selectedUser = selectedUserTmp;
        },
        function(err) {
          console.log("err", err);
        }
      );
    });
  }

  $scope.call = function(userCalled, userCalling) {
    console.log("calling...");
    let data = {
      called: userCalled,
      user: userCalling
    };
    RESTService.callBetweenClients(data).then(
      function(response) {
        console.log("completed");
      },
      function(err) {
        console.log("err", err);
      }
    );
  };

  $scope.joinConference = function(UserNo) {
    console.log("tranfering...", UserNo);
    let isRequestDone = false;
    if(!$scope.selectedUser.hasOwnProperty('conferenceSid')){
      console.log("Trying to create conference");
      let params = {};
      params.user1 = UserNo;

      params.user2No = $scope.selectedUser.number;
      params.user2CallSid = $scope.selectedUser.callSid;
      angular.forEach($scope.calls, function(value, key) {
        if (value.parentCallSid === $scope.selectedUser.callSid) {
          console.log("found call");
          isRequestDone = true;
          params.clientNo = value.to;
          params.clientCallSid = value.sid;
          RESTService.createConference(params).then(
            function(response) {
              console.log("response", response);
            },
            function(err) {
              console.log("err", err);
            }
          );
        }
      });
    }else{
      console.log("Move to conference");
      let data = {
        conferenceSid: $scope.selectedUser.conferenceSid,
        conferenceName: $scope.selectedUser.friendlyName,
        callNo: UserNo
      };
      isRequestDone = true;
      RESTService.createCallAndJoinConference(data).then(
        function(response) {
          console.log("response", response);
        },
        function(err) {
          console.log("err", err);
        }
      );
    }

    setTimeout(function() {
      if(!isRequestDone){
        $scope.joinConference(UserNo);
      }
    }, 500);
  };

  $scope.resumeCall = function(callSid, confName, confSid) {
    let data = {
      "callSid": callSid,
      "conferenceName": confName,
      "conferenceSid": confSid
    }
    RESTService.resumeCall(data).then(
      function(response) {
        console.log("response", response);
      },
      function(err) {
        console.log("err", err);
      }
    );
  };

});
<commit_msg>Created attempt limit<commit_after>"use strict";
app.controller("userListController", function(
  $scope,
  $state,
  $interval,
  $stateParams,
  RESTService
) {
  $scope.selectedUser = null;

  RESTService.getUsers().then(
    function(response) {
      $scope.users = response.data.users;
    },
    function(err) {
      console.log("Error to retrieve users", err);
    }
  );

  updateCalls();

  $interval(function() {
    updateCalls();
  }, 2000);

  function updateCalls() {
    RESTService.getCallList().then(function(response) {
      $scope.calls = response.data;
      RESTService.getConferenceList().then(
        function(response) {
          $scope.conferences = response.data;
          let selectedUserTmp = {};
          $scope.msg = undefined;
          angular.forEach($scope.users, function(usersVal) {
            usersVal.status = "free";
            if ($stateParams.user === usersVal.text) {
              selectedUserTmp = usersVal;
              if(selectedUserTmp.hasOwnProperty('conferenceSid')){
                delete selectedUserTmp.conferenceSid;
              }
              if(selectedUserTmp.hasOwnProperty('friendlyName')){
                delete selectedUserTmp.friendlyName;
              }
            }
            if(usersVal.hasOwnProperty('conferenceSid')){
              delete usersVal.conferenceSid;
            }
            if(usersVal.hasOwnProperty('friendlyName')){
              delete usersVal.friendlyName;
            }
            if(usersVal.hasOwnProperty('callSid')){
              delete usersVal.callSid;
            }
            angular.forEach($scope.conferences, function(confVal, confKey) {
              angular.forEach(confVal.participants, function(participant) {
                if(selectedUserTmp.hasOwnProperty('number')){
                  if(selectedUserTmp.number === participant.to){
                    selectedUserTmp.conferenceSid = confVal.sid;
                    selectedUserTmp.friendlyName = confVal.friendlyName;
                  }
                }
                if(usersVal.number === participant.to){
                  usersVal.conferenceSid = confVal.sid;
                  usersVal.friendlyName = confVal.friendlyName;
                  usersVal.callSid = participant.callSid;
                }
              });
            });
          });
          angular.forEach($scope.calls, function(callVal, callKey) {
            angular.forEach($scope.users, function(usersVal) {
              if (usersVal.number === callVal.to) {
                usersVal.status = "busy";
              }
              if ($stateParams.user === usersVal.text) {
                selectedUserTmp = usersVal;
                selectedUserTmp.callSid = callVal.sid;
              }
            });
          });
          if(!selectedUserTmp.hasOwnProperty('number')){
            $scope.msg = "There is no user selected";
          }
          $scope.selectedUser = selectedUserTmp;
        },
        function(err) {
          console.log("err", err);
        }
      );
    });
  }

  $scope.call = function(userCalled, userCalling) {
    console.log("calling...");
    let data = {
      called: userCalled,
      user: userCalling
    };
    RESTService.callBetweenClients(data).then(
      function(response) {
        console.log("completed");
      },
      function(err) {
        console.log("err", err);
      }
    );
  };

  const MAX_ATTEMPT = 10;
  let countAttempt = 0;

  $scope.joinConference = function(UserNo) {
    console.log("tranfering...", UserNo);
    let isRequestDone = false;
    if(!$scope.selectedUser.hasOwnProperty('conferenceSid')){
      console.log("Trying to create conference");
      let params = {};
      params.user1 = UserNo;

      params.user2No = $scope.selectedUser.number;
      params.user2CallSid = $scope.selectedUser.callSid;
      angular.forEach($scope.calls, function(value, key) {
        if (value.parentCallSid === $scope.selectedUser.callSid) {
          console.log("found call");
          isRequestDone = true;
          params.clientNo = value.to;
          params.clientCallSid = value.sid;
          RESTService.createConference(params).then(
            function(response) {
              console.log("response", response);
            },
            function(err) {
              console.log("err", err);
            }
          );
        }
      });
    }else{
      console.log("Move to conference");
      let data = {
        conferenceSid: $scope.selectedUser.conferenceSid,
        conferenceName: $scope.selectedUser.friendlyName,
        callNo: UserNo
      };
      isRequestDone = true;
      RESTService.createCallAndJoinConference(data).then(
        function(response) {
          console.log("response", response);
        },
        function(err) {
          console.log("err", err);
        }
      );
    }

    setTimeout(function() {
      console.log("countAttempt", countAttempt);
      console.log("attempts limit", MAX_ATTEMPT);
      if(MAX_ATTEMPT < countAttempt){
        countAttempt = 0;
        console.log("It was not possible to transfer your user, please try again.")
        return;
      }
      if(!isRequestDone){
        countAttempt++;
        $scope.joinConference(UserNo);
      }else{
        countAttempt = 0;
      }
    }, 500);
  };

  $scope.resumeCall = function(callSid, confName, confSid) {
    let data = {
      "callSid": callSid,
      "conferenceName": confName,
      "conferenceSid": confSid
    }
    RESTService.resumeCall(data).then(
      function(response) {
        console.log("response", response);
      },
      function(err) {
        console.log("err", err);
      }
    );
  };

});
<|endoftext|>


<commit_before>var GUI = (function(){ //IIFE for all Views

var TaskView = Backbone.View.extend({
  tagName: 'p',
  className: 'task',
  render: function(){
    console.log('RENDER TaskView!!\n===================');
    console.log('the model im rendering is ', this.model.get('title'));
    var description = this.model.get('title') + '
description: ' + this.model.get('description') + '
creator: ' + this.model.get('creator') + '
assigned to: ' + this.model.get('assignee') + '
status: ' + this.model.get('status');
    this.$el.html(description);
  },
  initialize: function(){
    $('#app').append(this.$el);
  }
});

var UnassignedTasksView = Backbone.View.extend({

// <<<<<<< HEAD
// 	render: function() {
// 		var header = '
Unassigned Tasks View
';
// 		this.$el.html ( header );
// 	},
// 	delete: function() {
// 			this.remove();
// 		},
// 		logout: function() {
// 			console.log("logging out");
// 			// unassigned.remove();
// 			// usertasks.remove();
// 			// this.delete(this.$el);
// 			console.log();
// 			this.render();
// 		}
// });
//
// var UserTasksView = Backbone.View.extend({
// 	render: function() {
// 		var header = '
User Tasks View
';
// 		this.$el.html ( header );
// 	},
// 	delete: function() {
// 			this.remove();
// 		},
// 		logout: function() {
// 			console.log("logging out");
// 			// unassigned.remove();
// 			// usertasks.remove();
// 			// this.delete(this.$el);
// 			console.log();
// 			this.render();
// 		}
// =======

	render: function () {
			// var usernames = UserModel.model.get("value");
			var btn = '<button id="newTask">New</button>';
			this.$el.html('
Unassigned Tasks
' + btn);
	},
	initialize: function () {
			this.listenTo(app.tasks, 'change', this.render);
			this.render();
	},
	events : {
			'click #newTask' : 'newTask'
	},
	newTask: function () {
		console.log('pushed NewTask button');
	},
});

var UserTasksView = Backbone.View.extend({
	render: function () {
			// var usernames = UserModel.model.get("value");
			var btn = '<button id="removeTask">New</button>';
			this.$el.html('
User Tasks
' + btn);
	},
	initialize: function () {
			this.listenTo(app.tasks, 'change', this.render);
			this.render();
	},
	events : {
			'click #removeTask' : 'removeTask'
	},
	removeTask: function () {
		console.log('pushed removeTask button');
	},

});

var UserView = Backbone.View.extend({
	render: function() {
			var logout = '<button id = "logout">Log-Out</button>';
			var header = '
Welcome, '+app.currentUser+'!
';
			var userTasksViewHeader = '
User Tasks View
';
			var userTasksView = new UserTasksView();
			userTasksView.render();
			var unassignedTasksViewHeader = '
Unassigned Tasks View
';
			var unassignedTasksView = new UnassignedTasksView();
			unassignedTasksView.render();
			var stuff = header + logout + userTasksViewHeader + userTasksView + unassignedTasksViewHeader + unassignedTasksView;
			this.$el.html ( stuff );
	},
	events: {
		"click #logout" : "logout"
	},
	logout: function() {
		console.log("logging out");
		// this.$el.empty();
		this.remove();
		app.gui.switchToLogin();
	}
});

var LoginView = Backbone.View.extend({
	render: function() {
		var button = '<button id = "login">Login</button>';
		console.log(app.users.pluck("username"));
		var users = app.users.pluck("username");
		var dropdown = '<select id = "dropdown">'
		users.forEach(function(element){dropdown += "<option>"+element+"</option>";})
		dropdown += ('</select>');
		var title = '
Please Choose A Username
';
		var all =  title + dropdown + button;
		this.$el.html(  all );
	},
	delete: function() {
			this.$el.html('');
	},
	initialize: function() {
		console.log("initializing");
		// this.on("logout", this.delete, this);

	},
	events: {
		"click #logout" : "logout",
		"click #login" : "login"
	},
	login: function() {
		app.currentUser = $('#dropdown').val();
		console.log(app.currentUser);
		console.log("loging in");
    this.remove();
			app.gui.switchToUser();
	},
	logout: function() {
		console.log("logging out");
		this.$el.empty();
		this.remove();
		app.gui.switchToLogin();
	}

});

// generic ctor to represent interface:
function GUI(users,tasks,el) {
	// users is collection of User models
	// tasks is collection of Task models
	// el is selector for where GUI connects in DOM
	this.switchToUser = function (){
		var userView = new UserView();
		userView.render();
		$('#app').append(userView.$el);
	};
	 this.switchToLogin = function() {
		 var login = new LoginView();
		 login.render();
		 $("#app").append(login.$el);
};
	var currentUser = this.currentUser;
this.switchToLogin();

	console.log( 'CONSTRUCTION gui\n===================');

  // users is collection of User models: app.users
  //===================================

  // tasks is collection of Task models: app.tasks
  //===================================
  console.log( 'the task collection is: ', tasks);

  // el is selector for where GUI connects in DOM: #app
  //===================================
  console.log('GUI thinks el is ', el);

  // render each task and append them
  //===================================

  tasks.each( function(task){

    console.log('LOOP tasks.each!!\n=================\n the current task is =>', task);

    console.log( 'task.title: "', task.get('title'), '"' );

    var issue = new TaskView({ model : task });

    console.log('renamed it issue: ', issue)
    issue.render();

  })

}
return GUI;

})();
<commit_msg>made login and logout work with proper views<commit_after>var GUI = (function(){ //IIFE for all Views

var TaskView = Backbone.View.extend({
  tagName: 'p',
  className: 'task',
  render: function(){
    console.log('RENDER TaskView!!\n===================');
    console.log('the model im rendering is ', this.model.get('title'));
    var description = this.model.get('title') + '
description: ' + this.model.get('description') + '
creator: ' + this.model.get('creator') + '
assigned to: ' + this.model.get('assignee') + '
status: ' + this.model.get('status');
    this.$el.html(description);
  },
  initialize: function(){
    $('#app').append(this.$el);
  }
});

var UnassignedTasksView = Backbone.View.extend({
	render: function () {
			// var usernames = UserModel.model.get("value");
			var btn = '<button id="newTask">New</button>';
			this.$el.html('
Unassigned Tasks
' + btn);
	},
	initialize: function () {
			this.listenTo(app.tasks, 'change', this.render);
			this.render();
	},
	events : {
			'click #newTask' : 'newTask'
	},
	newTask: function () {
		console.log('pushed NewTask button');
	},
});

var UserTasksView = Backbone.View.extend({
	render: function () {
			// var usernames = UserModel.model.get("value");
			var btn = '<button id="removeTask">New</button>';
			this.$el.html('
User Tasks
' + btn);
	},
	initialize: function () {
			this.listenTo(app.tasks, 'change', this.render);
			this.render();
	},
	events : {
			'click #removeTask' : 'removeTask'
	},
	removeTask: function () {
		console.log('pushed removeTask button');
	},

});

var UserView = Backbone.View.extend({
	render: function() {
			var logout = '<button id = "logout">Log-Out</button>';
			var header = '
Welcome, '+app.currentUser+'!
';
			var userTasksViewHeader = '
User Tasks View
';
			var userTasksView = new UserTasksView();
			userTasksView.render();
			var unassignedTasksViewHeader = '
Unassigned Tasks View
';
			var unassignedTasksView = new UnassignedTasksView();
			unassignedTasksView.render();
			var stuff = header + logout;
      this.$el.append(unassignedTasksView.$el);
      this.$el.append(userTasksView.$el);
      this.$el.prepend( stuff );
	},
	events: {
		"click #logout" : "logout"
	},
	logout: function() {
		console.log("logging out");
		// this.$el.empty();
    $('#app').html('');
		app.gui.switchToLogin();
	}
});

var LoginView = Backbone.View.extend({
	render: function() {
		var button = '<button id = "login">Login</button>';
		console.log(app.users.pluck("username"));
		var users = app.users.pluck("username");
		var dropdown = '<select id = "dropdown">'
    users.forEach(function(element){dropdown += "<option>"+element+"</option>";})
		dropdown += ('</select>');
		var title = '
Please Choose A Username
';
		var all =  title + dropdown + button;
		this.$el.html(  all );
	},
	delete: function() {
			this.$el.html('');
	},
	initialize: function() {
		console.log("initializing");
		// this.on("logout", this.delete, this);

	},
	events: {
		"click #logout" : "logout",
		"click #login" : "login"
	},
	login: function() {
		app.currentUser = $('#dropdown').val();
		console.log(app.currentUser);
		console.log("loging in");
    this.remove();
			app.gui.switchToUser();
	},
	logout: function() {
		console.log("logging out");
		this.$el.empty();
		this.remove();
		app.gui.switchToLogin();
	}

});

// generic ctor to represent interface:
function GUI(users,tasks,el) {
	// users is collection of User models
	// tasks is collection of Task models
	// el is selector for where GUI connects in DOM
	this.switchToUser = function (){
		var userView = new UserView();
		userView.render();
		$('#app').append(userView.$el);
	};
	 this.switchToLogin = function() {
		 var login = new LoginView();
		 login.render();
		 $("#app").append(login.$el);
};
	var currentUser = this.currentUser;
this.switchToLogin();

	console.log( 'CONSTRUCTION gui\n===================');

  // users is collection of User models: app.users
  //===================================

  // tasks is collection of Task models: app.tasks
  //===================================
  console.log( 'the task collection is: ', tasks);

  // el is selector for where GUI connects in DOM: #app
  //===================================
  console.log('GUI thinks el is ', el);

  // render each task and append them
  //===================================

  // tasks.each( function(task){
  //
  //   console.log('LOOP tasks.each!!\n=================\n the current task is =>', task);
  //
  //   console.log( 'task.title: "', task.get('title'), '"' );
  //
  //   var issue = new TaskView({ model : task });
  //
  //   console.log('renamed it issue: ', issue)
  //   issue.render();
  //
  // })

}
return GUI;

})();
<|endoftext|>


<commit_before>/* requires keymaster.js to be included and key() to be aliased as KEY() in the global namespace */
hqDefine('hqwebapp/js/keyboard_navigator.js', function () {
    var module = {};

    module.focus_in_fn = function($ele) {
        $ele.addClass('hovered');
        $ele.trigger('mouseenter');
        $ele.focus();
    };

    module.focus_out_fn = function($ele) {
        if ($ele) {
            $ele.removeClass('hovered');
            $ele.trigger('mouseleave');
            $ele.blur();
        }
    };

    module.model = function() {
        KEY.setScope('ready');
        var last_mover = '';
        var KeyboardNavigator = function() {
            var self = this;
            self.elements_generated = false;
            self.navigating = false;
            self.prior_scope = false;

            self.init = function(options) {
                self.focus_in_fn = options.focus_in_fn || module.focus_in_fn;
                self.focus_out_fn = options.focus_out_fn || module.focus_out_fn;
                self.action_fn = options.action_fn || self.action_fn;
                self.start_fn = options.start_fn;
                self.stop_fn = options.stop_fn;
                self.leave_context = options.leave_context_fn || self.leave_context;
                self.gen_elements = options.element_list_generator;
                self.reset_index = options.reset_index !== false;

                self.name = options.name || '_unnamed_';
                self.ready_scope = options.ready_scope || 'ready';
                self.nav_key = options.nav_key || 'option';
                self.action_key = options.action_key || 'enter';
                self.forward_keys = options.forward_keys || ['right'];
                self.back_keys = options.back_keys || ['left'];

                self.regen_list_on_exit = options.regen_list_on_exit === true;

                self.macchrome_keycodes = {
                    shift: 16,
                    ctrl: 17,
                    option: 18,
                    command: 91
                };

                $(function() {
                    $(document).keyup(function(event) {
                        if (KEY.getScope() === self.ready_scope) {
                            if ( event.which === self.macchrome_keycodes[self.nav_key] ) {
                                self.leave_nav();
                            }
                        }
                    });

                    KEY(self.nav_key, self.ready_scope, self.enter_nav);

                    var set_up_nav_key_handlers = function(key) {
                        KEY(self.nav_key + '+' + key, self.ready_scope, self.gen_handle_nav(key));
                    };
                    _.each(self.forward_keys, set_up_nav_key_handlers);
                    _.each(self.back_keys, set_up_nav_key_handlers);
                    KEY(self.nav_key + '+' + self.action_key, self.ready_scope, self.handle_action);
                    KEY(self.nav_key + '+' + 'space', self.ready_scope, self.handle_action);
                });
            };

            self.leave_context = function(side) {
                self.set_index(side === 'end' ? 0 : self.$elements.length - 1)
            };

            self.set_index = function(num) {
                if (num < 0) {
                    self.leave_context('beginning');
                } else if (num >= self.$elements.length) {
                    self.leave_context('end');
                } else {
                    self.index = num;
                    self.$active_element = $(self.$elements.get(self.index % self.$elements.length));
                    last_mover = self.name;
                }
            };

            self.enter_nav = function() {
                if (self.regen_list_on_exit || !self.elements_generated) {
                    self.$elements = self.gen_elements();
                    self.elements_generated = true;
                    self.set_index(0);
                }

                if (self.start_fn) {
                    self.start_fn();
                }

                if (self.reset_index) {
                    self.set_index(0);
                }

                console.log('Entering navigation: ' + self.name);
                console.log('Index set to: ' + self.index);
            };

            self.leave_nav = function() {
                console.log('Leaving navigation');

                self.handle_focus_out();
                KEY.setScope(self.ready_scope);
                self.navigating = false;

                if (self.stop_fn) {
                    self.stop_fn();
                }

                if (self.prior_scope) {
                    KEY.setScope(self.prior_scope);
                    self.prior_scope = false;
                }
            };

            self.gen_handle_nav = function(key) {
                return function() {
                    if (!self.navigating) {
                        self.enter_nav();
                    }
                    self.navigating = true;
                    self.handle_focus_out();
                    self.set_index(self.index + (self.forward_keys.indexOf(key) > -1 ? 1 : -1));
                    self.handle_focus_in();
                    return false;
                }
            };

            self.handle_focus_in = function() {
                console.log('hovering over...');
                console.log(self.$active_element.get(0));
                self.focus_in_fn(self.$active_element);
                return false;
            };

            self.handle_focus_out = function() {
                self.focus_out_fn(self.$active_element);
                return false;
            };

            self.action_fn = function($ele) {
                console.log(self);
                console.log($ele);
                $ele.click();
                // .click() only triggers a click event, below handles clicks for elements that have an href
                if ($ele.attr('href') && $ele.attr('href') != '#') {
                    window.location = $ele.attr('href');
                }
            };

            self.handle_action = function() {
                // last_mover is a pseudo-global variable stored in a closure that keeps track of which kn moved last
                // only want to handle the action of this navigator if it was the last mover.
                console.log('action button pressed');
                if (last_mover === self.name) {
                    self.action_fn(self.$active_element);
                    self.leave_nav();
                }
                return false
            };

            self.activate = function() {
                self.prior_scope = KEY.getScope();
                KEY.setScope(self.ready_scope);
                self.enter_nav();
                self.handle_focus_in();
                return false;
            }
        };
        return KeyboardNavigator;
    }();

    return module;
});
<commit_msg>drop logging<commit_after>/* requires keymaster.js to be included and key() to be aliased as KEY() in the global namespace */
hqDefine('hqwebapp/js/keyboard_navigator.js', function () {
    var module = {};

    module.focus_in_fn = function($ele) {
        $ele.addClass('hovered');
        $ele.trigger('mouseenter');
        $ele.focus();
    };

    module.focus_out_fn = function($ele) {
        if ($ele) {
            $ele.removeClass('hovered');
            $ele.trigger('mouseleave');
            $ele.blur();
        }
    };

    module.model = function() {
        KEY.setScope('ready');
        var last_mover = '';
        var KeyboardNavigator = function() {
            var self = this;
            self.elements_generated = false;
            self.navigating = false;
            self.prior_scope = false;

            self.init = function(options) {
                self.focus_in_fn = options.focus_in_fn || module.focus_in_fn;
                self.focus_out_fn = options.focus_out_fn || module.focus_out_fn;
                self.action_fn = options.action_fn || self.action_fn;
                self.start_fn = options.start_fn;
                self.stop_fn = options.stop_fn;
                self.leave_context = options.leave_context_fn || self.leave_context;
                self.gen_elements = options.element_list_generator;
                self.reset_index = options.reset_index !== false;

                self.name = options.name || '_unnamed_';
                self.ready_scope = options.ready_scope || 'ready';
                self.nav_key = options.nav_key || 'option';
                self.action_key = options.action_key || 'enter';
                self.forward_keys = options.forward_keys || ['right'];
                self.back_keys = options.back_keys || ['left'];

                self.regen_list_on_exit = options.regen_list_on_exit === true;

                self.macchrome_keycodes = {
                    shift: 16,
                    ctrl: 17,
                    option: 18,
                    command: 91
                };

                $(function() {
                    $(document).keyup(function(event) {
                        if (KEY.getScope() === self.ready_scope) {
                            if ( event.which === self.macchrome_keycodes[self.nav_key] ) {
                                self.leave_nav();
                            }
                        }
                    });

                    KEY(self.nav_key, self.ready_scope, self.enter_nav);

                    var set_up_nav_key_handlers = function(key) {
                        KEY(self.nav_key + '+' + key, self.ready_scope, self.gen_handle_nav(key));
                    };
                    _.each(self.forward_keys, set_up_nav_key_handlers);
                    _.each(self.back_keys, set_up_nav_key_handlers);
                    KEY(self.nav_key + '+' + self.action_key, self.ready_scope, self.handle_action);
                    KEY(self.nav_key + '+' + 'space', self.ready_scope, self.handle_action);
                });
            };

            self.leave_context = function(side) {
                self.set_index(side === 'end' ? 0 : self.$elements.length - 1)
            };

            self.set_index = function(num) {
                if (num < 0) {
                    self.leave_context('beginning');
                } else if (num >= self.$elements.length) {
                    self.leave_context('end');
                } else {
                    self.index = num;
                    self.$active_element = $(self.$elements.get(self.index % self.$elements.length));
                    last_mover = self.name;
                }
            };

            self.enter_nav = function() {
                if (self.regen_list_on_exit || !self.elements_generated) {
                    self.$elements = self.gen_elements();
                    self.elements_generated = true;
                    self.set_index(0);
                }

                if (self.start_fn) {
                    self.start_fn();
                }

                if (self.reset_index) {
                    self.set_index(0);
                }
            };

            self.leave_nav = function() {
                self.handle_focus_out();
                KEY.setScope(self.ready_scope);
                self.navigating = false;

                if (self.stop_fn) {
                    self.stop_fn();
                }

                if (self.prior_scope) {
                    KEY.setScope(self.prior_scope);
                    self.prior_scope = false;
                }
            };

            self.gen_handle_nav = function(key) {
                return function() {
                    if (!self.navigating) {
                        self.enter_nav();
                    }
                    self.navigating = true;
                    self.handle_focus_out();
                    self.set_index(self.index + (self.forward_keys.indexOf(key) > -1 ? 1 : -1));
                    self.handle_focus_in();
                    return false;
                }
            };

            self.handle_focus_in = function() {
                self.focus_in_fn(self.$active_element);
                return false;
            };

            self.handle_focus_out = function() {
                self.focus_out_fn(self.$active_element);
                return false;
            };

            self.action_fn = function($ele) {
                $ele.click();
                // .click() only triggers a click event, below handles clicks for elements that have an href
                if ($ele.attr('href') && $ele.attr('href') != '#') {
                    window.location = $ele.attr('href');
                }
            };

            self.handle_action = function() {
                // last_mover is a pseudo-global variable stored in a closure that keeps track of which kn moved last
                // only want to handle the action of this navigator if it was the last mover.
                if (last_mover === self.name) {
                    self.action_fn(self.$active_element);
                    self.leave_nav();
                }
                return false
            };

            self.activate = function() {
                self.prior_scope = KEY.getScope();
                KEY.setScope(self.ready_scope);
                self.enter_nav();
                self.handle_focus_in();
                return false;
            }
        };
        return KeyboardNavigator;
    }();

    return module;
});
<|endoftext|>


<commit_before>
module.exports = function(entity, game) {
  game.sounds.play("sfx-water-splash.mp3");
};
<commit_msg>Add water particles<commit_after>var particles = require("splat-ecs/lib/particles");

var water = new particles.Config("debris");
water.arcWidth = Math.PI * 2;
water.lifeSpanMin = 200;
water.lifeSpanMax = 500;
water.qtyMin = 20;
water.qtyMax = 20;
water.sizeMin = 10;
water.sizeMax = 15;
water.spreadType = "even";
water.velocityMin = 0.7;
water.velocityMax = 1.0;

module.exports = function(entity, game) {
  game.sounds.play("sfx-water-splash.mp3");

  var pos = game.entities.get(entity, "position");
  water.origin.x = pos.x + 50;
  water.origin.y = pos.y + 40;
  particles.create(game, water);
};
<|endoftext|>


<commit_before>var midi = require("midi");
var EventEmitter = require('events').EventEmitter;
var util = require('util');

require("./mn-midi.js");

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

var SFindMatching = function(inname, outname)
{
    var device =
    {
      inputs_ : [],
      outputs_ : [],

      getOutput: function (channel)
      {
        var output =
        {
          sendNoteOn : function(note, velocity)
          {
            this.port_.sendMessage(SMakeNoteOn(note, velocity, this.channel_));
          },

          sendNoteOff : function(note, velocity)
          {
            this.port_.sendMessage(SMakeNoteOff(note, 0));
          },

          sendSync : function()
          {
            this.port_.sendMessage([0xF8]);
          },

          sendStart : function()
          {
            this.port_.sendMessage([0xFA]);
          }

        };

        output.channel_ = channel;
        output.port_ = this.outputs_[0];

        return output;
      }
    }

    var lowercaseOutName = inname.toLowerCase();
    var output = new midi.output();
    var count = output.getPortCount();
    for (i=0; i < count; i++)
    {
      var outputName = output.getPortName(i);
      if (outputName.toLowerCase().indexOf(lowercaseOutName) != -1)
      {
        console.log("opening " + outputName);
        var currentOutput = new midi.output();
        currentOutput.openPort(i);
        device.outputs_.push(currentOutput);
      }
    }

    var lowercaseInName = outname.toLowerCase();
    var input = new midi.input();
    var count = input.getPortCount();
    for (i=0; i < count; i++)
    {
      var inputName = input.getPortName(i);
      if (inputName.toLowerCase().indexOf(lowercaseInName) != -1)
      {
        var currentInput = new midi.input();
  /*      currentInput.openPort(i);
        device.inputs_.push(currentInput);
  */    }
    }

    if (device.inputs_.length + device.outputs_.length > 0)
    {
      return device;
    }
}

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

MidiDevice = {

  find : function(name)
  {
    return SFindMatching(name, name);
  }
}

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

NoteStream = function()
{
  EventEmitter.call(this);
  this.notes_ = {};
}

util.inherits(NoteStream, EventEmitter);

NoteStream.prototype.broadcast = function(note, isOn)
{
  this.emit("note", {note: note, velocity:1.0, gate:isOn});
}

NoteStream.prototype.add = function(note, lengthInTick)
{
  if (this.notes_[note] === undefined)
  {
    this.notes_[note] = lengthInTick;
    this.broadcast(note, true);
  }
  else
  {
    this.broadcast(note, false);
    this.broadcast(note, true);
    var length = max(this.notes_[note], lengthInTick);
    this.notes_[note] = length;
  }
}

NoteStream.prototype.tick = function()
{
  for (var note in this.notes_)
  {
    if (this.notes_[note] == 0)
    {
      this.broadcast(note, false);
      delete this.notes_[note];
    }
    else
    {
      this.notes_[note] -= 1;
    }
  }
}

NoteStream.prototype.connect = function(target)
{
  if (target instanceof Function)
  {
    this.on("note", target);
  }
  else
  {
    this.on("note", function()
      {
        target.tick();
      });
  }
}
<commit_msg>Fixed issue with max()<commit_after>var midi = require("midi");
var EventEmitter = require('events').EventEmitter;
var util = require('util');

require("./mn-midi.js");

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

var SFindMatching = function(inname, outname)
{
    var device =
    {
      inputs_ : [],
      outputs_ : [],

      getOutput: function (channel)
      {
        var output =
        {
          sendNoteOn : function(note, velocity)
          {
            this.port_.sendMessage(SMakeNoteOn(note, velocity, this.channel_));
          },

          sendNoteOff : function(note, velocity)
          {
            this.port_.sendMessage(SMakeNoteOff(note, 0));
          },

          sendSync : function()
          {
            this.port_.sendMessage([0xF8]);
          },

          sendStart : function()
          {
            this.port_.sendMessage([0xFA]);
          }

        };

        output.channel_ = channel;
        output.port_ = this.outputs_[0];

        return output;
      }
    }

    var lowercaseOutName = inname.toLowerCase();
    var output = new midi.output();
    var count = output.getPortCount();
    for (i=0; i < count; i++)
    {
      var outputName = output.getPortName(i);
      if (outputName.toLowerCase().indexOf(lowercaseOutName) != -1)
      {
        console.log("opening " + outputName);
        var currentOutput = new midi.output();
        currentOutput.openPort(i);
        device.outputs_.push(currentOutput);
      }
    }

    var lowercaseInName = outname.toLowerCase();
    var input = new midi.input();
    var count = input.getPortCount();
    for (i=0; i < count; i++)
    {
      var inputName = input.getPortName(i);
      if (inputName.toLowerCase().indexOf(lowercaseInName) != -1)
      {
        var currentInput = new midi.input();
  /*      currentInput.openPort(i);
        device.inputs_.push(currentInput);
  */    }
    }

    if (device.inputs_.length + device.outputs_.length > 0)
    {
      return device;
    }
}

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

MidiDevice = {

  find : function(name)
  {
    return SFindMatching(name, name);
  }
}

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

NoteStream = function()
{
  EventEmitter.call(this);
  this.notes_ = {};
}

util.inherits(NoteStream, EventEmitter);

NoteStream.prototype.broadcast = function(note, isOn)
{
  this.emit("note", {note: note, velocity:1.0, gate:isOn});
}

NoteStream.prototype.add = function(note, lengthInTick)
{
  if (this.notes_[note] === undefined)
  {
    this.notes_[note] = lengthInTick;
    this.broadcast(note, true);
  }
  else
  {
    this.broadcast(note, false);
    this.broadcast(note, true);
    var length = Math.max(this.notes_[note], lengthInTick);
    this.notes_[note] = length;
  }
}

NoteStream.prototype.tick = function()
{
  for (var note in this.notes_)
  {
    if (this.notes_[note] == 0)
    {
      this.broadcast(note, false);
      delete this.notes_[note];
    }
    else
    {
      this.notes_[note] -= 1;
    }
  }
}

NoteStream.prototype.connect = function(target)
{
  if (target instanceof Function)
  {
    this.on("note", target);
  }
  else
  {
    this.on("note", function()
      {
        target.tick();
      });
  }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011-2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

/*jslint anon:true, sloppy:true, nomen:true*/
/*global YUI*/

/**
 * Common Library
 * @module CommonLibs
 */
YUI.add('mojito-rest-lib', function(Y, NAME) {

    Y.namespace('mojito.lib');

    /**
     * @private
     */
    function ResponseObject(resp) {
        this._resp = resp;
    }

    ResponseObject.prototype = {
        getStatusCode: function() {
            return this._resp.status;
        },
        getStatusMessage: function() {
            return this._resp.statusText;
        },
        getHeader: function() {
            return this._resp.getResponseHeader.apply(this._resp, arguments);
        },
        getHeaders: function() {
            return this._resp.getAllResponseHeaders();
        },
        getBody: function() {
            return this._resp.responseText;
        }
    };

    /**
     * The Rest module for Mojito provides an easy way to make RESTful calls to
     * URLs without messing about with Y.io.
     * @class REST
     * @namespace Y.mojito.lib
     */
    Y.namespace('mojito.lib').REST = {

        /**
         * Calls IO. Provides mockability
         * @param url
         * @param config the IO configuration
         * @param callback
         * @private
         */
        _doRequest: function (url, config) {
            Y.io(url, config);
        },

        /**
         * Creates the configuration to be passed to the IO request
         *
         * @param {String} method HTTP method
         * @param {String} url HTTP location
         * @param {Object} params Params that are passed in the request
         * @param {Object} config Additional configuration
         * @param {Object} config.headers Headers to be sent with the request
         * @param {Number} config.timeout Timeout for the IO request
         * @param {Function} callback The handler for the response
         * @private
         */
        _makeRequest: function(method, url, params, config, callback) {
            // TODO: [Issue 72] Figure out why 'params' values are attaching
            // themselves to headers!
            var ioConfig = {
                method: method,
                on: {}
            };
            if (params) {
                if (Y.Lang.isObject(params)) {
                    params = Y.QueryString.stringify(params);
                }
                if ('GET' === method) {
                    if (-1 === url.indexOf('?')) {
                        url += '?' + params;
                    } else {
                        url += '&' + params;
                    }
                } else if ('POST' === method || 'PUT' === method) {
                    ioConfig.data = params;
                }
            }
            if (config) {
                ioConfig.headers = config.headers;
                ioConfig.timeout = config.timeout;
            }
            if (callback) {
                ioConfig.on.success = function(txid, resp) {
                    var responseObj = new ResponseObject(resp);
                    callback(null, responseObj);
                };
                ioConfig.on.failure = function(txid, resp) {
                    callback(resp);
                };
            }
            this._doRequest(url, ioConfig);
        },

        /**
         * Makes a RESTful GET request to specified URL
         * @method GET
         * @param {String} url RESTful URL to hit.
         * @param {Object} params parameters to add to the request.
         * @param {Object} config may contain 'headers' or 'timeout' values.
         * @param {Function} callback called with response or error.
         */
        GET: function() {
            var args = ['GET'].concat(Array.prototype.slice.call(arguments));
            this._makeRequest.apply(this, args);
        },

        /**
         * Makes a RESTful POST request to specified URL
         * @method POST
         * @param {String} url RESTful URL to hit.
         * @param {Object} params parameters to add to the request.
         * @param {Object} config may contain 'headers' or 'timeout' values.
         * @param {Function} callback called with response or error.
         */
        POST: function() {
            var args = ['POST'].concat(Array.prototype.slice.call(arguments));
            this._makeRequest.apply(this, args);
        },

        /**
         * Makes a RESTful PUT request to specified URL
         * @method PUT
         * @param {String} url RESTful URL to hit.
         * @param {Object} params parameters to add to the request.
         * @param {Object} config may contain 'headers' or 'timeout' values.
         * @param {Function} callback called with response or error.
         */
        PUT: function() {
            var args = ['PUT'].concat(Array.prototype.slice.call(arguments));
            this._makeRequest.apply(this, args);
        },

        /**
         * Makes a RESTful DELETE request to specified URL
         * @method DELETE
         * @param {String} url RESTful URL to hit.
         * @param {Object} params parameters to add to the request.
         * @param {Object} config may contain 'headers' or 'timeout' values.
         * @param {Function} callback called with response or error.
         */
        DELETE: function() {
            var args = ['DELETE'].concat(Array.prototype.slice.call(arguments));
            this._makeRequest.apply(this, args);
        },

        /**
         * Makes a RESTful HEAD request to specified URL
         * @method HEAD
         * @param {String} url RESTful URL to hit.
         * @param {Object} params parameters to add to the request.
         * @param {Object} config may contain 'headers' or 'timeout' values.
         * @param {Function} callback called with response or error.
         */
        HEAD: function() {
            var args = ['HEAD'].concat(Array.prototype.slice.call(arguments));
            this._makeRequest.apply(this, args);
        }
    };

}, '0.1.0', {requires: [
    'io-base',
    'querystring-stringify-simple',
    'mojito'
]});
<commit_msg>Added @method tags<commit_after>/*
 * Copyright (c) 2011-2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

/*jslint anon:true, sloppy:true, nomen:true*/
/*global YUI*/

/**
 * Common Library
 * @module CommonLibs
 */
YUI.add('mojito-rest-lib', function(Y, NAME) {

    Y.namespace('mojito.lib');

    /**
     * @private
     */
    function ResponseObject(resp) {
        this._resp = resp;
    }

    ResponseObject.prototype = {
        getStatusCode: function() {
            return this._resp.status;
        },
        getStatusMessage: function() {
            return this._resp.statusText;
        },
        getHeader: function() {
            return this._resp.getResponseHeader.apply(this._resp, arguments);
        },
        getHeaders: function() {
            return this._resp.getAllResponseHeaders();
        },
        getBody: function() {
            return this._resp.responseText;
        }
    };

    /**
     * The Rest module for Mojito provides an easy way to make RESTful calls to
     * URLs without messing about with Y.io.
     * @class REST
     * @namespace Y.mojito.lib
     */
    Y.namespace('mojito.lib').REST = {

        /**
         * Calls IO. Provides mockability
         * @method _doRequest
         * @param url
         * @param config the IO configuration
         * @param callback
         * @private
         */
        _doRequest: function (url, config) {
            Y.io(url, config);
        },

        /**
         * Creates the configuration to be passed to the IO request
         * @method _makeRequest
         * @param {String} method HTTP method
         * @param {String} url HTTP location
         * @param {Object} params Params that are passed in the request
         * @param {Object} config Additional configuration
         * @param {Object} config.headers Headers to be sent with the request
         * @param {Number} config.timeout Timeout for the IO request
         * @param {Function} callback The handler for the response
         * @private
         */
        _makeRequest: function(method, url, params, config, callback) {
            // TODO: [Issue 72] Figure out why 'params' values are attaching
            // themselves to headers!
            var ioConfig = {
                method: method,
                on: {}
            };
            if (params) {
                if (Y.Lang.isObject(params)) {
                    params = Y.QueryString.stringify(params);
                }
                if ('GET' === method) {
                    if (-1 === url.indexOf('?')) {
                        url += '?' + params;
                    } else {
                        url += '&' + params;
                    }
                } else if ('POST' === method || 'PUT' === method) {
                    ioConfig.data = params;
                }
            }
            if (config) {
                ioConfig.headers = config.headers;
                ioConfig.timeout = config.timeout;
            }
            if (callback) {
                ioConfig.on.success = function(txid, resp) {
                    var responseObj = new ResponseObject(resp);
                    callback(null, responseObj);
                };
                ioConfig.on.failure = function(txid, resp) {
                    callback(resp);
                };
            }
            this._doRequest(url, ioConfig);
        },

        /**
         * Makes a RESTful GET request to specified URL
         * @method GET
         * @param {String} url RESTful URL to hit.
         * @param {Object} params parameters to add to the request.
         * @param {Object} config may contain 'headers' or 'timeout' values.
         * @param {Function} callback called with response or error.
         */
        GET: function() {
            var args = ['GET'].concat(Array.prototype.slice.call(arguments));
            this._makeRequest.apply(this, args);
        },

        /**
         * Makes a RESTful POST request to specified URL
         * @method POST
         * @param {String} url RESTful URL to hit.
         * @param {Object} params parameters to add to the request.
         * @param {Object} config may contain 'headers' or 'timeout' values.
         * @param {Function} callback called with response or error.
         */
        POST: function() {
            var args = ['POST'].concat(Array.prototype.slice.call(arguments));
            this._makeRequest.apply(this, args);
        },

        /**
         * Makes a RESTful PUT request to specified URL
         * @method PUT
         * @param {String} url RESTful URL to hit.
         * @param {Object} params parameters to add to the request.
         * @param {Object} config may contain 'headers' or 'timeout' values.
         * @param {Function} callback called with response or error.
         */
        PUT: function() {
            var args = ['PUT'].concat(Array.prototype.slice.call(arguments));
            this._makeRequest.apply(this, args);
        },

        /**
         * Makes a RESTful DELETE request to specified URL
         * @method DELETE
         * @param {String} url RESTful URL to hit.
         * @param {Object} params parameters to add to the request.
         * @param {Object} config may contain 'headers' or 'timeout' values.
         * @param {Function} callback called with response or error.
         */
        DELETE: function() {
            var args = ['DELETE'].concat(Array.prototype.slice.call(arguments));
            this._makeRequest.apply(this, args);
        },

        /**
         * Makes a RESTful HEAD request to specified URL
         * @method HEAD
         * @param {String} url RESTful URL to hit.
         * @param {Object} params parameters to add to the request.
         * @param {Object} config may contain 'headers' or 'timeout' values.
         * @param {Function} callback called with response or error.
         */
        HEAD: function() {
            var args = ['HEAD'].concat(Array.prototype.slice.call(arguments));
            this._makeRequest.apply(this, args);
        }
    };

}, '0.1.0', {requires: [
    'io-base',
    'querystring-stringify-simple',
    'mojito'
]});
<|endoftext|>


<commit_before>/* Richard Meadows 2013 */

/* Generates view functions for our CouchDB */

exports = module.exports = function() {

	/* ======== Main ======== */

	return {
		left: {
			map: function (doc) {
				/* If this is a record for the left em channel */
				if (doc.left && doc.time) {
					/* If the time is still in hex format from a direct upload */
					var time;
					if (typeof doc.time === 'string') {
						/*
						 * Parse the time to a number. Note the loss of precision in representing 64 bit time
						 * in javascript. Will become a problem around the year 300 million.
						 */
						time = parseInt(doc.time, 16);
					} else {
						time = doc.time;
					}
					/* If everything is as we expect */
					if (typeof time === 'number' && doc.left.value && typeof doc.left.value === 'number') {
						emit(time, doc.left.value);
					}
				}
			}
		},
		right: {
			map: function (doc) {
				/* If this is a record for the right em channel */
				if (doc.right && doc.time) {
					/* If the time is still in hex format from a direct upload */
					var time;
					if (typeof doc.time === 'string') {
						/*
						 * Parse the time to a number. Note the loss of precision in representing 64 bit time
						 * in javascript. Will become a problem around the year 300 million.
						 */
						time = parseInt(doc.time, 16);
					}
					else {
						time = doc.time;
					}
					/* If everything is as we expect */
					if (typeof time === 'number' && doc.right.value && typeof doc.right.value === 'number') {
						emit(time, doc.right.value);
					}
				}
			}
		},
		battery: {
			map: function (doc) {
				/* If this is a record for the battery */
				if (doc.battery && doc.time) {
					/* If the time is still in hex format from a direct upload */
					var time;
					if (typeof doc.time === 'string') {
						/*
						 * Parse the time to a number. Note the loss of precision in representing 64 bit time
						 * in javascript. Will become a problem around the year 300 million.
						 */
						time = parseInt(doc.time, 16);
					} else {
						time = doc.time;
					}
					/* If everything is as we expect */
					if (typeof time === 'number' && doc.battery.value && typeof doc.battery.value === 'number') {
						/* Compensate for the averaging */
						var adc_value = doc.battery.value/10;
						/* Determine the voltage at the adc pin, given a 1.8V ref and a 10-bit adc */
						var pin_voltage = (adc_value*1.8)/1024;
						/* Compensate for the resistor divider */
						var battery_voltage = pin_voltage*11;
						/* Output to 3 decimal places */
						emit(time, Math.round(battery_voltage*1000)/1000);
					}
				}
			}
		},
		rx_power: {
			map: function (doc) {
				/* If this is a record for the recieved signal strength indicator (rssi) */
				if (doc.rssi && doc.time) {
					/* If the time is still in hex format from a direct upload */
					var time;
					if (typeof doc.time === 'string') {
						/*
						 * Parse the time to a number. Note the loss of precision in representing 64 bit time
						 * in javascript. Will become a problem around the year 300 million.
						 */
						time = parseInt(doc.time, 16);
					} else {
						time = doc.time;
					}
					/* If everything is as we expect */
					if (typeof time === 'number' && doc.rssi.value && typeof doc.rssi.value === 'number') {
						/* Compensate for the averaging */
						var rssi = doc.rssi.value/1;
						/**
						 * Determine the receiver input power. See §6.5.3 of the AT86RF212 datasheet.
						 */
						var rx_power = -98 + (1.03*rssi);
						/* Output to 2 decimal places */
						emit(time, Math.round(rx_power*100)/100);
					}
				}
			}
		}
	};
}();
<commit_msg>Added views for envelope<commit_after>/* Richard Meadows 2013 */

/* Generates view functions for our CouchDB */

exports = module.exports = function() {

	/* ======== Main ======== */

	return {
		left: {
			map: function (doc) {
				/* If this is a record for the left em channel */
				if (doc.left && doc.time) {
					/* If the time is still in hex format from a direct upload */
					var time;
					if (typeof doc.time === 'string') {
						/*
						 * Parse the time to a number. Note the loss of precision in representing 64 bit time
						 * in javascript. Will become a problem around the year 300 million.
						 */
						time = parseInt(doc.time, 16);
					} else {
						time = doc.time;
					}
					/* If everything is as we expect */
					if (typeof time === 'number' && doc.left.value && typeof doc.left.value === 'number') {
						emit(time, doc.left.value);
					}
				}
			}
		},
		right: {
			map: function (doc) {
				/* If this is a record for the right em channel */
				if (doc.right && doc.time) {
					/* If the time is still in hex format from a direct upload */
					var time;
					if (typeof doc.time === 'string') {
						/*
						 * Parse the time to a number. Note the loss of precision in representing 64 bit time
						 * in javascript. Will become a problem around the year 300 million.
						 */
						time = parseInt(doc.time, 16);
					}
					else {
						time = doc.time;
					}
					/* If everything is as we expect */
					if (typeof time === 'number' && doc.right.value && typeof doc.right.value === 'number') {
						emit(time, doc.right.value);
					}
				}
			}
		},
		left_envelope: {
			map: function (doc) {
				/* If this is a record for the left envelope */
				if (doc.left_envelope && doc.time) {
					/* If the time is still in hex format from a direct upload */
					var time;
					if (typeof doc.time === 'string') {
						/*
						 * Parse the time to a number. Note the loss of precision in representing 64 bit time
						 * in javascript. Will become a problem around the year 300 million.
						 */
						time = parseInt(doc.time, 16);
					}
					else {
						time = doc.time;
					}
					/* If everything is as we expect */
					if (typeof time === 'number' && doc.left_envelope.value && typeof doc.left_envelope.value === 'number') {
						emit(time, doc.left_envelope.value);
					}
				}
			}
		},
		right_envelope: {
			map: function (doc) {
				/* If this is a record for the right envelope */
				if (doc.right_envelope && doc.time) {
					/* If the time is still in hex format from a direct upload */
					var time;
					if (typeof doc.time === 'string') {
						/*
						 * Parse the time to a number. Note the loss of precision in representing 64 bit time
						 * in javascript. Will become a problem around the year 300 million.
						 */
						time = parseInt(doc.time, 16);
					}
					else {
						time = doc.time;
					}
					/* If everything is as we expect */
					if (typeof time === 'number' && doc.right_envelope.value && typeof doc.right_envelope.value === 'number') {
						emit(time, doc.right_envelope.value);
					}
				}
			}
		},
		battery: {
			map: function (doc) {
				/* If this is a record for the battery */
				if (doc.battery && doc.time) {
					/* If the time is still in hex format from a direct upload */
					var time;
					if (typeof doc.time === 'string') {
						/*
						 * Parse the time to a number. Note the loss of precision in representing 64 bit time
						 * in javascript. Will become a problem around the year 300 million.
						 */
						time = parseInt(doc.time, 16);
					} else {
						time = doc.time;
					}
					/* If everything is as we expect */
					if (typeof time === 'number' && doc.battery.value && typeof doc.battery.value === 'number') {
						/* Compensate for the averaging */
						var adc_value = doc.battery.value/10;
						/* Determine the voltage at the adc pin, given a 1.8V ref and a 10-bit adc */
						var pin_voltage = (adc_value*1.8)/1024;
						/* Compensate for the resistor divider */
						var battery_voltage = pin_voltage*11;
						/* Output to 3 decimal places */
						emit(time, Math.round(battery_voltage*1000)/1000);
					}
				}
			}
		},
		rx_power: {
			map: function (doc) {
				/* If this is a record for the recieved signal strength indicator (rssi) */
				if (doc.rssi && doc.time) {
					/* If the time is still in hex format from a direct upload */
					var time;
					if (typeof doc.time === 'string') {
						/*
						 * Parse the time to a number. Note the loss of precision in representing 64 bit time
						 * in javascript. Will become a problem around the year 300 million.
						 */
						time = parseInt(doc.time, 16);
					} else {
						time = doc.time;
					}
					/* If everything is as we expect */
					if (typeof time === 'number' && doc.rssi.value && typeof doc.rssi.value === 'number') {
						/* Compensate for the averaging */
						var rssi = doc.rssi.value/1;
						/**
						 * Determine the receiver input power. See §6.5.3 of the AT86RF212 datasheet.
						 */
						var rx_power = -98 + (1.03*rssi);
						/* Output to 2 decimal places */
						emit(time, Math.round(rx_power*100)/100);
					}
				}
			}
		}
	};
}();
<|endoftext|>


<commit_before>/**
*  All Calls is a Node.js sample app that is powered by Usergrid
*  This app shows how to make the 4 REST calls (GET, POST,
*  PUT, DELETE) against the usergrid API.
*
*  Learn more at http://Usergrid.com/docs
*
*   Copyright 2012 Apigee Corporation
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*
*  Some code patterns were pulled from http://www.nodebeginner.org/.  Thank you!
*/
var http = require("http");
var path = require('path');
var url = require("url");
var fs = require('fs');
var sys = require('util');
//include local files
var router = require("./router");
var controller = require("./controller");

//routing info
var handle = {}
handle["/"] = controller.main;
handle["/main"] = controller.main;

//initialze the SDK
var sdk = require("../lib/usergrid.appSDK");
sdk.Usergrid.ApiClient.init('apigee', 'sandbox');

//main server
function start(route, handle) {
  function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    var querydata = url.parse(request.url, true).query;
    console.log("Request for " + pathname + " received.");
    sdk.Usergrid.session.start_session(request, response);

    var filePath = '.' + request.url;
    if (filePath == './')
        filePath = './index.html';
    var extname = path.extname(filePath);
    switch (extname) {
      case '.js':
        contentType = 'text/javascript';
        serveAsset(response, filePath, contentType);
        break;
      case '.css':
        contentType = 'text/css';
        serveAsset(response, filePath, contentType);
        break;
      default:
        //response.writeHead(200, {"Content-Type": "text/html"});
        route(handle, pathname, querydata, response, sdk);
        //response.end();
        break;
    }

    sdk.Usergrid.session.save_session();
  }

  http.createServer(onRequest).listen(8888, '127.0.0.1');
  console.log("Server has started.");
  console.log('Server running at http://127.0.0.1:8888/');
}

function serveAsset(response, filePath, contentType) {
   fs.exists(filePath, function(exists) {
    if (exists) {
      fs.readFile(filePath, function(error, content) {
        if (error) {
          response.writeHead(500);
          response.end();
        }
        else {
          response.writeHead(200, { 'Content-Type': contentType });
          response.end(content, 'utf-8');
        }
      });
    }
    else {
      response.writeHead(404);
      response.end();
    }
  });
}

start(router.route, handle);<commit_msg>removing server address from invocation<commit_after>/**
*  All Calls is a Node.js sample app that is powered by Usergrid
*  This app shows how to make the 4 REST calls (GET, POST,
*  PUT, DELETE) against the usergrid API.
*
*  Learn more at http://Usergrid.com/docs
*
*   Copyright 2012 Apigee Corporation
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*
*  Some code patterns were pulled from http://www.nodebeginner.org/.  Thank you!
*/
var http = require("http");
var path = require('path');
var url = require("url");
var fs = require('fs');
var sys = require('util');
//include local files
var router = require("./router");
var controller = require("./controller");

//routing info
var handle = {}
handle["/"] = controller.main;
handle["/main"] = controller.main;

//initialze the SDK
var sdk = require("../lib/usergrid.appSDK");
sdk.Usergrid.ApiClient.init('apigee', 'sandbox');

//main server
function start(route, handle) {
  function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    var querydata = url.parse(request.url, true).query;
    console.log("Request for " + pathname + " received.");
    sdk.Usergrid.session.start_session(request, response);

    var filePath = '.' + request.url;
    if (filePath == './')
        filePath = './index.html';
    var extname = path.extname(filePath);
    switch (extname) {
      case '.js':
        contentType = 'text/javascript';
        serveAsset(response, filePath, contentType);
        break;
      case '.css':
        contentType = 'text/css';
        serveAsset(response, filePath, contentType);
        break;
      default:
        //response.writeHead(200, {"Content-Type": "text/html"});
        route(handle, pathname, querydata, response, sdk);
        //response.end();
        break;
    }

    sdk.Usergrid.session.save_session();
  }

  //http.createServer(onRequest).listen(8888, '127.0.0.1');
  http.createServer(onRequest).listen(8888);
  console.log("Server has started.");
  console.log('Server running at port 8888');
}

function serveAsset(response, filePath, contentType) {
   fs.exists(filePath, function(exists) {
    if (exists) {
      fs.readFile(filePath, function(error, content) {
        if (error) {
          response.writeHead(500);
          response.end();
        }
        else {
          response.writeHead(200, { 'Content-Type': contentType });
          response.end(content, 'utf-8');
        }
      });
    }
    else {
      response.writeHead(404);
      response.end();
    }
  });
}

start(router.route, handle);<|endoftext|>


<commit_before>var ObjectID = require('mongodb').ObjectID,
    jsonSchema = require('json-schema');

module.exports = function (options) {

    //  Establish required options
    var app = options.app,
        collection = options.collection,
        name = options.name,
        path = options.path,
        schema = options.schema;

    var postTransform = options.postTransform,
        putTransform = options.putTransform;

    //  Build path structure
    var rootObjectPath = path + '/' + name;

    function respondError(res, err, code) {
        res.statusCode = code;
        res.json(err);
    }

    function respondSuccess(res, result) {
        res.statusCode = 200;
        res.json(result);
    }

    //  Build routes
    app.get(rootObjectPath, function (req, res) {
        var cursor = collection.find(),
            sort = req.param('sort'),
            limit = req.param('limit'),
            skip = req.param('skip');

        if (sort) {
            if (sort.match(/^[a-zA-Z]*$/)) cursor.sort(sort);
            else cursor.sort(JSON.parse(sort));
        }
        if (limit) cursor.limit(Number(limit));
        if (limit && skip) cursor.skip(Number(skip));
        cursor.toArray(function (err, documents) {
            if (err) return respondError(res, err, 500);
            else {
                if (limit && skip) cursor.count(function (err, count) {
                    if (err) return respondError(res, err, 500);
                    else respondSuccess(res, {data: documents, total: count});
                });
                else respondSuccess(res, {data: documents, total: documents.length});
            }
        });
    });

    app.get(rootObjectPath + '/:id', function (req, res) {
        collection.findOne({_id: ObjectID(req.params.id)}, function (err, document) {
            if (err) return respondError(res, err, 500);
            respondSuccess(res, document);
        });
    });

    app.post(rootObjectPath, function (req, res) {
        var report = jsonSchema.validate(req.body, schema);
        if (!report.valid) return respondError(res, report.errors, 400);
        if (postTransform) postTransform(req.body);
        collection.insert(req.body, function (err, document) {
            if (err) return respondError(res, err, 500);
            respondSuccess(res, document[0]);
        });
    });

    app.put(rootObjectPath + '/:id', function (req, res) {
        var report = jsonSchema.validate(req.body, schema);
        if (!report.valid) return  respondError(res, report.errors, 400);
        if (putTransform) putTransform(req.body);
        collection.update({_id: ObjectID(req.params.id)}, {$set: req.body}, function (err) {
            if (err) return respondError(res, err, 500);
            respondSuccess(res);
        });
    });

    app.delete(rootObjectPath + '/:id', function (req, res) {
        collection.remove({_id: ObjectID(req.params.id)}, function (err) {
            if (err) return respondError(res, err, 500);
            respondSuccess(res);
        });
    });
};<commit_msg>Added option for applying a default transform to both posts and puts.<commit_after>var ObjectID = require('mongodb').ObjectID,
    jsonSchema = require('json-schema');

module.exports = function (options) {

    //  Establish required options
    var app = options.app,
        collection = options.collection,
        name = options.name,
        path = options.path,
        schema = options.schema;

    var postTransform = (options.postTransform) ? options.postTransform : options.defaultTransform,
        putTransform = (options.putTransform) ? options.putTransform : options.defaultTranform;

    //  Build path structure
    var rootObjectPath = path + '/' + name;

    function respondError(res, err, code) {
        res.statusCode = code;
        res.json(err);
    }

    function respondSuccess(res, result) {
        res.statusCode = 200;
        res.json(result);
    }

    //  Build routes
    app.get(rootObjectPath, function (req, res) {
        var cursor = collection.find(),
            sort = req.param('sort'),
            limit = req.param('limit'),
            skip = req.param('skip');

        if (sort) {
            if (sort.match(/^[a-zA-Z]*$/)) cursor.sort(sort);
            else cursor.sort(JSON.parse(sort));
        }
        if (limit) cursor.limit(Number(limit));
        if (limit && skip) cursor.skip(Number(skip));
        cursor.toArray(function (err, documents) {
            if (err) return respondError(res, err, 500);
            else {
                if (limit && skip) cursor.count(function (err, count) {
                    if (err) return respondError(res, err, 500);
                    else respondSuccess(res, {data: documents, total: count});
                });
                else respondSuccess(res, {data: documents, total: documents.length});
            }
        });
    });

    app.get(rootObjectPath + '/:id', function (req, res) {
        collection.findOne({_id: ObjectID(req.params.id)}, function (err, document) {
            if (err) return respondError(res, err, 500);
            respondSuccess(res, document);
        });
    });

    app.post(rootObjectPath, function (req, res) {
        var report = jsonSchema.validate(req.body, schema);
        if (!report.valid) return respondError(res, report.errors, 400);
        if (postTransform) postTransform(req.body);
        collection.insert(req.body, function (err, document) {
            if (err) return respondError(res, err, 500);
            respondSuccess(res, document[0]);
        });
    });

    app.put(rootObjectPath + '/:id', function (req, res) {
        var report = jsonSchema.validate(req.body, schema);
        if (!report.valid) return  respondError(res, report.errors, 400);
        if (putTransform) putTransform(req.body);
        collection.update({_id: ObjectID(req.params.id)}, {$set: req.body}, function (err) {
            if (err) return respondError(res, err, 500);
            respondSuccess(res);
        });
    });

    app.delete(rootObjectPath + '/:id', function (req, res) {
        collection.remove({_id: ObjectID(req.params.id)}, function (err) {
            if (err) return respondError(res, err, 500);
            respondSuccess(res);
        });
    });
};<|endoftext|>