<commit_before>const slapp = require('./slapp.js').get();
const HashMap = require('hashmap');
const request = require('request');
const fs = require('fs');

var github = require('./github.js')
function _(obj){
  var str = JSON.stringify(obj, null, 4);
  console.log(str);
}
var buffer =[];
// Archiving feature state
var isArchiving = false;

/**
 * This function that handles the module behaviour when the server is about to restart
 */
function handle_restart(){
  keys = msgMap.keys();
  keys.forEach(function(key){
    var array = msgMap.get(key);
    if(array.length)
      archive_push(key);
  })
}
/**
 * This function receives a message and store it in a hashmap that will be pushed to the github archive
 * @param {object} msg the message sent by slapp that is meant to be archived
 */
function receive(msg){
  if(isArchiving){
    slapp.client.channels.info({token:msg.meta.bot_token,channel:msg.body.event.channel}, (err, resultChannel) => {
      slapp.client.users.info({token:msg.meta.bot_token,user:msg.body.event.user}, (uerr, resultUser) => {
        var timeStamp = new Date(msg.body.event.ts * 1000)
        var obj = {user:resultUser.user.name,
                    ts:timeStamp,
                    text:msg.body.event.text,
                    channel:resultChannel.channel.name};
        buffer.push(obj);
        archive_push();
      });
    });
  }
}
// Sets the handler for the slash command
slapp.command('/archivetogit','(.*)', (msg, text, value)  => {
  slapp.client.users.info({token:msg.meta.bot_token,user:msg.body.user_id}, (err, data) => {
    if( data.user.is_admin){
      if(!text)
        msg.respond("Options for /archivetogit: \n" +
                    "\`start\` starts the archiving to git. (Github token must be initialized first using /github)\n" +
                    "\`stop \` stops the archiving to git.\n" );
      else if(text == 'start')
        archive_start(msg);
      else if(text == 'stop')
        archive_stop(msg);
      else {
        msg.respond("Please use /archivetogit to print the available options.");
      }
    }
    else {
      msg.respond("Sorry, you're not an admin.");
    }
  })
})

function start(){
  isArchiving=true;
}
/**
 * This function starts the message archiving if a github token is specified
 * @param {object} msg the message received from slapp following the user command
 */
function archive_start(msg){
  if(github.getToken()!=''){
    if(!isArchiving){
  		isArchiving=true;
  	msg.respond("Archiving started.");
  	}
  	else {
  		msg.respond("Archiving is already in progress.");
  	}
  }else{
    msg.respond("Please set the github token first.");
  }
}
/**
 * This function stops the message archiving
 * @param {object} msg the message received from slapp following the user command
 */
function archive_stop(msg){
  if(isArchiving){
		isArchiving=false;
		msg.respond("Archiving stopped.");
	}
	else {
		msg.respond("Archiving is already stoped.");
	}
}
/**
 * This function pushes the message from the buffer to github
 */
function archive_push(){
  _('ARCHIVE PUSH buffer:');
  _(buffer);
  var channelPageName = buffer[0].channel + '.md';
  github.get().repos.getContent({
   owner:'NeuroTechX',
   repo:'ntx_slack_archive',
   path:''},function(err,result){
    var found = false;
    for (var i = 0; i < result.length && !found; i++) {
      if (result[i].name === channelPageName) {
        found = true;
      }
    }
    if(found)
      editPage(buffer[0]);
    else {
      createPage(buffer[0]);
    }
  });
}
/**
 * This function edits the github page specified by pageName adding values to it
 * @param {string} obj the data to push
 */
// function editPage(obj){
//   var filePath = "https://raw.githubusercontent.com/NeuroTechX/ntx_slack_archive/master/"+obj.channel+'.md';
//   var propertiesObject = {access_token:github.getToken()};
// 	request.get({url:filePath, qs:propertiesObject}, function (fileerror, fileresponse, fileBody) {
//   	if (!fileerror && fileresponse.statusCode == 200) {
//
//       var quotedText = obj.text.replace(/([\n\r])/g, '\n\n> $1');
//       fileBody+= ""+formatDate(obj.ts)+"\n\n **"+ obj.user +"**" + " :\n\n >" + quotedText + "\n\n";
//
// 			//fs.writeFile("slack-links.md", fileBody, {encoding: 'base64'}, function(err){console.log("error encoding the file to b64")});
//       var content = Buffer.from(fileBody, 'ascii');
//       var b64content = content.toString('base64');
// 			var blobPath = "https://api.github.com/repos/NeuroTechX/ntx_slack_archive/contents/"+obj.channel+'.md';
//       var options = {
//         url: blobPath,
//         headers: {
//           'User-Agent': 'Edubot-GitHub-App'
//         },
//         qs:propertiesObject
//       };
// 			request.get(options, function (bloberror, blobresponse, blobBody) {
// 	    	if (!bloberror && blobresponse.statusCode == 200) {
//           var shaStr = JSON.parse(blobBody).sha;
//           //("Sha str")
// 					github.get().repos.updateFile({
// 						owner:"NeuroTechX",
// 						repo:"ntx_slack_archive",
// 						path:obj.channel+'.md',
// 						message:"Edubot Push",
// 						content:b64content,
// 						sha: shaStr
// 					}, function(err, res) {
//             buffer = [];
//           });
//         }
// 			});
//   	}
// 	});
// }
function editPage(obj){
  github.get().repos.getContent({
      owner:"NeuroTechX",
      repo:"ntx_slack_archive",
      path:obj.channel+'.md',
    },
    function(err,res){
  // var filePath = "https://raw.githubusercontent.com/NeuroTechX/ntx_slack_archive/master/"+obj.channel+'.md';
  // var propertiesObject = {access_token:github.getToken()};
	// request.get({url:filePath, qs:propertiesObject}, function (fileerror, fileresponse, fileBody) {
  	if (!err) {

      var quotedText = obj.text.replace(/([\n\r])/g, '\n\n> $1');
      var fileBody = res.slice();
      _("Res slice")
      _(res);
      fileBody+= ""+formatDate(obj.ts)+"\n\n **"+ obj.user +"**" + " :\n\n >" + quotedText + "\n\n";

			//fs.writeFile("slack-links.md", fileBody, {encoding: 'base64'}, function(err){console.log("error encoding the file to b64")});
      var content = Buffer.from(fileBody, 'ascii');
      var b64content = content.toString('base64');
			var blobPath = "https://api.github.com/repos/NeuroTechX/ntx_slack_archive/contents/"+obj.channel+'.md';
      var options = {
        url: blobPath,
        headers: {
          'User-Agent': 'Edubot-GitHub-App'
        },
        qs:propertiesObject
      };
			request.get(options, function (bloberror, blobresponse, blobBody) {
	    	if (!bloberror && blobresponse.statusCode == 200) {
          var shaStr = JSON.parse(blobBody).sha;
          //("Sha str")
					github.get().repos.updateFile({
						owner:"NeuroTechX",
						repo:"ntx_slack_archive",
						path:obj.channel+'.md',
						message:"Edubot Push",
						content:b64content,
						sha: shaStr
					}, function(err, res) {
            buffer = [];
          });
        }
			});
  	}
	});
}
/**
 * This function formats the timestamp to a user friendly format
 * @param {timestamp} ts the time stamp to format
 */
function formatDate(ts){
  return ts.toLocaleDateString("en-US") + " " + ts.toLocaleTimeString(["en-US"], {hour: '2-digit', minute:'2-digit'});
}
/**
 * This function creates a github archiving page
 * @param {string} obj data to push
 */
function createPage(obj){
      var fileBody = "######"+obj.channel+"\n\n";
      var quotedText = obj.text.replace(/([\n\r])/g, '\n\n> $1');
			fileBody+= ""+formatDate(obj.ts)+"\n\n **"+ obj.user +"**" + " :\n\n >" + quotedText + "\n\n";

      var content = Buffer.from(fileBody, 'ascii');
      var b64content = content.toString('base64');

      github.get().repos.createFile({
        owner:"NeuroTechX",
        repo:"ntx_slack_archive",
        path:obj.channel+'.md',
        message:"Edubot Push",
        content:b64content
      }, function(err, res) {
        buffer = [];
      });
}
module.exports = {
  receive:receive,
  handle_restart:handle_restart,
  start:start
}
<commit_msg>debug res<commit_after>const slapp = require('./slapp.js').get();
const HashMap = require('hashmap');
const request = require('request');
const fs = require('fs');

var github = require('./github.js')
function _(obj){
  var str = JSON.stringify(obj, null, 4);
  console.log(str);
}
var buffer =[];
// Archiving feature state
var isArchiving = false;

/**
 * This function that handles the module behaviour when the server is about to restart
 */
function handle_restart(){
  keys = msgMap.keys();
  keys.forEach(function(key){
    var array = msgMap.get(key);
    if(array.length)
      archive_push(key);
  })
}
/**
 * This function receives a message and store it in a hashmap that will be pushed to the github archive
 * @param {object} msg the message sent by slapp that is meant to be archived
 */
function receive(msg){
  if(isArchiving){
    slapp.client.channels.info({token:msg.meta.bot_token,channel:msg.body.event.channel}, (err, resultChannel) => {
      slapp.client.users.info({token:msg.meta.bot_token,user:msg.body.event.user}, (uerr, resultUser) => {
        var timeStamp = new Date(msg.body.event.ts * 1000)
        var obj = {user:resultUser.user.name,
                    ts:timeStamp,
                    text:msg.body.event.text,
                    channel:resultChannel.channel.name};
        buffer.push(obj);
        archive_push();
      });
    });
  }
}
// Sets the handler for the slash command
slapp.command('/archivetogit','(.*)', (msg, text, value)  => {
  slapp.client.users.info({token:msg.meta.bot_token,user:msg.body.user_id}, (err, data) => {
    if( data.user.is_admin){
      if(!text)
        msg.respond("Options for /archivetogit: \n" +
                    "\`start\` starts the archiving to git. (Github token must be initialized first using /github)\n" +
                    "\`stop \` stops the archiving to git.\n" );
      else if(text == 'start')
        archive_start(msg);
      else if(text == 'stop')
        archive_stop(msg);
      else {
        msg.respond("Please use /archivetogit to print the available options.");
      }
    }
    else {
      msg.respond("Sorry, you're not an admin.");
    }
  })
})

function start(){
  isArchiving=true;
}
/**
 * This function starts the message archiving if a github token is specified
 * @param {object} msg the message received from slapp following the user command
 */
function archive_start(msg){
  if(github.getToken()!=''){
    if(!isArchiving){
  		isArchiving=true;
  	msg.respond("Archiving started.");
  	}
  	else {
  		msg.respond("Archiving is already in progress.");
  	}
  }else{
    msg.respond("Please set the github token first.");
  }
}
/**
 * This function stops the message archiving
 * @param {object} msg the message received from slapp following the user command
 */
function archive_stop(msg){
  if(isArchiving){
		isArchiving=false;
		msg.respond("Archiving stopped.");
	}
	else {
		msg.respond("Archiving is already stoped.");
	}
}
/**
 * This function pushes the message from the buffer to github
 */
function archive_push(){
  _('ARCHIVE PUSH buffer:');
  _(buffer);
  var channelPageName = buffer[0].channel + '.md';
  github.get().repos.getContent({
   owner:'NeuroTechX',
   repo:'ntx_slack_archive',
   path:''},function(err,result){
    var found = false;
    for (var i = 0; i < result.length && !found; i++) {
      if (result[i].name === channelPageName) {
        found = true;
      }
    }
    if(found)
      editPage(buffer[0]);
    else {
      createPage(buffer[0]);
    }
  });
}
/**
 * This function edits the github page specified by pageName adding values to it
 * @param {string} obj the data to push
 */
// function editPage(obj){
//   var filePath = "https://raw.githubusercontent.com/NeuroTechX/ntx_slack_archive/master/"+obj.channel+'.md';
//   var propertiesObject = {access_token:github.getToken()};
// 	request.get({url:filePath, qs:propertiesObject}, function (fileerror, fileresponse, fileBody) {
//   	if (!fileerror && fileresponse.statusCode == 200) {
//
//       var quotedText = obj.text.replace(/([\n\r])/g, '\n\n> $1');
//       fileBody+= ""+formatDate(obj.ts)+"\n\n **"+ obj.user +"**" + " :\n\n >" + quotedText + "\n\n";
//
// 			//fs.writeFile("slack-links.md", fileBody, {encoding: 'base64'}, function(err){console.log("error encoding the file to b64")});
//       var content = Buffer.from(fileBody, 'ascii');
//       var b64content = content.toString('base64');
// 			var blobPath = "https://api.github.com/repos/NeuroTechX/ntx_slack_archive/contents/"+obj.channel+'.md';
//       var options = {
//         url: blobPath,
//         headers: {
//           'User-Agent': 'Edubot-GitHub-App'
//         },
//         qs:propertiesObject
//       };
// 			request.get(options, function (bloberror, blobresponse, blobBody) {
// 	    	if (!bloberror && blobresponse.statusCode == 200) {
//           var shaStr = JSON.parse(blobBody).sha;
//           //("Sha str")
// 					github.get().repos.updateFile({
// 						owner:"NeuroTechX",
// 						repo:"ntx_slack_archive",
// 						path:obj.channel+'.md',
// 						message:"Edubot Push",
// 						content:b64content,
// 						sha: shaStr
// 					}, function(err, res) {
//             buffer = [];
//           });
//         }
// 			});
//   	}
// 	});
// }
function editPage(obj){
  github.get().repos.getContent({
      owner:"NeuroTechX",
      repo:"ntx_slack_archive",
      path:obj.channel+'.md',
    },
    function(err,res){
  // var filePath = "https://raw.githubusercontent.com/NeuroTechX/ntx_slack_archive/master/"+obj.channel+'.md';
  // var propertiesObject = {access_token:github.getToken()};
	// request.get({url:filePath, qs:propertiesObject}, function (fileerror, fileresponse, fileBody) {
  	if (!err) {

      var quotedText = obj.text.replace(/([\n\r])/g, '\n\n> $1');
      //var fileBody = res.slice();
      _("Res slice")
      _(res);
      fileBody+= ""+formatDate(obj.ts)+"\n\n **"+ obj.user +"**" + " :\n\n >" + quotedText + "\n\n";

			//fs.writeFile("slack-links.md", fileBody, {encoding: 'base64'}, function(err){console.log("error encoding the file to b64")});
      var content = Buffer.from(fileBody, 'ascii');
      var b64content = content.toString('base64');
			var blobPath = "https://api.github.com/repos/NeuroTechX/ntx_slack_archive/contents/"+obj.channel+'.md';
      var options = {
        url: blobPath,
        headers: {
          'User-Agent': 'Edubot-GitHub-App'
        },
        qs:propertiesObject
      };
			request.get(options, function (bloberror, blobresponse, blobBody) {
	    	if (!bloberror && blobresponse.statusCode == 200) {
          var shaStr = JSON.parse(blobBody).sha;
          //("Sha str")
					github.get().repos.updateFile({
						owner:"NeuroTechX",
						repo:"ntx_slack_archive",
						path:obj.channel+'.md',
						message:"Edubot Push",
						content:b64content,
						sha: shaStr
					}, function(err, res) {
            buffer = [];
          });
        }
			});
  	}
	});
}
/**
 * This function formats the timestamp to a user friendly format
 * @param {timestamp} ts the time stamp to format
 */
function formatDate(ts){
  return ts.toLocaleDateString("en-US") + " " + ts.toLocaleTimeString(["en-US"], {hour: '2-digit', minute:'2-digit'});
}
/**
 * This function creates a github archiving page
 * @param {string} obj data to push
 */
function createPage(obj){
      var fileBody = "######"+obj.channel+"\n\n";
      var quotedText = obj.text.replace(/([\n\r])/g, '\n\n> $1');
			fileBody+= ""+formatDate(obj.ts)+"\n\n **"+ obj.user +"**" + " :\n\n >" + quotedText + "\n\n";

      var content = Buffer.from(fileBody, 'ascii');
      var b64content = content.toString('base64');

      github.get().repos.createFile({
        owner:"NeuroTechX",
        repo:"ntx_slack_archive",
        path:obj.channel+'.md',
        message:"Edubot Push",
        content:b64content
      }, function(err, res) {
        buffer = [];
      });
}
module.exports = {
  receive:receive,
  handle_restart:handle_restart,
  start:start
}
<|endoftext|>


<commit_before>'use strict';

/**
* Module dependencies
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;

/**
* Tasks Schema
*/

var taskSchema = new Schema ({
	name: {
		type: String,
		required: true
	},
	completed: {
		type: Boolean,
		required: true
	},
	description: {
		type: String,
		required: false
	},
	assignedMembers: {
		type: Array,
		required: true
	},
	dueDates: {
		type: Date,
		required: true
	}
});

mongoose.model('Tasks',taskSchema);<commit_msg>Changed datatype for assignedMembers from array to string (derp)<commit_after>'use strict';

/**
* Module dependencies
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;

/**
* Tasks Schema
*/

var taskSchema = new Schema ({
	name: {
		type: String,
		required: true
	},
	completed: {
		type: Boolean,
		required: true
	},
	description: {
		type: String,
		required: false
	},
	assignedMembers: {
		type: String,
		required: true
	},
	dueDates: {
		type: Date,
		required: true
	}
});

mongoose.model('Tasks',taskSchema);<|endoftext|>


<commit_before>let PROTO_PATH = __dirname + "/wkrpt401.proto"

let grpc = require('grpc');
let proto = grpc.load(PROTO_PATH).wkrpt401;

function getBestPersonality(call, callback) {
  let userData = call.request;
  var maxPersonalityValue = -1;
  var maxPersonalityName = "";
  for (var key in userData.personality) {
    if (userData.hasOwnProperty(key)) {
      let personalityValue = userData.personality[key];
      if (personalityValue > maxPersonalityValue) {
        maxPersonalityValue = personalityValue;
        maxPersonalityName = key;
      }
    }
  }

  let name = userData.name;
  let level = userData.level;
  let response = "The best personality attribute for " + name
                    + " (Lv. " + level + ") is " +
                    + maxPersonalityName;
  print("getBestPersonality called with response '" + response + "''");
  callback(null, {response: response});
}

function main() {
  var server = new grpc.Server();
  server.addProtoService(proto.UserManager.service, {getBestPersonality: getBestPersonality});
  let url = "localhost:8080";
  if (process.env.PORT) {
    url = "https://bmo-wkrpt401-grpc.herokuapp.com:" + process.env.PORT;
  }
  server.bind(url, grpc.ServerCredentials.createInsecure());

  server.start();
  console.log("WKRPT401 gRPC server starting @ " + url);
}

main();
<commit_msg>Remove "https" in server URL path<commit_after>let PROTO_PATH = __dirname + "/wkrpt401.proto"

let grpc = require('grpc');
let proto = grpc.load(PROTO_PATH).wkrpt401;

function getBestPersonality(call, callback) {
  let userData = call.request;
  var maxPersonalityValue = -1;
  var maxPersonalityName = "";
  for (var key in userData.personality) {
    if (userData.hasOwnProperty(key)) {
      let personalityValue = userData.personality[key];
      if (personalityValue > maxPersonalityValue) {
        maxPersonalityValue = personalityValue;
        maxPersonalityName = key;
      }
    }
  }

  let name = userData.name;
  let level = userData.level;
  let response = "The best personality attribute for " + name
                    + " (Lv. " + level + ") is " +
                    + maxPersonalityName;
  print("getBestPersonality called with response '" + response + "''");
  callback(null, {response: response});
}

function main() {
  var server = new grpc.Server();
  server.addProtoService(proto.UserManager.service, {getBestPersonality: getBestPersonality});
  let url = "localhost:8080";
  if (process.env.PORT) {
    url = "bmo-wkrpt401-grpc.herokuapp.com:" + process.env.PORT;
  }
  server.bind(url, grpc.ServerCredentials.createInsecure());

  server.start();
  console.log("WKRPT401 gRPC server starting @ " + url);
}

main();
<|endoftext|>


<commit_before>#!/bin/env node
//  OpenShift sample Node application
var express = require('express');
var fs      = require('fs');

/**
 *  Define the sample application.
 */
var SampleApp = function() {

    //  Scope.
    var self = this;

    /*  ================================================================  */
    /*  Helper functions.                                                 */
    /*  ================================================================  */

    /**
     *  Set up server IP address and port # using env variables/defaults.
     */
    self.setupVariables = function() {
        //  Set the environment variables we need.
        self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
        self.port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

        if (typeof self.ipaddress === "undefined") {
            //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
            //  allows us to run/test the app locally.
            console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
            self.ipaddress = "127.0.0.1";
        };
    };

    /**
     *  Populate the cache.
     */
    self.populateCache = function() {
        if (typeof self.zcache === "undefined") {
            self.zcache = { 'index.html': '' };
        }

        //  Local cache for static content.
        self.zcache['index.html'] = fs.readFileSync('./index.html');
    };

    /**
     *  Retrieve entry (content) from cache.
     *  @param {string} key  Key identifying content to retrieve from cache.
     */
    self.cache_get = function(key) { return self.zcache[key]; };

    /**
     *  terminator === the termination handler
     *  Terminate server on receipt of the specified signal.
     *  @param {string} sig  Signal to terminate on.
     */
    self.terminator = function(sig){
        if (typeof sig === "string") {
           console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), sig);
           process.exit(1);
        }
        console.log('%s: Node server stopped.', Date(Date.now()) );
    };

    /**
     *  Setup termination handlers (for exit and a list of signals).
     */
    self.setupTerminationHandlers = function(){
        //  Process on exit and signals.
        process.on('exit', function() { self.terminator(); });

        // Removed 'SIGPIPE' from the list - bugz 852598.
        ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { self.terminator(element); });
        });
    };

    /*  ================================================================  */
    /*  App server functions (main app logic here).                       */
    /*  ================================================================  */

    /**
     *  Create the routing table entries + handlers for the application.
     */
    self.createRoutes = function() {
        self.routes = { };

        self.routes['/asciimo'] = function(req, res) {
            var link = "http://i.imgur.com/kmbjB.png";
            res.send("");
        };

        self.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('index.html') );
        };
    };

    /**
     *  Initialize the server (express) and create the routes and register
     *  the handlers.
     */
    self.initializeServer = function() {
        self.createRoutes();
        self.app = express.createServer();

        //  Add handlers for the app (from the routes).
        for (var r in self.routes) {
            self.app.get(r, self.routes[r]);
        }
    };

    /**
     *  Initializes the sample application.
     */
    self.initialize = function() {
        self.setupVariables();
        self.populateCache();
        self.setupTerminationHandlers();

        // Create the express server and routes.
        self.initializeServer();
    };

    /**
     *  Start the server (starts up the sample application).
     */
    self.start = function() {
        //  Start the app on the specific interface (and port).
        self.app.listen(self.port, self.ipaddress, function() {
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), self.ipaddress, self.port);
        });
    };

};   /*  Sample Application.  */

/**
 *  main():  Main code.
 */
var zapp = new SampleApp();
zapp.initialize();
zapp.start();

<commit_msg>first-commit<commit_after>#!/bin/env node
//  OpenShift sample Node application
var express = require('express');
var fs      = require('fs');

/**
 *  Define the sample application.
 */
var SampleApp = function() {

    //  Scope.
    var self = this;

    /*  ================================================================  */
    /*  Helper functions.                                                 */
    /*  ================================================================  */

    /**
     *  Set up server IP address and port # using env variables/defaults.
     */
    self.setupVariables = function() {
        //  Set the environment variables we need.
        self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
        self.port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

        if (typeof self.ipaddress === "undefined") {
            //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
            //  allows us to run/test the app locally.
            console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
            self.ipaddress = "127.0.0.1";
        };
    };

    /**
     *  Populate the cache.
     */
    self.populateCache = function() {
        if (typeof self.zcache === "undefined") {
            self.zcache = { 'index.html': '' };
        }

        //  Local cache for static content.
        self.zcache['index.html'] = fs.readFileSync('./index.html');
    };

    /**
     *  Retrieve entry (content) from cache.
     *  @param {string} key  Key identifying content to retrieve from cache.
     */
    self.cache_get = function(key) { return self.zcache[key]; };

    /**
     *  terminator === the termination handler
     *  Terminate server on receipt of the specified signal.
     *  @param {string} sig  Signal to terminate on.
     */
    self.terminator = function(sig){
        if (typeof sig === "string") {
           console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), sig);
           process.exit(1);
        }
        console.log('%s: Node server stopped.', Date(Date.now()) );
    };

    /**
     *  Setup termination handlers (for exit and a list of signals).
     */
    self.setupTerminationHandlers = function(){
        //  Process on exit and signals.
        process.on('exit', function() { self.terminator(); });

        // Removed 'SIGPIPE' from the list - bugz 852598.
        ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { self.terminator(element); });
        });
    };

    /*  ================================================================  */
    /*  App server functions (main app logic here).                       */
    /*  ================================================================  */

    /**
     *  Create the routing table entries + handlers for the application.
     */
    self.createRoutes = function() {
        self.routes = { };

        self.routes['/alisson'] = function(req, res) {
            res.json({mensagem:"JSON rima com Alisson"});
        };

        self.routes['/asciimo'] = function(req, res) {
            var link = "http://i.imgur.com/kmbjB.png";
            res.send("");
        };

        self.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('index.html') );
        };
    };

    /**
     *  Initialize the server (express) and create the routes and register
     *  the handlers.
     */
    self.initializeServer = function() {
        self.createRoutes();
        self.app = express.createServer();

        //  Add handlers for the app (from the routes).
        for (var r in self.routes) {
            self.app.get(r, self.routes[r]);
        }
    };

    /**
     *  Initializes the sample application.
     */
    self.initialize = function() {
        self.setupVariables();
        self.populateCache();
        self.setupTerminationHandlers();

        // Create the express server and routes.
        self.initializeServer();
    };

    /**
     *  Start the server (starts up the sample application).
     */
    self.start = function() {
        //  Start the app on the specific interface (and port).
        self.app.listen(self.port, self.ipaddress, function() {
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), self.ipaddress, self.port);
        });
    };

};   /*  Sample Application.  */

/**
 *  main():  Main code.
 */
var zapp = new SampleApp();
zapp.initialize();
zapp.start();

<|endoftext|>


<commit_before>'use strict';
/**
 * Module dependencies.
 */
var init = require('./config/init')(),
	config = require('./config/config'),
	mongoose = require('mongoose'),
	chalk = require('chalk');

/**
 * Main application entry file.
 * Please note that the order of loading is important.
 */

// Bootstrap db connection
var db = mongoose.connect(config.db, function(err) {
	if (err) {
		console.error(chalk.red('Could not connect to MongoDB!'));
		console.log(chalk.red(err));
	}
});

// Init the express application
var app = require('./config/express')(db);

// Bootstrap passport config
require('./config/passport')();

// Start the app by listening on <port>
app.listen(config.port);

// Expose app
exports = module.exports = app;

// Logging initialization
console.log('MEAN.JS application started on port ' + config.port);<commit_msg>attempt without DB<commit_after>'use strict';
/**
 * Module dependencies.
 */
var init = require('./config/init')(),
	config = require('./config/config'),
	mongoose = require('mongoose'),
	chalk = require('chalk');

/**
 * Main application entry file.
 * Please note that the order of loading is important.
 */

// Bootstrap db connection
var db = {};
/*
For now, no database (!)
mongoose.connect(config.db, function(err) {
	if (err) {
		console.error(chalk.red('Could not connect to MongoDB!'));
		console.log(chalk.red(err));
	}
});
*/

// Init the express application
var app = require('./config/express')(db);

// Bootstrap passport config
require('./config/passport')();

// Start the app by listening on <port>
app.listen(config.port);

// Expose app
exports = module.exports = app;

// Logging initialization
console.log('MEAN.JS application started on port ' + config.port);<|endoftext|>


<commit_before>'use strict';

const Koa = require('koa');
const app = new Koa();
const bodyParser = require('koa-bodyparser');

// x-response-time

app.use(async function (ctx, next) {
    const start = new Date();
    await next();
    const ms = new Date() - start;
    ctx.set('X-Response-Time', `${ms}ms`);
});

// logger

app.use(async function (ctx, next) {
    const start = new Date();
    await next();
    const ms = new Date() - start;
    console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});

// response

app.use(bodyParser());

app.use(ctx => {
    ctx.body = ctx.request.body.text;

    // const inputCommand = ctx.originalUrl.replace('/', '');
    // const bitbucketRegex = /^https:\/\/bitbucket.org\/([a-z0-9\-_]+)\/([a-z0-9\-_]+)\/pull-requests\/([0-9]+)/gi
    // const bitbucketMatch = inputCommand.match(bitbucketRegex);
    //
    // ctx.body = "!" + inputCommand;

    // if (bitbucketMatch) {
    //     ctx.body = `It's a beautiful, bouncing, pull-request! Click <a href="${inputCommand}>here</a> to see it`;
    // } else {
    //     ctx.body = 'Sorry, but this wasn\'t recongised.  Either it\'s not a Bitbucket pull request, or @owen sucks at regex';
    // }
});

const port = process.env.PORT || 3000;

app.listen(port);<commit_msg>Should be a working version<commit_after>'use strict';

const Koa = require('koa');
const app = new Koa();
const bodyParser = require('koa-bodyparser');

// x-response-time

app.use(async function (ctx, next) {
    const start = new Date();
    await next();
    const ms = new Date() - start;
    ctx.set('X-Response-Time', `${ms}ms`);
});

// logger

app.use(async function (ctx, next) {
    const start = new Date();
    await next();
    const ms = new Date() - start;
    console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});

// response

app.use(bodyParser());

app.use(ctx => {
    const inputCommand = ctx.body.request.text;
    const bitbucketRegex = /^https:\/\/bitbucket.org\/([a-z0-9\-_]+)\/([a-z0-9\-_]+)\/pull-requests\/([0-9]+)/gi
    const bitbucketMatch = inputCommand.match(bitbucketRegex);

    if (bitbucketMatch) {
        ctx.body = `It's a beautiful, bouncing, pull-request! Click <a href="${inputCommand}>here</a> to see it`;
    } else {
        ctx.body = 'Sorry, but this wasn\'t recognised.  Either it\'s not a Bitbucket pull request, or @owen sucks at regex';
    }
});

const port = process.env.PORT || 3000;

app.listen(port);<|endoftext|>


<commit_before>var express = require('express'),
    app = express(),
    http = require('http'),
    socketIo = require('socket.io');

// start webserver on port 8080
var server =  http.createServer(app);
var io = socketIo.listen(server);
server.listen(8080);
// add directory with our static files
app.use(express.static(__dirname + '/public'));
console.log("Server running on 127.0.0.1:8080");

// array of all lines drawn
// 2000 x 2000
// characters are 5 x 5

var characterHistory = {};

// event-handler for new incoming connections
io.on('connection', function (socket) {

   // first send the history to the new client
   socket.emit('update_characters', characterHistory);

   // add handler for message type "draw_line".
   socket.on('move_character', function (data) {
      // add received line to history
      characterHistory[data.id]={x: data.pos.x, y: data.pos.y};
      // send line to all clients
      io.emit('update_characters', characterHistory);
   });

   // {id:ID, attack:{x: X, y: Y}, type:'A'}
   socket.on('attack', function(data) {
     for (var key in characterHistory) {
       if (characterHistory.hasOwnProperty(key)) {
         var character = characterHistory[key];
         if (Math.abs(character.x - data.attack.x) <= 2) && (Math.abs(character.y - data.attack.y) <= 2) {
           io.emit('character_dead', {id:i});
         }
       }
     }
   });

   socket.on('connect', function() {
     characterHistory[socket.id] = {x: ((Math.random()*1990)+5), y: ((Math.random()*1990)+5)};
     socket.emit('init_character', {id: socket.id, pos: characterHistory[characterHistory.length-1]});
   });

   socket.on('disconnect', function() {
     delete characterHistory[socket.id];
   });
});
<commit_msg>Another fix<commit_after>var express = require('express'),
    app = express(),
    http = require('http'),
    socketIo = require('socket.io');

// start webserver on port 8080
var server =  http.createServer(app);
var io = socketIo.listen(server);
server.listen(8080);
// add directory with our static files
app.use(express.static(__dirname + '/public'));
console.log("Server running on 127.0.0.1:8080");

// array of all lines drawn
// 2000 x 2000
// characters are 5 x 5

var characterHistory = {};

// event-handler for new incoming connections
io.on('connection', function (socket) {

   // first send the history to the new client
   socket.emit('update_characters', characterHistory);

   // add handler for message type "draw_line".
   socket.on('move_character', function (data) {
      // add received line to history
      characterHistory[data.id]={x: data.pos.x, y: data.pos.y};
      // send line to all clients
      io.emit('update_characters', characterHistory);
   });

   // {id:ID, attack:{x: X, y: Y}, type:'A'}
   socket.on('attack', function(data) {
     for (var key in characterHistory) {
       if (characterHistory.hasOwnProperty(key)) {
         var character = characterHistory[key];
         if (Math.abs(character.x - data.attack.x) <= 2) && (Math.abs(character.y - data.attack.y) <= 2) {
           io.emit('character_dead', {id:i});
         }
       }
     }
   });

   characterHistory[socket.id] = {x: ((Math.random()*1990)+5), y: ((Math.random()*1990)+5)};
   socket.emit('init_character', {id: socket.id, pos: characterHistory[socket.id]});

   socket.on('disconnect', function() {
     delete characterHistory[socket.id];
   });
});
<|endoftext|>


<commit_before>var http = require('http');

http.createServer(function (req, res) {

    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end('Hello, world!');

}).listen(process.env.PORT || 8080);<commit_msg>udpate default port<commit_after>var http = require('http');

http.createServer(function (req, res) {

    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end('Hello, world!');

}).listen(process.env.PORT || 3000);<|endoftext|>


<commit_before>var url = require('url'),
    fs = require('fs'),
    http = require('http'),
    bee = require('beeline'),
    SC_CLIENT_ID = '1288146c708a6fa789f74748fe960337';

var makeChain = function (args) {
  var chain = Array.prototype.slice.call(args, 2);
  chain.unshift(args[0]);
  return chain;
};

var chainCallbacks = function (args) {
  var chain = makeChain(args);
  var callback = args[1].apply(this, chain);
  return callback;
};

var errorHandler = function (err, response) {
  console.log(err);
  response.writeHead(500);
  response.end();
};

var serveError = function (response) {
  return function (err) {
    errorHandler(err, response);
  };
};

var handleResponse = function (response, callback, errorStatusCode, errorHeaders) {
  var responseHandler = function (res) {
    if (!res.headers.location) {
      res.headers['Content-Length'] = 0;
      errorStatusCode = errorStatusCode || res.statusCode;
      errorHeaders = errorHeaders || res.headers;
      response.writeHead(errorStatusCode, errorHeaders);
      response.end();
    } else {
      callback && callback(res);
    }
  };
  return responseHandler;
};

// resolves 'resource' from the SC API, and if found, passes it to a callback
var scResolve = function (resource, response, callback) {
  var reqOptions = {
    host: 'api.soundcloud.com',
    port: 80,
    path: '/resolve.json?client_id=' + SC_CLIENT_ID + '&url=http://soundcloud.com/' + resource,
    method: 'GET',
    headers: {
      'User-Agent': 'AudioJedit'
    }
  };

  var req = http.request(reqOptions, handleResponse(response, callback));

  req.on('error', serveError(response));

  req.end();

  return req;
};

var resolveTrack = function (response) {
  var callback = chainCallbacks(arguments);

  var responseHandler = function (track) {
    track = JSON.parse(track);
    var reqOptions = url.parse(track.stream_url);
    reqOptions = {
      host: reqOptions.host,
      path: reqOptions.pathname + '?client_id=' + SC_CLIENT_ID,
      headers: {
        'User-Agent': 'AudioJedit'
      }
    };

    var req = http.get(reqOptions, handleResponse(response, callback, 404, { 'Content-Type': 'application/octet-stream' }));

    req.on('error', serveError(response));

    return req;
  };
  return responseHandler;
};

var writeResponse = function (response) {
  var responseHandler = function (res) {
    response.writeHead(res.statusCode, res.headers);
    res.on('data', function (chunk) {
      response.write(chunk);
    });
    res.on('end', function () {
      response.end();
    });
  };
  return responseHandler;
};

var makeRequest = function (response) {
  var callback = chainCallbacks(arguments);

  var responseHandler = function (res) {
    var reqOptions = url.parse(res.headers.location);
    reqOptions = {
      host: reqOptions.host,
      port: 80,
      path: reqOptions.pathname + reqOptions.search,
      headers: {
        'User-Agent': 'AudioJedit'
      }
    };

    var req = http.get(reqOptions, callback);

    req.on('error', serveError(response));

    return req;
  };
  return responseHandler;
};

// gets chunked data, then passes data to a callback
var getChunks = function (response) {
  var callback = chainCallbacks(arguments);

  var responseHandler = function (res) {
    res.setEncoding('utf-8');
    var data = '';
    res.on('data', function (chunk) {
      data += chunk;
    });
    res.on('end', function () {
      callback(data);
    });
  };
  return responseHandler;
};

var serveIndex = function (response) {
  return fs.readFile('./public/index.html', function (err, data) {
    if (err) {
      console.log(err);
    } else {
      response.writeHead(200, { 'Content-Type': 'text/html' });
      response.end(data);
    }
  });
};

var router = bee.route({

  'r`^/public/(.*)`': bee.staticDir('./public/', {
    '.html': 'text/html',
    '.css': 'text/css',
    '.gif': 'image/gif',
    '.png': 'image/png',
    '.ico': 'image/png',
    '.js': 'text/javascript'
  }),

  'r`^/(index(\\.html?)?)?(\\?.*)?$`': function (req, response, matches) {
    return serveIndex(response);
  },

  'r`^/([\\w-_]+)/([\\w-_]+)/audio`': function (req, response, matches) {
    var resource = matches.join('/');

    return scResolve(resource, response, makeRequest(response, getChunks, resolveTrack, makeRequest, writeResponse));
  },

  'r`^/([\\w-_]+)/([\\w-_]+)(\\.\\w+)?`': function (req, response, matches) {
    var format = matches.filter(Boolean).length == 3 ? matches.pop().substring(1) : 'html';
    var resource = matches.join('/');

    // only json is permitted, else serve index
    if (format != 'json') {
      return serveIndex(response);
    }

    return scResolve(resource, response, makeRequest(response, writeResponse));
  }
});

http.createServer(router).listen(process.env.PORT || 8181);

<commit_msg>chain callbacks in scResolve<commit_after>var url = require('url'),
    fs = require('fs'),
    http = require('http'),
    bee = require('beeline'),
    SC_CLIENT_ID = '1288146c708a6fa789f74748fe960337';

var makeChain = function (args) {
  var chain = Array.prototype.slice.call(args, 2);
  chain.unshift(args[0]);
  return chain;
};

var chainCallbacks = function (args) {
  var chain = makeChain(args);
  var callback = args[1].apply(this, chain);
  return callback;
};

var errorHandler = function (err, response) {
  console.log(err);
  response.writeHead(500);
  response.end();
};

var serveError = function (response) {
  return function (err) {
    errorHandler(err, response);
  };
};

var handleResponse = function (response, callback, errorStatusCode, errorHeaders) {
  var responseHandler = function (res) {
    if (!res.headers.location) {
      res.headers['Content-Length'] = 0;
      errorStatusCode = errorStatusCode || res.statusCode;
      errorHeaders = errorHeaders || res.headers;
      response.writeHead(errorStatusCode, errorHeaders);
      response.end();
    } else {
      callback && callback(res);
    }
  };
  return responseHandler;
};

// resolves 'resource' from the SC API, and if found, passes it to a callback
var scResolve = function (resource, response) {
  var chainableArgs = Array.prototype.slice.call(arguments, 1);
  var callback = chainCallbacks(chainableArgs);

  var reqOptions = {
    host: 'api.soundcloud.com',
    port: 80,
    path: '/resolve.json?client_id=' + SC_CLIENT_ID + '&url=http://soundcloud.com/' + resource,
    method: 'GET',
    headers: {
      'User-Agent': 'AudioJedit'
    }
  };

  var req = http.request(reqOptions, handleResponse(response, callback));

  req.on('error', serveError(response));

  req.end();

  return req;
};

var resolveTrack = function (response) {
  var callback = chainCallbacks(arguments);

  var responseHandler = function (track) {
    track = JSON.parse(track);
    var reqOptions = url.parse(track.stream_url);
    reqOptions = {
      host: reqOptions.host,
      path: reqOptions.pathname + '?client_id=' + SC_CLIENT_ID,
      headers: {
        'User-Agent': 'AudioJedit'
      }
    };

    var req = http.get(reqOptions, handleResponse(response, callback, 404, { 'Content-Type': 'application/octet-stream' }));

    req.on('error', serveError(response));

    return req;
  };
  return responseHandler;
};

var writeResponse = function (response) {
  var responseHandler = function (res) {
    response.writeHead(res.statusCode, res.headers);
    res.on('data', function (chunk) {
      response.write(chunk);
    });
    res.on('end', function () {
      response.end();
    });
  };
  return responseHandler;
};

var makeRequest = function (response) {
  var callback = chainCallbacks(arguments);

  var responseHandler = function (res) {
    var reqOptions = url.parse(res.headers.location);
    reqOptions = {
      host: reqOptions.host,
      port: 80,
      path: reqOptions.pathname + reqOptions.search,
      headers: {
        'User-Agent': 'AudioJedit'
      }
    };

    var req = http.get(reqOptions, callback);

    req.on('error', serveError(response));

    return req;
  };
  return responseHandler;
};

// gets chunked data, then passes data to a callback
var getChunks = function (response) {
  var callback = chainCallbacks(arguments);

  var responseHandler = function (res) {
    res.setEncoding('utf-8');
    var data = '';
    res.on('data', function (chunk) {
      data += chunk;
    });
    res.on('end', function () {
      callback(data);
    });
  };
  return responseHandler;
};

var serveIndex = function (response) {
  return fs.readFile('./public/index.html', function (err, data) {
    if (err) {
      console.log(err);
    } else {
      response.writeHead(200, { 'Content-Type': 'text/html' });
      response.end(data);
    }
  });
};

var router = bee.route({

  'r`^/public/(.*)`': bee.staticDir('./public/', {
    '.html': 'text/html',
    '.css': 'text/css',
    '.gif': 'image/gif',
    '.png': 'image/png',
    '.ico': 'image/png',
    '.js': 'text/javascript'
  }),

  'r`^/(index(\\.html?)?)?(\\?.*)?$`': function (req, response, matches) {
    return serveIndex(response);
  },

  'r`^/([\\w-_]+)/([\\w-_]+)/audio`': function (req, response, matches) {
    var resource = matches.join('/');

    return scResolve(resource, response, makeRequest, getChunks, resolveTrack, makeRequest, writeResponse);
  },

  'r`^/([\\w-_]+)/([\\w-_]+)(\\.\\w+)?`': function (req, response, matches) {
    var format = matches.filter(Boolean).length == 3 ? matches.pop().substring(1) : 'html';
    var resource = matches.join('/');

    // only json is permitted, else serve index
    if (format != 'json') {
      return serveIndex(response);
    }

    return scResolve(resource, response, makeRequest, writeResponse);
  }
});

http.createServer(router).listen(process.env.PORT || 8181);

<|endoftext|>


<commit_before>// Credited: https://github.com/tkh44/shallow-compare
function shallowDiffers (a, b) {
  for (let i in a) if (!(i in b)) return true
  for (let i in b) if (a[i] !== b[i]) return true
  return false
}

export default (instance, nextProps, nextState) => {
  return (
    shallowDiffers(instance.props, nextProps) ||
    shallowDiffers(instance.state, nextState)
  )
}
<commit_msg>converted to ES5<commit_after>// Credited: https://github.com/tkh44/shallow-compare
function shallowDiffers (a, b) {
  for (var i in a) if (!(i in b)) return true
  for (var i in b) if (a[i] !== b[i]) return true
  return false
}

module.exports = function (instance, nextProps, nextState) {
  return (
    shallowDiffers(instance.props, nextProps) ||
    shallowDiffers(instance.state, nextState)
  )
}
<|endoftext|>


<commit_before>'use strict'

// const express = require('express')
// const Slapp = require('slapp')
// const ConvoStore = require('slapp-convo-beepboop')
// const Context = require('slapp-context-beepboop')

const App = require('./library/')
const express = require('express')
const PORT = process.env.PORT || 3000

App(express()).listen(PORT, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log('http server started on port %s', PORT)
})

express.get('/main', function (req, res) {
	res.send('Hello World')
})
<commit_msg>More attempts to get main route working.<commit_after>'use strict'

// const express = require('express')
// const Slapp = require('slapp')
// const ConvoStore = require('slapp-convo-beepboop')
// const Context = require('slapp-context-beepboop')

const App = require('./library/')
const express = require('express')
const PORT = process.env.PORT || 3000

App(express()).listen(PORT, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log('http server started on port %s', PORT)
})

Application = express()

Application.get('/main', function (req, res) {
	res.send('Hello World')
})

<|endoftext|>


<commit_before>var express = require('express'),
    app = express();

app.use(express.logger());

app.set('title', 'InfoCINC | Conception Sites Webs Adaptatifs | Minage | Visualisation ');

var halfHour = 1800000;

app.use(express.compress());
app.use(express.static(__dirname + '/public', { maxAge: halfHour }));

app.get('/', function(req, res){
    res.sendfile('index.html');
});

var server = app.listen(process.env.PORT, function() {
 console.log(__dirname);
 console.log('Express server started on port %s', process.env.PORT);
});

<commit_msg>add client side caching<commit_after>var express = require('express'),
    app = express();

app.use(express.logger());

app.set('title', 'InfoCINC | Conception Sites Webs Adaptatifs | Minage | Visualisation ');

var oneDay = 86400000;
var halfHour = 1800000;  // cache control for shared and private caches

app.use(express.compress());
app.use(express.static(__dirname + '/public', { maxAge: oneDay }));

app.use(function(req,res,next) {
  res.setHeader('Cache-Control','public, max-age=' + (halfHour / 1000));
});

app.get('/', function(req, res){
    res.sendfile('index.html');
});

var server = app.listen(process.env.PORT, function() {
 console.log(__dirname);
 console.log('Express server started on port %s', process.env.PORT);
});

<|endoftext|>


<commit_before>var express = require('express');
var http = require('http');
var app = express();
var path = require('path');

app.use(express.static('public'));

app.get('/secret', function(req, res) {
  // res.status(200).send('THE fog comes
on little cat feet.

It sits looking
over harbor and city
on silent haunches
and then moves on.

Carl Sandburg, Fog');
  var secret = "Shhhhhh...";
  console.log(secret);
  res.send(secret);
});

app.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname, '/public/404.html'));
});

http.createServer(app).listen(5000);
console.log("The server is listening on port 5000...");
<commit_msg>updated server.js<commit_after>var express = require('express');
var http = require('http');
var app = express();
var path = require('path');

app.use(express.static('public'));

app.get('/secret', function(req, res) {
  // res.status(200).send('THE fog comes
on little cat feet.

It sits looking
over harbor and city
on silent haunches
and then moves on.

Carl Sandburg, Fog');
  var secret = "Shhhhhh...";
  console.log(secret);
  res.send(secret);
});

app.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname, '/public/404.html'));
});

http.createServer(app).listen(process.env.PORT || 5000);
console.log("The server is listening on port 5000...");
<|endoftext|>


<commit_before>"use strict";
//  IMPORTS

    let express = require('express');

//  VARIABLES

    let port = process.env.PORT || 3000;
    let app = express();

    app.use(express.static('./example'));
    app.use(express.static('./build'));

//  ROUTES

    app.get('/', function (req, res, next) {
        res.sendFile(__dirname + '/example/index.html');
    });

    app.get('/file', function (req, res, next) {
        res.sendFile(__dirname + '/example/index_file.html');
    });

    app.get('/regular', function (req, res, next) {
        res.sendFile(__dirname + '/example/index_regular.html');
    });

//  SERVER

    let server = require('http').Server(app);

    server.listen(port, function () {
        console.log('Server listening [%s]', port);
    });<commit_msg>remove unnecessary routes<commit_after>"use strict";
//  IMPORTS

    let express = require('express');

//  VARIABLES

    let port = process.env.PORT || 3000;
    let app = express();

    app.use(express.static('./example'));
    app.use(express.static('./build'));

//  ROUTES

    app.get('/', function (req, res, next) {
        res.sendFile(__dirname + '/example/index.html');
    });

//  SERVER

    let server = require('http').Server(app);

    server.listen(port, function () {
        console.log('Server listening [%s]', port);
    });<|endoftext|>


<commit_before>// 2017.02.22 : LTW : Connection Completed, source clensing
// 2017.02.23 : LTW : Sensor Receive
// 2017.02.24 : LTW : Sensor Msg Send Logic Modified
// 2017.03.15 : LTW : Source Refactoring
'use strict';
function Module() {
    this.sensory = {
        msgStatus: "end",
        msg:[0,0,0],
        leftFloorValue: 0,
        rightFloorValue: 0,
        BothFloorDetection: 0,
        leftProximityValue: 0,
        rightProximityValue: 0,
        BothProximityDetection: 0,
        obstacleDetection: 0,
        light: 0,
        temp: 0,
        extA2 : 0,
        extA3 : 0,
	};
    this.motoring = {
        msg: [],
        rightWheel: 0,
        buzzer: 0,
        outputA: 0,
        outputB: 0,
        topology: 0,
        leftLed: 0,
        rightLed: 0,
        note: 0,
        lineTracerMode: 0,
        lineTracerModeId: -1,
        lineTracerSpeed: 5,
        ioModeA: 0,
        ioModeB: 0,
        configProximity: 2,
        configGravity: 0,
        configBandWidth: 3
    };
    this.lineTracer = {
        written: false,
        flag: 0,
        event: 0,
        state: 0
    };
}

var isSending = true;                //전문 보내는 상태
var isBlockedJSSending = false;      //대기중이던 전문을 보내는 상태
var blockedJSMsg;                    //대기중인 전문
var msgSentTime = 0;                 //센서보낸 시간
var sensorDurationTime = 200;        //센서수집 전문 주기
var isInitialBle = false;            //블루투스 초기화 상태
var sensorCorrectMsg = ["0xff","0x56","0x02","0x00","0x05"];
var Coconut = {
    MSG_VALUE: 'msgValue',
};

Module.prototype.lostController = function () {}

Module.prototype.toHex = function(number) {
    var value = parseInt(number);
    if(value < 0) value += 0x100;

    value = value.toString(16).toUpperCase();
    if(value.length > 1) return value;
    else return '0' + value;
};

Module.prototype.toHex3 = function(number) {
    var value = parseInt(number);
    if(value < 0) value += 0x1000000;

    value = value.toString(16).toUpperCase();
    var result = '';
    for(var i = value.length; i < 6; ++i) {
        result += '0';
    }
    return result + value;
};

Module.prototype.requestInitialData = function() {
	var arrMsg = ["0xff","0x55","0x06","0x00","0x02","0x19", "0x00", "0x00", "0x04"];
	return arrMsg;
};

Module.prototype.checkInitialData = function(data, config) {

    var response_format = [0x53, 0x03, 0x00, 0x00, 0xff, 0x45];
    var response_real = stringToAsciiByteArray(data);
    var is_same = (response_format.length == response_real.length) && response_format.every(function(element, index) {
    return element === response_real[index];
    });
    if (is_same)
    {
        return true;
    }

    isSending = false;

    var response_format = [0xff, 0x55];
    var is_same = (response_format.length == response_real.length) && response_format.every(function(element, index) {
    return element === response_real[index];
    });
    if (is_same)
    {
        return true;
    }

    if (response_real[0] == 0xff && response_real[1] == 0x56)
    {
        return true;
    }

    var response_format ="Corea Coding Nut...COCONUT";
    if (response_format == data)
    {
        return true;
    }
    else
        return false;
};

function h2d(ch)
{
    var d;
    if (ch >= 48 && ch <= 57) d = ch - 48;
    else if(ch >= 65 && ch <= 70 ) d = ch - 55;
    else {
        //throw new Error('Character ' + String.fromCharCode(ch) + 'can\`t be convert');
    }

    return d;
}

function stringToAsciiByteArray(str)
{
    var bytes = [];
    for (var i = 0; i < str.length; ++i)
    {
        var charCode = str.charCodeAt(i);
        if (charCode >= 0xFF) charCode = 0xff; // 2017.01.13 : SCS
        bytes.push(charCode);
    }
    return bytes;
}

Module.prototype.validateLocalData = function(data) {
    return true;
};

Module.prototype.handleLocalData = function(data) { // data: string
    var array = stringToAsciiByteArray(data);
    var sensory = this.sensory;
    var now = new Date();
    if (array[0] == 0xff && array[1] == 0x55)
    {
        sensory.msgStatus = "end";
        isSending = false;
        this.motoring.msg = "";
    }
    else if (array[0] == 0xff && array[1] == 0x56)
    {
        sensory.msgStatus = "sensor";
        sensory.leftProximityValue = readInt16(array, 2);
        sensory.rightProximityValue = readInt16(array, 4);
        sensory.BothProximityDetection = readInt8(array, 6);
        sensory.leftFloorValue = readInt8(array, 7);
        sensory.rightFloorValue = readInt8(array, 8);
        sensory.BothFloorDetection = readInt8(array, 9);
        sensory.temperature = readInt16(array, 10);
        sensory.accelerationX = accCalibrate(readInt16(array, 12));
        sensory.accelerationY = accCalibrate(readInt16(array, 14));
        sensory.accelerationZ = accCalibrate(readInt16(array, 16));
        sensory.light = analogCalibrate(readInt16(array, 18));
        sensory.extA2 = analogCalibrate(readInt16(array, 20));
        sensory.extA3 = analogCalibrate(readInt16(array, 22));
        isSending = false;
    }
    else
    {
        sensory.msgStatus = "continue";
    }

    return;
};

Module.prototype.requestRemoteData = function(handler) {
    var sensory = this.sensory;
    for(var key in sensory) {
        handler.write(key, sensory[key]);
    }
    sensory.lineTracerState = 0;
};

Module.prototype.handleRemoteData = function(handler) {
    var now = new Date();

    if(handler.e(Coconut.MSG_VALUE)) {
        var t = handler.read(Coconut.MSG_VALUE);
        if (t != "")
        {
            this.motoring.msg = t;
        }
    }
};

Module.prototype.requestLocalData = function() {
    var now = new Date();
    var motoring = this.motoring;

    if (isSending == true )
    {
        if (!isInitialBle)
        {
            isInitialBle = true;
            return sensorCorrectMsg;
        }
        return;
    }
    if (isBlockedJSSending)
    {
        isSending= true;
        isBlockedJSSending = false;
        return blockedJSMsg;
    }

    if (now - msgSentTime >= sensorDurationTime) //�����ð����� ���� ���� ����
	{
        if (motoring.msg.length > 0 )
        {
            blockedJSMsg = motoring.msg;
            isBlockedJSSending = true;
        } else {
            blockedJSMsg = "";
        }
        saveLastSensorTime(now);
        isSending = true;
        return sensorCorrectMsg;
    }

    if (motoring.msg.length > 0)
    {
        isSending = true;
        return motoring.msg;
    }
    return;
};

Module.prototype.reset = function() {
    var motoring = this.motoring;
    motoring.leftWheel = 0;
    motoring.rightWheel = 0;
    motoring.buzzer = 0;
    motoring.outputA = 0;
    motoring.outputB = 0;
    motoring.topology = 0;
    motoring.leftLed = 0;
    motoring.rightLed = 0;
    motoring.note = 0;
    motoring.lineTracerMode = 0;
    motoring.lineTracerModeId = -1;
    motoring.lineTracerSpeed = 5;
    motoring.ioModeA = 0;
    motoring.ioModeB = 0;
    motoring.configProximity = 2;
    motoring.configGravity = 0;
    motoring.configBandWidth = 3;
    var sensory = this.sensory;
    sensory.lineTracerState = 0;
    sensory.lineTracerStateId = 0;
    var lineTracer = this.lineTracer;
    lineTracer.written = false;
    lineTracer.flag = 0;
    lineTracer.event = 0;
    lineTracer.state = 0;
};

    function readInt16(arr, position) {
        var charCode = h2d(arr[position+0]) * 16 + h2d(arr[position+1]);
        return charCode;
    }

    function accCalibrate(value){
        if (value > 0x7f)
        {
            value = value - 0x100;
        }

        return value;
    }

    function analogCalibrate(value) {
        return value = value * 9;
    }

    function readInt8(arr, position) {
        var charCode = h2d(arr[position]);
        return charCode;
    }

    function readFloat(arr, position) {
        var f3 = arr[position+3] << 24;
        f3 = f3 | arr[position+2] << 16;
        f3 = f3 | arr[position+1] << 8 ;
        f3 = f3 | arr[position+0];

        return Bytes2Float32(f3);
    }

    // IEEE 754 Converter
    // https://www.h-schmidt.net/FloatConverter/IEEE754.html
    function Bytes2Float32(bytes) {
        var sign = (bytes & 0x80000000) ? -1 : 1;
        var exponent = ((bytes >> 23) & 0xFF) - 127;
        var significand = (bytes & ~(-1 << 23));

        if (exponent == 128)
            return sign * ((significand) ? Number.NaN : Number.POSITIVE_INFINITY);

        if (exponent == -127) {
            if (significand == 0) return sign * 0.0;
            exponent = -126;
            significand /= (1 << 22);
        } else significand = (significand | (1 << 23)) / (1 << 23);

        return sign * significand * Math.pow(2, exponent);
    }

    function saveLastSensorTime(time){
        msgSentTime = time;
    }

module.exports = new Module();

// =================================== End of File =====================================
<commit_msg>stop command logic add<commit_after>// 2017.02.22 : LTW : Connection Completed, source clensing
// 2017.02.23 : LTW : Sensor Receive
// 2017.02.24 : LTW : Sensor Msg Send Logic Modified
// 2017.03.15 : LTW : Source Refactoring
// 2017.04.16 : LTW : Stop Function Add
// 2017.04.17 : LTW : Stop Function Update
'use strict';
function Module() {
    this.sensory = {
        msgStatus: "end",
        msg:[0,0,0],
        leftFloorValue: 0,
        rightFloorValue: 0,
        BothFloorDetection: 0,
        leftProximityValue: 0,
        rightProximityValue: 0,
        BothProximityDetection: 0,
        obstacleDetection: 0,
        light: 0,
        temp: 0,
        extA2 : 0,
        extA3 : 0,
	};
    this.motoring = {
        msg: [],
        rightWheel: 0,
        buzzer: 0,
        outputA: 0,
        outputB: 0,
        topology: 0,
        leftLed: 0,
        rightLed: 0,
        note: 0,
        lineTracerMode: 0,
        lineTracerModeId: -1,
        lineTracerSpeed: 5,
        ioModeA: 0,
        ioModeB: 0,
        configProximity: 2,
        configGravity: 0,
        configBandWidth: 3
    };
    this.lineTracer = {
        written: false,
        flag: 0,
        event: 0,
        state: 0
    };
}

var isSending = true;                //전문 보내는 상태
var isBlockedJSSending = false;      //대기중이던 전문을 보내는 상태
var blockedJSMsg;                    //대기중인 전문
var msgSentTime = 0;                 //센서보낸 시간
var sensorDurationTime = 200;        //센서수집 전문 주기
var isInitialBle = false;            //블루투스 초기화 상태
var sensorCorrectMsg = ["0xff","0x56","0x02","0x00","0x05"];
var resetMsg = ["0xff", "0x55", "0x02", "0x00", "0x04"];
var resetStatus = false;

var Coconut = {
    MSG_VALUE: 'msgValue',
};

Module.prototype.lostController = function () {}

Module.prototype.toHex = function(number) {
    var value = parseInt(number);
    if(value < 0) value += 0x100;

    value = value.toString(16).toUpperCase();
    if(value.length > 1) return value;
    else return '0' + value;
};

Module.prototype.toHex3 = function(number) {
    var value = parseInt(number);
    if(value < 0) value += 0x1000000;

    value = value.toString(16).toUpperCase();
    var result = '';
    for(var i = value.length; i < 6; ++i) {
        result += '0';
    }
    return result + value;
};

Module.prototype.requestInitialData = function() {
	var arrMsg = ["0xff","0x55","0x06","0x00","0x02","0x19", "0x00", "0x00", "0x04"];
	return arrMsg;
};

Module.prototype.checkInitialData = function(data, config) {

    var response_format = [0x53, 0x03, 0x00, 0x00, 0xff, 0x45];
    var response_real = stringToAsciiByteArray(data);
    var is_same = (response_format.length == response_real.length) && response_format.every(function(element, index) {
    return element === response_real[index];
    });
    if (is_same)
    {
        return true;
    }

    isSending = false;

    var response_format = [0xff, 0x55];
    var is_same = (response_format.length == response_real.length) && response_format.every(function(element, index) {
    return element === response_real[index];
    });
    if (is_same)
    {
        return true;
    }

    if (response_real[0] == 0xff && response_real[1] == 0x56)
    {
        return true;
    }

    var response_format ="Corea Coding Nut...COCONUT";
    if (response_format == data)
    {
        return true;
    }
    else
        return false;
};

function h2d(ch)
{
    var d;
    if (ch >= 48 && ch <= 57) d = ch - 48;
    else if(ch >= 65 && ch <= 70 ) d = ch - 55;
    else {
        //throw new Error('Character ' + String.fromCharCode(ch) + 'can\`t be convert');
    }

    return d;
}

function stringToAsciiByteArray(str)
{
    var bytes = [];
    for (var i = 0; i < str.length; ++i)
    {
        var charCode = str.charCodeAt(i);
        if (charCode >= 0xFF) charCode = 0xff; // 2017.01.13 : SCS
        bytes.push(charCode);
    }
    return bytes;
}

Module.prototype.validateLocalData = function(data) {
    return true;
};

Module.prototype.handleLocalData = function(data) { // data: string
    var array = stringToAsciiByteArray(data);
    var sensory = this.sensory;
    var now = new Date();
    if (array[0] == 0xff && array[1] == 0x55)
    {
        sensory.msgStatus = "end";
        isSending = false;
        this.motoring.msg = "";
    }
    else if (array[0] == 0xff && array[1] == 0x56)
    {
        sensory.msgStatus = "sensor";
        sensory.leftProximityValue = readInt16(array, 2);
        sensory.rightProximityValue = readInt16(array, 4);
        sensory.BothProximityDetection = readInt8(array, 6);
        sensory.leftFloorValue = readInt8(array, 7);
        sensory.rightFloorValue = readInt8(array, 8);
        sensory.BothFloorDetection = readInt8(array, 9);
        sensory.temperature = readInt16(array, 10);
        sensory.accelerationX = accCalibrate(readInt16(array, 12));
        sensory.accelerationY = accCalibrate(readInt16(array, 14));
        sensory.accelerationZ = accCalibrate(readInt16(array, 16));
        sensory.light = analogCalibrate(readInt16(array, 18));
        sensory.extA2 = analogCalibrate(readInt16(array, 20));
        sensory.extA3 = analogCalibrate(readInt16(array, 22));
        isSending = false;
    }
    else
    {
        sensory.msgStatus = "continue";
    }

    return;
};

Module.prototype.requestRemoteData = function(handler) {
    var sensory = this.sensory;
    for(var key in sensory) {
        handler.write(key, sensory[key]);
    }
    sensory.lineTracerState = 0;
};

Module.prototype.handleRemoteData = function(handler) {
    var now = new Date();

    if(handler.e(Coconut.MSG_VALUE)) {
        var t = handler.read(Coconut.MSG_VALUE);
        if (t != "")
        {
            this.motoring.msg = t;
        }

        if (t[0] == 255 && t[1] == 85 && t[2] == 2 && t[3] == 0 && t[4] == 4)
        {
            resetStatus = true;
        }
    }
};

Module.prototype.requestLocalData = function() {
    var now = new Date();
    var motoring = this.motoring;

    if (resetStatus == true)
    {
        resetStatus = false;
        this.motoring.msg = "";
        isBlockedJSSending = false;
        return resetMsg;
    }
    if (isSending == true )
    {
        if (!isInitialBle)
        {
            isInitialBle = true;
            return sensorCorrectMsg;
        }
        return;
    }
    if (isBlockedJSSending)
    {
        isSending= true;
        isBlockedJSSending = false;
        return blockedJSMsg;
    }

    if (now - msgSentTime >= sensorDurationTime) //�����ð����� ���� ���� ����
	{
        if (motoring.msg.length > 0 )
        {
            blockedJSMsg = motoring.msg;
            isBlockedJSSending = true;
        } else {
            blockedJSMsg = "";
        }
        saveLastSensorTime(now);
        isSending = true;
        return sensorCorrectMsg;
    }

    if (motoring.msg.length > 0)
    {
        isSending = true;
        return motoring.msg;
    }
    return;
};

Module.prototype.reset = function() {
    var motoring = this.motoring;
    motoring.leftWheel = 0;
    motoring.rightWheel = 0;
    motoring.buzzer = 0;
    motoring.outputA = 0;
    motoring.outputB = 0;
    motoring.topology = 0;
    motoring.leftLed = 0;
    motoring.rightLed = 0;
    motoring.note = 0;
    motoring.lineTracerMode = 0;
    motoring.lineTracerModeId = -1;
    motoring.lineTracerSpeed = 5;
    motoring.ioModeA = 0;
    motoring.ioModeB = 0;
    motoring.configProximity = 2;
    motoring.configGravity = 0;
    motoring.configBandWidth = 3;
    var sensory = this.sensory;
    sensory.lineTracerState = 0;
    sensory.lineTracerStateId = 0;
    var lineTracer = this.lineTracer;
    lineTracer.written = false;
    lineTracer.flag = 0;
    lineTracer.event = 0;
    lineTracer.state = 0;
};

    function readInt16(arr, position) {
        var charCode = h2d(arr[position+0]) * 16 + h2d(arr[position+1]);
        return charCode;
    }

    function accCalibrate(value){
        if (value > 0x7f)
        {
            value = value - 0x100;
        }

        return value;
    }

    function analogCalibrate(value) {
        return value = value * 9;
    }

    function readInt8(arr, position) {
        var charCode = h2d(arr[position]);
        return charCode;
    }

    function readFloat(arr, position) {
        var f3 = arr[position+3] << 24;
        f3 = f3 | arr[position+2] << 16;
        f3 = f3 | arr[position+1] << 8 ;
        f3 = f3 | arr[position+0];

        return Bytes2Float32(f3);
    }

    // IEEE 754 Converter
    // https://www.h-schmidt.net/FloatConverter/IEEE754.html
    function Bytes2Float32(bytes) {
        var sign = (bytes & 0x80000000) ? -1 : 1;
        var exponent = ((bytes >> 23) & 0xFF) - 127;
        var significand = (bytes & ~(-1 << 23));

        if (exponent == 128)
            return sign * ((significand) ? Number.NaN : Number.POSITIVE_INFINITY);

        if (exponent == -127) {
            if (significand == 0) return sign * 0.0;
            exponent = -126;
            significand /= (1 << 22);
        } else significand = (significand | (1 << 23)) / (1 << 23);

        return sign * significand * Math.pow(2, exponent);
    }

    function saveLastSensorTime(time){
        msgSentTime = time;
    }

module.exports = new Module();

// =================================== End of File =====================================
<|endoftext|>


<commit_before>#!/usr/bin/env node
"use strict";

// increase the libuv threadpool size to 1.5x the number of logical CPUs.
process.env.UV_THREADPOOL_SIZE = process.env.UV_THREADPOOL_SIZE || Math.ceil(Math.max(4, require('os').cpus().length * 1.5));

var cors = require("cors"),
    express = require("express"),
    Peechee = require('peechee'),
    spawnasync = require('spawn-async'),
    bunyan = require('bunyan'),
    config = require("config"),
    fs = require('fs'),
    bodyParser = require('body-parser'),
    responseTime = require("response-time"),
    koop = require('koop-server')(config);

global['config'] = config;

// Scan package for koop plugins and require them
var files = fs.readdirSync('node_modules');
files.forEach(function(f){
  if ( f.match(/koop-*.+/) ){
    try { koop.register(require(f)); } catch (e) { console.log(e)}
  }
});

var app = express();

app.disable("x-powered-by");
app.use(responseTime());
app.use(cors());

app.post('/arcgis/rest/info', function(req, res){
  res.send({},200);
});

app.set('view engine', 'ejs');
app.set('view options', {layout: 'layout.ejs'});

if (process.env.NODE_ENV === "development") {
  app.use(express.logger());
}

// handle POST requests
app.use(bodyParser());

app.use(express.static(__dirname + '/public'));

// add koop middleware
app.use( koop );

app.listen(process.env.PORT || config.server.port,  function() {
  console.log("Listening at http://%s:%d/", this.address().address, this.address().port);

  // Start the Cache DB with the conn string from config
  if ( config.db ) {
    if ( config.db.postgis ){
      Cache.db = PostGIS.connect( config.db.postgis.conn );
    } else if ( config.db.sqlite ) {
      Cache.db = SQLite.connect(config.db.sqlite);
    }
  } else {
    console.log('Exiting since no DB configuration found in config');
    process.exit();
  }

  // A bunyan log is required for the async workers
  config.log = new bunyan({
    'name': 'koop-log',
    streams: [{
      type: 'rotating-file',
      path: config.logfile || __dirname + '/koop.log',
      period: '1d',
      count: 3
    }]
  });

  // allow us to kick off system commands w/o blocking
  config.worker = spawnasync.createWorker({'log': config.log});

  // set up an instance of peechee for saving files (downloads)
  global['peechee'] = {};
  if ( config.peechee && config.peechee.type == 's3' ){
    global['peechee'] = new Peechee( config.peechee );
  }

});

<commit_msg>no globals<commit_after>#!/usr/bin/env node
"use strict";

// increase the libuv threadpool size to 1.5x the number of logical CPUs.
process.env.UV_THREADPOOL_SIZE = process.env.UV_THREADPOOL_SIZE || Math.ceil(Math.max(4, require('os').cpus().length * 1.5));

var cors = require("cors"),
    express = require("express"),
    Peechee = require('peechee'),
    spawnasync = require('spawn-async'),
    bunyan = require('bunyan'),
    config = require("config"),
    fs = require('fs'),
    bodyParser = require('body-parser'),
    responseTime = require("response-time"),
    koop = require('koop-server')(config);

// Scan package for koop plugins and require them
var files = fs.readdirSync('node_modules');
files.forEach(function(f){
  if ( f.match(/koop-*.+/) ){
    try { koop.register(require(f)); } catch (e) { console.log('Error', e)}
  }
});

var app = express();

app.disable("x-powered-by");
app.use(responseTime());
app.use(cors());

app.post('/arcgis/rest/info', function(req, res){
  res.send({},200);
});

app.set('view engine', 'ejs');
app.set('view options', {layout: 'layout.ejs'});

if (process.env.NODE_ENV === "development") {
  app.use(express.logger());
}

// handle POST requests
app.use(bodyParser());

app.use(express.static(__dirname + '/public'));

// add koop middleware
app.use( koop );

app.listen(process.env.PORT || config.server.port,  function() {
  console.log("Listening at http://%s:%d/", this.address().address, this.address().port);

  // A bunyan log is required for the async workers
  /*config.log = new bunyan({
    'name': 'koop-log',
    streams: [{
      type: 'rotating-file',
      path: config.logfile || __dirname + '/koop.log',
      period: '1d',
      count: 3
    }]
  });

  // allow us to kick off system commands w/o blocking
  config.worker = spawnasync.createWorker({'log': config.log});

  // set up an instance of peechee for saving files (downloads)
  global['peechee'] = {};
  if ( config.peechee && config.peechee.type == 's3' ){
    global['peechee'] = new Peechee( config.peechee );
  }*/

});

<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { ActivityIndicator, View, TouchableOpacity } from 'react-native'
import { checkPermission, requestPermission } from 'react-native-android-permissions'

import { DefaultText } from '../components/textComponents'
import styles from '../styles/stylesheet'
import strings from '../resources/translations'

import StartViewButtons from '../components/StartViewButtons'
import AccessibilityView from '../components/AccessibilityView'

import { getLocation } from '../actions/locationActions'

class StartView extends Component {
    constructor(props)
    {
        super(props)

        this.state = {
            locationPermissionsError: false
        }
    }

    componentWillMount = () =>
    {
        checkPermission('android.permission.ACCESS_FINE_LOCATION').then(() =>
        {
            this.props.getLocation()
        }, () =>
        {
            setTimeout(() =>
            {
                requestPermission('android.permission.ACCESS_FINE_LOCATION').then(() =>
            {
                    this.props.getLocation()
                }, () =>
            {
                    this.setState({locationPermissionsError: true})
                })
          // for the correct StatusBar behaviour with translucent={true} we need to wait a bit and ask for permission after the first render cycle
          // (check https://github.com/facebook/react-native/issues/9413 for more info)
            }, 0)
        })
    }

    render()
    {
        let viewElement

        if (this.state.locationPermissionsError)
        {
            viewElement = <View>
                          <DefaultText style={styles.locationErrorText}>{strings.locationPermissionsError}</DefaultText>
                        </View>
        }
        else if (this.props.locationError)
            {
            viewElement = <View>
                              <DefaultText style={styles.locationErrorText}>{strings.locationError}</DefaultText>
                              <TouchableOpacity onPress={this.props.getLocation} accessibilityComponentType="button" accessibilityLabel={strings.tryAgain}>
                                <DefaultText style={styles.tryAgain}>{strings.tryAgain}</DefaultText>
                              </TouchableOpacity>
                            </View>
        }
        else if (this.props.gettingLocation == false)
        {
            viewElement = <StartViewButtons />
        }
        else
        {
            viewElement = <View><DefaultText style={styles.gettingLocationText}>{strings.gettingLocation}</DefaultText><ActivityIndicator /></View>
        }

        return (
      <AccessibilityView style={styles.start} name="start">
        {viewElement}
      </AccessibilityView>
        )
    }
}

StartView.propTypes = {
    gettingLocation: React.PropTypes.bool.isRequired,
    locationError: React.PropTypes.string,
    getLocation: React.PropTypes.func.isRequired
}

const mapStateToProps = (state) =>
{
    return {
        gettingLocation: state.locationReducer.gettingLocation,
        locationError: state.locationReducer.error
    }
}

const mapDispatchToProps = (dispatch) =>
{
    return {
        getLocation: () =>
        {
            dispatch(getLocation())
        }
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(StartView)
<commit_msg>use native methods to grant location permissions rather than react-native-android-permissions<commit_after>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { ActivityIndicator, View, TouchableOpacity, PermissionsAndroid } from 'react-native'

import { DefaultText } from '../components/textComponents'
import styles from '../styles/stylesheet'
import strings from '../resources/translations'

import StartViewButtons from '../components/StartViewButtons'
import AccessibilityView from '../components/AccessibilityView'

import { getLocation } from '../actions/locationActions'

class StartView extends Component {
    constructor(props)
    {
        super(props)

        this.state = {
            locationPermissionsError: false
        }
    }

    async requestLocationPermission() {
        try {
            const granted = await PermissionsAndroid.requestPermission(
                PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
                {
                    'title': strings.locationPermissionTitle,
                    'message': strings.locationPermissionMessage
                }
            )

            if (granted) {
                this.props.getLocation()
            } else {
                this.setState({locationPermissionsError: true})
            }
        } catch (err) {
            this.setState({locationError: true})
        }
    }

    componentWillMount = () =>
    {
        this.requestLocationPermission()
    }

    render()
    {
        let viewElement

        if (this.state.locationPermissionsError)
        {
            viewElement = <View>
                          <DefaultText style={styles.locationErrorText}>{strings.locationPermissionsError}</DefaultText>
                        </View>
        }
        else if (this.props.locationError)
            {
            viewElement = <View>
                              <DefaultText style={styles.locationErrorText}>{strings.locationError}</DefaultText>
                              <TouchableOpacity onPress={this.props.getLocation} accessibilityComponentType="button" accessibilityLabel={strings.tryAgain}>
                                <DefaultText style={styles.tryAgain}>{strings.tryAgain}</DefaultText>
                              </TouchableOpacity>
                            </View>
        }
        else if (this.props.gettingLocation == false)
        {
            viewElement = <StartViewButtons />
        }
        else
        {
            viewElement = <View><DefaultText style={styles.gettingLocationText}>{strings.gettingLocation}</DefaultText><ActivityIndicator /></View>
        }

        return (
      <AccessibilityView style={styles.start} name="start">
        {viewElement}
      </AccessibilityView>
        )
    }
}

StartView.propTypes = {
    gettingLocation: React.PropTypes.bool.isRequired,
    locationError: React.PropTypes.string,
    getLocation: React.PropTypes.func.isRequired
}

const mapStateToProps = (state) =>
{
    return {
        gettingLocation: state.locationReducer.gettingLocation,
        locationError: state.locationReducer.error
    }
}

const mapDispatchToProps = (dispatch) =>
{
    return {
        getLocation: () =>
        {
            dispatch(getLocation())
        }
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(StartView)
<|endoftext|>


<commit_before>var express = require("express");
var mbta = require('./mbta');
var app = express();
app.use(express.logger());
app.use(express.compress());

app.all('*', function(req, res, next) {
	res.header("Access-Control-Allow-Origin", "*");
	res.header("Access-Control-Allow-Headers", "X-Requested-With");
	next();
});
app.get('/',function(req,res,next){
	res.jsonp({
		"list of routes":'/list',
		"details of a route":"/route/[route id]",
		"details of a stop":"/stop/[stop id]",
		"geojson of current location on a route":"/locations/[route]",
		"schedule of a route":"/schedule/[route]"
		"subway line":"/[line]"
	});
});
app.get('/list',function(req,res,next){
	mbta.list().then(function(result){
		res.jsonp(result);
	},function(err){
		res.jsonp(404,{status:"error",details:err});
	});
});
app.get('/route/:route',function(req,res,next){
	mbta.route(req.params.route).then(function(result){
		res.jsonp(result);
	},function(err){
		res.jsonp(404,{status:"error",details:err});
	});
});
app.get('/stop/:stop',function(req,res,next){
	mbta.stop(req.params.stop).then(function(result){
		res.jsonp(result);
	},function(err){
		res.jsonp(404,{status:"error",details:err});
	});
});
app.get('/:line',function(req,res,next){
	mbta.subway(req.params.line).then(function(result){
		res.jsonp(result);
	},function(err){
		res.jsonp(404,{status:"error",details:err});
	});
});
app.get('/locations/:route',function(req,res,next){
	mbta.locations(req.params.route).then(function(result){
		res.jsonp(result);
	},function(err){
		res.jsonp(404,{status:"error",details:err});
	});
});
app.get('/schedule/:route',function(req,res,next){
	mbta.schedule(req.params.route).then(function(result){
		res.jsonp(result);
	},function(err){
		res.jsonp(404,{status:"error",details:err});
	});
});
app.listen(process.env['PORT'] || 3000, '127.0.0.1');
<commit_msg>fix typo<commit_after>var express = require("express");
var mbta = require('./mbta');
var app = express();
app.use(express.logger());
app.use(express.compress());

app.all('*', function(req, res, next) {
	res.header("Access-Control-Allow-Origin", "*");
	res.header("Access-Control-Allow-Headers", "X-Requested-With");
	next();
});
app.get('/',function(req,res,next){
	res.jsonp({
		"list of routes":'/list',
		"details of a route":"/route/[route id]",
		"details of a stop":"/stop/[stop id]",
		"geojson of current location on a route":"/locations/[route]",
		"schedule of a route":"/schedule/[route]",
		"subway line":"/[line]"
	});
});
app.get('/list',function(req,res,next){
	mbta.list().then(function(result){
		res.jsonp(result);
	},function(err){
		res.jsonp(404,{status:"error",details:err});
	});
});
app.get('/route/:route',function(req,res,next){
	mbta.route(req.params.route).then(function(result){
		res.jsonp(result);
	},function(err){
		res.jsonp(404,{status:"error",details:err});
	});
});
app.get('/stop/:stop',function(req,res,next){
	mbta.stop(req.params.stop).then(function(result){
		res.jsonp(result);
	},function(err){
		res.jsonp(404,{status:"error",details:err});
	});
});
app.get('/:line',function(req,res,next){
	mbta.subway(req.params.line).then(function(result){
		res.jsonp(result);
	},function(err){
		res.jsonp(404,{status:"error",details:err});
	});
});
app.get('/locations/:route',function(req,res,next){
	mbta.locations(req.params.route).then(function(result){
		res.jsonp(result);
	},function(err){
		res.jsonp(404,{status:"error",details:err});
	});
});
app.get('/schedule/:route',function(req,res,next){
	mbta.schedule(req.params.route).then(function(result){
		res.jsonp(result);
	},function(err){
		res.jsonp(404,{status:"error",details:err});
	});
});
app.listen(process.env['PORT'] || 3000, '127.0.0.1');
<|endoftext|>


<commit_before>define( [ "slick/plugins/RowsModel" ], function( RowsModel ) {

	"use strict";

	var defaults = {
		columnId : "_checkbox_selector",
		toolTip: "Select/Deselect All",
		cssClass: "slick-cell-checkbox",
		width: 35,

		/** TODO: Max selected */
		max: 0
	}

	/** CLASS */
	, CheckboxSelectColumn = function( $G, dataView, settings ) {

		var handler = new Slick.EventHandler()

		/** Cache the selected items */
		, selecteds = {}

		, instance = {

			init: function( grid ) {

				handler
					.subscribe( $G.onSelectedRowsChanged, handleSelectedRowsChanged )
					.subscribe( $G.onClick, handleClick )
					.subscribe( $G.onHeaderClick, handleHeaderClick );
			},

			destroy: function() {
				handler.unsubscribeAll();
			},

			getColumnDefinifion: function() {

				return {
					id: settings.columnId,
					name: settings.max ? "" :"<input type='checkbox'>",
					toolTip: settings.toolTip,
					width: settings.width,
					resizable: false,
					sortable: false,
					cssClass: settings.cssClass,
					formatter: function( row, cell, value, column, dataContext ) {

						var condition = settings.condition, res = true;

						if ( dataContext ) {

							if ( "function" === typeof condition ) {

								res = condition.apply( this, arguments );
							}

							return res && selecteds[ row ]
								? "<input type='checkbox' checked='checked'>"
								: "<input type='checkbox'>";
						}
					}
				};
			}
		};

		function handleSelectedRowsChanged( e, args ) {

			var lookup = {}, rows = $G.getSelectedRows();

			for ( var i = 0, row, length = rows.length; i < length; ) {

				row = rows[ i++ ];
				lookup[ row ] = true;

				if ( lookup[ row ] !== selecteds[ row ] ) {
					$G.invalidateRow( row );
					delete selecteds[ row ];
				}
			}

			for ( i in selecteds ) {
				$G.invalidateRow( i );
			}

			selecteds = lookup;

			$G.render();

			$G.updateColumnHeader( settings.columnId
						, settings.max ? "" : (rows.length && rows.length === $G.getDataLength() ? "<input type='checkbox' checked='checked'>" : "<input type='checkbox'>")
						, settings.toolTip );
		}

		function handleClick( e, args ) {

			var toggleRowSelection = function( row ) {

				if ( selecteds[ row ] ) {
					$G.setSelectedRows( $.grep( $G.getSelectedRows(), function( index ) {

						var res = index !== row;

						!res && $G.onRowDeselected.notify( { row: row } );

						return res;
					} ) );
				} else {
					$G.onRowSelected.notify( { row: row } );
					$G.setSelectedRows( $G.getSelectedRows().concat( row ) );
				}
			};

			if ( $G.getColumns()[ args.cell ][ "id" ] === settings.columnId ) {

				/** If editing, try to commit */
				if ( $G.getEditorLock().isActive() && !$G.getEditorLock().commitCurrentEdit() ) {

					e.preventDefault();
					e.stopImmediatePropagation();
					return;
				}

				toggleRowSelection( args.row );
			}
		}

		function handleHeaderClick( e, args ) {

			if ( args.column.id !== settings.columnId ||

					/** If editing, try to commit and return */
					($G.getEditorLock().isActive() && !$G.getEditorLock().commitCurrentEdit()) ) {

						e.preventDefault();
						e.stopImmediatePropagation();
						return;
					}

			/** Select all */
			if ( !$( e.target ).prev().is( ":checked" ) ) {

				var rows = [];

				for ( var i = 0, length = $G.getDataLength(); i < length; rows.push( i++ ) );

				$G.setSelectedRows( rows );

			/** Deselect */
			} else $G.setSelectedRows( [] );

			e.preventDefault();
			e.stopImmediatePropagation();
		}

		$.extend( this, instance );
	};

	return function( $G, dataView, options ) {

		var
		  settings = $.extend( true, {}, defaults, options || {} ),
		  plugin = new CheckboxSelectColumn( $G, dataView, settings );

		/** Enable rows selected ability */
		$G.setSelectionModel( RowsModel( $G ) );

		/** Register plugin */
		$G.registerPlugin( plugin );

		/** On the rows changed clear the selected */
		dataView.onRowsChanged.subscribe( function( e, args ) {
			$G.setSelectedRows( [] );
		} );

		/** Add events hook */
		$.extend( $G, {
			onRowSelected: new Slick.Event(),
			onRowDeselected: new Slick.Event()
		} );

		/** Return the column definition */
		return plugin.getColumnDefinifion();
	};
} );

<commit_msg>Update Checkboxcolumn.js<commit_after>define( [ "slick/plugins/RowsModel" ], function( RowsModel ) {

	"use strict";

	var defaults = {
		columnId : "_checkbox_selector",
		toolTip: "Select/Deselect All",
		cssClass: "slick-cell-checkbox",
		width: 35,

		/** TODO: Max selected */
		max: 0
	}

	/** CLASS */
	, CheckboxSelectColumn = function( $G, dataView, settings ) {

		var handler = new Slick.EventHandler()

		/** Cache the selected items */
		, selecteds = {}

		, instance = {

			init: function( grid ) {

				handler
					.subscribe( $G.onSelectedRowsChanged, handleSelectedRowsChanged )
					.subscribe( $G.onClick, handleClick )
					.subscribe( $G.onHeaderClick, handleHeaderClick );
			},

			destroy: function() {
				handler.unsubscribeAll();
			},

			getColumnDefinifion: function() {

				return {
					id: settings.columnId,
					name: settings.max ? "" :"<input type='checkbox'>",
					toolTip: settings.toolTip,
					width: settings.width,
					resizable: false,
					sortable: false,
					cssClass: settings.cssClass,
					formatter: function( row, cell, value, column, dataContext ) {

						var condition = settings.condition, res = true;

						if ( dataContext ) {

							if ( "function" === typeof condition ) {

								res = condition.apply( this, arguments );
							}

							return res && selecteds[ row ]
								? "<input type='checkbox' checked='checked'>"
								: "<input type='checkbox'>";
						}
					}
				};
			}
		};

		function handleSelectedRowsChanged( e, args ) {

			var lookup = {}, rows = $G.getSelectedRows();

			for ( var i = 0, row, length = rows.length; i < length; ) {

				row = rows[ i++ ];
				lookup[ row ] = true;

				if ( lookup[ row ] !== selecteds[ row ] ) {
					$G.invalidateRow( row );
					delete selecteds[ row ];
				}
			}

			for ( i in selecteds ) {
				$G.invalidateRow( i );
			}

			selecteds = lookup;

			$G.render();

			$G.updateColumnHeader( settings.columnId
						, settings.max ? "" : (rows.length && rows.length === $G.getDataLength() ? "<input type='checkbox' checked='checked'>" : "<input type='checkbox'>")
						, settings.toolTip );
		}

		function handleClick( e, args ) {

			var toggleRowSelection = function( row ) {

				if ( selecteds[ row ] ) {
					$G.setSelectedRows( $.grep( $G.getSelectedRows(), function( index ) {

						var res = index !== row;

						!res && $G.onRowDeselected.notify( { row: row } );

						return res;
					} ) );
				} else {
					$G.onRowSelected.notify( { row: row } );
					$G.setSelectedRows( $G.getSelectedRows().concat( row ) );
				}
			};

			if ( $G.getColumns()[ args.cell ][ "id" ] === settings.columnId ) {

				/** If editing, try to commit */
				if ( $G.getEditorLock().isActive() && !$G.getEditorLock().commitCurrentEdit() ) {

					e.preventDefault();
					e.stopImmediatePropagation();
					return;
				}

				toggleRowSelection( args.row );
			}
		}

		function handleHeaderClick( e, args ) {

			if ( args.column.id !== settings.columnId ||

					/** If editing, try to commit and return */
					($G.getEditorLock().isActive() && !$G.getEditorLock().commitCurrentEdit()) ) {

						e.preventDefault();
						e.stopImmediatePropagation();
						return;
					}

			/** Select all */
			if ( !$( e.target ).prev().is( ":checked" ) ) {

				var rows = [];

				for ( var i = 0, length = $G.getDataLength(); i < length; rows.push( i++ ) );

				$G.setSelectedRows( rows );

			/** Deselect */
			} else $G.setSelectedRows( [] );

			e.preventDefault();
			e.stopImmediatePropagation();
		}

		$.extend( this, instance );
	};

	return function( $G, dataView, options ) {

		var
		  settings = $.extend( true, {}, defaults, options || {} ),
		  plugin = new CheckboxSelectColumn( $G, dataView, settings );

		/** Enable rows selected ability */
		$G.setSelectionModel( RowsModel( $G ) );

		/** Register plugin */
		$G.registerPlugin( plugin );

		/** On the rows changed clear the selected */
		dataView.onRowsChanged.subscribe( function( e, args ) {
			$G.setSelectedRows( [] );
		} );

		/** Add events hook */
		$.extend( $G, {
			onRowSelected: new Slick.Event(),
			onRowDeselected: new Slick.Event()
		} );

		/** Return the column definition */
		return plugin.getColumnDefinifion();
	};
} );

<|endoftext|>