<commit_before>var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('q'), require('superagent'), require('route-parser'), require('cache-manager')) : typeof define === 'function' && define.amd ? define(['q', 'superagent', 'route-parser', 'cache-manager'], factory) : global.superRes = factory(global.Q, global.superagent, global.Route, global.cacheManager);
})(this, function (Q, superagent, Route, cacheManager) {
  'use strict';

  var actionDefaults = actionDefaults = {
    method: 'GET',
    responseType: 'json',
    transformRequest: [],
    transformResponse: [],
    withCredentials: false,
    cache: null
  };

  var ResourceAction_js__assign = ResourceAction_js__assign || require('object.assign');

  function applyResponseTransforms(transforms, response) {
    return transforms.reduceRight(function (memo, transform) {
      return transform(memo, response.header);
    }, response.body);
  }

  function applyRequestTransforms(transforms, request, data) {
    return transforms.reduceRight(function (memo, transform) {
      return transform(memo, request.header);
    }, data);
  }

  var ResourceAction = (function () {
    function ResourceAction(url, defaultParams, action) {
      _classCallCheck(this, ResourceAction);

      this.config = ResourceAction_js__assign({ url: url }, actionDefaults, action);
      this.route = new Route(this.config.url);
      this.defaultParams = defaultParams;

      if (this.config.cache === true) {
        this.config.cache = cacheManager.caching({ store: 'memory', max: 100, ttl: 1200 });
      }
    }

    _createClass(ResourceAction, [{
      key: 'getCacheKey',
      value: function getCacheKey(params, data) {
        return this.route.reverse(params) + JSON.stringify(data);
      }
    }, {
      key: 'buildRequest',
      value: function buildRequest(params, data) {
        var method = this.config.method.toLowerCase();
        var currentRequest = superagent[method === 'delete' ? 'del' : method](this.route.reverse(params));

        currentRequest = currentRequest.accept(this.config.responseType);
        if (this.config.headers) {
          currentRequest = currentRequest.set(this.config.headers);
        }

        if (this.config.timeout) {
          currentRequest.timeout(this.config.timeout);
        } else {
          currentRequest.clearTimeout();
        }

        if (this.config.withCredentials) {
          currentRequest = currentRequest.withCredentials();
        }

        if (data) {
          var transformedData = applyRequestTransforms(this.config.transformRequest, currentRequest, data);
          if (method === 'get') {
            currentRequest = currentRequest.query(transformedData);
          } else {
            currentRequest = currentRequest.send(transformedData);
          }
        }

        return currentRequest;
      }
    }, {
      key: 'makeRequest',
      value: function makeRequest(params, data) {
        var _this = this;

        var deferred = Q.defer();
        var fullParams = ResourceAction_js__assign({}, this.defaultParams, params);

        var doRequest = function doRequest() {
          _this.buildRequest(fullParams, data).end(function (err, res) {
            if (err) {
              deferred.reject(err);
            } else {
              var transformedReponse = applyResponseTransforms(_this.config.transformResponse, res);

              if (_this.config.cache) {
                _this.config.cache.set(_this.getCacheKey(fullParams, data), transformedReponse);
              }

              deferred.resolve(transformedReponse);
            }
          });
        };

        if (this.config.cache && this.config.method.toLowerCase() === 'get') {
          var key = this.getCacheKey(fullParams, data);
          this.config.cache.get(key, function (err, result) {
            if (err) {
              deferred.reject(err);
            } else if (result) {
              deferred.resolve(result);
            } else {
              doRequest();
            }
          });
        } else {
          doRequest();
        }

        return deferred.promise;
      }
    }]);

    return ResourceAction;
  })();

  var super_res__assign = super_res__assign || require('object.assign');

  var super_res__superRes = {};

  function generateDefaultActions(url, defaultParams) {
    var resource = {};

    var action = new ResourceAction(url, defaultParams, super_res__assign({}, actionDefaults));
    resource.get = action.makeRequest.bind(action);
    resource.query = resource.get;

    action = new ResourceAction(url, defaultParams, super_res__assign({}, actionDefaults, { method: 'POST' }));
    resource.save = action.makeRequest.bind(action);

    action = new ResourceAction(url, defaultParams, super_res__assign({}, actionDefaults, { method: 'PUT' }));
    resource.put = action.makeRequest.bind(action);

    action = new ResourceAction(url, defaultParams, super_res__assign({}, actionDefaults, { method: 'DELETE' }));
    resource.remove = action.makeRequest.bind(action);
    resource['delete'] = resource.remove;

    return resource;
  }

  super_res__superRes.resource = function (url, defaultParams, actions) {
    var resource = generateDefaultActions(url, defaultParams);
    if (actions) {
      Object.getOwnPropertyNames(actions).forEach(function (name) {
        var action = new ResourceAction(url, defaultParams, actions[name]);
        resource[name] = function () {
          action.makeRequest.apply(action, arguments);
        };
      });
    }
    return resource;
  };

  super_res__superRes.promiseWrapper = function promiseWrapper(wrapperFunc) {
    return function (resource) {
      var proxiedResource = super_res__assign({}, resource);
      Object.getOwnPropertyNames(resource).forEach(function (name) {
        var actionFunction = proxiedResource[name];
        proxiedResource[name] = function () {
          for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }

          var promise = actionFunction.apply(proxiedResource, args);
          return wrapperFunc(promise);
        };
      });
      return proxiedResource;
    };
  };

  var super_res = super_res__superRes;

  return super_res;
});
//# sourceMappingURL=super-res.js.map<commit_msg>Build<commit_after>var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('q'), require('superagent'), require('route-parser'), require('cache-manager')) : typeof define === 'function' && define.amd ? define(['q', 'superagent', 'route-parser', 'cache-manager'], factory) : global.superRes = factory(global.Q, global.superagent, global.Route, global.cacheManager);
})(this, function (Q, superagent, Route, cacheManager) {
  'use strict';

  var actionDefaults = actionDefaults = {
    method: 'GET',
    responseType: 'json',
    transformRequest: [],
    transformResponse: [],
    withCredentials: false,
    cache: null
  };

  var ResourceAction_js__assign = ResourceAction_js__assign || require('object.assign');

  function applyResponseTransforms(transforms, response) {
    return transforms.reduceRight(function (memo, transform) {
      return transform(memo, response.header);
    }, response.body);
  }

  function applyRequestTransforms(transforms, request, data) {
    return transforms.reduceRight(function (memo, transform) {
      return transform(memo, request.header);
    }, data);
  }

  var ResourceAction = (function () {
    function ResourceAction(url, defaultParams, action) {
      _classCallCheck(this, ResourceAction);

      this.config = ResourceAction_js__assign({ url: url }, actionDefaults, action);
      this.route = new Route(this.config.url);
      this.defaultParams = defaultParams;

      if (this.config.cache === true) {
        this.config.cache = cacheManager.caching({ store: 'memory', max: 100, ttl: 1200 });
      }
    }

    _createClass(ResourceAction, [{
      key: 'getCacheKey',
      value: function getCacheKey(params, data) {
        return this.route.reverse(params) + JSON.stringify(data);
      }
    }, {
      key: 'buildRequest',
      value: function buildRequest(params, data) {
        var method = this.config.method.toLowerCase();
        var currentRequest = superagent[method === 'delete' ? 'del' : method](this.route.reverse(params));

        currentRequest = currentRequest.accept(this.config.responseType);
        if (this.config.headers) {
          currentRequest = currentRequest.set(this.config.headers);
        }

        if (this.config.timeout) {
          currentRequest.timeout(this.config.timeout);
        } else {
          currentRequest.clearTimeout();
        }

        if (this.config.withCredentials) {
          currentRequest = currentRequest.withCredentials();
        }

        if (data) {
          var transformedData = applyRequestTransforms(this.config.transformRequest, currentRequest, data);
          if (method === 'get') {
            currentRequest = currentRequest.query(transformedData);
          } else {
            currentRequest = currentRequest.send(transformedData);
          }
        }

        return currentRequest;
      }
    }, {
      key: 'makeRequest',
      value: function makeRequest(params, data) {
        var _this = this;

        var deferred = Q.defer();
        var fullParams = ResourceAction_js__assign({}, this.defaultParams, params);

        var doRequest = function doRequest() {
          _this.buildRequest(fullParams, data).end(function (err, res) {
            if (err) {
              deferred.reject(err);
            } else {
              var transformedReponse = applyResponseTransforms(_this.config.transformResponse, res);

              if (_this.config.cache) {
                _this.config.cache.set(_this.getCacheKey(fullParams, data), transformedReponse);
              }

              deferred.resolve(transformedReponse);
            }
          });
        };

        if (this.config.cache && this.config.method.toLowerCase() === 'get') {
          var key = this.getCacheKey(fullParams, data);
          this.config.cache.get(key, function (err, result) {
            if (err) {
              deferred.reject(err);
            } else if (result) {
              deferred.resolve(result);
            } else {
              doRequest();
            }
          });
        } else {
          doRequest();
        }

        return deferred.promise;
      }
    }]);

    return ResourceAction;
  })();

  var super_res__assign = super_res__assign || require('object.assign');

  var super_res__superRes = {};

  function generateDefaultActions(url, defaultParams) {
    var resource = {};

    var action = new ResourceAction(url, defaultParams, super_res__assign({}, actionDefaults));
    resource.get = action.makeRequest.bind(action);
    resource.query = resource.get;

    action = new ResourceAction(url, defaultParams, super_res__assign({}, actionDefaults, { method: 'POST' }));
    resource.save = action.makeRequest.bind(action);

    action = new ResourceAction(url, defaultParams, super_res__assign({}, actionDefaults, { method: 'PUT' }));
    resource.put = action.makeRequest.bind(action);

    action = new ResourceAction(url, defaultParams, super_res__assign({}, actionDefaults, { method: 'DELETE' }));
    resource.remove = action.makeRequest.bind(action);
    resource['delete'] = resource.remove;

    return resource;
  }

  super_res__superRes.resource = function (url, defaultParams, actions) {
    var resource = generateDefaultActions(url, defaultParams);
    if (actions) {
      Object.getOwnPropertyNames(actions).forEach(function (name) {
        var action = new ResourceAction(url, defaultParams, actions[name]);
        resource[name] = function () {
          action.makeRequest.apply(action, arguments);
        };
      });
    }
    return resource;
  };

  super_res__superRes.promiseWrapper = function promiseWrapper(wrapperFunc) {
    return function (resource) {
      var proxiedResource = super_res__assign({}, resource);
      Object.getOwnPropertyNames(resource).forEach(function (name) {
        var actionFunction = proxiedResource[name];
        proxiedResource[name] = function () {
          for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }

          var promise = actionFunction.apply(proxiedResource, args);
          return wrapperFunc(promise);
        };
      });
      return proxiedResource;
    };
  };

  var super_res = super_res__superRes;

  return super_res;
});
//# sourceMappingURL=super-res.js.map<|endoftext|>


<commit_before>/**
	Copyright (C) 2014  Matheus Borges Teixeira

	This is a part of Arkanos Organizer Suite (AOS) app.
	AOS is a web application for organizing personal goals.

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

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

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

/**
 * View for displaying instructions and disclaimers.
 */
Ext.define('AOS.view.Information', {
	extend: 'Ext.tab.Panel',
	requires: [
		'Ext.TitleBar',
		'AOS.view.statistics.CompletionGraph',
		'AOS.view.statistics.DedicationGraph',
		'AOS.view.statistics.ProductivityGraph',
		'AOS.view.statistics.FocusGraph',
		'AOS.view.button.Logout',
		'AOS.view.button.MainMenu'
	],
	config: {
		tabBarPosition: 'bottom',
		scrollable: 'horizontal',
		items: [
			{
				docked: 'top',
				xtype: 'titlebar',
				title: 'Information',
				items: [
					{
						xtype:'button',
						ui: 'round',
						iconCls: 'aos-icon-back',
						align: 'left',
						handler: function(){
							AOS.Helper.switchTo('AOS.view.Login',{ type: 'slide', direction: 'right' });
						}
					}
				]
			},
			{
				title: 'About',
				iconCls: 'aos-icon-about',
				styleHtmlContent: true,
				scrollable: true,
				html:	'
'+
						'
About
'+
						'
 AOSv0.2.1
Arkanos Organizer Suite
Matheus Borges Teixeira
'+
						'
 This is a tool for managing personal goals, with possibility of breaking down into tasks and logging work, allowing statistical analysis on performance. It was created by Matheus Borges Teixeira. This application is offered free of charge under the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
'+
						'
 Contact the Author via matheus.bt at gmail or via his GitHub.'+

						'
Important links
'+
						'
Complete Source Code
'+
						'
Report issues
'+
						'
Source Code of the App
'+

						'
Cookie Policy
'+
						'
 Cookies are only used to store the authentication token.
'+

						'
Security
'+
						'
All passwords are hashed in the client, so they are never stored. The problem with security is that this first version of the application can do all network comunication without secured connection. Make sure always to use the application with HTTPS if you want protection.
'+
						'
',
				items: []
			},
			{
				title: 'Instructions',
				iconCls: 'aos-icon-instructions',
				styleHtmlContent: true,
				scrollable: true,
				html:	'
'+

						'
General Instructions
'+
						'
Login and Sign Up
'+
						'
 There is no mistery here. Either a user can log in using an existing account or create a new one. For users who forgot their credentials, AOS offers a reset via the "Forgot password?" button.
'+
						'
Creating new accounts
'+
						'
No confirmation is needed after the account is created for the user to start operating the application, but unconfirmed emails will be removed (along with any other user data) after one week. Please check your inbox and spam folder and follow the email instructions to confirm the email.
'+
						'
Authentication and Security
'+
						'
Due to technical limitations on the hosting server, unfortunately the credentials will not last more than a couple hours. The design is set to a day, so this is the max, but depending on traffic for the app it will last mostly less than that. Your password is secured via a MD5 hash, but for the first version of the application all communication is performed through an unsecure protocol.
'+

						'
Main operations
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-back','Back Button')+'
'+
						'
Will always return you to the previous screen.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-mainmenu','Menu Button')+'
'+
						'
Displays the drop down menu with all possible views from the application.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-logout','Logout Button')+'
'+
						'
 Either on the drop menu or in the top right corner, it will invalidate the user\'s authentication and remove local data, requiring a new login to be made.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-save','Save Button')+'
'+
						'
For Goals, Tasks and Work entries, makes the changes effective.
'+

						'
'+AOS.Helper.wrapInIcon('aos-icon-statistics','Statistics')+'
'+
						'
 Here you will be able to see how things are going with your goals and some graphical display of interesting metrics.
'+
						'
Important
'+
						'
 All legend labels are scrollable horizontally.
'+
						''+
						'
'+AOS.Helper.wrapInIcon('aos-icon-overview','Overview')+'
'+
						'
Most of the numbers in this tab are really straightforward, with exception of some:
'+
						'
Surplus/Deficit
'+
						'
The server will do a simple calculation of how much time have you should have spent based on the amount of days passed, comparing this number to the actual count of spent hours. Please note that this system assumes a linear progression (i.e. your planning is based on a fixed amount of hours per day) which should be fine for most of the cases and over the days the difference will average itself out. For a non-uniform distribution, keep in mind this metric might be off.
'+
						'
Expected Completion
'+
						'
Based on the current day, estimates how your progression should be. Basically this metric will always show how much of the year has actually passed.
'+
						'
Dedication
'+
						'
It is defined by the percentage of time spent on a goal in relation to the original planned time.
'+
						'
Productivity
'+
						'
Simple relation between the dedication and completion. Closer this value is to 1.0, means that plan is proceeding as expected. Lower productivity indicates initial planned time might have been not enough and higher values indicate overestimation.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-completion','Completion')+'
'+
						'
Simple line chart with the progression over time for each goal.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-dedication','Dedication')+'
'+
						'
Simple line chart with the dedication over time for each goal.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-productivity','Productivity')+'
'+
						'
Bar chart indicating the effective productivity for each goal. It is very important to note that the productivity in a particular time takes into consideration the time up to that point. This means the last (most recent) information indicates the most correct effective productivity. Regarding usability, the graph only displays half of the available time range, but it is possible to pan over the entire period.
'+
						''+
						'
'+AOS.Helper.wrapInIcon('aos-icon-focus','Focus')+'
'+
						'
Displays the distribution of the time spent by each goal over time. The distribution is only within the actual logged work, and does not show relation to the time planned. It also does not consider the obtained results.
'+

						'
'+AOS.Helper.wrapInIcon('aos-icon-goals','Goals')+'
'+
						'
In this view the user can see a list and a brief status of all the current goals, ordered by completion ascending.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-details','Details')+'
'+
						'
Opens an overlay with more detailed information about the selected goal.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-remove','Remove')+'
'+
						'
Removes the selected goal.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-tasks','New Task')+'
'+
						'
Creates a new task for the selected goal.
'+
						'
Creating Tasks
'+
						'
Only three fields are possible to be set: "Task Name", "Initial", "Target" and all are required.
'+
						'
How to select the values
'+
						'
It is very important that appropriate values are selected both in the initial and target fields. The system will use them in a linear progression (from:0%, to:100%) to calculate completion. Once logging work, it will have an "result" that accumulates in this progression.
'+
						'
Any numeric value is accepted. Suggested and most common strategies are based on number of parts, or simply, if the task is atomic, a binary value. If the task is hard to quanticize, it is suggested that an arbitrary progression from 0 to 100 to be used.
'+
						'
The selected strategy must be in mind once work will be logged, as the result will accumulate here.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-new','New')+'
'+
						'
Creates a new goal. Only three fields are possible to be set: "Goal Title", "Total Time Planned" in hours and "Description".
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-edit','Edit')+'
'+
						'
This is inside the Details overlay, but basically opens the same view with a preselected Goal to be changed.
'+

						'
'+AOS.Helper.wrapInIcon('aos-icon-tasks','Tasks')+'
'+
						'
In this view the user can see a list and a detailed status of all the current tasks. Those are ordered alphabetically by the "Goal Name" where they belong to.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-details','Edit')+'
'+
						'
Opens the same view as the task creation on the "Goals" view, but with a preselected task to be edited.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-remove','Remove')+'
'+
						'
Removes the selected task.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-worklog','Log Work')+'
'+
						'
Here the user can add an entry to the worklog. Only one field cannot be edited, the "Task Name". All others can, and the only optional is the "Comment".
'+
						'
Date
'+
						'
The date unfortunately follows the US pattern and by default is always the current day, but any date, now, before on in the future can be selected.
'+
						'
Hour and Minute
'+
						'
The hour is standard 24 hour time, and the minute is restricted to quarters. This time indicates when the work actually started.
'+
						'
Added Value
'+
						'
This field is very important, as it will be added to the "Initial" value of the task to define completion towards the "Target". The user must have in mind what kind of strategy was selected on the task creation, to define an adequate value in this log entry.
'+
						'
Spent Time
'+
						'
Total time spent, in minutes, with the given work.
'+

						'
'+AOS.Helper.wrapInIcon('aos-icon-worklog','Worklog')+'
'+
						'
In this view the user can see a complete list of the work entries logged in the application. The worklog is ordered by date descending.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-remove','Remove')+'
'+
						'
Removes the selected work entry.
'+
						'
'+
						'
 AOS Arkanos Organizer Suite
'+
						'
 Copyright (C) 2014 Matheus Borges Teixeira
'+
						'

'+
						'
',
				items: []
			},
			{
				title: 'Copyrights',
				iconCls: 'aos-icon-copyright',
				styleHtmlContent: true,
				scrollable: true,
				html:	'
'+
						'
 AOS - Arkanos Organizer Suite
'+
						'
 Copyright (C) 2014 Matheus Borges Teixeira
'+
						'

'+
						'
 PW Small Icons
'+
						'Copyright (C) 2013 Peax Webdesign
'+
						'
 Kingthings Trypewriter
'+
						'Copyright (C) 2005 Kingthings
'+
						'
 Crypto JS
'+
						'Copyright (c) 2009  Jeff Mott
'+
						'
',
				items: []
			}
		]
	}
});
<commit_msg>Closing first milestone: v1.0.0<commit_after>/**
	Copyright (C) 2014  Matheus Borges Teixeira

	This is a part of Arkanos Organizer Suite (AOS) app.
	AOS is a web application for organizing personal goals.

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

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

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

/**
 * View for displaying instructions and disclaimers.
 */
Ext.define('AOS.view.Information', {
	extend: 'Ext.tab.Panel',
	requires: [
		'Ext.TitleBar',
		'AOS.view.statistics.CompletionGraph',
		'AOS.view.statistics.DedicationGraph',
		'AOS.view.statistics.ProductivityGraph',
		'AOS.view.statistics.FocusGraph',
		'AOS.view.button.Logout',
		'AOS.view.button.MainMenu'
	],
	config: {
		tabBarPosition: 'bottom',
		scrollable: 'horizontal',
		items: [
			{
				docked: 'top',
				xtype: 'titlebar',
				title: 'Information',
				items: [
					{
						xtype:'button',
						ui: 'round',
						iconCls: 'aos-icon-back',
						align: 'left',
						handler: function(){
							AOS.Helper.switchTo('AOS.view.Login',{ type: 'slide', direction: 'right' });
						}
					}
				]
			},
			{
				title: 'About',
				iconCls: 'aos-icon-about',
				styleHtmlContent: true,
				scrollable: true,
				html:	'
'+
						'
About
'+
						'
 AOSv1.0.0
Arkanos Organizer Suite
Matheus Borges Teixeira
'+
						'
 This is a tool for managing personal goals, with possibility of breaking down into tasks and logging work, allowing statistical analysis on performance. It was created by Matheus Borges Teixeira. This application is offered free of charge under the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
'+
						'
 Contact the Author via matheus.bt at gmail or via his GitHub.'+

						'
Important links
'+
						'
Complete Source Code
'+
						'
Report issues
'+
						'
Source Code of the App
'+

						'
Cookie Policy
'+
						'
 Cookies are only used to store the authentication token.
'+

						'
Security
'+
						'
All passwords are hashed in the client, so they are never stored. The problem with security is that this first version of the application can do all network comunication without secured connection. Make sure always to use the application with HTTPS if you want protection.
'+
						'
',
				items: []
			},
			{
				title: 'Instructions',
				iconCls: 'aos-icon-instructions',
				styleHtmlContent: true,
				scrollable: true,
				html:	'
'+

						'
General Instructions
'+
						'
Login and Sign Up
'+
						'
 There is no mistery here. Either a user can log in using an existing account or create a new one. For users who forgot their credentials, AOS offers a reset via the "Forgot password?" button.
'+
						'
Creating new accounts
'+
						'
No confirmation is needed after the account is created for the user to start operating the application, but unconfirmed emails will be removed (along with any other user data) after one week. Please check your inbox and spam folder and follow the email instructions to confirm the email.
'+
						'
Authentication and Security
'+
						'
Due to technical limitations on the hosting server, unfortunately the credentials will not last more than a couple hours. The design is set to a day, so this is the max, but depending on traffic for the app it will last mostly less than that. Your password is secured via a MD5 hash, but for the first version of the application all communication is performed through an unsecure protocol.
'+

						'
Main operations
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-back','Back Button')+'
'+
						'
Will always return you to the previous screen.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-mainmenu','Menu Button')+'
'+
						'
Displays the drop down menu with all possible views from the application.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-logout','Logout Button')+'
'+
						'
 Either on the drop menu or in the top right corner, it will invalidate the user\'s authentication and remove local data, requiring a new login to be made.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-save','Save Button')+'
'+
						'
For Goals, Tasks and Work entries, makes the changes effective.
'+

						'
'+AOS.Helper.wrapInIcon('aos-icon-statistics','Statistics')+'
'+
						'
 Here you will be able to see how things are going with your goals and some graphical display of interesting metrics.
'+
						'
Important
'+
						'
 All legend labels are scrollable horizontally.
'+
						''+
						'
'+AOS.Helper.wrapInIcon('aos-icon-overview','Overview')+'
'+
						'
Most of the numbers in this tab are really straightforward, with exception of some:
'+
						'
Surplus/Deficit
'+
						'
The server will do a simple calculation of how much time have you should have spent based on the amount of days passed, comparing this number to the actual count of spent hours. Please note that this system assumes a linear progression (i.e. your planning is based on a fixed amount of hours per day) which should be fine for most of the cases and over the days the difference will average itself out. For a non-uniform distribution, keep in mind this metric might be off.
'+
						'
Expected Completion
'+
						'
Based on the current day, estimates how your progression should be. Basically this metric will always show how much of the year has actually passed.
'+
						'
Dedication
'+
						'
It is defined by the percentage of time spent on a goal in relation to the original planned time.
'+
						'
Productivity
'+
						'
Simple relation between the dedication and completion. Closer this value is to 1.0, means that plan is proceeding as expected. Lower productivity indicates initial planned time might have been not enough and higher values indicate overestimation.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-completion','Completion')+'
'+
						'
Simple line chart with the progression over time for each goal.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-dedication','Dedication')+'
'+
						'
Simple line chart with the dedication over time for each goal.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-productivity','Productivity')+'
'+
						'
Bar chart indicating the effective productivity for each goal. It is very important to note that the productivity in a particular time takes into consideration the time up to that point. This means the last (most recent) information indicates the most correct effective productivity. Regarding usability, the graph only displays half of the available time range, but it is possible to pan over the entire period.
'+
						''+
						'
'+AOS.Helper.wrapInIcon('aos-icon-focus','Focus')+'
'+
						'
Displays the distribution of the time spent by each goal over time. The distribution is only within the actual logged work, and does not show relation to the time planned. It also does not consider the obtained results.
'+

						'
'+AOS.Helper.wrapInIcon('aos-icon-goals','Goals')+'
'+
						'
In this view the user can see a list and a brief status of all the current goals, ordered by completion ascending.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-details','Details')+'
'+
						'
Opens an overlay with more detailed information about the selected goal.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-remove','Remove')+'
'+
						'
Removes the selected goal.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-tasks','New Task')+'
'+
						'
Creates a new task for the selected goal.
'+
						'
Creating Tasks
'+
						'
Only three fields are possible to be set: "Task Name", "Initial", "Target" and all are required.
'+
						'
How to select the values
'+
						'
It is very important that appropriate values are selected both in the initial and target fields. The system will use them in a linear progression (from:0%, to:100%) to calculate completion. Once logging work, it will have an "result" that accumulates in this progression.
'+
						'
Any numeric value is accepted. Suggested and most common strategies are based on number of parts, or simply, if the task is atomic, a binary value. If the task is hard to quanticize, it is suggested that an arbitrary progression from 0 to 100 to be used.
'+
						'
The selected strategy must be in mind once work will be logged, as the result will accumulate here.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-new','New')+'
'+
						'
Creates a new goal. Only three fields are possible to be set: "Goal Title", "Total Time Planned" in hours and "Description".
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-edit','Edit')+'
'+
						'
This is inside the Details overlay, but basically opens the same view with a preselected Goal to be changed.
'+

						'
'+AOS.Helper.wrapInIcon('aos-icon-tasks','Tasks')+'
'+
						'
In this view the user can see a list and a detailed status of all the current tasks. Those are ordered alphabetically by the "Goal Name" where they belong to.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-details','Edit')+'
'+
						'
Opens the same view as the task creation on the "Goals" view, but with a preselected task to be edited.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-remove','Remove')+'
'+
						'
Removes the selected task.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-worklog','Log Work')+'
'+
						'
Here the user can add an entry to the worklog. Only one field cannot be edited, the "Task Name". All others can, and the only optional is the "Comment".
'+
						'
Date
'+
						'
The date unfortunately follows the US pattern and by default is always the current day, but any date, now, before on in the future can be selected.
'+
						'
Hour and Minute
'+
						'
The hour is standard 24 hour time, and the minute is restricted to quarters. This time indicates when the work actually started.
'+
						'
Added Value
'+
						'
This field is very important, as it will be added to the "Initial" value of the task to define completion towards the "Target". The user must have in mind what kind of strategy was selected on the task creation, to define an adequate value in this log entry.
'+
						'
Spent Time
'+
						'
Total time spent, in minutes, with the given work.
'+

						'
'+AOS.Helper.wrapInIcon('aos-icon-worklog','Worklog')+'
'+
						'
In this view the user can see a complete list of the work entries logged in the application. The worklog is ordered by date descending.
'+
						'
'+AOS.Helper.wrapInIcon('aos-icon-remove','Remove')+'
'+
						'
Removes the selected work entry.
'+
						'
'+
						'
 AOS Arkanos Organizer Suite
'+
						'
 Copyright (C) 2014 Matheus Borges Teixeira
'+
						'

'+
						'
',
				items: []
			},
			{
				title: 'Copyrights',
				iconCls: 'aos-icon-copyright',
				styleHtmlContent: true,
				scrollable: true,
				html:	'
'+
						'
 AOS - Arkanos Organizer Suite
'+
						'
 Copyright (C) 2014 Matheus Borges Teixeira
'+
						'

'+
						'
 PW Small Icons
'+
						'Copyright (C) 2013 Peax Webdesign
'+
						'
 Kingthings Trypewriter
'+
						'Copyright (C) 2005 Kingthings
'+
						'
 Crypto JS
'+
						'Copyright (c) 2009  Jeff Mott
'+
						'
',
				items: []
			}
		]
	}
});
<|endoftext|>


<commit_before>SB.Player = function (scene, x, y) {
	this.scene = scene;

	this.startX = x || 0;
	this.startY = y || 0;
};

Object.defineProperty(SB.Player.prototype, 'x', {
	get: function () {
		return this.torso.m_position.x;
	}
});

Object.defineProperty(SB.Player.prototype, 'y', {
	get: function () {
		return this.torso.m_position.y;
	}
});

Object.defineProperty(SB.Player.prototype, 'r', {
	get: function () {
		return this.torso.m_R;
	}
});

SB.Player.prototype.init = function (physSim) {
	// Torso
	var boxSd = new b2BoxDef();
	boxSd.extents.Set(15, 25);
	boxSd.density = 1.0;
	boxSd.restitution = 0.5;
	boxSd.friction = 0;
	var boxBd = new b2BodyDef();
	boxBd.AddShape(boxSd);
	boxBd.position.Set(this.startX, this.startY);
	this.torso = physSim.CreateBody(boxBd);

	// Head
	var circleSd = new b2CircleDef();
	circleSd.density = 1.0;
	circleSd.radius = 15;
	circleSd.restitution = 0.5;
	circleSd.friction = 0;
	var circleBd = new b2BodyDef();
	circleBd.AddShape(circleSd);
	circleBd.position.Set(this.startX, this.startY-40);
	this.colliderDef = circleBd;
	this.head = physSim.CreateBody(circleBd);

	// Neck
	var jointDef = new b2DistanceJointDef();
	jointDef.anchorPoint1 = this.head.m_position;
	jointDef.anchorPoint2 = this.torso.m_position;
	jointDef.body1 = this.head;
	jointDef.body2 = this.torso;
	physSim.CreateJoint(jointDef);
};

SB.Player.prototype.render = function (ctx) {
	ctx.save();
	ctx.setTransform(this.r.col1.x, this.r.col1.y, this.r.col2.x, this.r.col2.y, this.x, this.y);
	ctx.fillStyle = 'blue';
	ctx.fillRect(-15, -25, 30, 50);
	ctx.beginPath();
	ctx.arc(0, -40, 15, 0, 2*Math.PI);
	ctx.fillStyle = 'red';
	ctx.fill();
	ctx.restore();

	ctx.beginPath();
	ctx.arc(this.x, this.y, this.radius, 0, 2*Math.PI);
	ctx.fillStyle = 'red';
	ctx.fill();
	return true;
};<commit_msg>Give player some semblance of a body<commit_after>SB.Player = function (scene, x, y) {
	this.scene = scene;

	this.startX = x || 0;
	this.startY = y || 0;
};

Object.defineProperty(SB.Player.prototype, 'x', {
	get: function () {
		return this.torso.m_position.x;
	}
});

Object.defineProperty(SB.Player.prototype, 'y', {
	get: function () {
		return this.torso.m_position.y;
	}
});

Object.defineProperty(SB.Player.prototype, 'r', {
	get: function () {
		return this.torso.m_R;
	}
});

SB.Player.prototype.init = function (physSim) {
	// TODO: Figure out a more elegant way to do this.

	// Torso
	var boxSd = new b2BoxDef();
	boxSd.extents.Set(15, 25);
	boxSd.density = 1.0;
	boxSd.restitution = 0.5;
	boxSd.friction = 0;
	var boxBd = new b2BodyDef();
	boxBd.AddShape(boxSd);
	boxBd.position.Set(this.startX, this.startY);
	this.torso = physSim.CreateBody(boxBd);

	// Head
	var circleSd = new b2CircleDef();
	circleSd.density = 1.0;
	circleSd.radius = 15;
	circleSd.restitution = 0.5;
	circleSd.friction = 0;
	var circleBd = new b2BodyDef();
	circleBd.AddShape(circleSd);
	circleBd.position.Set(this.startX, this.startY-40);
	this.colliderDef = circleBd;
	this.head = physSim.CreateBody(circleBd);

	// Neck
	var jointDef = new b2RevoluteJointDef();
	jointDef.anchorPoint.Set(this.startX, this.startY-25);
	jointDef.body1 = this.torso;
	jointDef.body2 = this.head;
	jointDef.lowerAngle = -0.2*Math.PI;
	jointDef.upperAngle = 0.2*Math.PI;
	jointDef.enableLimit = true;
	physSim.CreateJoint(jointDef);

	// ArmR
	var boxSd = new b2BoxDef();
	boxSd.extents.Set(5, 15);
	boxSd.density = 1.0;
	boxSd.restitution = 0.5;
	boxSd.friction = 0;
	var boxBd = new b2BodyDef();
	boxBd.AddShape(boxSd);
	boxBd.position.Set(this.startX-15, this.startY-10);
	this.armR = physSim.CreateBody(boxBd);

	// ShoulderR
	var jointDef = new b2RevoluteJointDef();
	jointDef.anchorPoint.Set(this.startX-15, this.startY-10-15);
	jointDef.body1 = this.torso;
	jointDef.body2 = this.armR;
	physSim.CreateJoint(jointDef);

	// ArmL
	var boxSd = new b2BoxDef();
	boxSd.extents.Set(5, 15);
	boxSd.density = 1.0;
	boxSd.restitution = 0.5;
	boxSd.friction = 0;
	var boxBd = new b2BodyDef();
	boxBd.AddShape(boxSd);
	boxBd.position.Set(this.startX+15, this.startY-10);
	this.armL = physSim.CreateBody(boxBd);

	// ShoulderL
	var jointDef = new b2RevoluteJointDef();
	jointDef.anchorPoint.Set(this.startX+15, this.startY-10-15);
	jointDef.body1 = this.torso;
	jointDef.body2 = this.armL;
	physSim.CreateJoint(jointDef);

	// LegR
	var boxSd = new b2BoxDef();
	boxSd.extents.Set(5, 15);
	boxSd.density = 1.0;
	boxSd.restitution = 0.5;
	boxSd.friction = 0;
	var boxBd = new b2BodyDef();
	boxBd.AddShape(boxSd);
	boxBd.position.Set(this.startX-10, this.startY+40);
	this.legR = physSim.CreateBody(boxBd);

	// HipR
	var jointDef = new b2RevoluteJointDef();
	jointDef.anchorPoint.Set(this.startX-10, this.startY+40-15);
	jointDef.body1 = this.torso;
	jointDef.body2 = this.legR;
	jointDef.lowerAngle = -0.5*Math.PI;
	jointDef.upperAngle = 0.5*Math.PI;
	jointDef.enableLimit = true;
	physSim.CreateJoint(jointDef);

	// LegL
	var boxSd = new b2BoxDef();
	boxSd.extents.Set(5, 15);
	boxSd.density = 1.0;
	boxSd.restitution = 0.5;
	boxSd.friction = 0;
	var boxBd = new b2BodyDef();
	boxBd.AddShape(boxSd);
	boxBd.position.Set(this.startX+10, this.startY+40);
	this.legL = physSim.CreateBody(boxBd);

	// HipL
	var jointDef = new b2RevoluteJointDef();
	jointDef.anchorPoint.Set(this.startX+10, this.startY+40-15);
	jointDef.body1 = this.torso;
	jointDef.body2 = this.legL;
	jointDef.lowerAngle = -0.5*Math.PI;
	jointDef.upperAngle = 0.5*Math.PI;
	jointDef.enableLimit = true;
	physSim.CreateJoint(jointDef);
};

SB.Player.prototype.render = function (ctx) {
	ctx.save();

	// TODO: And this.

	ctx.setTransform(this.r.col1.x, this.r.col1.y, this.r.col2.x, this.r.col2.y, this.x, this.y);
	ctx.fillStyle = 'red';
	ctx.fillRect(-15, -25, 30, 50);

	ctx.beginPath();
	ctx.setTransform(this.head.m_R.col1.x, this.head.m_R.col1.y, this.head.m_R.col2.x, this.head.m_R.col2.y, this.head.m_position.x, this.head.m_position.y);
	ctx.arc(0, 0, 15, 0, 2*Math.PI);
	ctx.fillStyle = 'pink';
	ctx.fill();

	ctx.setTransform(this.armR.m_R.col1.x, this.armR.m_R.col1.y, this.armR.m_R.col2.x, this.armR.m_R.col2.y, this.armR.m_position.x, this.armR.m_position.y);
	ctx.fillStyle = 'orange';
	ctx.fillRect(-5, -15, 10, 30);

	ctx.setTransform(this.armL.m_R.col1.x, this.armL.m_R.col1.y, this.armL.m_R.col2.x, this.armL.m_R.col2.y, this.armL.m_position.x, this.armL.m_position.y);
	ctx.fillStyle = 'orange';
	ctx.fillRect(-5, -15, 10, 30);

	ctx.setTransform(this.legR.m_R.col1.x, this.legR.m_R.col1.y, this.legR.m_R.col2.x, this.legR.m_R.col2.y, this.legR.m_position.x, this.legR.m_position.y);
	ctx.fillStyle = 'green';
	ctx.fillRect(-5, -15, 10, 30);

	ctx.setTransform(this.legL.m_R.col1.x, this.legL.m_R.col1.y, this.legL.m_R.col2.x, this.legL.m_R.col2.y, this.legL.m_position.x, this.legL.m_position.y);
	ctx.fillStyle = 'green';
	ctx.fillRect(-5, -15, 10, 30);

	ctx.restore();

	ctx.beginPath();
	ctx.arc(this.x, this.y, this.radius, 0, 2*Math.PI);
	ctx.fillStyle = 'red';
	ctx.fill();
	return true;
};<|endoftext|>


<commit_before>'use strict'

let cli = require('heroku-cli-util')
let fs = require('fs')
let uuid = require('node-uuid')
let os = require('os')
let path = require('path')
let request = require('request')
let exec = require('child_process').execSync
let nodeTar = require('../../lib/node_tar')

function compressSource (context, tar, cwd, tempFile, cb) {
  let tarVersion = exec(tar + ' --version').toString()

  if (tarVersion.match(/GNU tar/)) {
    let excludeVcsIgnore = context.flags['exclude-vcs-ignore'] || 'true'
    let command = tar + ' cz -C ' + cwd + ' --exclude .git --exclude .gitmodules .'

    if (excludeVcsIgnore === 'true') {
      command += ' --exclude-vcs-ignores'
    }

    exec(command + ' > ' + tempFile)
    cb()
  } else {
    cli.warn('Couldn\'t detect GNU tar. Builds could fail due to decompression errors')
    cli.warn('See https://devcenter.heroku.com/articles/platform-api-deploying-slugs#create-slug-archive')
    cli.warn('Please install it, or specify the \'--tar\' option')
    cli.warn('Falling back to node\'s built-in compressor')
    nodeTar.call(cwd, tempFile, cb)
  }
}

function uploadCwdToSource (context, app, cwd, tar, fn) {
  let tempFilePath = path.join(os.tmpdir(), uuid.v4() + '.tar.gz')

  app.sources().create({}).then(function (source) {
    compressSource(context, tar, cwd, tempFilePath, function () {
      let requestOptions = {
        url: source.source_blob.put_url,
        headers: {
          'Content-Type': '',
          'Content-Length': fs.statSync(tempFilePath).size
        }
      }

      var stream = fs.createReadStream(tempFilePath)
      stream.on('close', function () {
        fs.unlink(tempFilePath)
      })

      stream.pipe(request.put(requestOptions, function () {
        fn(source.source_blob.get_url)
      }))
    })
  })
}

function create (context, heroku) {
  let app = heroku.apps(context.app)

  var sourceUrl = context.flags['source-url']
  var tar = context.flags['tar'] || 'tar'

  var sourceUrlPromise = sourceUrl
    ? new Promise(function (resolve) { resolve(sourceUrl) })
    : new Promise(function (resolve) { uploadCwdToSource(context, app, process.cwd(), tar, resolve) })

  return sourceUrlPromise.then(function (sourceGetUrl) {
    return app.builds().create({
      source_blob: {
        url: sourceGetUrl,
        // TODO provide better default, eg. archive md5
        version: context.flags.version || ''
      }
    })
  })
  .then(function (build) {
    request.get(build.output_stream_url).pipe(process.stderr)
  })
}

module.exports = {
  topic: 'builds',
  command: 'create',
  needsAuth: true,
  needsApp: true,
  help: 'Create build from contents of current dir',
  description: 'create build',
  flags: [
    { name: 'source-url', description: 'source URL that points to the tarball of your application\'s source code', hasValue: true },
    { name: 'tar', description: 'path to the executable GNU tar', hasValue: true },
    { name: 'version', description: 'description of your new build', hasValue: true },
    { name: 'exclude-vcs-ignore', description: 'exclude files ignores by VCS (.gitignore, ...) from the build', hasValue: true }
  ],
  run: cli.command(create)
}
<commit_msg>inverse include/exclude vcs-ignore and make the parameter a boolean<commit_after>'use strict'

let cli = require('heroku-cli-util')
let fs = require('fs')
let uuid = require('node-uuid')
let os = require('os')
let path = require('path')
let request = require('request')
let exec = require('child_process').execSync
let nodeTar = require('../../lib/node_tar')

function compressSource (context, tar, cwd, tempFile, cb) {
  let tarVersion = exec(tar + ' --version').toString()

  if (tarVersion.match(/GNU tar/)) {
    let includeVcsIgnore = context.flags['include-vcs-ignore']
    let command = tar + ' cz -C ' + cwd + ' --exclude .git --exclude .gitmodules .'

    if (!includeVcsIgnore) {
      command += ' --exclude-vcs-ignores'
    }

    exec(command + ' > ' + tempFile)
    cb()
  } else {
    cli.warn('Couldn\'t detect GNU tar. Builds could fail due to decompression errors')
    cli.warn('See https://devcenter.heroku.com/articles/platform-api-deploying-slugs#create-slug-archive')
    cli.warn('Please install it, or specify the \'--tar\' option')
    cli.warn('Falling back to node\'s built-in compressor')
    nodeTar.call(cwd, tempFile, cb)
  }
}

function uploadCwdToSource (context, app, cwd, tar, fn) {
  let tempFilePath = path.join(os.tmpdir(), uuid.v4() + '.tar.gz')

  app.sources().create({}).then(function (source) {
    compressSource(context, tar, cwd, tempFilePath, function () {
      let requestOptions = {
        url: source.source_blob.put_url,
        headers: {
          'Content-Type': '',
          'Content-Length': fs.statSync(tempFilePath).size
        }
      }

      var stream = fs.createReadStream(tempFilePath)
      stream.on('close', function () {
        fs.unlink(tempFilePath)
      })

      stream.pipe(request.put(requestOptions, function () {
        fn(source.source_blob.get_url)
      }))
    })
  })
}

function create (context, heroku) {
  let app = heroku.apps(context.app)

  var sourceUrl = context.flags['source-url']
  var tar = context.flags['tar'] || 'tar'

  var sourceUrlPromise = sourceUrl
    ? new Promise(function (resolve) { resolve(sourceUrl) })
    : new Promise(function (resolve) { uploadCwdToSource(context, app, process.cwd(), tar, resolve) })

  return sourceUrlPromise.then(function (sourceGetUrl) {
    return app.builds().create({
      source_blob: {
        url: sourceGetUrl,
        // TODO provide better default, eg. archive md5
        version: context.flags.version || ''
      }
    })
  })
  .then(function (build) {
    request.get(build.output_stream_url).pipe(process.stderr)
  })
}

module.exports = {
  topic: 'builds',
  command: 'create',
  needsAuth: true,
  needsApp: true,
  help: 'Create build from contents of current dir',
  description: 'create build',
  flags: [
    { name: 'source-url', description: 'source URL that points to the tarball of your application\'s source code', hasValue: true },
    { name: 'tar', description: 'path to the executable GNU tar', hasValue: true },
    { name: 'version', description: 'description of your new build', hasValue: true },
    { name: 'include-vcs-ignore', description: 'include files ignores by VCS (.gitignore, ...) from the build' }
  ],
  run: cli.command(create)
}
<|endoftext|>


<commit_before>var express = require('express');
var User = require('../models/user');
var Loan = require('../models/loan');
var request = require('request');
var passport = require('../configs/passport');
var router = express.Router();

router.get('/', function(req, res){
    User.find({}, function(err, users){
        return res.json({
            'status': true,
            'users': users
        });
    });
});

/* User Autherization */
router.get('/authenticate', passport.authenticate('venmo', { 'scope': []}));

router.get('/authenticate/callback', passport.authenticate('venmo'), function(req, res){
    if(req.user){
        return res.json({
            "status" : true
        });
    }

    return res.json({
        "status" : false
    });
});

router.get('/:username', function(req, res){
    User.findOne({'username' : req.params.username}, function(err, user){
        if(err){
            return res.json({
                'status': false,
                'error': err
            });
        }

        if(!user){
            return res.json({
                'status': false,
                'message': "Couldn't find User"
            });
        }

        return res.json({
            'status': true,
            'user': user
        });
    });
});

router.get('/:username/:loanID', function(req, res){
    User.findOne({'username' : req.params.username}, function(err, user){
        if(err){
            return res.json({
                'status': false,
                'error': err
            });
        }

        if(!user){
            return res.json({
                'status': false,
                'message': "Couldn't find loan"
            });
        }

        for(var i = 0; i < user.loans_given.length(); i++){
            if(user.loans_given[i] == 'loanID'){
                Loan.findOne({'_id' : req.params.loanID}, function(err, loan){
                    if(err){
                        return res.json({
                            'status': false,
                            'error': err
                        });
                    }

                    return res.json({
                        'status': true,
                        'loan': loan
                    });
                });
            }
        }
    });
});

router.post('/:username', function(req, res){
    User.findOne({'username' : req.params.username}, function(err, user){
        if(err){
            return res.json({
                'status': false,
                'error': err
            });
        }

        if(!user){
            return res.json({
                'status': false,
                'message': "Couldn't find User"
            });
        }

        var loan = new Loan({'borrower_username' : req.body.borrower, 'loaner_username' : req.body.loaner,
            'amount' : req.body.amount, 'interest_rate' : req.body.interest_rate, 'loan_period' : req.body.loan_period,
            'payback_start_date' : req.body.payback_start_date});

        loan.save(function (err, loan) {

            if (err){
                return res.json({
                    'status': false,
                    'error': err
                });
            }
        });

    });
});

module.exports = router;<commit_msg>save the dam user doe<commit_after>var express = require('express');
var User = require('../models/user');
var Loan = require('../models/loan');
var request = require('request');
var passport = require('../configs/passport');
var router = express.Router();

router.get('/', function(req, res){
    User.find({}, function(err, users){
        return res.json({
            'status': true,
            'users': users
        });
    });
});

/* User Autherization */
router.get('/authenticate', passport.authenticate('venmo', { scope: []}));

router.get('/authenticate/callback', passport.authenticate('venmo'), function(req, res){
    if(req.user){
        return res.json({
            "status" : true
        });
    }

    return res.json({
        "status" : false
    });
});

router.get('/:username', function(req, res){
    User.findOne({'username' : req.params.username}, function(err, user){
        if(err){
            return res.json({
                'status': false,
                'error': err
            });
        }

        if(!user){
            return res.json({
                'status': false,
                'message': "Couldn't find User"
            });
        }

        return res.json({
            'status': true,
            'user': user
        });
    });
});

router.get('/:username/:loanID', function(req, res){
    User.findOne({'username' : req.params.username}, function(err, user){
        if(err){
            return res.json({
                'status': false,
                'error': err
            });
        }

        if(!user){
            return res.json({
                'status': false,
                'message': "Couldn't find loan"
            });
        }

        for(var i = 0; i < user.loans_given.length(); i++){
            if(user.loans_given[i] == 'loanID'){
                Loan.findOne({'_id' : req.params.loanID}, function(err, loan){
                    if(err){
                        return res.json({
                            'status': false,
                            'error': err
                        });
                    }

                    return res.json({
                        'status': true,
                        'loan': loan
                    });
                });
            }
        }
    });
});

router.post('/:username', function(req, res){
    User.findOne({'username' : req.params.username}, function(err, user){
        if(err){
            return res.json({
                'status': false,
                'error': err
            });
        }

        if(!user){
            return res.json({
                'status': false,
                'message': "Couldn't find User"
            });
        }

        var loan = new Loan({'borrower_username' : req.body.borrower, 'loaner_username' : req.body.loaner,
            'amount' : req.body.amount, 'interest_rate' : req.body.interest_rate, 'loan_period' : req.body.loan_period,
            'payback_start_date' : req.body.payback_start_date});

        loan.save(function (err, loan) {

            if (err){
                return res.json({
                    'status': false,
                    'error': err
                });
            }
        });

    });
});

module.exports = router;<|endoftext|>


<commit_before>/**
 * Server-side application framework for Node.js
 * @version v1.0.0-rc.1
 * @link https://github.com/xublit/xublit-io#readme
 * @license MIT License, http://www.opensource.org/licenses/MIT
 */
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

Object.defineProperty(exports, "__esModule", {
    value: true
});

require('babel-polyfill');

var _events = require('events');

var _events2 = _interopRequireDefault(_events);

var _xublitInjector = require('xublit-injector');

var _xublitInjector2 = _interopRequireDefault(_xublitInjector);

var _path = require('path');

var path = _interopRequireWildcard(_path);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * XublitApp
 *
 * @class
 */

var XublitApp = function (_EventEmitter) {
    _inherits(XublitApp, _EventEmitter);

    /**
     * Constructor
     *
     * @method     constructor
     * @param      {object}  opts    Options for the XublitApp
     */

    function XublitApp(opts) {
        _classCallCheck(this, XublitApp);

        var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(XublitApp).call(this));

        opts = parseOptions(_this, opts);

        initInjector(_this, {
            baseDir: opts.baseDir,
            includeDirs: _this.includeDirs,
            bootstrapScopeVars: {
                app: _this
            }
        });

        return _this;
    }

    _createClass(XublitApp, [{
        key: 'emit',
        value: function emit() {
            throw new Error('No.');
        }

        /**
         * Run `fn` before starting
         *
         * Same as calling `xublitApp.once('before:start', fn)`
         *
         * @method     beforeStart
         * @param      {Function}  fn      The function to run
         * @return     {XublitApp}
         */

    }, {
        key: 'beforeStart',
        value: function beforeStart(fn) {
            this.once('before:start', fn);
            return this;
        }

        /**
         * Run `fn` when all modules have been bootstrapped
         *
         * This is the best place to get your modules to do startup things like
         * connecting to databases, starting web servers, etc.
         *
         * Same as calling `xublitApp.once('bootstrapped', fn)`
         *
         * @method     afterBootstrap
         * @param      {Function}  fn      The function to run
         * @return     {XublitApp}
         */

    }, {
        key: 'afterBootstrap',
        value: function afterBootstrap(fn) {
            this.once('bootstrapped', fn);
            return this;
        }

        /**
         * Run `fn` when the app is started
         *
         * @method     onceStarted
         * @param      {Function}  fn      The function to run
         * @return     {XublitApp}
         */

    }, {
        key: 'onceStarted',
        value: function onceStarted(fn) {
            this.once('started', fn);
            return this;
        }

        /**
         * Starts the XublitApp by bootstrapping all modules
         *
         * @method     start
         * @return     {XublitApp}
         */

    }, {
        key: 'start',
        value: function start() {

            emit(this, 'before:start');

            this.injector.bootstrap();

            emit(this, 'bootstrapped');
            emit(this, 'started');

            return this;
        }

        /**
         * Stops the XublitApp
         *
         * @method     stop
         * @return     {XublitApp}
         */

    }, {
        key: 'stop',
        value: function stop() {
            var _this2 = this;

            this.on('stop', function () {
                _this2.halt();
            });

            emit(this, 'stop');

            return this;
        }

        /**
         * Exits the process
         *
         * @method     halt
         * @param      {boolean}  confirm  Must be true to exit
         * @return     {XublitApp}
         */

    }, {
        key: 'halt',
        value: function halt(confirm) {

            if (true !== confirm) {
                return this;
            }

            process.exit();
        }
    }, {
        key: 'includeDirs',
        get: function get() {

            var opts = this.options;

            var includeDirs = opts.includeDirs.concat([path.join(opts.baseDir, opts.srcDir)]);

            if (true === opts.includeNpmXublits) {
                includeDirs.push(path.join(opts.baseDir, 'node_modules', 'xublit-*'));
            }

            return includeDirs;
        }
    }]);

    return XublitApp;
}(_events2.default);

exports.default = XublitApp;

function initInjector(xublitApp, opts) {
    Object.defineProperty(xublitApp, 'injector', {
        value: new _xublitInjector2.default(opts)
    });
}

function parseOptions(xublitApp, opts) {

    if (!opts.baseDir) {
        throw new Error('Missing "baseDir" option');
    }

    Object.defineProperty(xublitApp, 'options', {
        value: {}
    });

    var defaults = {
        baseDir: '',
        srcDir: './src',
        etcDir: './etc',
        includeNpmXublits: true,
        includeDirs: []
    };

    Object.keys(defaults).forEach(function (key) {

        var value = key in opts ? opts[key] : defaults[key];

        switch (key) {

            case 'includeDirs':
                _xublitInjector2.default.assertValidIncludeDirs(value);
                value = value.slice(0);
                break;

        }

        Object.defineProperty(xublitApp.options, key, {
            value: value,
            enumerable: true
        });
    });

    return xublitApp.options;
}

function emit(xublitApp) {
    var emitArgs = [].concat(Array.prototype.slice.call(arguments));
    emitArgs.shift();
    _events2.default.prototype.emit.apply(xublitApp, emitArgs);
}
//# sourceMappingURL=xublit-io.js.map
<commit_msg>release 1.0.0-rc.2<commit_after>/**
 * Server-side application framework for Node.js
 * @version v1.0.0-rc.2
 * @link https://github.com/xublit/xublit-io#readme
 * @license MIT License, http://www.opensource.org/licenses/MIT
 */
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

Object.defineProperty(exports, "__esModule", {
    value: true
});

require('babel-polyfill');

var _events = require('events');

var _events2 = _interopRequireDefault(_events);

var _xublitInjector = require('xublit-injector');

var _xublitInjector2 = _interopRequireDefault(_xublitInjector);

var _path = require('path');

var path = _interopRequireWildcard(_path);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * XublitApp
 *
 * @class
 */

var XublitApp = function (_EventEmitter) {
    _inherits(XublitApp, _EventEmitter);

    /**
     * Constructor
     *
     * @method     constructor
     * @param      {object}  opts    Options for the XublitApp
     */

    function XublitApp(opts) {
        _classCallCheck(this, XublitApp);

        var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(XublitApp).call(this));

        opts = parseOptions(_this, opts);

        initInjector(_this, {
            baseDir: opts.baseDir,
            includeDirs: _this.includeDirs,
            bootstrapScopeVars: {
                app: _this
            }
        });

        return _this;
    }

    _createClass(XublitApp, [{
        key: 'emit',
        value: function emit() {
            throw new Error('No.');
        }

        /**
         * Run `fn` before starting
         *
         * Same as calling `xublitApp.once('before:start', fn)`
         *
         * @method     beforeStart
         * @param      {Function}  fn      The function to run
         * @return     {XublitApp}
         */

    }, {
        key: 'beforeStart',
        value: function beforeStart(fn) {
            this.once('before:start', fn);
            return this;
        }

        /**
         * Run `fn` when all modules have been bootstrapped
         *
         * This is the best place to get your modules to do startup things like
         * connecting to databases, starting web servers, etc.
         *
         * Same as calling `xublitApp.once('bootstrapped', fn)`
         *
         * @method     afterBootstrap
         * @param      {Function}  fn      The function to run
         * @return     {XublitApp}
         */

    }, {
        key: 'afterBootstrap',
        value: function afterBootstrap(fn) {
            this.once('bootstrapped', fn);
            return this;
        }

        /**
         * Run `fn` when the app is started
         *
         * @method     onceStarted
         * @param      {Function}  fn      The function to run
         * @return     {XublitApp}
         */

    }, {
        key: 'onceStarted',
        value: function onceStarted(fn) {
            this.once('started', fn);
            return this;
        }

        /**
         * Starts the XublitApp by bootstrapping all modules
         *
         * @method     start
         * @return     {XublitApp}
         */

    }, {
        key: 'start',
        value: function start() {

            emit(this, 'before:start');

            this.injector.bootstrap();

            emit(this, 'bootstrapped');
            emit(this, 'started');

            return this;
        }

        /**
         * Stops the XublitApp
         *
         * @method     stop
         * @return     {XublitApp}
         */

    }, {
        key: 'stop',
        value: function stop() {
            var _this2 = this;

            this.on('stop', function () {
                _this2.halt();
            });

            emit(this, 'stop');

            return this;
        }

        /**
         * Exits the process
         *
         * @method     halt
         * @param      {boolean}  confirm  Must be true to exit
         * @return     {XublitApp}
         */

    }, {
        key: 'halt',
        value: function halt(confirm) {

            if (true !== confirm) {
                return this;
            }

            process.exit();
        }
    }, {
        key: 'includeDirs',
        get: function get() {

            var opts = this.options;

            var includeDirs = opts.includeDirs.concat([path.join(opts.baseDir, opts.srcDir)]);

            if (true === opts.includeNpmXublits) {
                includeDirs.push(path.join(opts.baseDir, 'node_modules', 'xublit-*'));
            }

            return includeDirs;
        }
    }]);

    return XublitApp;
}(_events2.default);

exports.default = XublitApp;

function initInjector(xublitApp, opts) {
    Object.defineProperty(xublitApp, 'injector', {
        value: new _xublitInjector2.default(opts)
    });
}

function parseOptions(xublitApp, opts) {

    if (!opts.baseDir) {
        throw new Error('Missing "baseDir" option');
    }

    Object.defineProperty(xublitApp, 'options', {
        value: {}
    });

    var defaults = {
        baseDir: '',
        srcDir: './src',
        etcDir: './etc',
        includeNpmXublits: true,
        includeDirs: []
    };

    Object.keys(defaults).forEach(function (key) {

        var value = key in opts ? opts[key] : defaults[key];

        switch (key) {

            case 'includeDirs':
                _xublitInjector2.default.assertValidIncludeDirs(value);
                value = value.slice(0);
                break;

        }

        Object.defineProperty(xublitApp.options, key, {
            value: value,
            enumerable: true
        });
    });

    return xublitApp.options;
}

function emit(xublitApp) {
    var emitArgs = [].concat(Array.prototype.slice.call(arguments));
    emitArgs.shift();
    _events2.default.prototype.emit.apply(xublitApp, emitArgs);
}
//# sourceMappingURL=xublit-io.js.map
<|endoftext|>


<commit_before>var struct = require('./structure');
var vector = require('./vector');
var Vec2 = vector.Vec2;

function Player(team, source, homeLocation, world) {
  this.team = team;
  this.ants = [];
  this.homeLocation = homeLocation;
  this.world = world;

  var aether = this.aether = new Aether({
    yieldAutomatically: true
    // yieldConditionally: true
  });

  aether.lint(source);
  // TODO(michael): Check for any problems

  aether.transpile(source);
  this.func = aether.createFunction();

  // TODO(michael): Debug
  console.log(aether.pure);

  var actionComplete = false;
  // Add an ant to the player object
  this.addAnt = function(location) {
    console.log("Adding an ant");
    // Create the ant
    var ant = new struct.Ant(this.team, location, world);
    this.ants.push(ant);

    var shim = Object.create(null);
    // MOVEMENT
    shim.moveLeft = function() {
      actionComplete = true;
      return ant.move(new Vec2(-1, 0));
    };
    shim.moveRight = function() {
      actionComplete = true;
      return ant.move(new Vec2(1, 0));
    };
    shim.moveUp = function() {
      actionComplete = true;
      return ant.move(new Vec2(0, -1));
    };
    shim.moveDown = function() {
      actionComplete = true;
      return ant.move(new Vec2(0, 1));
    };

    shim.digLeft = function() {
      actionComplete = true;
      return ant.dig(new Vec2(-1, 0));
    };
    shim.digRight = function() {
      actionComplete = true;
      return ant.dig(new Vec2(1, 0));
    };
    shim.digUp = function() {
      actionComplete = true;
      return ant.dig(new Vec2(0, -1));
    };
    shim.digDown = function() {
      actionComplete = true;
      return ant.dig(new Vec2(0, 1));
    };

    shim.moveDigLeft = function() {
      if (! shim.moveLeft()) {
        return shim.digLeft();
      }
      return true;
    };
    shim.moveDigRight = function() {
      if (! shim.moveRight()) {
        return shim.digRight();
      }
      return true;
    };
    shim.moveDigUp = function() {
      if (! shim.moveUp()) {
        return shim.digUp();
      }
      return true;
    };
    shim.moveDigDown = function() {
      if (! shim.moveDown()) {
        return shim.digDown();
      }
      return true;
    };

    shim.getTeam = function() {
      return team;
    };

    // Checking or laying pheramones
    // NOTE(michael): Temporarially not working
    shim.sniff = function() {
      return world.map.pherAt(team,
                              new Vec2(ant.position.x, ant.position.y));
    };
    shim.spray = function(pheramone) {
      world.map.setPherAt(team,
                          new Vec2(ant.position.x, ant.position.y),
                          // Ensure that the object is valid JSON
                          JSON.parse(JSON.stringify(pheramone)));
    };

    shim.waffle = function() {
      console.log("WAFFLE");
    };

    shim.hasFood = function() {
        return ant.hasFood;
    };

    shim.homeLocation = function() {
        return homeLocation.clone();
    };

    shim.location = function() {
        return ant.position.clone();
    };

    // Start the script
    var func = aether.createFunction();
    ant.state = func.call(shim);
  };

  // Iterate over each of the ants, performing an action
  // var counter = 0; // TODO(michael): Rename
  var spawnCounter = 0;
  this.step = function() {
    this.ants.forEach(function(ant, index) {
      actionComplete = false;
      for (var i=0; i<500; i++) {
        var next = ant.state.next();
        if (next.done) { // Nuke the state object
          ant.state = {
            next: function() { }
          };
          break;
        }
        if (actionComplete) {
          break;
        }
      }
    });

    spawnCounter++;
    if (spawnCounter > 60) {
      this.addAnt(homeLocation.clone());
      spawnCounter = 0;
    }

    // Ant adding
    /* counter++;
    if (counter > 5) {
      console.log("Added an ant!");
      this.addAnt(homeLocation);
      counter = 0;
    } */
  };

  this.addAnt(homeLocation.clone());
}

module.exports = {
  Player: Player
};
<commit_msg>look api command<commit_after>var struct = require('./structure');
var vector = require('./vector');
var Vec2 = vector.Vec2;

function Player(team, source, homeLocation, world) {
  this.team = team;
  this.ants = [];
  this.homeLocation = homeLocation;
  this.world = world;

  var aether = this.aether = new Aether({
    yieldAutomatically: true
    // yieldConditionally: true
  });

  aether.lint(source);
  // TODO(michael): Check for any problems

  aether.transpile(source);
  this.func = aether.createFunction();

  // TODO(michael): Debug
  console.log(aether.pure);

  var actionComplete = false;
  // Add an ant to the player object
  this.addAnt = function(location) {
    console.log("Adding an ant");
    // Create the ant
    var ant = new struct.Ant(this.team, location, world);
    this.ants.push(ant);

    var shim = Object.create(null);
    // MOVEMENT
    shim.moveLeft = function() {
      actionComplete = true;
      return ant.move(new Vec2(-1, 0));
    };
    shim.moveRight = function() {
      actionComplete = true;
      return ant.move(new Vec2(1, 0));
    };
    shim.moveUp = function() {
      actionComplete = true;
      return ant.move(new Vec2(0, -1));
    };
    shim.moveDown = function() {
      actionComplete = true;
      return ant.move(new Vec2(0, 1));
    };

    shim.digLeft = function() {
      actionComplete = true;
      return ant.dig(new Vec2(-1, 0));
    };
    shim.digRight = function() {
      actionComplete = true;
      return ant.dig(new Vec2(1, 0));
    };
    shim.digUp = function() {
      actionComplete = true;
      return ant.dig(new Vec2(0, -1));
    };
    shim.digDown = function() {
      actionComplete = true;
      return ant.dig(new Vec2(0, 1));
    };

    shim.moveDigLeft = function() {
      if (! shim.moveLeft()) {
        return shim.digLeft();
      }
      return true;
    };
    shim.moveDigRight = function() {
      if (! shim.moveRight()) {
        return shim.digRight();
      }
      return true;
    };
    shim.moveDigUp = function() {
      if (! shim.moveUp()) {
        return shim.digUp();
      }
      return true;
    };
    shim.moveDigDown = function() {
      if (! shim.moveDown()) {
        return shim.digDown();
      }
      return true;
    };

    shim.getTeam = function() {
      return team;
    };

    // Checking or laying pheramones
    // NOTE(michael): Temporarially not working
    shim.sniff = function() {
      return world.map.pherAt(team,
                              new Vec2(ant.position.x, ant.position.y));
    };
    shim.spray = function(pheramone) {
      world.map.setPherAt(team,
                          new Vec2(ant.position.x, ant.position.y),
                          // Ensure that the object is valid JSON
                          JSON.parse(JSON.stringify(pheramone)));
    };

    shim.waffle = function() {
      console.log("WAFFLE");
    };

    shim.hasFood = function() {
        return ant.hasFood;
    };

    shim.homeLocation = function() {
        return homeLocation.clone();
    };

    shim.location = function() {
        return ant.position.clone();
    };

    shim.look = function(direction) {
        if (direction === 'up') {
            return world.map.map[ant.position.y-1][ant.position.x].type
        } else if (direction === 'down') {
            return world.map.map[ant.position.y+1][ant.position.x].type
        } else if (direction === 'left') {
            return world.map.map[ant.position.y][ant.position.x-1].type
        } else if (direction === 'right') {
            return world.map.map[ant.position.y][ant.position.x+1].type
        } else {
            return false;
        }
    }

    // Start the script
    var func = aether.createFunction();
    ant.state = func.call(shim);
  };

  // Iterate over each of the ants, performing an action
  // var counter = 0; // TODO(michael): Rename
  var spawnCounter = 0;
  this.step = function() {
    this.ants.forEach(function(ant, index) {
      actionComplete = false;
      for (var i=0; i<500; i++) {
        var next = ant.state.next();
        if (next.done) { // Nuke the state object
          ant.state = {
            next: function() { }
          };
          break;
        }
        if (actionComplete) {
          break;
        }
      }
    });

    spawnCounter++;
    if (spawnCounter > 60) {
      this.addAnt(homeLocation.clone());
      spawnCounter = 0;
    }

    // Ant adding
    /* counter++;
    if (counter > 5) {
      console.log("Added an ant!");
      this.addAnt(homeLocation);
      counter = 0;
    } */
  };

  this.addAnt(homeLocation.clone());
}

module.exports = {
  Player: Player
};
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var admin = require("firebase-admin");
var serviceAccount = require('../firebase_config.json');

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "https://unithon-8bf36.firebaseio.com/"
});

var client_id = 'SywgbqwVSP4an161TdKS';
var client_secret = 'DhTfuacMl_';
var state = "RANDOM_STATE";
var redirectURI = encodeURI("http://localhost:3000/users/auth");
var api_url = "";

router.get('/naverlogin', function (req, res) {
  api_url = 'https://nid.naver.com/oauth2.0/authorize?response_type=code&client_id=' + client_id + '&redirect_uri=' + redirectURI + '&state=' + state;
  res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
  res.end("");
});

router.get('/auth', function(req, res, next) {
  code = req.query.code;
  state = req.query.state;
  api_url = 'https://nid.naver.com/oauth2.0/token?grant_type=authorization_code&client_id='
      + client_id + '&client_secret=' + client_secret + '&redirect_uri=' + redirectURI + '&code=' + code + '&state=' + state;
  var request = require('request');
  var options = {
    url: api_url,
    headers: {'X-Naver-Client-Id':client_id, 'X-Naver-Client-Secret': client_secret}
  };
  request.get(options, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log("yeah");
      res.writeHead(200, {'Content-Type': 'text/json;charset=utf-8'});
      res.end(body);
      // admin.database().ref('users').set({
      //     username: "hi"
      // }).then((id) => {
      //     res.status(200).json("hi");
      // })

      //sess.userId = ""

    } else {
      res.status(response.statusCode).end();
      console.log('error = ' + response.statusCode);
    }
  });
});

router.get('/add', function(req, res, next) {
  const newRef = admin.database().ref('users').push();
  const newKey = newRef.key;
  const userObj = {
    id: newKey,
    name: "sarah"
  };
  newRef.set(userObj)
    .then(() => {
      return admin.database().ref('users').child(newKey).once('value');
    })
    .then((snap) => res.status(200).json(snap));
});

router.post('/account', function(req, res, next) {
  const id = "-KqCstYTIIxeecYJa8-n"; // Todo: Should be "req.session.userId" after naver login complete
  admin.database().ref('users').orderByChild('id').equalTo(id).once('value')
    .then((user) => {
      if (user.val() === null) {
        throw new Error("No matching user");
      }
      const key = Object.keys(user.val());
      return admin.database().ref('users').child(key[0]).set({
        id: id,
        bank: req.body.bank,
        accountNumber: req.body.accountNumber
      });
    })
    .then((user) => {
      res.status(200).json(user);
    })
    .catch((err) => {
      res.status(400).json({ err_msg: err.message });
    });
});

router.get('/id', function(req, res, next) {
  admin.database().ref('user').set({
    username: "hi"
  }).then((id) => {
    res.status(200).json("hi");
  })
});

module.exports = router;
<commit_msg>naver profile 조회<commit_after>var express = require('express');
var router = express.Router();
var admin = require("firebase-admin");
var serviceAccount = require('../firebase_config.json');

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "https://unithon-8bf36.firebaseio.com/"
});

var client_id = 'SywgbqwVSP4an161TdKS';
var client_secret = 'DhTfuacMl_';
var state = "RANDOM_STATE";
var redirectURI = encodeURI("http://localhost:3000/users/auth");
var api_url = "";

router.get('/naverlogin', function (req, res) {
  api_url = 'https://nid.naver.com/oauth2.0/authorize?response_type=code&client_id=' + client_id + '&redirect_uri=' + redirectURI + '&state=' + state;
  res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
  res.end("");
});

router.get('/auth', function(req, res, next) {
  code = req.query.code;
  state = req.query.state;
  api_url = 'https://nid.naver.com/oauth2.0/token?grant_type=authorization_code&client_id='
      + client_id + '&client_secret=' + client_secret + '&redirect_uri=' + redirectURI + '&code=' + code + '&state=' + state;
  var request = require('request');
  var options = {
    url: api_url,
    headers: {'X-Naver-Client-Id':client_id, 'X-Naver-Client-Secret': client_secret}
  };

  request.get(options, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      req.session.token = body.access_token;
      console.log(body.access_token);
      res.writeHead(200, {'Content-Type': 'text/json;charset=utf-8'});
      res.end(body);
    } else {
      res.status(response.statusCode).end();
      console.log('error = ' + response.statusCode);
    }
  });
});

router.get('/member', function (req, res) {
   var token = req.session.token;
   console.log(token);
   var header = "Bearer " + token;
   var api_url = 'https://openapi.naver.com/v1/nid/me';
   var request = require('request');
   var options = {
       url: api_url,
       headers: {'Authorization': header}
    };
   request.get(options, function (error, response, body) {
     if (!error && response.statusCode == 200) {
       res.writeHead(200, {'Content-Type': 'text/json;charset=utf-8'});
       res.end(body);
       console.log(body);
     } else {
       console.log('error');
       if(response != null) {
         res.status(response.statusCode).end();
         console.log('error = ' + response.statusCode);
       }
     }
   });
 });

router.get('/add', function(req, res, next) {
  const newRef = admin.database().ref('users').push();
  const newKey = newRef.key;
  const userObj = {
    id: newKey,
    name: "sarah"
  };
  newRef.set(userObj)
    .then(() => {
      return admin.database().ref('users').child(newKey).once('value');
    })
    .then((snap) => res.status(200).json(snap));
});

router.post('/account', function(req, res, next) {
  const id = "-KqCstYTIIxeecYJa8-n"; // Todo: Should be "req.session.userId" after naver login complete
  admin.database().ref('users').orderByChild('id').equalTo(id).once('value')
    .then((user) => {
      if (user.val() === null) {
        throw new Error("No matching user");
      }
      const key = Object.keys(user.val());
      return admin.database().ref('users').child(key[0]).set({
        id: id,
        bank: req.body.bank,
        accountNumber: req.body.accountNumber
      });
    })
    .then((user) => {
      res.status(200).json(user);
    })
    .catch((err) => {
      res.status(400).json({ err_msg: err.message });
    });
});

router.get('/id', function(req, res, next) {
  admin.database().ref('user').set({
    username: "hi"
  }).then((id) => {
    res.status(200).json("hi");
  })
});

module.exports = router;
<|endoftext|>