<commit_before>'use strict';

angular.module('mean.project').controller('ProjectCtrl', ['$scope', '$rootScope', '$http', '$location', '$stateParams', 'Global',
  function($scope,  $rootScope, $http, $location, $stateParams, Global) {
    $scope.global = Global;
    if (!$scope.global.authenticated)
      return $location.url('/');
    $scope.project = {};
    $scope.editingMembers = false;

    $scope.permissionLevels = ['admin', 'general', 'view_only'];

    function findCurrentMember() {
      for (var i = $scope.project.members.length - 1; i >= 0; i-=1) {
        if($scope.project.members[i]._id === $scope.global.user._id)
          return $scope.project.members[i];
      }
      return false;
    }

    function getProject() {
      $http.get('/projects/' + $stateParams.projectId)
        .success(function (res) {
          $scope.project = res;

          // test for empty response
          if (!Object.keys($scope.project).length)
            // for now reroute to home but we should reroute to a custom 404
            $location.url('/');

          // determine the current user's membership on project.
          $scope.currentMember = findCurrentMember();
          if ($scope.currentMember === false)
            // they aren't allowed to see this project
            $location.url('/');
        })
        .error(function () {
          alert('Could not retrieve project :(');
        });
    }
    getProject();
  }
])
.controller('CreateProjectCtrl', ['$scope', '$rootScope', '$http', '$location', 'Global',
  function($scope,  $rootScope, $http, $location, Global) {
    $scope.global = Global;
    if (!$scope.global.authenticated)
      return $location.url('/');

    // This will be the object filled in by the form data
    $scope.project = {};
    $scope.createError = false;

    /* Extra initialization */
    // TODO: should not hard code permissions (they'll be used else-where)
    $scope.permissionLevels = ['admin', 'general', 'view_only'];

    // make current user the project owner
    $scope.project.owner = $scope.global.user._id;

    // add starting current user as first admin user
    $scope.project.members = [
        {
            _id: $scope.global.user._id,
            name: $scope.global.user.name,
            permission: $scope.permissionLevels[0]
        }
    ];

    function validProject() {
      $scope.createError = false;
      if ($scope.project.name === undefined) {
        $scope.createError = 'Project must have a name';
        return false;
      }
      return true;
    }

    $scope.createProject = function() {
      event.preventDefault();
      if(validProject()) {
        $http.post('/projects', $scope.project)
          .success(function(res) {
            console.log(res);
            $location.url('/project/'+res._id);
          })
          .error(function() {
            alert('Could not create your project. Check network connection and try again');
          });
      }
    };

    // if the browser isn't chrome, use jquery-ui for input type date
    if (!window.chrome) {
      if($('input[type=date]')) {
        $('input[type=date]').each(function() {
          $(this).datepicker().datepicker('option', 'dateFormat', 'yy-mm-dd');
        });
      }
    }
  }
])
.controller('TeamMemberCtrl', ['$scope', '$rootScope', '$http', 'Global',
  function($scope, $rootScope, $http, $parent, Global){
    $scope.global = Global;
    $scope.searchText = '';
    $scope.searchError = false;
    $scope.searchUsersResults = [];

    function arrayObjectIndexOf(arr, obj){
      for(var i = 0; i < arr.length; i+=1){
          if(arr[i]._id === obj._id){
              return i;
          }
      }
      return false;
    }

    function filterResults() {
      $scope.project.members.forEach(function (member) {
        var index = arrayObjectIndexOf($scope.searchUsersResults, member);
        if (index !== false) {
          // remove existing members from results
          $scope.searchUsersResults.splice(index, 1);

          // if the results are now empty
          if (!$scope.searchUsersResults.length)
              $scope.searchError = 'No results found';
        }
      });
    }

    $scope.searchForTeamMembers = function() {
      if(!!$scope.searchText) {
        $http({
          url: '/users',
          method: 'GET',
          params: {q: $scope.searchText}
        })
          .success(function(res) {
            $scope.searchError = false;
            $scope.searchUsersResults = res;
            if (!res.length) {
              $scope.searchError = 'No results found';
            } else {
              filterResults();
            }
          })
          .error(function() {
            $scope.searchError = 'Errors occured making your request :(';
          });
      }
    };

    $scope.removeTeamMember = function(member) {
      $scope.project.members.splice(member, 1);
    };

    $scope.addTeamMember = function(member) {
      event.preventDefault();
      $scope.project.members.push({
        _id: member._id,
        name: member.name,
        permission: $scope.permissionLevels[$scope.permissionLevels.indexOf('general')]
      });
      $scope.searchUsersResults.splice(arrayObjectIndexOf($scope.searchUsersResults, member), 1);
    };
}])
.controller('MessageBoardCtrl', ['$scope', '$rootScope', '$http', '$stateParams', 'Global',
  function($scope, $rootScope, $http, $stateParams, Global) {
    $scope.global = Global;
    $scope.messageError = false;
    $scope.messages = [];
    $scope.message = {};
    console.log($scope.project);
    $http.get('/projects/' + $stateParams.projectId + '/messages')
      .success(function (res) {
        $scope.messages = res;
      })
      .error(function (error) {
        $scope.messageError = error;
      });

      $('.messagesDisplay').animate({
            scrollTop: $('.messagesDisplay').get(0).scrollHeight
            }, 1500);

    $scope.addMessage = function () {
      $scope.message.user = $scope.global.user._id;
      $scope.message.project_id = $stateParams.projectId;

      $http.post('/projects/' + $stateParams.projectId + '/messages', $scope.message)
        .success(function (res) {
          $scope.messages.push(res);
          $('[name="post_message"]').val('');
          $('.messagesDisplay').animate({
            scrollTop: $('.messagesDisplay').get(0).scrollHeight
            }, 1500);
        })
        .error(function (error) {
          $scope.messageError = error;
        });
    };

    (function poll(){
      setTimeout(function(){

        $http.get('/projects/' + $stateParams.projectId + '/messages')
          .success(function (res) {
            $scope.messages = res;
          })
          .error(function (error) {
            $scope.messageError = error;
          });

          $('.messagesDisplay').animate({
            scrollTop: $('.messagesDisplay').get(0).scrollHeight
          }, 1500);
      }, 1000);
    })();

}])
.directive('crnMessageBoard', function () {
  return {
    restrict: 'A',
    templateUrl: 'project/views/message-board.html'
  };
})
.directive('crnTeamModifer', function(){
  // Runs during compile
  return {
    restrict: 'A',
    templateUrl: 'project/views/team-finder.html'
  };
});
<commit_msg>minor fix to spacing<commit_after>'use strict';

angular.module('mean.project').controller('ProjectCtrl', ['$scope', '$rootScope', '$http', '$location', '$stateParams', 'Global',
  function($scope,  $rootScope, $http, $location, $stateParams, Global) {
    $scope.global = Global;
    if (!$scope.global.authenticated)
      return $location.url('/');
    $scope.project = {};
    $scope.editingMembers = false;

    $scope.permissionLevels = ['admin', 'general', 'view_only'];

    function findCurrentMember() {
      for (var i = $scope.project.members.length - 1; i >= 0; i-=1) {
        if($scope.project.members[i]._id === $scope.global.user._id)
          return $scope.project.members[i];
      }
      return false;
    }

    function getProject() {
      $http.get('/projects/' + $stateParams.projectId)
        .success(function (res) {
          $scope.project = res;

          // test for empty response
          if (!Object.keys($scope.project).length)
            // for now reroute to home but we should reroute to a custom 404
            $location.url('/');

          // determine the current user's membership on project.
          $scope.currentMember = findCurrentMember();
          if ($scope.currentMember === false)
            // they aren't allowed to see this project
            $location.url('/');
        })
        .error(function () {
          alert('Could not retrieve project :(');
        });
    }
    getProject();
  }
])
.controller('CreateProjectCtrl', ['$scope', '$rootScope', '$http', '$location', 'Global',
  function($scope,  $rootScope, $http, $location, Global) {
    $scope.global = Global;
    if (!$scope.global.authenticated)
      return $location.url('/');

    // This will be the object filled in by the form data
    $scope.project = {};
    $scope.createError = false;

    /* Extra initialization */
    // TODO: should not hard code permissions (they'll be used else-where)
    $scope.permissionLevels = ['admin', 'general', 'view_only'];

    // make current user the project owner
    $scope.project.owner = $scope.global.user._id;

    // add starting current user as first admin user
    $scope.project.members = [
        {
            _id: $scope.global.user._id,
            name: $scope.global.user.name,
            permission: $scope.permissionLevels[0]
        }
    ];

    function validProject() {
      $scope.createError = false;
      if ($scope.project.name === undefined) {
        $scope.createError = 'Project must have a name';
        return false;
      }
      return true;
    }

    $scope.createProject = function() {
      event.preventDefault();
      if(validProject()) {
        $http.post('/projects', $scope.project)
          .success(function(res) {
            console.log(res);
            $location.url('/project/'+res._id);
          })
          .error(function() {
            alert('Could not create your project. Check network connection and try again');
          });
      }
    };

    // if the browser isn't chrome, use jquery-ui for input type date
    if (!window.chrome) {
      if($('input[type=date]')) {
        $('input[type=date]').each(function() {
          $(this).datepicker().datepicker('option', 'dateFormat', 'yy-mm-dd');
        });
      }
    }
  }
])
.controller('TeamMemberCtrl', ['$scope', '$rootScope', '$http', 'Global',
  function($scope, $rootScope, $http, $parent, Global){
    $scope.global = Global;
    $scope.searchText = '';
    $scope.searchError = false;
    $scope.searchUsersResults = [];

    function arrayObjectIndexOf(arr, obj){
      for(var i = 0; i < arr.length; i+=1){
          if(arr[i]._id === obj._id){
              return i;
          }
      }
      return false;
    }

    function filterResults() {
      $scope.project.members.forEach(function (member) {
        var index = arrayObjectIndexOf($scope.searchUsersResults, member);
        if (index !== false) {
          // remove existing members from results
          $scope.searchUsersResults.splice(index, 1);

          // if the results are now empty
          if (!$scope.searchUsersResults.length)
              $scope.searchError = 'No results found';
        }
      });
    }

    $scope.searchForTeamMembers = function() {
      if(!!$scope.searchText) {
        $http({
          url: '/users',
          method: 'GET',
          params: {q: $scope.searchText}
        })
          .success(function(res) {
            $scope.searchError = false;
            $scope.searchUsersResults = res;
            if (!res.length) {
              $scope.searchError = 'No results found';
            } else {
              filterResults();
            }
          })
          .error(function() {
            $scope.searchError = 'Errors occured making your request :(';
          });
      }
    };

    $scope.removeTeamMember = function(member) {
      $scope.project.members.splice(member, 1);
    };

    $scope.addTeamMember = function(member) {
      event.preventDefault();
      $scope.project.members.push({
        _id: member._id,
        name: member.name,
        permission: $scope.permissionLevels[$scope.permissionLevels.indexOf('general')]
      });
      $scope.searchUsersResults.splice(arrayObjectIndexOf($scope.searchUsersResults, member), 1);
    };
}])
.controller('MessageBoardCtrl', ['$scope', '$rootScope', '$http', '$stateParams', 'Global',
  function($scope, $rootScope, $http, $stateParams, Global) {
    $scope.global = Global;
    $scope.messageError = false;
    $scope.messages = [];
    $scope.message = {};
    console.log($scope.project);
    $http.get('/projects/' + $stateParams.projectId + '/messages')
      .success(function (res) {
        $scope.messages = res;
      })
      .error(function (error) {
        $scope.messageError = error;
      });

      $('.messagesDisplay').animate({
            scrollTop: $('.messagesDisplay').get(0).scrollHeight
            }, 1500);

    $scope.addMessage = function () {
      $scope.message.user = $scope.global.user._id;
      $scope.message.project_id = $stateParams.projectId;

      $http.post('/projects/' + $stateParams.projectId + '/messages', $scope.message)
        .success(function (res) {
          $scope.messages.push(res);
          $('[name="post_message"]').val('');
          $('.messagesDisplay').animate({
            scrollTop: $('.messagesDisplay').get(0).scrollHeight
            }, 1500);
        })
        .error(function (error) {
          $scope.messageError = error;
        });
    };

    (function poll(){
      setTimeout(function(){

        $http.get('/projects/' + $stateParams.projectId + '/messages')
          .success(function (res) {
            $scope.messages = res;
          })
          .error(function (error) {
            $scope.messageError = error;
          });

          $('.messagesDisplay').animate({
            scrollTop: $('.messagesDisplay').get(0).scrollHeight
          }, 1500);
      }, 1000);
    })();
}])
.directive('crnMessageBoard', function () {
  return {
    restrict: 'A',
    templateUrl: 'project/views/message-board.html'
  };
})
.directive('crnTeamModifer', function(){
  // Runs during compile
  return {
    restrict: 'A',
    templateUrl: 'project/views/team-finder.html'
  };
});
<|endoftext|>


<commit_before>'use strict';

var should = require('should');
var rewire = require('rewire');
var updateAction = rewire('../../lib/models/updateAction.js');
var chai = require('chai');
var sinon = require('sinon');
var sinonChai = require('sinon-chai');
chai.Should();
chai.use(sinonChai);

var metaExample = {
    'timestamp': '2018-12-05T12:34:32.00Z'
};
var action1 = {
    'type': 'update',
    'parameters': {
        'id':'${id}_NGSIv2Test',
        'type':'NGSIv2TypesTest',
        'version': '2',
        'attributes': [
            {
                'name':'streetLightID',
                'type': 'Text',
                'value': '${id}'
            },
            {
                'name':'illuminanceLevel',
                'type': 'Number',
                'value': '${lastLightIllum}'
            },
            {
                'name':'lastchange',
                'type': 'DateTime',
                'value': '${lastchange}'
            },
            {
                'name':'isonline',
                'type': 'Boolean',
                'value': '${isconnected}',
                'metadata': metaExample
            },
            {
                'name':'district',
                'type': 'Text',
                'value': '${areaServed}'
            },
            {
                'name':'status',
                'type': 'Text',
                'value': '${laststatus}'
            },
            {
                'name':'address',
                'type': 'Address',
                'value': '${streetAddress}, ${addressLocality}'
            },
            {
                'name':'powerState',
                'type': 'Text',
                'value': '${powerState}'
            },
            {
                'name':'ref',
                'type': '${refType}',
                'value': 'futureNull'
            }
        ]
    }
};
var event1 = {
    'ruleName': 'switch_on',
    'id': 'AmbientLightSensor:1',
    'lastLightIllum': 80,
    'isconnected': true,
    'streetAddress': 'Vasagatan 1',
    'addressLocality': 'Stockholm',
    'laststatus': 'allright',
    'powerState':'on',
    'lastchange': '2018-12-05T11:31:39.00Z',
    'subservice': '/',
    'areaServed': 'Stockholm center',
    'service': 'dev_test',
    'refType': 'None',
    'fiwarePerseoContext': {
        'path': '/actions/do',
        'op': '/actions/do',
        'comp': 'perseo-fe',
        'trans': 'f8636710-5fc6-4070-9b1e-8d414fc6522a',
        'corr': 'd5f0a9cc-0258-11e9-b678-0242ac160003; perseocep=15',
        'srv': 'dev_test',
        'subsrv': '/'
    }
};

var expectedChanges = {
    'address': {
        'value': 'Vasagatan 1, Stockholm',
        'type': 'Address'
    },
    'status': {
        'value': 'allright',
        'type': 'Text'
    },
    'ref': {
        'value': null,
        'type': 'None'
    },
    'isonline': {
        'value': true,
        'type': 'Boolean',
        'metadata': metaExample
    },
    'powerState': {
        'value': 'on',
        'type': 'Text'
    },
    'illuminanceLevel': {
        'value': 80,
        'type': 'Number'
    },
    'streetLightID': {
        'value': 'AmbientLightSensor:1',
        'type': 'Text'
    },
    'district': {
        'value': 'Stockholm center',
        'type': 'Text'
    },
    'lastchange': {
        'value': '2018-12-05T11:31:39.00Z',
        'type': 'DateTime'
    },
    'id': 'AmbientLightSensor:1_NGSIv2Test',
    'type': 'NGSIv2TypesTest'
};

describe('doIt', function() {

    describe('#NGSIv2 simple updateAction', function() {

        beforeEach(function () {
        });

        it('should accept NGSIv1 entities', function (done) {

            // Mocks
            var createEntityThen = sinon.spy(function (successCB, errorCB) {
                setTimeout(function () {
                    successCB({'httpCode': '200', 'message': 'all right'}); // success callback
                }, 0);
                return '__TEST';
            });
            var createEntityMock = sinon.spy(
                function (changes, options) {
                    return {'then': createEntityThen};
                }
            );
            var NGSICloseMock = sinon.spy(
                function () {
                    return 'closed';
                }
            );
            var NGSIConnectionMock = sinon.spy(
                function () {
                    return {
                        'v2': {'createEntity': createEntityMock},
                        'close': NGSICloseMock
                    };
                }
            );

            updateAction.__with__({
                'NGSI.Connection': NGSIConnectionMock
            })(function () {
                var callback = function (e, request) {
                    should.exist(request);
                    request.should.not.be.instanceof(Error);
                    should.equal(request.httpCode, 200);
                    createEntityMock.should.be.calledOnceWith(expectedChanges, {upsert: true});
                    done();
                };
                updateAction.doIt(action1, event1, callback);
            });
        });

    });
});<commit_msg>Add more test for update Action<commit_after>'use strict';

var should = require('should');
var rewire = require('rewire');
var updateAction = rewire('../../lib/models/updateAction.js');
var chai = require('chai');
var sinon = require('sinon');
var sinonChai = require('sinon-chai');
chai.Should();
chai.use(sinonChai);

var metaExample = {
    'timestamp': '2018-12-05T12:34:32.00Z'
};
var action1 = {
    'type': 'update',
    'parameters': {
        'version': '2',
        'attributes': [
            {
                'name':'streetLightID',
                'type': 'Text',
                'value': '${id}'
            },
            {
                'name':'illuminanceLevel',
                'type': 'Number',
                'value': '${lastLightIllum}'
            },
            {
                'name':'lastchange',
                'type': 'DateTime',
                'value': '${lastchange}'
            },
            {
                'name':'isonline',
                'type': 'Boolean',
                'value': '${isconnected}',
                'metadata': metaExample
            },
            {
                'name':'district',
                'type': 'Text',
                'value': '${areaServed}'
            },
            {
                'name':'status',
                'type': 'Text',
                'value': '${laststatus}'
            },
            {
                'name':'address',
                'type': 'Address',
                'value': '${streetAddress}, ${addressLocality}'
            },
            {
                'name':'powerState',
                'type': 'Text',
                'value': '${powerState}'
            },
            {
                'name':'ref',
                'type': '${refType}',
                'value': 'futureNull'
            }
        ]
    }
};
var event1 = {
    'ruleName': 'switch_on',
    'id': 'AmbientLightSensor:1',
    'type': 'AmbientLightSensor',
    'lastLightIllum': 80,
    'isconnected': true,
    'streetAddress': 'Vasagatan 1',
    'addressLocality': 'Stockholm',
    'laststatus': 'allright',
    'powerState':'on',
    'lastchange': '2018-12-05T11:31:39.00Z',
    'subservice': '/',
    'areaServed': 'Stockholm center',
    'service': 'dev_test',
    'refType': 'None',
    'fiwarePerseoContext': {
        'path': '/actions/do',
        'op': '/actions/do',
        'comp': 'perseo-fe',
        'trans': 'f8636710-5fc6-4070-9b1e-8d414fc6522a',
        'corr': 'd5f0a9cc-0258-11e9-b678-0242ac160003; perseocep=15',
        'srv': 'dev_test',
        'subsrv': '/'
    }
};

var expectedChanges = {
    'address': {
        'value': 'Vasagatan 1, Stockholm',
        'type': 'Address'
    },
    'status': {
        'value': 'allright',
        'type': 'Text'
    },
    'ref': {
        'value': null,
        'type': 'None'
    },
    'isonline': {
        'value': true,
        'type': 'Boolean',
        'metadata': metaExample
    },
    'powerState': {
        'value': 'on',
        'type': 'Text'
    },
    'illuminanceLevel': {
        'value': 80,
        'type': 'Number'
    },
    'streetLightID': {
        'value': 'AmbientLightSensor:1',
        'type': 'Text'
    },
    'district': {
        'value': 'Stockholm center',
        'type': 'Text'
    },
    'lastchange': {
        'value': '2018-12-05T11:31:39.00Z',
        'type': 'DateTime'
    }
};

describe('doIt', function() {

    describe('#NGSIv2 updateActions', function() {

        beforeEach(function () {
        });

        it('should accept NGSIv2 entities', function (done) {

            // Mocks
            var createEntityThen = sinon.spy(function (successCB, errorCB) {
                setTimeout(function () {
                    successCB({'httpCode': '200', 'message': 'all right'}); // success callback
                }, 0);
                return '__TEST';
            });
            var createEntityMock = sinon.spy(
                function (changes, options) {
                    return {'then': createEntityThen};
                }
            );
            var NGSICloseMock = sinon.spy(
                function () {
                    return 'closed';
                }
            );
            var NGSIConnectionMock = sinon.spy(
                function () {
                    return {
                        'v2': {'createEntity': createEntityMock},
                        'close': NGSICloseMock
                    };
                }
            );

            updateAction.__with__({
                'NGSI.Connection': NGSIConnectionMock
            })(function () {
                var callback = function (e, request) {
                    should.exist(request);
                    should.not.exist(e);
                    should.equal(request.httpCode, 200);
                    expectedChanges.id = 'AmbientLightSensor:1_NGSIv2Test';
                    expectedChanges.type = 'NGSIv2TypesTest';
                    createEntityMock.should.be.calledOnceWith(expectedChanges, {upsert: true});
                    done();
                };
                action1.parameters.id = '${id}_NGSIv2Test';
                action1.parameters.type = 'NGSIv2TypesTest';
                updateAction.doIt(action1, event1, callback);
            });
        });

        it('should accept NGSIv2 entities without type and id', function (done) {

            // Mocks
            var createEntityThen = sinon.spy(function (successCB, errorCB) {
                setTimeout(function () {
                    successCB({'httpCode': '200', 'message': 'all right'}); // success callback
                }, 0);
                return '__TEST';
            });
            var createEntityMock = sinon.spy(
                function (changes, options) {
                    return {'then': createEntityThen};
                }
            );
            var NGSICloseMock = sinon.spy(
                function () {
                    return 'closed';
                }
            );
            var NGSIConnectionMock = sinon.spy(
                function () {
                    return {
                        'v2': {'createEntity': createEntityMock},
                        'close': NGSICloseMock
                    };
                }
            );

            updateAction.__with__({
                'NGSI.Connection': NGSIConnectionMock
            })(function () {
                var callback = function (e, request) {
                    should.exist(request);
                    should.not.exist(e);
                    should.equal(request.httpCode, 200);
                    expectedChanges.id = 'AmbientLightSensor:1';
                    expectedChanges.type = 'AmbientLightSensor';
                    createEntityMock.should.be.calledOnceWith(expectedChanges, {upsert: true});
                    done();
                };
                delete action1.parameters.id;
                delete action1.parameters.type;
                updateAction.doIt(action1, event1, callback);
            });
        });

        it('should control failed update actions', function (done) {

            // Mocks
            var theCBError = new Error();
            var createEntityThen = sinon.spy(function (successCB, errorCB) {
                setTimeout(function () {
                    errorCB(theCBError); // success callback
                }, 0);
                return '__TEST';
            });
            var createEntityMock = sinon.spy(
                function (changes, options) {
                    return {'then': createEntityThen};
                }
            );
            var NGSICloseMock = sinon.spy(
                function () {
                    return 'closed';
                }
            );
            var NGSIConnectionMock = sinon.spy(
                function () {
                    return {
                        'v2': {'createEntity': createEntityMock},
                        'close': NGSICloseMock
                    };
                }
            );

            updateAction.__with__({
                'NGSI.Connection': NGSIConnectionMock
            })(function () {
                var callback = function (e, request) {
                    should.not.exist(request);
                    should.exist(e);
                    e.should.be.instanceof(Error);
                    expectedChanges.id = 'AmbientLightSensor:1_NGSIv2Test';
                    expectedChanges.type = 'NGSIv2TypesTest';
                    createEntityMock.should.be.calledOnceWith(expectedChanges, {upsert: true});
                    done();
                };
                action1.parameters.id = '${id}_NGSIv2Test';
                action1.parameters.type = 'NGSIv2TypesTest';
                updateAction.doIt(action1, event1, callback);
            });
        });

    });
});<|endoftext|>


<commit_before>var JS_GAME = {};

JS_GAME.game = (function () {
  var isKeyDown = [];
  var context;
  var userData = [];
  var enemies = [];
  var enemyStride = 7;
  var frameLength = 1;// in milliseconds
  var socket;
  var connected = false;
  var user = "";
  var pass = "";
  var windowWidth = $(window).innerWidth();
  var windowHeight = $(window).innerHeight();
  var textures = new Object();

  function init() {

    user = document.getElementById("loginInfo").user.value;
    pass = document.getElementById("loginInfo").pass.value;
    if (user.indexOf(",") >= 0 || user.indexOf(":") >= 0){
      document.getElementById("loginInfo").user.value = "INVALID INPUT";
      return;
    }

    socket = new WebSocket("ws:167.88.120.57:38734");

    socket.onopen = function() {
      connected = true;
      socket.send("login:" + user + "," + pass);
    };

    socket.onmessage = function(message) {
      if (message.data.indexOf("pos") == 0){
        userData = message.data.split(":")[1].split(",");
        for (i = 0; i < 4; i++) {
          userData[i] = Number(userData[i]);
        }
      } else if (message.data.indexOf("dat") == 0){
        enemies = message.data.split(":")[1].split(",");
        enemyStride = Number(message.data.split(":")[0].replace("dat", ""));
      }
    };

    socket.onclose = function() {
      window.location.reload(false);
    };

    socket.onerror = function() {

    };

    $("body").empty();

    for (i = 0; i < 256; i++){
      isKeyDown[i] = false;
    }
    $('body').append('<canvas id="GameCanvas">');
    canvasElement = $('#GameCanvas');
    canvasElement.attr({
      width: windowWidth,
      height: windowHeight,
      tabIndex: 0,
      onblur: clearInput,
    }).focus();
    window.onblur = clearInput;

    var canvas = canvasElement[0];

    window.addEventListener( "keydown", keyPress, false);
    window.addEventListener( "keyup", keyRelease, false);
    context = canvas.getContext('2d');
    context.globalCompositeOperation = "normal";
    gameLoop();

    $(window).resize(function() {
      windowWidth = $(window).innerWidth();
      windowHeight = $(window).innerHeight();

      canvasElement.attr({
        width: windowWidth,
        height: windowHeight
      });
    });
  }

  function gameLoop() {
    var keyData = "";
    for (i = 0; i < 256; i++){
      keyData += isKeyDown[i] ? 1 : 0;
    }
    try {
      socket.send("keys:" + keyData);
    } catch (err) {
    }
    context.clearRect(0, 0, windowWidth, windowHeight);
    context.fillStyle = "#FFFFFF"
    context.fillRect(0, 0, windowWidth, windowHeight);

    //draw enemies
    for (i = 0; i < enemies.length; i += enemyStride){
      context.fillStyle = enemies[i+4];
      context.drawImage(getImageMasked("player", enemies[i+4]),gPIVX(enemies[i]), gPIVY(enemies[i+1]), enemies[i+2], enemies[i+3]);
    }

    //draw enemy names
    for (i = 0; i < enemies.length; i += enemyStride){
      context.fillStyle = enemies[i+4];
      context.fillText(enemies[i+5],(gPIVX(enemies[i]) - (context.measureText(enemies[i+5]).width / 2)) + 15,gPIVY(enemies[i+1]) - 5);
    }

    //draw player name
    //context.fillStyle = userData[4];
    //context.font = "15px Arial";
    //context.fillText(userData[5],(gPIVX(userData[0]) - (context.measureText(userData[5]).width / 2)) + 15,gPIVY(userData[1]) - 5);

    setTimeout(gameLoop, frameLength);
  }

  function gPIVX(x){
    //getPositionInViewportX
    var ret = new Object();
    return ((x - (userData[0] + userData[2])) + (windowWidth / 2.0));
  }
  function gPIVY(y){
    //getPositionInViewportY
    return ((y - (userData[1] + userData[3])) + (windowHeight / 2.0));
  }

  function clearInput(){
    for (i = 0; i < 256; i++){
      isKeyDown[i] = false;
    }
  }

  function keyPress(e){
    e.preventDefault();
    isKeyDown[e.keyCode] = true;
    return false;
  }
  function keyRelease(e){
    e.preventDefault();
    isKeyDown[e.keyCode] = false;
  }
  function isKeyPressed(c){
    return isKeyDown[c.charCodeAt(0)];
  }

  function getImageData(image){
    var tempCanv = document.createElement('canvas');
    tempCanv.width = image.width;
    tempCanv.height = image.height;
    var tempCTX = tempCanv.getContext('2d');
    tempCTX.drawImage(image, 0, 0, image.width, image.height);
    return tempCTX.getImageData(0, 0, image.width, image.height);
  }

  function getImage(name){
  	if ((name) in textures){
  		return textures[name];
  	} else {
  		textures[name] = new Image;
  		textures[name].src = 'http://monolc.com/FellJS/res/' + name + '.png';
  		return textures[name];
  	}
  }
  function getImageMasked(name, color){
  	if ((name + "-mask" + color) in textures){
  		return textures[name + "-mask" + color];
  	}
    var image = getImage(name);
    var mask = getImage(name + "-mask");
    if (image.width == 0 || image.height == 0 || mask.width == 0 || mask.height == 0){
      return new Image();
    }
    var maskData = getImageData(mask);
    var regex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
    var colorRGBS = regex.exec(color);
    var colorRGB = [];
    for (i = 0; i < 3; i++){
      colorRGB[i] = parseInt(colorRGBS[i], 16);
    }
    for (i = 0; i < maskData.data.length; i+=4){
      maskData.data[i] =  colorRGB[0];
      maskData.data[i+1] =  colorRGB[1];
      maskData.data[i+2] =  colorRGB[2];
    }
    var tempCanv = document.createElement('canvas');
    tempCanv.width = image.width;
    tempCanv.height = image.height;
    var tempCTX=tempCanv.getContext("2d");
    tempCTX.drawImage(image,0,0,image.width, image.height);
    tempCTX.putImageData(maskData, 0, 0)
    var ret = new Image();
    ret.src = tempCanv.toDataURL("image/png");
    textures[name + "-mask" + color] = ret;
    return ret;
  }

  return {
    init: init
  };
})();

$(document).ready(function() {
  $("#loginInfo").submit(function(e){
    e.preventDefault();
    JS_GAME.game.init();
    return false;
  });
});
<commit_msg>logging<commit_after>var JS_GAME = {};

JS_GAME.game = (function () {
  var isKeyDown = [];
  var context;
  var userData = [];
  var enemies = [];
  var enemyStride = 7;
  var frameLength = 1;// in milliseconds
  var socket;
  var connected = false;
  var user = "";
  var pass = "";
  var windowWidth = $(window).innerWidth();
  var windowHeight = $(window).innerHeight();
  var textures = new Object();

  function init() {

    user = document.getElementById("loginInfo").user.value;
    pass = document.getElementById("loginInfo").pass.value;
    if (user.indexOf(",") >= 0 || user.indexOf(":") >= 0){
      document.getElementById("loginInfo").user.value = "INVALID INPUT";
      return;
    }

    socket = new WebSocket("ws:167.88.120.57:38734");

    socket.onopen = function() {
      connected = true;
      socket.send("login:" + user + "," + pass);
    };

    socket.onmessage = function(message) {
      if (message.data.indexOf("pos") == 0){
        userData = message.data.split(":")[1].split(",");
        for (i = 0; i < 4; i++) {
          userData[i] = Number(userData[i]);
        }
      } else if (message.data.indexOf("dat") == 0){
        enemies = message.data.split(":")[1].split(",");
        enemyStride = Number(message.data.split(":")[0].replace("dat", ""));
      }
    };

    socket.onclose = function() {
      window.location.reload(false);
    };

    socket.onerror = function() {

    };

    $("body").empty();

    for (i = 0; i < 256; i++){
      isKeyDown[i] = false;
    }
    $('body').append('<canvas id="GameCanvas">');
    canvasElement = $('#GameCanvas');
    canvasElement.attr({
      width: windowWidth,
      height: windowHeight,
      tabIndex: 0,
      onblur: clearInput,
    }).focus();
    window.onblur = clearInput;

    var canvas = canvasElement[0];

    window.addEventListener( "keydown", keyPress, false);
    window.addEventListener( "keyup", keyRelease, false);
    context = canvas.getContext('2d');
    context.globalCompositeOperation = "normal";
    gameLoop();

    $(window).resize(function() {
      windowWidth = $(window).innerWidth();
      windowHeight = $(window).innerHeight();

      canvasElement.attr({
        width: windowWidth,
        height: windowHeight
      });
    });
  }

  function gameLoop() {
    var keyData = "";
    for (i = 0; i < 256; i++){
      keyData += isKeyDown[i] ? 1 : 0;
    }
    try {
      socket.send("keys:" + keyData);
    } catch (err) {
    }
    context.clearRect(0, 0, windowWidth, windowHeight);
    context.fillStyle = "#FFFFFF"
    context.fillRect(0, 0, windowWidth, windowHeight);

    //draw enemies
    for (i = 0; i < enemies.length; i += enemyStride){
      context.fillStyle = enemies[i+4];
      context.drawImage(getImageMasked("player", enemies[i+4]),gPIVX(enemies[i]), gPIVY(enemies[i+1]), enemies[i+2], enemies[i+3]);
    }

    //draw enemy names
    for (i = 0; i < enemies.length; i += enemyStride){
      context.fillStyle = enemies[i+4];
      context.fillText(enemies[i+5],(gPIVX(enemies[i]) - (context.measureText(enemies[i+5]).width / 2)) + 15,gPIVY(enemies[i+1]) - 5);
    }

    //draw player name
    //context.fillStyle = userData[4];
    //context.font = "15px Arial";
    //context.fillText(userData[5],(gPIVX(userData[0]) - (context.measureText(userData[5]).width / 2)) + 15,gPIVY(userData[1]) - 5);

    setTimeout(gameLoop, frameLength);
  }

  function gPIVX(x){
    //getPositionInViewportX
    var ret = new Object();
    return ((x - (userData[0] + userData[2])) + (windowWidth / 2.0));
  }
  function gPIVY(y){
    //getPositionInViewportY
    return ((y - (userData[1] + userData[3])) + (windowHeight / 2.0));
  }

  function clearInput(){
    for (i = 0; i < 256; i++){
      isKeyDown[i] = false;
    }
  }

  function keyPress(e){
    e.preventDefault();
    isKeyDown[e.keyCode] = true;
    return false;
  }
  function keyRelease(e){
    e.preventDefault();
    isKeyDown[e.keyCode] = false;
  }
  function isKeyPressed(c){
    return isKeyDown[c.charCodeAt(0)];
  }

  function getImageData(image){
    var tempCanv = document.createElement('canvas');
    tempCanv.width = image.width;
    tempCanv.height = image.height;
    var tempCTX = tempCanv.getContext('2d');
    tempCTX.drawImage(image, 0, 0, image.width, image.height);
    return tempCTX.getImageData(0, 0, image.width, image.height);
  }

  function getImage(name){
  	if ((name) in textures){
  		return textures[name];
  	} else {
  		textures[name] = new Image;
  		textures[name].src = 'http://monolc.com/FellJS/res/' + name + '.png';
  		return textures[name];
  	}
  }
  function getImageMasked(name, color){
  	if ((name + "-mask" + color) in textures){
  		return textures[name + "-mask" + color];
  	}
    var image = getImage(name);
    var mask = getImage(name + "-mask");
    if (image.width == 0 || image.height == 0 || mask.width == 0 || mask.height == 0){
      return new Image();
    }
    var maskData = getImageData(mask);
    var regex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
    console.log(color + "|" + colorRGBS[0] + "|" + colorRGBS[1] + "|" + colorRGBS[2] + "|" + colorRGBS[3])
    var colorRGBS = regex.exec(color);
    var colorRGB = [];
    for (i = 0; i < 3; i++){
      colorRGB[i] = parseInt(colorRGBS[i], 16);
    }
    for (i = 0; i < maskData.data.length; i+=4){
      maskData.data[i] =  colorRGB[0];
      maskData.data[i+1] =  colorRGB[1];
      maskData.data[i+2] =  colorRGB[2];
    }
    var tempCanv = document.createElement('canvas');
    tempCanv.width = image.width;
    tempCanv.height = image.height;
    var tempCTX=tempCanv.getContext("2d");
    tempCTX.drawImage(image,0,0,image.width, image.height);
    tempCTX.putImageData(maskData, 0, 0)
    var ret = new Image();
    ret.src = tempCanv.toDataURL("image/png");
    textures[name + "-mask" + color] = ret;
    return ret;
  }

  return {
    init: init
  };
})();

$(document).ready(function() {
  $("#loginInfo").submit(function(e){
    e.preventDefault();
    JS_GAME.game.init();
    return false;
  });
});
<|endoftext|>


<commit_before>var global = (typeof window !== 'undefined') ? window : {},
    Ember = global.Ember;

/**
  __The session provides access to the current authentication state as well as
  any data the authenticator resolved with__ (see
  [`Authenticators.Base#authenticate`](#SimpleAuth-Authenticators-Base-authenticate)).
  It is created when Ember Simple Auth is set up and __injected into all
  controllers and routes so that these parts of the application can always
  access the current authentication state and other data__, depending on the
  authenticator in use and whether the session is actually authenticated (see
  [`Authenticators.Base`](#SimpleAuth-Authenticators-Base)).

  The session also provides methods to authenticate and to invalidate itself
  (see
  [`Session#authenticate`](#SimpleAuth-Session-authenticate),
  [`Session#invaldiate`](#SimpleAuth-Session-invaldiate)).
  These methods are usually invoked through actions from routes or controllers.
  To authenticate the session manually, simple call the
  [`Session#authenticate`](#SimpleAuth-Session-authenticate)
  method with the authenticator factory to use as well as any options the
  authenticator needs to authenticate the session:

  ```javascript
  this.get('session').authenticate('authenticator:custom', { some: 'option' }).then(function() {
    // authentication was successful
  }, function() {
    // authentication failed
  });
  ```

  The session also observes the store and - if it is authenticated - the
  authenticator for changes (see
  [`Authenticators.Base`](#SimpleAuth-Authenticators-Base)
  end [`Stores.Base`](#SimpleAuth-Stores-Base)).

  @class Session
  @namespace SimpleAuth
  @module simple-auth/session
  @extends Ember.ObjectProxy
  @uses Ember.Evented
*/
export default Ember.ObjectProxy.extend(Ember.Evented, {
  /**
    Triggered __whenever the session is successfully authenticated__. When the
    application uses the
    [`ApplicationRouteMixin` mixin](#SimpleAuth-ApplicationRouteMixin),
    [`ApplicationRouteMixin.actions#sessionAuthenticationSucceeded`](#SimpleAuth-ApplicationRouteMixin-sessionAuthenticationSucceeded)
    will be invoked whenever this event is triggered.

    @event sessionAuthenticationSucceeded
  */
  /**
    Triggered __whenever an attempt to authenticate the session fails__. When
    the application uses the
    [`ApplicationRouteMixin` mixin](#SimpleAuth-ApplicationRouteMixin),
    [`ApplicationRouteMixin.actions#sessionAuthenticationFailed`](#SimpleAuth-ApplicationRouteMixin-sessionAuthenticationFailed)
    will be invoked whenever this event is triggered.

    @event sessionAuthenticationFailed
    @param {Object} error The error object; this depends on the authenticator in use, see [SimpleAuth.Authenticators.Base#authenticate](#SimpleAuth-Authenticators-Base-authenticate)
  */
  /**
    Triggered __whenever the session is successfully invalidated__. When the
    application uses the
    [`ApplicationRouteMixin` mixin](#SimpleAuth-ApplicationRouteMixin),
    [`ApplicationRouteMixin.actions#sessionInvalidationSucceeded`](#SimpleAuth-ApplicationRouteMixin-sessionInvalidationSucceeded)
    will be invoked whenever this event is triggered.

    @event sessionInvalidationSucceeded
  */
  /**
    Triggered __whenever an attempt to invalidate the session fails__. When the
    application uses the
    [`ApplicationRouteMixin` mixin](#SimpleAuth-ApplicationRouteMixin),
    [`ApplicationRouteMixin.actions#sessionInvalidationFailed`](#SimpleAuth-ApplicationRouteMixin-sessionInvalidationFailed)
    will be invoked whenever this event is triggered.

    @event sessionInvalidationFailed
    @param {Object} error The error object; this depends on the authenticator in use, see [SimpleAuth.Authenticators.Base#invalidate](#SimpleAuth-Authenticators-Base-invalidate)
  */
  /**
    Triggered __whenever the server rejects the authorization information
    passed with a request and responds with status 401__. When the application
    uses the
    [`ApplicationRouteMixin` mixin](#SimpleAuth-ApplicationRouteMixin),
    [`ApplicationRouteMixin.actions#authorizationFailed`](#SimpleAuth-ApplicationRouteMixin-authorizationFailed)
    will be invoked whenever this event is triggered.

    @event authorizationFailed
  */

  /**
    The authenticator factory to use as it is registered with Ember's
    container, see
    [Ember's API docs](http://emberjs.com/api/classes/Ember.Application.html#method_register).
    This is only set when the session is currently authenticated.

    @property authenticator
    @type String
    @readOnly
    @default null
  */
  authenticator: null,
  /**
    The store used to persist session properties.

    @property store
    @type SimpleAuth.Stores.Base
    @readOnly
    @default null
  */
  store: null,
  /**
    Returns whether the session is currently authenticated.

    @property isAuthenticated
    @type Boolean
    @readOnly
    @default false
  */
  isAuthenticated: false,
  /**
    @property attemptedTransition
    @private
  */
  attemptedTransition: null,
  /**
    @property content
    @private
  */
  content: {},

  /**
    @method init
    @private
  */
  init: function() {
    this.bindToStoreEvents();
  },

  /**
    Authenticates the session with an `authenticator` and appropriate
    `options`. __This delegates the actual authentication work to the
    `authenticator`__ and handles the returned promise accordingly (see
    [`Authenticators.Base#authenticate`](#SimpleAuth-Authenticators-Base-authenticate)).
    All data the authenticator resolves with will be saved in the session.

    __This method returns a promise itself. A resolving promise indicates that
    the session was successfully authenticated__ while a rejecting promise
    indicates that authentication failed and the session remains
    unauthenticated.

    @method authenticate
    @param {String} authenticator The authenticator factory to use as it is registered with Ember's container, see [Ember's API docs](http://emberjs.com/api/classes/Ember.Application.html#method_register)
    @param {Object} options The options to pass to the authenticator; depending on the type of authenticator these might be a set of credentials, a Facebook OAuth Token, etc.
    @return {Ember.RSVP.Promise} A promise that resolves when the session was authenticated successfully
  */
  authenticate: function(authenticator, options) {
    Ember.assert('Session#authenticate requires the authenticator factory to be specified, was ' + authenticator, !Ember.isEmpty(authenticator));
    var _this = this;
    return new Ember.RSVP.Promise(function(resolve, reject) {
      _this.container.lookup(authenticator).authenticate(options).then(function(content) {
        _this.setup(authenticator, content, true);
        resolve();
      }, function(error) {
        _this.clear();
        _this.trigger('sessionAuthenticationFailed', error);
        reject(error);
      });
    });
  },

  /**
    Invalidates the session with the authenticator it is currently
    authenticated with (see
    [`Session#authenticator`](#SimpleAuth-Session-authenticator)). __This
    invokes the authenticator's `invalidate` method and handles the returned
    promise accordingly__ (see
    [`Authenticators.Base#invalidate`](#SimpleAuth-Authenticators-Base-invalidate)).

    __This method returns a promise itself. A resolving promise indicates that
    the session was successfully invalidated__ while a rejecting promise
    indicates that the promise returned by the `authenticator` rejected and
    thus invalidation was cancelled. In that case the session remains
    authenticated. Once the session is successfully invalidated it clears all
    of its data.

    @method invalidate
    @return {Ember.RSVP.Promise} A promise that resolves when the session was invalidated successfully
  */
  invalidate: function() {
    var _this = this;
    return new Ember.RSVP.Promise(function(resolve, reject) {
      var authenticator = _this.container.lookup(_this.authenticator);
      authenticator.invalidate(_this.content).then(function() {
        authenticator.off('sessionDataUpdated');
        _this.clear(true);
        resolve();
      }, function(error) {
        _this.trigger('sessionInvalidationFailed', error);
        reject(error);
      });
    });
  },

  /**
    @method restore
    @private
  */
  restore: function() {
    var _this = this;
    return new Ember.RSVP.Promise(function(resolve, reject) {
      var restoredContent = _this.store.restore();
      var authenticator   = restoredContent.authenticator;
      if (!!authenticator) {
        delete restoredContent.authenticator;
        _this.container.lookup(authenticator).restore(restoredContent).then(function(content) {
          _this.setup(authenticator, content);
          resolve();
        }, function() {
          _this.store.clear();
          reject();
        });
      } else {
        _this.store.clear();
        reject();
      }
    });
  },

  /**
    @method setup
    @private
  */
  setup: function(authenticator, content, trigger) {
    trigger = !!trigger && !this.get('isAuthenticated');
    this.beginPropertyChanges();
    this.setProperties({
      isAuthenticated: true,
      authenticator:   authenticator,
      content:         content
    });
    this.bindToAuthenticatorEvents();
    var data = Ember.$.extend({ authenticator: authenticator }, this.content);
    this.store.replace(data);
    this.endPropertyChanges();
    if (trigger) {
      this.trigger('sessionAuthenticationSucceeded');
    }
  },

  /**
    @method clear
    @private
  */
  clear: function(trigger) {
    trigger = !!trigger && this.get('isAuthenticated');
    this.beginPropertyChanges();
    this.setProperties({
      isAuthenticated: false,
      authenticator:   null,
      content:         {}
    });
    this.store.clear();
    this.endPropertyChanges();
    if (trigger) {
      this.trigger('sessionInvalidationSucceeded');
    }
  },

  /**
    @method bindToAuthenticatorEvents
    @private
  */
  bindToAuthenticatorEvents: function() {
    var _this = this;
    var authenticator = this.container.lookup(this.authenticator);
    authenticator.off('sessionDataUpdated');
    authenticator.off('sessionDataInvalidated');
    authenticator.on('sessionDataUpdated', function(content) {
      _this.setup(_this.authenticator, content);
    });
    authenticator.on('sessionDataInvalidated', function(content) {
      _this.clear(true);
    });
  },

  /**
    @method bindToStoreEvents
    @private
  */
  bindToStoreEvents: function() {
    var _this = this;
    this.store.on('sessionDataUpdated', function(content) {
      var authenticator = content.authenticator;
      if (!!authenticator) {
        delete content.authenticator;
        _this.container.lookup(authenticator).restore(content).then(function(content) {
          _this.setup(authenticator, content, true);
        }, function() {
          _this.clear(true);
        });
      } else {
        _this.clear(true);
      }
    });
  }
});
<commit_msg>added assertion for clearer error, close #250<commit_after>var global = (typeof window !== 'undefined') ? window : {},
    Ember = global.Ember;

/**
  __The session provides access to the current authentication state as well as
  any data the authenticator resolved with__ (see
  [`Authenticators.Base#authenticate`](#SimpleAuth-Authenticators-Base-authenticate)).
  It is created when Ember Simple Auth is set up and __injected into all
  controllers and routes so that these parts of the application can always
  access the current authentication state and other data__, depending on the
  authenticator in use and whether the session is actually authenticated (see
  [`Authenticators.Base`](#SimpleAuth-Authenticators-Base)).

  The session also provides methods to authenticate and to invalidate itself
  (see
  [`Session#authenticate`](#SimpleAuth-Session-authenticate),
  [`Session#invaldiate`](#SimpleAuth-Session-invaldiate)).
  These methods are usually invoked through actions from routes or controllers.
  To authenticate the session manually, simple call the
  [`Session#authenticate`](#SimpleAuth-Session-authenticate)
  method with the authenticator factory to use as well as any options the
  authenticator needs to authenticate the session:

  ```javascript
  this.get('session').authenticate('authenticator:custom', { some: 'option' }).then(function() {
    // authentication was successful
  }, function() {
    // authentication failed
  });
  ```

  The session also observes the store and - if it is authenticated - the
  authenticator for changes (see
  [`Authenticators.Base`](#SimpleAuth-Authenticators-Base)
  end [`Stores.Base`](#SimpleAuth-Stores-Base)).

  @class Session
  @namespace SimpleAuth
  @module simple-auth/session
  @extends Ember.ObjectProxy
  @uses Ember.Evented
*/
export default Ember.ObjectProxy.extend(Ember.Evented, {
  /**
    Triggered __whenever the session is successfully authenticated__. When the
    application uses the
    [`ApplicationRouteMixin` mixin](#SimpleAuth-ApplicationRouteMixin),
    [`ApplicationRouteMixin.actions#sessionAuthenticationSucceeded`](#SimpleAuth-ApplicationRouteMixin-sessionAuthenticationSucceeded)
    will be invoked whenever this event is triggered.

    @event sessionAuthenticationSucceeded
  */
  /**
    Triggered __whenever an attempt to authenticate the session fails__. When
    the application uses the
    [`ApplicationRouteMixin` mixin](#SimpleAuth-ApplicationRouteMixin),
    [`ApplicationRouteMixin.actions#sessionAuthenticationFailed`](#SimpleAuth-ApplicationRouteMixin-sessionAuthenticationFailed)
    will be invoked whenever this event is triggered.

    @event sessionAuthenticationFailed
    @param {Object} error The error object; this depends on the authenticator in use, see [SimpleAuth.Authenticators.Base#authenticate](#SimpleAuth-Authenticators-Base-authenticate)
  */
  /**
    Triggered __whenever the session is successfully invalidated__. When the
    application uses the
    [`ApplicationRouteMixin` mixin](#SimpleAuth-ApplicationRouteMixin),
    [`ApplicationRouteMixin.actions#sessionInvalidationSucceeded`](#SimpleAuth-ApplicationRouteMixin-sessionInvalidationSucceeded)
    will be invoked whenever this event is triggered.

    @event sessionInvalidationSucceeded
  */
  /**
    Triggered __whenever an attempt to invalidate the session fails__. When the
    application uses the
    [`ApplicationRouteMixin` mixin](#SimpleAuth-ApplicationRouteMixin),
    [`ApplicationRouteMixin.actions#sessionInvalidationFailed`](#SimpleAuth-ApplicationRouteMixin-sessionInvalidationFailed)
    will be invoked whenever this event is triggered.

    @event sessionInvalidationFailed
    @param {Object} error The error object; this depends on the authenticator in use, see [SimpleAuth.Authenticators.Base#invalidate](#SimpleAuth-Authenticators-Base-invalidate)
  */
  /**
    Triggered __whenever the server rejects the authorization information
    passed with a request and responds with status 401__. When the application
    uses the
    [`ApplicationRouteMixin` mixin](#SimpleAuth-ApplicationRouteMixin),
    [`ApplicationRouteMixin.actions#authorizationFailed`](#SimpleAuth-ApplicationRouteMixin-authorizationFailed)
    will be invoked whenever this event is triggered.

    @event authorizationFailed
  */

  /**
    The authenticator factory to use as it is registered with Ember's
    container, see
    [Ember's API docs](http://emberjs.com/api/classes/Ember.Application.html#method_register).
    This is only set when the session is currently authenticated.

    @property authenticator
    @type String
    @readOnly
    @default null
  */
  authenticator: null,
  /**
    The store used to persist session properties.

    @property store
    @type SimpleAuth.Stores.Base
    @readOnly
    @default null
  */
  store: null,
  /**
    Returns whether the session is currently authenticated.

    @property isAuthenticated
    @type Boolean
    @readOnly
    @default false
  */
  isAuthenticated: false,
  /**
    @property attemptedTransition
    @private
  */
  attemptedTransition: null,
  /**
    @property content
    @private
  */
  content: {},

  /**
    @method init
    @private
  */
  init: function() {
    this.bindToStoreEvents();
  },

  /**
    Authenticates the session with an `authenticator` and appropriate
    `options`. __This delegates the actual authentication work to the
    `authenticator`__ and handles the returned promise accordingly (see
    [`Authenticators.Base#authenticate`](#SimpleAuth-Authenticators-Base-authenticate)).
    All data the authenticator resolves with will be saved in the session.

    __This method returns a promise itself. A resolving promise indicates that
    the session was successfully authenticated__ while a rejecting promise
    indicates that authentication failed and the session remains
    unauthenticated.

    @method authenticate
    @param {String} authenticator The authenticator factory to use as it is registered with Ember's container, see [Ember's API docs](http://emberjs.com/api/classes/Ember.Application.html#method_register)
    @param {Object} options The options to pass to the authenticator; depending on the type of authenticator these might be a set of credentials, a Facebook OAuth Token, etc.
    @return {Ember.RSVP.Promise} A promise that resolves when the session was authenticated successfully
  */
  authenticate: function(authenticator, options) {
    Ember.assert('Session#authenticate requires the authenticator factory to be specified, was ' + authenticator, !Ember.isEmpty(authenticator));
    var _this = this;
    return new Ember.RSVP.Promise(function(resolve, reject) {
      _this.container.lookup(authenticator).authenticate(options).then(function(content) {
        _this.setup(authenticator, content, true);
        resolve();
      }, function(error) {
        _this.clear();
        _this.trigger('sessionAuthenticationFailed', error);
        reject(error);
      });
    });
  },

  /**
    Invalidates the session with the authenticator it is currently
    authenticated with (see
    [`Session#authenticator`](#SimpleAuth-Session-authenticator)). __This
    invokes the authenticator's `invalidate` method and handles the returned
    promise accordingly__ (see
    [`Authenticators.Base#invalidate`](#SimpleAuth-Authenticators-Base-invalidate)).

    __This method returns a promise itself. A resolving promise indicates that
    the session was successfully invalidated__ while a rejecting promise
    indicates that the promise returned by the `authenticator` rejected and
    thus invalidation was cancelled. In that case the session remains
    authenticated. Once the session is successfully invalidated it clears all
    of its data.

    @method invalidate
    @return {Ember.RSVP.Promise} A promise that resolves when the session was invalidated successfully
  */
  invalidate: function() {
    Ember.assert('Session#invalidate requires the session to be authenticated', this.get('isAuthenticated'));
    var _this = this;
    return new Ember.RSVP.Promise(function(resolve, reject) {
      var authenticator = _this.container.lookup(_this.authenticator);
      authenticator.invalidate(_this.content).then(function() {
        authenticator.off('sessionDataUpdated');
        _this.clear(true);
        resolve();
      }, function(error) {
        _this.trigger('sessionInvalidationFailed', error);
        reject(error);
      });
    });
  },

  /**
    @method restore
    @private
  */
  restore: function() {
    var _this = this;
    return new Ember.RSVP.Promise(function(resolve, reject) {
      var restoredContent = _this.store.restore();
      var authenticator   = restoredContent.authenticator;
      if (!!authenticator) {
        delete restoredContent.authenticator;
        _this.container.lookup(authenticator).restore(restoredContent).then(function(content) {
          _this.setup(authenticator, content);
          resolve();
        }, function() {
          _this.store.clear();
          reject();
        });
      } else {
        _this.store.clear();
        reject();
      }
    });
  },

  /**
    @method setup
    @private
  */
  setup: function(authenticator, content, trigger) {
    trigger = !!trigger && !this.get('isAuthenticated');
    this.beginPropertyChanges();
    this.setProperties({
      isAuthenticated: true,
      authenticator:   authenticator,
      content:         content
    });
    this.bindToAuthenticatorEvents();
    var data = Ember.$.extend({ authenticator: authenticator }, this.content);
    this.store.replace(data);
    this.endPropertyChanges();
    if (trigger) {
      this.trigger('sessionAuthenticationSucceeded');
    }
  },

  /**
    @method clear
    @private
  */
  clear: function(trigger) {
    trigger = !!trigger && this.get('isAuthenticated');
    this.beginPropertyChanges();
    this.setProperties({
      isAuthenticated: false,
      authenticator:   null,
      content:         {}
    });
    this.store.clear();
    this.endPropertyChanges();
    if (trigger) {
      this.trigger('sessionInvalidationSucceeded');
    }
  },

  /**
    @method bindToAuthenticatorEvents
    @private
  */
  bindToAuthenticatorEvents: function() {
    var _this = this;
    var authenticator = this.container.lookup(this.authenticator);
    authenticator.off('sessionDataUpdated');
    authenticator.off('sessionDataInvalidated');
    authenticator.on('sessionDataUpdated', function(content) {
      _this.setup(_this.authenticator, content);
    });
    authenticator.on('sessionDataInvalidated', function(content) {
      _this.clear(true);
    });
  },

  /**
    @method bindToStoreEvents
    @private
  */
  bindToStoreEvents: function() {
    var _this = this;
    this.store.on('sessionDataUpdated', function(content) {
      var authenticator = content.authenticator;
      if (!!authenticator) {
        delete content.authenticator;
        _this.container.lookup(authenticator).restore(content).then(function(content) {
          _this.setup(authenticator, content, true);
        }, function() {
          _this.clear(true);
        });
      } else {
        _this.clear(true);
      }
    });
  }
});
<|endoftext|>


<commit_before>const pg = require('co-pg')(require('pg'));

module.exports = (function () {
  function* addUser(userObj) {
    try {
      const client = new pg.Client(process.env.DB);
      yield client.connectPromise();
      yield client.queryPromise('INSERT INTO users(username, password) values($1, $2)',
        [userObj.username, userObj.password]);
      client.end();
    } catch (ex) {
      console.error(ex.toString());
    }
  }

  function* getUser(username) {
    try {
      const client = new pg.Client(process.env.DB);
      yield client.connectPromise();
      const result = yield client.queryPromise(
        'SELECT username, password FROM users WHERE username = ($1)',
        [username]);
      client.end();
      return result.rows;
    } catch (ex) {
      console.error(ex.toString());
    }
  }

  return {
    addUser,
    getUser
  };
}());
<commit_msg>[refactor] return promises in model fns<commit_after>const co = require('co');
const pg = require('co-pg')(require('pg'));

module.exports = {
  addUser: co.wrap(function* (userObj) {
    try {
      const client = new pg.Client(process.env.DB);
      yield client.connectPromise();
      yield client.queryPromise('INSERT INTO users(username, password) values($1, $2)',
        [userObj.username, userObj.password]);
      return Promise.resolve(client.end());
    } catch (ex) {
      console.error(ex.toString());
      throw ex;
    }
  }),

  getUser: co.wrap(function* (username) {
    try {
      const client = new pg.Client(process.env.DB);
      yield client.connectPromise();
      const result = yield client.queryPromise(
        'SELECT username, password FROM users WHERE username = ($1)',
        [username]);
      client.end();
      return Promise.resolve(result.rows);
    } catch (ex) {
      console.error(ex.toString());
      throw ex;
    }
  })
};
<|endoftext|>


<commit_before>import Phaser from 'phaser'

const movementSpeed = 500

export default class extends Phaser.Sprite {
  constructor ({ game, x, y, asset }) {
    super(game, x, y, asset)
    this.anchor.setTo(0.5)

    // Set up the physics for this ship.
    game.physics.enable(this, Phaser.Physics.ARCADE)
    this.body.drag.set(100)
    this.body.maxVelocity.set(movementSpeed)
  }

  update () {
    if (game.cursors.up.isDown) {
      game.physics.arcade.accelerationFromRotation(this.rotation, movementSpeed, this.body.acceleration)
    } else {
      this.body.acceleration.set(0)
    }

    if (game.cursors.left.isDown) {
      this.body.angularVelocity = -300
    } else if (game.cursors.right.isDown) {
      this.body.angularVelocity = 300
    } else {
      this.body.angularVelocity = 0
    }

    if (game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) {
      // shoot
    }
  }
}
<commit_msg>Add backwards movement<commit_after>import Phaser from 'phaser'

const movementSpeed = 500

export default class extends Phaser.Sprite {
  constructor ({ game, x, y, asset }) {
    super(game, x, y, asset)
    this.anchor.setTo(0.5)

    // Set up the physics for this ship.
    game.physics.enable(this, Phaser.Physics.ARCADE)
    this.body.drag.set(100)
    this.body.maxVelocity.set(movementSpeed)
  }

  update () {
    if (game.cursors.up.isDown) {
      game.physics.arcade.accelerationFromRotation(this.rotation, movementSpeed, this.body.acceleration)
    } else if (game.cursors.down.isDown) {
      game.physics.arcade.accelerationFromRotation(this.rotation, -movementSpeed, this.body.acceleration)
    } else {
      this.body.acceleration.set(0)
    }

    if (game.cursors.left.isDown) {
      this.body.angularVelocity = -300
    } else if (game.cursors.right.isDown) {
      this.body.angularVelocity = 300
    } else {
      this.body.angularVelocity = 0
    }

    if (game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) {
      // shoot
    }
  }
}
<|endoftext|>


<commit_before>var models  = require('../../models'),
    async = require('async'),
    numeral = require('numeral'),
    parser = require('fec-parse'),
    _ = require('lodash'),
    brake = require('brake');

var payload = 200; // how many rows get processed by cargo at a time

var formModels = [
    models.fec_filing,
    models.fec_presidential_summary,
    models.fec_pac_summary,
    models.fec_group_summary,
    models.fec_lobbyist_bundler,
    models.fec_contribution,
    models.fec_expenditure,
    models.fec_debt,
    models.fec_loan,
    models.fec_ie
];

function importFiling(task,callback) {
    var transaction = null;

    var processed = 0,
        queued = 0,
        finished = false;

    function error(err) {
        cargo.kill();

        if (!finished) {
            finished = true;

            notify('fecImportFailed',{ filing_id: filing_id });

            console.error(err);

            if (transaction !== null) {
                console.error('rolling back transaction');

                transaction.rollback()
                    .then(callback.bind(this,err))
                    .catch(function () {
                        console.error('error rolling back transaction');

                        callback(err);
                    });
            }
            else {
                callback(err);
            }
        }
        else {
            throw new Error('error called for ' + filing_id + ', but already finished');
        }
    }

    function done() {
        if (processed == queued && !finished) {
            finished = true;

            console.log('inserted ' + processed + ' rows from ' + task.name);
            console.log('commiting transaction');

            transaction.commit()
                .then(function (result) {
                    notify('fecImportComplete',{ filing_id: filing_id });

                    callback(null,result);
                })
                .catch(error);
        }
        else if (finished) {
            throw new Error('done called for ' + filing_id + ', but already finished');
        }
        else if (processed !== queued) {
            throw new Error('done called for ' + filing_id + ', but processed is ' + processed + ' and queued is ' + queued);
        }
    }

    function startTransaction(cb) {
        models.sequelize.transaction()
                .then(cb)
                .catch(error);
    }

    function processRows(task,cb) {
        if (finished) {
            cb();
            return;
        }

        rows = task.rows;

        if (rows[0].report_id === '') {
            rows[0].report_id = null;
        }
        if (rows[0].report_number === '') {
            rows[0].report_number = null;
        }

        console.log('processing ' + numeral(processed).format() + ' - ' + numeral(processed+task.rows.length).format() + ' of ' + numeral(queued).format());

        rows[0].model
            .bulkCreate(rows,{
                transaction: transaction
            })
            .then(function () {
                processed += task.rows.length;

                cb();
            })
            .catch(function (err) {
                if (err.name == 'SequelizeUniqueConstraintError') {
                    console.log('already inserted ' + rows[0].filing_id);
                }
                else {
                    console.error('error inserting ' + rows[0].filing_id + ':');
                    console.log(err);
                }

                cb(err);
            });
    }

    function queueRows(rows,cb) {
        if (finished) {
            cb();
            return;
        }

        var modelGroups = _(rows)
                    .groupBy(function (row) {
                        return row.model.name;
                    })
                    .toArray()
                    .map(function (rows) {
                        return {
                            rows: rows
                        };
                    })
                    .value();

        var q = async.queue(processRows,1);

        q.push(modelGroups,function (err) {
            if (err) {
                q.kill();

                cb(err);
            }
        });

        q.drain = cb;
    }

    function notify(channel,data) {
        if (models.sequelize.getDialect() == 'postgres') {
            if (data.coverage_from_date) {
                data = _.pick(data,[
                    'filing_id',
                    'form_type',
                    'committee_name',
                    'organization_name',
                    'filer_committee_id_number',
                    'coverage_from_date',
                    'coverage_through_date',
                    'col_a_total_receipts',
                    'col_a_total_disbursements',
                    'col_a_cash_on_hand_close_of_period']);
            }

            return models.sequelize.query('NOTIFY ' + channel + ',  ' +
                    models.sequelize.escape(JSON.stringify(data)) + ';');
        }
    }

    function processFiling(openStream, cb) {
        console.log('== importing ' + filing_id + ' ==');

        var parse = parser();

        openStream(function (err,stream) {
            if (err) {
                error(err);
                return;
            }

            stream
                .pipe(brake(45164*3))
                .pipe(parse)
                .on('data',function (row) {
                    row.filing_id = filing_id;
                    row.model = formModels.find(function (model) {
                        return model.match(row);
                    });

                    if (typeof row.model !== 'undefined' && !finished) {
                        queued++;

                        if (queued == 2 && row.coverage_from_date) {
                            notify('fecImportStart',row);
                        }

                        cargo.push(row,function (err) {
                            if (err) {
                                error();
                            }
                        });
                    }

                })
                .on('end',function () {
                    cargo.drain = done;

                    if (processed === queued) {
                        done();
                    }
                })
                .on('error',error);
        });
    }

    function checkForFiling(id,cb) {
        models.fec_filing.findById(id)
            .then(function (result) {
                if (result) {
                    //console.log('already inserted ' + filing_id);

                    callback();
                }
                else {
                    cb();
                }
            })
            .catch(error);
    }

    var filing_id = task.name.replace(/[^0-9]+/g,''); // assume the filing number is just the numeric portion of the file name

    var cargo = async.cargo(queueRows,payload);

    checkForFiling(filing_id,function () {
        startTransaction(function (t) {
            transaction = t;

            processFiling(task.openStream,done);
        });
    });

}

function FilingQueue() {
    var q = async.queue(importFiling, 1);

    return q;
}

module.exports = new FilingQueue();
<commit_msg>Hmm. Try this instead<commit_after>var models  = require('../../models'),
    async = require('async'),
    numeral = require('numeral'),
    parser = require('fec-parse'),
    _ = require('lodash'),
    brake = require('brake');

var payload = 200; // how many rows get processed by cargo at a time

var formModels = [
    models.fec_filing,
    models.fec_presidential_summary,
    models.fec_pac_summary,
    models.fec_group_summary,
    models.fec_lobbyist_bundler,
    models.fec_contribution,
    models.fec_expenditure,
    models.fec_debt,
    models.fec_loan,
    models.fec_ie
];

function importFiling(task,callback) {
    var transaction = null;

    var processed = 0,
        queued = 0,
        finished = false;

    function error(err) {
        cargo.kill();

        if (!finished) {
            finished = true;

            notify('fecImportFailed',{ filing_id: filing_id });

            console.error(err);

            if (transaction !== null) {
                console.error('rolling back transaction');

                transaction.rollback()
                    .then(callback.bind(this,err))
                    .catch(function () {
                        console.error('error rolling back transaction');

                        callback(err);
                    });
            }
            else {
                callback(err);
            }
        }
        else {
            throw new Error('error called for ' + filing_id + ', but already finished');
        }
    }

    function done() {
        if (processed == queued && !finished) {
            finished = true;

            console.log('inserted ' + processed + ' rows from ' + task.name);
            console.log('commiting transaction');

            transaction.commit()
                .then(function (result) {
                    notify('fecImportComplete',{ filing_id: filing_id });

                    callback(null,result);
                })
                .catch(error);
        }
        else if (finished) {
            throw new Error('done called for ' + filing_id + ', but already finished');
        }
        else if (processed !== queued) {
            throw new Error('done called for ' + filing_id + ', but processed is ' + processed + ' and queued is ' + queued);
        }
    }

    function startTransaction(cb) {
        models.sequelize.transaction()
                .then(cb)
                .catch(error);
    }

    function processRows(task,cb) {
        if (finished) {
            cb();
            return;
        }

        rows = task.rows;

        if (rows[0].report_id === '') {
            rows[0].report_id = null;
        }
        if (rows[0].report_number === '') {
            rows[0].report_number = null;
        }

        console.log('processing ' + numeral(processed).format() + ' - ' + numeral(processed+task.rows.length).format() + ' of ' + numeral(queued).format());

        rows[0].model
            .bulkCreate(rows,{
                transaction: transaction
            })
            .then(function () {
                processed += task.rows.length;

                cb();
            })
            .catch(function (err) {
                if (err.name == 'SequelizeUniqueConstraintError') {
                    console.log('already inserted ' + rows[0].filing_id);
                }
                else {
                    console.error('error inserting ' + rows[0].filing_id + ':');
                    console.log(err);
                }

                cb(err);
            });
    }

    function queueRows(rows,cb) {
        if (finished) {
            cb();
            return;
        }

        var modelGroups = _(rows)
                    .groupBy(function (row) {
                        return row.model.name;
                    })
                    .toArray()
                    .map(function (rows) {
                        return {
                            rows: rows
                        };
                    })
                    .value();

        var q = async.queue(processRows,1);

        q.push(modelGroups,function (err) {
            if (err) {
                q.kill();

                cb(err);
            }
        });

        q.drain = cb;
    }

    function notify(channel,data) {
        if (models.sequelize.getDialect() == 'postgres') {
            if (data.coverage_from_date) {
                data = _.pick(data,[
                    'filing_id',
                    'form_type',
                    'committee_name',
                    'organization_name',
                    'filer_committee_id_number',
                    'coverage_from_date',
                    'coverage_through_date',
                    'col_a_total_receipts',
                    'col_a_total_disbursements',
                    'col_a_cash_on_hand_close_of_period']);
            }

            return models.sequelize.query('NOTIFY ' + channel + ',  ' +
                    models.sequelize.escape(JSON.stringify(data)) + ';');
        }
    }

    function processFiling(openStream, cb) {
        console.log('== importing ' + filing_id + ' ==');

        var parse = parser();

        openStream(function (err,stream) {
            if (err) {
                error(err);
                return;
            }

            stream
                .pipe(brake(45164*3))
                .pipe(parse)
                .on('data',function (row) {
                    row.filing_id = filing_id;
                    row.model = formModels.find(function (model) {
                        return model.match(row);
                    });

                    if (row.coverage_from_date) {
                        notify('fecImportStart',row);
                    }

                    if (typeof row.model !== 'undefined' && !finished) {
                        queued++;

                        cargo.push(row,function (err) {
                            if (err) {
                                error();
                            }
                        });
                    }

                })
                .on('end',function () {
                    cargo.drain = done;

                    if (processed === queued) {
                        done();
                    }
                })
                .on('error',error);
        });
    }

    function checkForFiling(id,cb) {
        models.fec_filing.findById(id)
            .then(function (result) {
                if (result) {
                    //console.log('already inserted ' + filing_id);

                    callback();
                }
                else {
                    cb();
                }
            })
            .catch(error);
    }

    var filing_id = task.name.replace(/[^0-9]+/g,''); // assume the filing number is just the numeric portion of the file name

    var cargo = async.cargo(queueRows,payload);

    checkForFiling(filing_id,function () {
        startTransaction(function (t) {
            transaction = t;

            processFiling(task.openStream,done);
        });
    });

}

function FilingQueue() {
    var q = async.queue(importFiling, 1);

    return q;
}

module.exports = new FilingQueue();
<|endoftext|>


<commit_before>// Required modules
var mongoose = require('mongoose');
var _        = require('underscore');

// Required data schema
var Thing 	= require('../../data/thing');
var socket	= require('../../server.js');

/**
 * @api {post} /things POST - Create a Thing
 * @apiName PostThing
 * @apiGroup Thing
 * @apiVersion 1.0.0
 *
 * @apiParam {String} name			Name of the Thing.
 * @apiParam {Point} loc			Location of the Thing.
 * @apiParam {String} userId		User's unique ID.
 *
 * @apiSuccess {String} thingId 	Thing's unique ID.
 *
 * @apiSuccessExample Success-Response:
 *     HTTP/1.1 200 OK
 *     {
 *       "name": "ifgi",
 *       "userId": "<< generated MongoDB ID >>",
 *       "_id": "<< generated MongoDB ID >>",
 *       "__v": 0,
 *       "loc": {
 *         "coordinates": [
 *           51.969114,
 *           7.595794
 *         ],
 *         "type": "Point"
 *       }
 *     }
 *
 * @apiUse ServerError
 */
exports.request = function(req, res) {
	var thing = new Thing(_.extend({}, req.body));

	thing.save(function(err) {
		if (err) {
			res.send(err);
		} else {
			res.json(thing);
			socket.notify("things", thing);
		}
	});
}<commit_msg>Updated POST Thing request<commit_after>// Required modules
var mongoose = require('mongoose');
var _        = require('underscore');

// Required data schema
var Thing 		= require('../../data/thing');
var Waterbody	= require('../../data/waterbody.js');
var socket		= require('../../server.js');

/**
 * @api {post} /things POST - Create a Thing
 * @apiName PostThing
 * @apiGroup Thing
 * @apiVersion 1.0.0
 *
 * @apiParam {String} name			Name of the Thing.
 * @apiParam {Point} loc			Location of the Thing.
 * @apiParam {String} userId		User's unique ID.
 *
 * @apiSuccess {String} thingId 	Thing's unique ID.
 *
 * @apiSuccessExample Success-Response:
 *     HTTP/1.1 200 OK
 *     {
 *       "name": "ifgi",
 *       "userId": "<< generated MongoDB ID >>",
 *		 "waterbodyId": "<< generatedMongoDB ID >>",
 *       "_id": "<< generated MongoDB ID >>",
 *       "__v": 0,
 *       "loc": {
 *         "coordinates": [
 *           51.969114,
 *           7.595794
 *         ],
 *         "type": "Point"
 *       }
 *     }
 *
 * @apiUse ServerError
 */
exports.request = function(req, res) {
	var thing = new Thing(_.extend({}, req.body));

	var coordinates = [thing.loc.coordinates[1], thing.loc.coordinates[0]];

	Waterbody.find({
		"geometry": {
			$near: {
				$geometry: {
					type: "Point",
					coordinates: coordinates
				},
				$maxDistance: 800,
				$minDistance: 0
			}
		}
	}, function(err, waterbody) {
		if(err) {
			res.send(err);
		} else {
			if(waterbody.length > 0) {
				thing.waterbodyId = waterbody[0]._id;
			}
			thing.save(function(err) {
				if (err) {
					res.send(err);
				} else {
					res.json(thing);
					socket.notify("things", thing);
				}
			});
		}
	});
}<|endoftext|>


<commit_before>'use strict';

var aFrom           = require('es5-ext/array/from')
  , ensureIterable  = require('es5-ext/itrable/validate-object')
  , ensureType      = require('dbjs/valid-dbjs-type')
  , debug           = require('debug-ext')('business-process-flow')
  , resolveStepPath = require('../../utils/resolve-processing-step-full-path')
  , setupTriggers   = require('../_setup-triggers');

module.exports = function (BusinessProcessType, stepShortPaths) {
	var businessProcesses = ensureType(BusinessProcessType).instances
		.filterByKey('isFromEregistrations', true).filterByKey('isDemo', false);

	stepShortPaths = aFrom(ensureIterable(stepShortPaths));
	var stepPaths = stepShortPaths.map(resolveStepPath);

	// isSubmitted
	setupTriggers({
		trigger: businessProcesses.filterByKey('isSubmittedReady', true)
			.filterByKey('isSubmitted', false)
	}, function (businessProcess) {
		debug('%s submitted', businessProcess.__id__);
		businessProcess.isSubmitted = true;
	});

	var businessProcessesSubmitted = businessProcesses.filterByKey('isSubmitted', true);

	// Processing step statuses
	stepPaths.forEach(function (stepPath, index) {
		// status
		setupTriggers({
			trigger: businessProcessesSubmitted.filterByKeyPath(stepPath + '/status', function (value) {
				return value && (value !== 'pending');
			})
		}, function (businessProcess) {
			var step = businessProcess.getBySKeyPath(stepPath);
			if (step.getOwnDescriptor('status').hasOwnProperty('_value_')) return;
			debug('%s processing step (%s) status set to %s', businessProcess.__id__,
				stepShortPaths[index], step.status);
			step.set('status', step.status);
		});

		// isSatisfied
		setupTriggers({
			trigger: businessProcessesSubmitted.filterByKeyPath(stepPath + '/isSatisfiedReady', true)
				.filterByKeyPath(stepPath + '/isSatisfied', false)
		}, function (businessProcess) {
			var step = businessProcess.getBySKeyPath(stepPath);
			debug('%s processing step (%s) was satisified', businessProcess.__id__,
				stepShortPaths[index]);
			step.isSatisfied = true;
		});
	});
};
<commit_msg>Documentation<commit_after>'use strict';

var aFrom           = require('es5-ext/array/from')
  , ensureIterable  = require('es5-ext/itrable/validate-object')
  , ensureType      = require('dbjs/valid-dbjs-type')
  , debug           = require('debug-ext')('business-process-flow')
  , resolveStepPath = require('../../utils/resolve-processing-step-full-path')
  , setupTriggers   = require('../_setup-triggers');

module.exports = function (BusinessProcessType, stepShortPaths) {
	var businessProcesses = ensureType(BusinessProcessType).instances
		.filterByKey('isFromEregistrations', true).filterByKey('isDemo', false);

	stepShortPaths = aFrom(ensureIterable(stepShortPaths));
	var stepPaths = stepShortPaths.map(resolveStepPath);

	// Business process: isSubmitted
	setupTriggers({
		trigger: businessProcesses.filterByKey('isSubmittedReady', true)
			.filterByKey('isSubmitted', false)
	}, function (businessProcess) {
		debug('%s submitted', businessProcess.__id__);
		businessProcess.isSubmitted = true;
	});

	var businessProcessesSubmitted = businessProcesses.filterByKey('isSubmitted', true);

	// Processing steps:
	stepPaths.forEach(function (stepPath, index) {
		// status
		setupTriggers({
			trigger: businessProcessesSubmitted.filterByKeyPath(stepPath + '/status', function (value) {
				return value && (value !== 'pending');
			})
		}, function (businessProcess) {
			var step = businessProcess.getBySKeyPath(stepPath);
			if (step.getOwnDescriptor('status').hasOwnProperty('_value_')) return;
			debug('%s processing step (%s) status set to %s', businessProcess.__id__,
				stepShortPaths[index], step.status);
			step.set('status', step.status);
		});

		// isSatisfied
		setupTriggers({
			trigger: businessProcessesSubmitted.filterByKeyPath(stepPath + '/isSatisfiedReady', true)
				.filterByKeyPath(stepPath + '/isSatisfied', false)
		}, function (businessProcess) {
			var step = businessProcess.getBySKeyPath(stepPath);
			debug('%s processing step (%s) was satisfied', businessProcess.__id__,
				stepShortPaths[index]);
			step.isSatisfied = true;
		});
	});
};
<|endoftext|>