<commit_before>'use strict'
let React = require("react")
,	app = require("koa")()
,	_static = require("koa-static")
,	router = require("./router")
,	config = require("config")
,	port = config.port || 80

app
.use(function* (next) {
	try {
		if (config.online) {
			console.log(this.method + " " + this.href + " from " + this.ip)
			if ( /liaozhongwu\.cn/.test(this.host) ) {
				this.status = 404
				this.body = "404 Not Found."
				return
			}
			if ( !(/www\.liaozhongwu\.com/.test(this.host)) ) {
				this.status = 301
				this.redirect(this.href.replace(this.host, "www.liaozhongwu.com"))
				return
			}
		}
		yield next
	} catch (err) {
		console.log(this.method + " " + this.href + " errored")
		console.error(err)
		this.status = 301
		this.redirect("/")
	}
})
.use(_static("public"))
.use(router.routes())
.use(function* (next) {
	if (this.status === 404) {
		console.log(this.method + " " + this.href + " was not found")
		this.status = 301
		this.redirect("/")
	}
	yield next
})
.listen(port, () => {
  console.log('========================')
  console.log('App is listening to ' + port)
  console.log('========================')

	if (!config.online) {
		require("./gulpfile")
		require("gulp").start("default")
	}
})<commit_msg>update<commit_after>'use strict'
let React = require("react")
,	app = require("koa")()
,	_static = require("koa-static")
,	router = require("./router")
,	config = require("config")
,	port = config.port || 80

app
.use(function* (next) {
	try {
		if (config.online) {
			console.log(this.method + " " + this.href + " from " + this.ip)
			// if ( /liaozhongwu\.cn/.test(this.host) ) {
			// 	this.status = 404
			// 	this.body = "404 Not Found."
			// 	return
			// }
			if ( !(/www\.liaozhongwu\.com/.test(this.host)) ) {
				this.status = 301
				this.redirect(this.href.replace(this.host, "www.liaozhongwu.com"))
				return
			}
		}
		yield next
	} catch (err) {
		console.log(this.method + " " + this.href + " errored")
		console.error(err)
		this.status = 301
		this.redirect("/")
	}
})
.use(_static("public"))
.use(router.routes())
.use(function* (next) {
	if (this.status === 404) {
		console.log(this.method + " " + this.href + " was not found")
		this.status = 301
		this.redirect("/")
	}
	yield next
})
.listen(port, () => {
  console.log('========================')
  console.log('App is listening to ' + port)
  console.log('========================')

	if (!config.online) {
		require("./gulpfile")
		require("gulp").start("default")
	}
})<|endoftext|>


<commit_before>
var userName = prompt('WHAT, is your name?');
alert('Correct, ' + userName + ' Next question...');
console.log('The user\'s name is ' + 'userName');

var answer1 = prompt('WHAT, is your favorite color?');
  if (answer1.length < 6 || answer1.length > 3) {
    alert('CORRECT!, last question...');
  }
  else {
    alert('INCORRECT! To the pits with you!!!');
  }

var answer2 = prompt('WHAT, is the airspeed velocity of an unladen swallow?');
  if (answer2 === 'African or European?' || 'african or european?') {
    alert('I don\'t know... AHHHH!!!');
  }
  else {
    alert('To the pits with you!!!');
  }

    alert('You may pass the bridge of death if all were answered correctly');

    alert('You enter the room of The Holy Grail');

  var userNumber = prompt('Pick a cup, they are numbered 1-10');
  var computerNumber = Math.floor((Math.random() * 10) + 1);
    if (userNumber <= 5 && computerNumber <= 5) {
      alert('You drink the water and embrace the feeling of immortality! \
      The Holy Grail is yours!');
    }
    else if (userNumber > 5 && computerNumber > 5) {
      alert('You drink the water, shit out your guts and die...');

    }
    else {
      alert('You are a Pu*** and refuse to drink out of any cup... \
      Your journey was for nothing.');
    }
<commit_msg>JS is more done-ish<commit_after>
var userName = prompt('WHAT, is your name?');
alert('Correct, ' + userName + ' Next question...');
console.log('The user\'s name is ' + 'userName');

var answer1 = prompt('WHAT, is your favorite color?');
  if (answer1.length < 6 && answer1.length > 3) {
    alert('CORRECT!, last question...');
  }
  else {
    alert('INCORRECT! To the pits with you!!!');
  }

var answer2 = prompt('WHAT, is the airspeed velocity of an unladen swallow?');
  if (answer2 === 'African or European?' || 'african or european?') {
    alert('I don\'t know... AHHHH!!!');
  }
  else {
    alert('To the pits with you!!!');
  }

    alert('You may pass the bridge of death if all were answered correctly');

    alert('You enter the room of The Holy Grail');

  var userNumber = prompt('Pick a cup, they are numbered 1-10');
  var computerNumber = Math.floor((Math.random() * 10) + 1);
    if (userNumber <= 5 && computerNumber <= 5) {
      alert('You drink the water and embrace the feeling of immortality! \
      The Holy Grail is yours!');
    }
    else if (userNumber > 5 && computerNumber > 5) {
      alert('You drink the water, shit your guts out and die...');

    }
    else {
      alert('You are a Pu*** and refuse to drink out of any cup... \
      Your journey was for nothing.');
    }
<|endoftext|>


<commit_before>var express = require("express");

var app = express();

app.get("/hello", function (req, res) {
    res.send("Hello world");
});

app.listen(9095);
<commit_msg>Trying to push the changes again.<commit_after>var express = require("express");

var app = express();

app.get("/hello", function (req, res) {
    res.send("Hello world");
});

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


<commit_before>var express = require('express'),
    app = express(),
    bodyParser = require('body-parser'),
    methodOverride = require('method-override'),
    passport = require('passport'),
    passportLocal = require('passport-local'),
    cookieParser = require('cookie-parser'),
    session = require('cookie-session'),
    flash = require('connect-flash'),
    seed = require('./OFAdata'),
    seedDataWrapper = require('./seedData'),
    db = require('./models/index');

app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride('_method'));

//set up our session
app.use(session({
  secret: 'secretkey',
  name: 'chocolate chip',
//this is in milliseconds
  maxage: 3600000
}));

//get passport started
app.use(passport.initialize());
app.use(passport.session());

//include flash messages
app.use(flash());

//let's serialize a admin if authenticated successfully
passport.serializeUser(function(admin,done){
  console.log("SERIALIZED JUST RAN");
  done(null,admin.id);
});

passport.deserializeUser(function (id,done) {
  console.log("DESERIALIZED JUST RAN");
  db.Admin.find({
    where: {
      id: id
    }
  }).done(function (error,user) {
    done(error,user);
  });
});

app.post("/refresh",function(req,res){
  seedDataWrapper.seedDatabase();
  res.redirect('/admin');
});

//authentication routes for admin in routes/authenticate.js
require('./routes/authenticate')(app);

//-------function for grabbing search-------//

//-------routes-------//

//home
app.get('/', function(req, res){
  db.Politician.findAll({where: {chamber:'house'},order:'lastname ASC', include: [db.IndustriesPoliticians]}).done(function (err,reps) {
    db.Politician.findAll({where: {chamber:'senate'}, order:'lastname ASC'}).done(function(err,senators){
      db.sequelize.query('SELECT DISTINCT state FROM "Politicians" ORDER BY state ASC').success(function (states) {
        var stateNames = states.map(function(elem){
          if(elem.state != null && elem.state !== undefined)
            return elem.state;
        });

        res.render('home', {allReps: reps, allSenators: senators, allStates:stateNames});
      });//end state query
    });//end senate findall
  }); //end house findall
});//end home route

app.get('/search', function (req, res) {
  var state = req.query.state;

  db.Politician.findAll({where: {chamber:'house', state:state},order:'lastname ASC', include: [db.IndustriesPoliticians]}).done(function (err,reps) {
    db.Politician.findAll({where: {chamber:'senate', state:state}, order:'lastname ASC'}).done(function(err,senators){
      db.sequelize.query('SELECT DISTINCT state FROM "Politicians" ORDER BY state ASC').success(function (states) {
        var stateNames = states.map(function(elem){
          if(elem.state != null && elem.state !== undefined)
            return elem.state;
        });

        res.render('home', {allReps: reps, allSenators: senators, allStates:stateNames, state:state});
      });//end state query
    });//end senate findall
  }); //end house findall}
});//end search route

var server = app.listen(3000, function() {
    console.log('Listening on port %d', server.address().port);
});<commit_msg>portz<commit_after>var express = require('express'),
    app = express(),
    bodyParser = require('body-parser'),
    methodOverride = require('method-override'),
    passport = require('passport'),
    passportLocal = require('passport-local'),
    cookieParser = require('cookie-parser'),
    session = require('cookie-session'),
    flash = require('connect-flash'),
    seed = require('./OFAdata'),
    seedDataWrapper = require('./seedData'),
    db = require('./models/index');

app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride('_method'));

//set up our session
app.use(session({
  secret: 'secretkey',
  name: 'chocolate chip',
//this is in milliseconds
  maxage: 3600000
}));

//get passport started
app.use(passport.initialize());
app.use(passport.session());

//include flash messages
app.use(flash());

//let's serialize a admin if authenticated successfully
passport.serializeUser(function(admin,done){
  console.log("SERIALIZED JUST RAN");
  done(null,admin.id);
});

passport.deserializeUser(function (id,done) {
  console.log("DESERIALIZED JUST RAN");
  db.Admin.find({
    where: {
      id: id
    }
  }).done(function (error,user) {
    done(error,user);
  });
});

app.post("/refresh",function(req,res){
  seedDataWrapper.seedDatabase();
  res.redirect('/admin');
});

//authentication routes for admin in routes/authenticate.js
require('./routes/authenticate')(app);

//-------function for grabbing search-------//

//-------routes-------//

//home
app.get('/', function(req, res){
  db.Politician.findAll({where: {chamber:'house'},order:'lastname ASC', include: [db.IndustriesPoliticians]}).done(function (err,reps) {
    db.Politician.findAll({where: {chamber:'senate'}, order:'lastname ASC'}).done(function(err,senators){
      db.sequelize.query('SELECT DISTINCT state FROM "Politicians" ORDER BY state ASC').success(function (states) {
        var stateNames = states.map(function(elem){
          if(elem.state != null && elem.state !== undefined)
            return elem.state;
        });

        res.render('home', {allReps: reps, allSenators: senators, allStates:stateNames});
      });//end state query
    });//end senate findall
  }); //end house findall
});//end home route

app.get('/search', function (req, res) {
  var state = req.query.state;

  db.Politician.findAll({where: {chamber:'house', state:state},order:'lastname ASC', include: [db.IndustriesPoliticians]}).done(function (err,reps) {
    db.Politician.findAll({where: {chamber:'senate', state:state}, order:'lastname ASC'}).done(function(err,senators){
      db.sequelize.query('SELECT DISTINCT state FROM "Politicians" ORDER BY state ASC').success(function (states) {
        var stateNames = states.map(function(elem){
          if(elem.state != null && elem.state !== undefined)
            return elem.state;
        });

        res.render('home', {allReps: reps, allSenators: senators, allStates:stateNames, state:state});
      });//end state query
    });//end senate findall
  }); //end house findall}
});//end search route

var server = app.listen(process.env.PORT || 3000, function() {
    console.log('Listening on port %d', server.address().port);
});<|endoftext|>


<commit_before>#!/usr/bin/env node

var spawn = require('child_process').spawn;
var process = require('process');
var async = require('async');

var scripts = ['locker/locker.js', 'messagebroker/messagebroker.js',
               'bcmonitor/bcmonitor.js', 'emailservice/emailservice.js',
               'pushnotificationsservice/pushnotificationsservice.js',
               'fiatrateservice/fiatrateservice.js', 'bws.js'];

async.eachSeries(scripts, function(script, callback) {
  console.log(`Spawning ${script}`);

  var node = spawn('node', [script]);
  node.stdout.on('data', (data) => {
    console.log(`${data}`);
  });
  node.stderr.on('data', (data) => {
    console.error(`${data}`);
  });

  callback();
});
<commit_msg>Remove unused process require, fixed spacing<commit_after>#!/usr/bin/env node

var spawn = require('child_process').spawn;
var async = require('async');

var scripts = ['locker/locker.js', 'messagebroker/messagebroker.js',
  'bcmonitor/bcmonitor.js', 'emailservice/emailservice.js',
  'pushnotificationsservice/pushnotificationsservice.js',
  'fiatrateservice/fiatrateservice.js', 'bws.js'];

async.eachSeries(scripts, function(script, callback) {
  console.log(`Spawning ${script}`);

  var node = spawn('node', [script]);
  node.stdout.on('data', (data) => {
    console.log(`${data}`);
  });
  node.stderr.on('data', (data) => {
    console.error(`${data}`);
  });

  callback();
});
<|endoftext|>


<commit_before>//    MongoStore = require('connect-mongo'),

var express = require('express'),
    graph = require('fbgraph')             ,
    crypto = require('crypto'),
    express = require('express'),
    connect = require('connect')       ,
    http = require('http')     ,
    path = require('path')    ,
    mongoose = require('mongoose'),
    fs = require('fs'),
    sys = require('sys'),
    extname = require('path').extname;

var app = express();

app.configure(function () {
    app.set('port', process.env.PORT || 3000);
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
    app.use(express.favicon());
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(app.router);
    app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function () {
    app.use(express.errorHandler());
});

try {
    cfg = JSON.parse(fs.readFileSync(process.cwd() + "/config.json"));
} catch (e) {
    // ignore
}

// file loader (for controllers, models, ...)
var loader = function (dir) {
    fs.readdir(dir, function (err, files) {
        if (err) {
            throw err;
        }
        files.forEach(function (file) {
            if ('.js' == extname(file)) {
                console.log(dir + '/' + file.replace('.js', ''));
                require(dir + '/' + file.replace('.js', ''));
            }
        });
    });
};

// enable debugger
if (true == cfg.debug) {
    app.use(express.errorHandler({
        showStack:true,
        dumpExceptions:true
    }));
}

// enable logger
if (true == cfg.logger) {
    app.use(express.logger());
}

// load models
cfg.loader.models.forEach(loader);
//cfg.loader.controllers.forEach(loader);

db = mongoose.connect(cfg.mongodb);

var handleError = function (msg, err, req, res, next) {
    if (req.session) {
        req.session.destroy();
    }
    console.log(msg, err);
    res.json({ success:false, error:err });
};

// load default controller
if (cfg.loader.use_default_controller) {
    app.get('/:collection', function (req, res, next) {
        var model_class = req.params.collection.charAt(0).toUpperCase() + req.params.collection.slice(1);
        var qw = eval(model_class).where('profileId');
        if (req.param('query')) {
            qw.where(req.param('query'));
        }
        if (req.param('order')) {
            var order = [];
            req.param('order').forEach(function (dir, field) {
                order.push([field, dir]);
            });
            qw.sort(order);
        }
        if (req.param('limit')) {
            qw.limit(req.param('limit'));
        }
        if (req.param('offset')) {
            qw.skip(req.param('offset'));
        }
        qw.run(function (err, rows) {
            if (err) {
                handleError('Could not retrieve list of runs', rows, req, res);
                return;
            }
            console.log("Found " + rows.length + " posts.");
            res.json(rows);
        });
    });

    // READ
    app.get('/:collection/:id', function (req, res, next) {
        var model_class = req.params.collection.charAt(0).toUpperCase() + req.params.collection.slice(1);
        qw = eval(model_class).findById(req.params.id);
        qw.run(function (err, rows) {
            if (err) {
                handleError('Could not retrieve list of runs', rows, req, res);
                return;
            }
            console.log("Found " + rows.length + " " + model_class + "s");
            res.json(rows);
        });

    });

    // CREATE
    var createDoc = function (req, res, next) {
        var model_class = req.params.collection.charAt(0).toUpperCase() + req.params.collection.slice(1);
        var doc = new eval(model_class);
        doc.merge(req.param(req.params.collection));
        doc.save(function () {
            res.json(doc, 201);
        });
    };

    app.put('/:collection', createDoc);
    app.post('/:collection', createDoc);

    // MODIFY
    var modifyDoc = function (req, res, next) {
        var model_class = req.params.collection.charAt(0).toUpperCase() + req.params.collection.slice(1);
        eval(model_class).findById(req.params.id, function (doc) {
            if (!doc) {
                next(new NotFound);
            } else {
                doc.merge(req.param(req.params.collection));

                doc.save(function () {
                    res.json(doc.toObject(), 200);
                });
            }
        });
    };

    app.put('/:collection/:id', modifyDoc);
    app.post('/:collection/:id', modifyDoc);

    // REMOVE
    app.del('/:collection/:id', function (req, res, next) {
        var model_class = req.params.collection.charAt(0).toUpperCase() + req.params.collection.slice(1);
        eval(model_class).findById(req.params.id, function (doc) {
            if (!doc) {
                next(new NotFound);
            } else {
                doc.remove(function () {
                    res.json('200 OK', 200);
                });
            }
        });
    });
}

http.createServer(app).listen(app.get('port'), function () {
    console.log("Express server listening on port " + app.get('port'));
});
<commit_msg>places model added<commit_after>//    MongoStore = require('connect-mongo'),

var express = require('express'),
    graph = require('fbgraph'),
    crypto = require('crypto'),
    express = require('express'),
    connect = require('connect'),
    http = require('http'),
    path = require('path'),
    mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId,
    fs = require('fs'),
    sys = require('sys'),
    extname = require('path').extname;

var app = module.exports = express();

app.configure(function () {
    app.set('port', process.env.PORT || 3000);
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
    app.use(express.favicon());
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(app.router);
    app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function () {
    app.use(express.errorHandler());
});

try {
    cfg = JSON.parse(fs.readFileSync(process.cwd() + "/config.json"));
} catch (e) {
    // ignore
}

// file loader (for controllers, models, ...)
var loader = function (dir) {
    fs.readdir(dir, function (err, files) {
        if (err) {
            throw err;
        }
        files.forEach(function (file) {
            if ('.js' == extname(file)) {
                console.log(dir + '/' + file.replace('.js', ''));
                require(dir + '/' + file.replace('.js', ''));
            }
        });
    });
};

// enable debugger
if (true == cfg.debug) {
    app.use(express.errorHandler({
        showStack:true,
        dumpExceptions:true
    }));
}

// enable logger
if (true == cfg.logger) {
    app.use(express.logger());
}

// load models
cfg.loader.models.forEach(loader);
//cfg.loader.controllers.forEach(loader);

db = mongoose.connect(cfg.mongodb);

var handleError = function (err, req, res, next) {
//    if (req.session) {
//        req.session.destroy();
//    }
    console.log(err);
    res.json({ success:false, error:err });
};

// load default controller
if (cfg.loader.use_default_controller) {
    app.get('/:collection', function (req, res, next) {
        model_class = require("./models/" + req.params.collection.charAt(0).toUpperCase() + req.params.collection.slice(1));
        var qw = model_class.where('profileId');
        if (req.param('query')) {
            qw.where(req.param('query'));
        }
        if (req.param('order')) {
            var order = [];
            req.param('order').forEach(function (dir, field) {
                order.push([field, dir]);
            });
            qw.sort(order);
        }
        if (req.param('limit')) {
            qw.limit(req.param('limit'));
        }
        if (req.param('offset')) {
            qw.skip(req.param('offset'));
        }
        qw.run(function (err, rows) {
            if (err) {
                handleError('Could not retrieve list of runs', rows, req, res);
                return;
            }
            console.log("Found " + rows.length + " posts.");
            res.json(rows);
        });
    });

    // READ
    app.get('/:collection/:id', function (req, res, next) {
        model_class = require("./models/" + req.params.collection.charAt(0).toUpperCase() + req.params.collection.slice(1));
        qw = model_class.findById(req.params.id);
        qw.run(function (err, rows) {
            if (err) {
                handleError('Could not retrieve list of runs', rows, req, res);
                return;
            }
            console.log("Found " + rows.length + " " + model_class + "s");
            res.json(rows);
        });

    });

    // CREATE
    var createDoc = function (req, res, next) {
        model_class = require("./models/" + req.params.collection.charAt(0).toUpperCase() + req.params.collection.slice(1));
        placeModel = require("./models/Place");
        var doc = new model_class(req.body);
        doc.save(function (err) {
            if (err) return handleError(err);
            res.json(req.body, 201);
        });
    };

    app.put('/:collection', createDoc);
    app.post('/:collection', createDoc);

    // MODIFY
    var modifyDoc = function (req, res, next) {
        model_class = require("./models/" + req.params.collection.charAt(0).toUpperCase() + req.params.collection.slice(1));
        model_class.update({_id:req.params.id}, req.body, function (err) {
            if (err) return handleError(err);
        });
        res.json(req.body, 200);
    };

    app.put('/:collection/:id', modifyDoc);
    app.post('/:collection/:id', modifyDoc);

    // REMOVE
    app.del('/:collection/:id', function (req, res, next) {
        model_class = require("./models/" + req.params.collection.charAt(0).toUpperCase() + req.params.collection.slice(1));
        model_class.remove({_id:req.params.id}, function (err) {
            if (err) return handleError(err);
        });
        res.json(req.body, 200);
    });
}

http.createServer(app).listen(app.get('port'), function () {
    console.log("Express server listening on port " + app.get('port'));
});
<|endoftext|>


<commit_before>angular.module('listDocApp',[])
			.controller('ListDocCtrl', [function(){
				var self = this;

				self.docs = [
					{name: 'First Note', done: false},
					{name 'Second Note', done: false},
					{name: 'Done Note', done: true},
					{name: 'Last Note', done: false}
				];
			}]); <commit_msg>remove unsed file<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env node
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 8080;

server.listen(port, function () {
  console.log('Server listening at port %d', port);
});

////////////////////////////////////////////////////
// Models
require("coffee-script/register")

var Player = require('./models/player');

var Game = require('./models/game');
    game = new Game(io);

////////////////////////////////////////////////////
// Globals
var game_started = false;
var game_length = 60 * 1000; // 60 seconds
//var game_length = 6 * 1000;

////////////////////////////////////////////////////
// RPC methods
app.get('/rpc/words', function(req, res) {
    res.send(game.getWords());
});

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

////////////////////////////////////////////////////
// Socket.io
io.on('connection', function (socket) {
  console.log("CONNECTION");

  socket.on('new player', function (playerName) {
    console.log("PLAYER " + playerName);
    var player = new Player(0, socket, game, playerName);
    socket.player = player

    game.addPlayer(player);

    socket.emit('user joined', {
      player: socket.player.name,
    });
  });

  // when the client emits 'new message', this listens and executes
  socket.on('new word', function (word) {
    console.log("WORD " + word);

    if ( ! game_started) {
      setTimeout(function() {
        var scores = [];
        for (player in game.players) {
          scores.push({player: player.name,
                       score: player.score});
        }
        socket.emit('game over', {
          scores: scores
        });
      }, game_length);
    }

    socket.emit('new word', {
      player: socket.player.name,
      word: word
    });

    game.addWord(socket.player, word);

    var words = game.getWordCounts();
    var wordCounts = [];
    for (countedWord in words) {
      wordCounts.push({text: countedWord,
                       size: Math.sqrt(words[countedWord] * 200)});
    }

    socket.emit('wordcloud', {
      words: wordCounts
    });

  });

  // when the user disconnects.. perform this
  socket.on('disconnect', function () {
    ////////////////////////////
    // REMOVE PLAYER FROM GAME
    //
  });
});

module.exports = app;
<commit_msg>Send wordcloud update to everyone on all words<commit_after>#!/usr/bin/env node
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 8080;

server.listen(port, function () {
  console.log('Server listening at port %d', port);
});

////////////////////////////////////////////////////
// Models
require("coffee-script/register")

var Player = require('./models/player');

var Game = require('./models/game');
    game = new Game(io);

////////////////////////////////////////////////////
// Globals
var game_started = false;
var game_length = 60 * 1000; // 60 seconds
//var game_length = 6 * 1000;

////////////////////////////////////////////////////
// RPC methods
app.get('/rpc/words', function(req, res) {
    res.send(game.getWords());
});

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

////////////////////////////////////////////////////
// Socket.io
io.on('connection', function (socket) {
  console.log("CONNECTION");

  socket.on('new player', function (playerName) {
    console.log("PLAYER " + playerName);
    var player = new Player(0, socket, game, playerName);
    socket.player = player

    game.addPlayer(player);

    socket.emit('user joined', {
      player: socket.player.name,
    });
  });

  // when the client emits 'new message', this listens and executes
  socket.on('new word', function (word) {
    console.log("WORD " + word);

    if ( ! game_started) {
      setTimeout(function() {
        var scores = [];
        for (player in game.players) {
          scores.push({player: player.name,
                       score: player.score});
        }
        socket.emit('game over', {
          scores: scores
        });
      }, game_length);
    }

    socket.emit('new word', {
      player: socket.player.name,
      word: word
    });

    game.addWord(socket.player, word);

    var words = game.getWordCounts();
    var wordCounts = [];
    for (countedWord in words) {
      wordCounts.push({text: countedWord,
                       size: Math.sqrt(words[countedWord] * 200)});
    }

    // TODO(sam): this is a hack to get the moderator interface to work; we
    // should have moderators join like any player and notify only moderator
    // sockets
    io.sockets.emit('wordcloud', {
      words: wordCounts
    });

  });

  // when the user disconnects.. perform this
  socket.on('disconnect', function () {
    ////////////////////////////
    // REMOVE PLAYER FROM GAME
    //
  });
});

module.exports = app;
<|endoftext|>


<commit_before>var hours = ["10am: ", "11am: ", "12pm: ", "1pm: ", "2pm: ", "3pm: ", "4pm: ", "5pm: ",];

var pikePlace = new Store('Pike Place', 17, 88, 5.2);
var seaTac = new Store('SeaTac Airport', 6, 24, 1.2);
var southcenter = new Store('Southcenter', 11, 38, 1.9);
var bellevue = new Store('Bellevue Square', 20, 48, 3.3);
var alki = new Store('Alki', 3, 24, 2.6);

function Store (name, minCustomer, maxCustomer, avgCookieSale) {
  this.name = name;
  this.minCustomer = minCustomer;
  this.maxCustomer = maxCustomer;
  this.avgCookieSale = avgCookieSale;
  this.hourlyCookieSales = [];
  this.totalCookieSales = 0;
}

Store.prototype.randNumber = function(max, min){
  return Math.random() * (max - min) + min;
};

Store.prototype.getHourlyCookieSales = function(rand, max, min, arr, totals, avg, hour) {
  for (var i = 0; i < hour.length; i++){
    var cookies = Math.floor(rand(max, min) * avg);
    arr.push(cookies);
    totals += cookies;
  };

Store.prototype.render = function(){
  this.getHourlyCookieSales(this.randNumber, this.maxCustomer, this.minCustomer, this.hourlyCookieSales, this.totalCookieSales, this.avgCookieSale, hours);
  var ulEl = document.createElement("ul");
  ulEl.appendChild(document.createTextNode(this.name));
  var sectionEl = document.getElementById('myInfoList').appendChild(ulEl);
    for (var i = 0; i < hours.length; i++){
      var liEl = document.createElement('li');
      liEl.textContent = hours[i] + this.hourlyCookieSales[i];
      ulEl.appendChild(liEl);
    }
    var liEl_two =  document.createElement('li');
    liEl_two.textContent = "Total: " + this.totalCookieSales;
    ulEl.appendChild(liEl_two);
  }
};

Store.pikePlace.render();
Store.seaTac.render();
Store.southcenter.render();
Store.bellevue.render();
Store.alki.render();

// var pikePlace = {
//   name: "Pike Place",
//   minCustomer: 17,
//   maxCustomer: 88,
//   avgCookieSale: 5.2,
//   hourlyCookieSales: [],
//   totalCookieSales: 0 ,
//   randNumber: function(max, min) {
//     return Math.random() * (max - min) + min;
//   },

// var seaTac = {
//   name: "SeaTac Airport",
//   minCustomer: 6,
//   maxCustomer: 24,
//   avgCookieSale: 1.2,
//   hourlyCookieSales: [],
//   totalCookieSales: 0,
//   randNumber: function(max, min){
//     return Math.random() * (max - min) + min;
//   },
//   getHourlyCookieSales: function(arr, totals, avg, rand, hour){
//     for (var i = 0; i < hour.length; i++){
//       var cookies = Math.floor(this.randNumber(this.maxCustomer,this.minCustomer) * avg);
//       arr.push(cookies);
//       this.totalCookieSales += cookies;
//     }
//   },
//   render: function(){
//     this.getHourlyCookieSales(this.hourlyCookieSales, this.totalCookieSales, this.avgCookieSale, this.randNumber,hours);
//     var ulEl = document.createElement("ul");
//     ulEl.appendChild(document.createTextNode(this.name));
//     var sectionEl = document.getElementById('seaTacList').appendChild(ulEl);
//     for (var i = 0; i < hours.length; i++){
//       var liEl = document.createElement('li');
//       liEl.textContent = hours[i] + this.hourlyCookieSales[i];
//       ulEl.appendChild(liEl);
//     }
//     var liEl_two = document.createElement('li');
//     liEl_two.textContent = "Total: " + this.totalCookieSales;
//     ulEl.appendChild(liEl_two);
//   }
// };
//
//
//   var southcenter = {
//     name: "Southcenter",
//     minCustomer: 11,
//     maxCustomer: 38,
//     avgCookieSale: 1.9,
//     hourlyCookieSales: [],
//     totalCookieSales: 0,
//     randNumber: function(max, min){
//       return Math.random() * (max - min) + min;
//     },
//     getHourlyCookieSales: function(arr, totals, avg, rand, hour){
//       for (var i = 0; i < hour.length; i++){
//         var cookies = Math.floor(this.randNumber(this.maxCustomer, this.minCustomer) * avg);
//         arr.push(cookies);
//         this.totalCookieSales += cookies;
//       }
//     },
//     render: function(){
//       this.getHourlyCookieSales(this.hourlyCookieSales, this.totalCookieSales, this.avgCookieSale, this.randNumber, hours);
//       var ulEl = document.createElement('ul');
//       ulEl.appendChild(document.createTextNode(this.name));
//       var sectionEl = document.getElementById('southCenterList').appendChild(ulEl);
//       for (var i = 0; i < hours.length; i++){
//         var liEl = document.createElement('li');
//         liEl.textContent = hours[i] + this.hourlyCookieSales[i];
//         ulEl.appendChild(liEl);
//       }
//       var liEl_two = document.createElement('li');
//       liEl_two.textContent = "Total: " + this.totalCookieSales;
//       ulEl.appendChild(liEl_two);
//     }
//   };
//
//     var bellevue = {
//       name: "Bellevue Square",
//       minCustomer: 20,
//       maxCustomer: 48,
//       avgCookieSale: 3.3,
//       hourlyCookieSales: [],
//       totalCookieSales: 0,
//       randNumber: function(max, min){
//         return Math.random() * (max - min) + min;
//       },
//       getHourlyCookieSales: function(arr, totals, avg, rand, hour){
//         for (var i = 0; i < hour.length; i++){
//           var cookies = Math.floor(this.randNumber(this.maxCustomer, this.minCustomer) * avg);
//           arr.push(cookies);
//           this.totalCookieSales += cookies;
//         }
//       },
//       render: function(){
//         this.getHourlyCookieSales(this.hourlyCookieSales, this.totalCookieSales, this.avgCookieSale, this.randNumber, hours);
//         var ulEl = document.createElement('ul');
//         ulEl.appendChild(document.createTextNode(this.name));
//         var sectionEl = document.getElementById("bellevueList").appendChild(ulEl);
//         for (var i = 0; i < hours.length; i++){
//           var liEl = document.createElement('li');
//           liEl.textContent = hours[i] + this.hourlyCookieSales[i];
//           ulEl.appendChild(liEl);
//         }
//         var liEl_two = document.createElement('li');
//         liEl_two.textContent = "Total: " + this.totalCookieSales;
//         ulEl.appendChild(liEl_two);
//       }
//     };
//
//       var alki = {
//         name: "Alki",
//         minCustomer: 3,
//         maxCustomer: 24,
//         avgCookieSale: 2.6,
//         hourlyCookieSales: [],
//         totalCookieSales: 0,
//         randNumber: function(max, min){
//           return Math.random() * (max -min) +min;
//         },
//         getHourlyCookieSales: function(arr, totals, avg, rand, hour){
//           for (var i = 0; i < hour.length; i++){
//             var cookies = Math.floor(this.randNumber(this.maxCustomer, this.minCustomer) * avg);
//             arr.push(cookies);
//             this.totalCookieSales += cookies;
//           }
//         },
//         render: function(){
//           this.getHourlyCookieSales(this.hourlyCookieSales, this.totalCookieSales, this.avgCookieSale, this.randNumber, hours);
//           var ulEl = document.createElement('ul');
//           ulEl.appendChild(document.createTextNode(this.name));
//           var sectionEl = document.getElementById("alkiList").appendChild(ulEl);
//           for (var i = 0; i < hours.length; i++){
//             var liEl = document.createElement('li');
//             liEl.textContent = hours[i] + this.hourlyCookieSales[i];
//             ulEl.appendChild(liEl);
//           }
//           var liEl_two = document.createElement('li');
//           liEl_two.textContent = "Total for these nasty ass cookies are: " + this.totalCookieSales;
//           ulEl.appendChild(liEl_two);
//         }
//       };
//
// var stores = [
//   pikePlace, seaTac, bellevue, alki,
// ];
// for (var k = 0; k < stores.length; k++) {
//   stores[k].render();
// }
<commit_msg>finished construtor<commit_after>var hours = ["10am: ", "11am: ", "12pm: ", "1pm: ", "2pm: ", "3pm: ", "4pm: ", "5pm: "];

var pikePlace = new Store('Pike Place', 17, 88, 5.2);
var seaTac = new Store('SeaTac Airport', 6, 24, 1.2);
var southcenter = new Store('Southcenter', 11, 38, 1.9);
var bellevue = new Store('Bellevue Square', 20, 48, 3.3);
var alki = new Store('Alki', 3, 24, 2.6);

function Store (name, minCustomer, maxCustomer, avgCookieSale) {
  this.name = name;
  this.minCustomer = minCustomer;
  this.maxCustomer = maxCustomer;
  this.avgCookieSale = avgCookieSale;
  this.hourlyCookieSales = [];
  this.totalCookieSales = 0;
}

Store.prototype.randNumber = function(max, min){
  return Math.random() * (max - min) + min;
};

Store.prototype.getHourlyCookieSales = function() {
  for (var i = 0; i < hours.length; i++){
    var cookies = Math.floor(this.randNumber(this.maxCustomer, this.minCustomer) * this.avgCookieSale);
    this.hourlyCookieSales.push(cookies);
    this.totalCookieSales += cookies;
  }
};

Store.prototype.render = function(){
  this.getHourlyCookieSales();
  var ulEl = document.createElement("ul");
  ulEl.appendChild(document.createTextNode(this.name));
  var sectionEl = document.getElementById('myInfoList').appendChild(ulEl);
    for (var i = 0; i < hours.length; i++){
      var liEl = document.createElement('li');
      liEl.textContent = hours[i] + this.hourlyCookieSales[i];
      ulEl.appendChild(liEl);
    }
    var liEl_two =  document.createElement('li');
    liEl_two.textContent = "Total: " + this.totalCookieSales;
    ulEl.appendChild(liEl_two);

};

pikePlace.render();
seaTac.render();
southcenter.render();
bellevue.render();
alki.render();

// var pikePlace = {
//   name: "Pike Place",
//   minCustomer: 17,
//   maxCustomer: 88,
//   avgCookieSale: 5.2,
//   hourlyCookieSales: [],
//   totalCookieSales: 0 ,
//   randNumber: function(max, min) {
//     return Math.random() * (max - min) + min;
//   },

// var seaTac = {
//   name: "SeaTac Airport",
//   minCustomer: 6,
//   maxCustomer: 24,
//   avgCookieSale: 1.2,
//   hourlyCookieSales: [],
//   totalCookieSales: 0,
//   randNumber: function(max, min){
//     return Math.random() * (max - min) + min;
//   },
//   getHourlyCookieSales: function(arr, totals, avg, rand, hour){
//     for (var i = 0; i < hour.length; i++){
//       var cookies = Math.floor(this.randNumber(this.maxCustomer,this.minCustomer) * avg);
//       arr.push(cookies);
//       this.totalCookieSales += cookies;
//     }
//   },
//   render: function(){
//     this.getHourlyCookieSales(this.hourlyCookieSales, this.totalCookieSales, this.avgCookieSale, this.randNumber,hours);
//     var ulEl = document.createElement("ul");
//     ulEl.appendChild(document.createTextNode(this.name));
//     var sectionEl = document.getElementById('seaTacList').appendChild(ulEl);
//     for (var i = 0; i < hours.length; i++){
//       var liEl = document.createElement('li');
//       liEl.textContent = hours[i] + this.hourlyCookieSales[i];
//       ulEl.appendChild(liEl);
//     }
//     var liEl_two = document.createElement('li');
//     liEl_two.textContent = "Total: " + this.totalCookieSales;
//     ulEl.appendChild(liEl_two);
//   }
// };
//
//
//   var southcenter = {
//     name: "Southcenter",
//     minCustomer: 11,
//     maxCustomer: 38,
//     avgCookieSale: 1.9,
//     hourlyCookieSales: [],
//     totalCookieSales: 0,
//     randNumber: function(max, min){
//       return Math.random() * (max - min) + min;
//     },
//     getHourlyCookieSales: function(arr, totals, avg, rand, hour){
//       for (var i = 0; i < hour.length; i++){
//         var cookies = Math.floor(this.randNumber(this.maxCustomer, this.minCustomer) * avg);
//         arr.push(cookies);
//         this.totalCookieSales += cookies;
//       }
//     },
//     render: function(){
//       this.getHourlyCookieSales(this.hourlyCookieSales, this.totalCookieSales, this.avgCookieSale, this.randNumber, hours);
//       var ulEl = document.createElement('ul');
//       ulEl.appendChild(document.createTextNode(this.name));
//       var sectionEl = document.getElementById('southCenterList').appendChild(ulEl);
//       for (var i = 0; i < hours.length; i++){
//         var liEl = document.createElement('li');
//         liEl.textContent = hours[i] + this.hourlyCookieSales[i];
//         ulEl.appendChild(liEl);
//       }
//       var liEl_two = document.createElement('li');
//       liEl_two.textContent = "Total: " + this.totalCookieSales;
//       ulEl.appendChild(liEl_two);
//     }
//   };
//
//     var bellevue = {
//       name: "Bellevue Square",
//       minCustomer: 20,
//       maxCustomer: 48,
//       avgCookieSale: 3.3,
//       hourlyCookieSales: [],
//       totalCookieSales: 0,
//       randNumber: function(max, min){
//         return Math.random() * (max - min) + min;
//       },
//       getHourlyCookieSales: function(arr, totals, avg, rand, hour){
//         for (var i = 0; i < hour.length; i++){
//           var cookies = Math.floor(this.randNumber(this.maxCustomer, this.minCustomer) * avg);
//           arr.push(cookies);
//           this.totalCookieSales += cookies;
//         }
//       },
//       render: function(){
//         this.getHourlyCookieSales(this.hourlyCookieSales, this.totalCookieSales, this.avgCookieSale, this.randNumber, hours);
//         var ulEl = document.createElement('ul');
//         ulEl.appendChild(document.createTextNode(this.name));
//         var sectionEl = document.getElementById("bellevueList").appendChild(ulEl);
//         for (var i = 0; i < hours.length; i++){
//           var liEl = document.createElement('li');
//           liEl.textContent = hours[i] + this.hourlyCookieSales[i];
//           ulEl.appendChild(liEl);
//         }
//         var liEl_two = document.createElement('li');
//         liEl_two.textContent = "Total: " + this.totalCookieSales;
//         ulEl.appendChild(liEl_two);
//       }
//     };
//
//       var alki = {
//         name: "Alki",
//         minCustomer: 3,
//         maxCustomer: 24,
//         avgCookieSale: 2.6,
//         hourlyCookieSales: [],
//         totalCookieSales: 0,
//         randNumber: function(max, min){
//           return Math.random() * (max -min) +min;
//         },
//         getHourlyCookieSales: function(arr, totals, avg, rand, hour){
//           for (var i = 0; i < hour.length; i++){
//             var cookies = Math.floor(this.randNumber(this.maxCustomer, this.minCustomer) * avg);
//             arr.push(cookies);
//             this.totalCookieSales += cookies;
//           }
//         },
//         render: function(){
//           this.getHourlyCookieSales(this.hourlyCookieSales, this.totalCookieSales, this.avgCookieSale, this.randNumber, hours);
//           var ulEl = document.createElement('ul');
//           ulEl.appendChild(document.createTextNode(this.name));
//           var sectionEl = document.getElementById("alkiList").appendChild(ulEl);
//           for (var i = 0; i < hours.length; i++){
//             var liEl = document.createElement('li');
//             liEl.textContent = hours[i] + this.hourlyCookieSales[i];
//             ulEl.appendChild(liEl);
//           }
//           var liEl_two = document.createElement('li');
//           liEl_two.textContent = "Total for these nasty ass cookies are: " + this.totalCookieSales;
//           ulEl.appendChild(liEl_two);
//         }
//       };
//
// var stores = [
//   pikePlace, seaTac, bellevue, alki,
// ];
// for (var k = 0; k < stores.length; k++) {
//   stores[k].render();
// }
<|endoftext|>


<commit_before>'use strict';

var hoursOpenPerDay = ['6:00am', '7:00am', '8:00am', '9:00am', '10:00am', '11:00am', '12:00pm', '1:00pm', '2:00pm', '3:00pm', '4:00pm', '5:00pm', '6:00pm', '7:00pm'];
var businesses = [];
var hourlyCookieSales = [];
var totalAllLocationsSales = [];

//Constructor
function Stores(minCustomersPerHour, maxCustomersPerHour, avgCookiesPerCustomer, location) {
  this.minCustomersPerHour = minCustomersPerHour;
  this.maxCustomersPerHour = maxCustomersPerHour;
  this.avgCookiesPerCustomer = avgCookiesPerCustomer;
  this.location = location;
  this.customersPerHour = [];
  this.cookiesSoldPerHour = [];
  this.totalDailyCookiesSold = 0;
  this.calcCustomersPerHour = function() {
    for (var i = 0; i < hoursOpenPerDay.length; i++) {
      this.customersPerHour.push(Math.floor(Math.random() * (this.maxCustomersPerHour - this.minCustomersPerHour + 1)) + this.minCustomersPerHour);
    }
  };
  this.calcCookiesSoldPerHour = function() {
    for (var i = 0; i < hoursOpenPerDay.length; i++) {
      this.cookiesSoldPerHour.push(Math.ceil(this.customersPerHour[i] * this.avgCookiesPerCustomer));
      this.totalDailyCookiesSold += this.cookiesSoldPerHour[i];
    }
  };
  this.renderTableBody = function () {
    var tableDataDisplay = document.getElementById('businesses_reporting_js');
    for (var i = 0; i < businesses.length; i++) {
      var trEl = document.createElement('tr'); //Create a row for each business location
      var tdEl = document.createElement('td'); //Create a column for the business location name
      tdEl.textContent = businesses[i].location; //Add business location name to column
      trEl.appendChild(tdEl); //Add business location name column to row for current business location[i]
      for (var a = 0; a <= hoursOpenPerDay.length; a++) { //Create a column for each hour of the day loop
        tdEl = document.createElement('td'); //Create a column for earch hour of the day
        tdEl.textContent = businesses[i].cookiesSoldPerHour[a]; //Add hourly sales of cookies per business[i] to hourly column
        trEl.appendChild(tdEl); //Add hourly sales of cookies per business to column for current business location[i] row
      }
      tdEl.textContent = businesses[i].totalDailyCookiesSold; //Create a column for the daily total cookies sold
      trEl.appendChild(tdEl); //Add daily cookies total sold to business location row
    }
    tableDataDisplay.appendChild(trEl); //Add row for each business location to reporting table
  };
  this.calculate = function () {
    this.calcCustomersPerHour();
    this.calcCookiesSoldPerHour();
    this.renderTableBody();
  };
  businesses.push(this);
  this.calculate();
}

function renderTableHeader() {
  var tableDataDisplay = document.getElementById('businesses_reporting_js');
  var trEl = document.createElement('tr'); //Create a row for each business location
  var thEl = document.createElement('th'); //Create a table header column to hold hours of the day
  thEl.textContent = ''; //Create a blank space as the first column in the tabel header row
  trEl.appendChild(thEl); //Add blank space to the table header row
  for (var i = 0; i < hoursOpenPerDay.length; i++) {
    thEl = document.createElement('th'); //Create a table header row to hold hours of the day
    thEl.textContent = hoursOpenPerDay[i]; //Add hour of the day to the table header
    trEl.appendChild(thEl); //Add hour of the day to the table header row
  }
  thEl = document.createElement('th'); //Create a table header row for daily totals
  thEl.textContent = 'Totals!'; //Add totals to the table header row as last column
  trEl.appendChild(thEl); //Add totals to the table header row as last column
  tableDataDisplay.appendChild(trEl); //Add table header row to daily data table
};
renderTableHeader();

new Stores(23, 65, 6.3, '1st and Pike');
new Stores(3, 24, 1.2, 'SeaTac Airport');
new Stores(11, 38, 3.7, 'Seattle Center');
new Stores(20, 38, 2.3, 'Capitol Hill');
new Stores(2, 16, 4.6, 'Alki Beach');
<commit_msg>add footer<commit_after>'use strict';

var hoursOpenPerDay = ['6:00am', '7:00am', '8:00am', '9:00am', '10:00am', '11:00am', '12:00pm', '1:00pm', '2:00pm', '3:00pm', '4:00pm', '5:00pm', '6:00pm', '7:00pm'];
var businesses = [];
var salesByHour = [];
var totalAllLocationsSales = 0;

//Constructor
function Stores(minCustomersPerHour, maxCustomersPerHour, avgCookiesPerCustomer, location) {
  this.minCustomersPerHour = minCustomersPerHour;
  this.maxCustomersPerHour = maxCustomersPerHour;
  this.avgCookiesPerCustomer = avgCookiesPerCustomer;
  this.location = location;
  this.customersPerHour = [];
  this.cookiesSoldPerHour = [];
  this.totalDailyCookiesSold = 0;
  this.calcCustomersPerHour = function() {
    for (var i = 0; i < hoursOpenPerDay.length; i++) {
      this.customersPerHour.push(Math.floor(Math.random() * (this.maxCustomersPerHour - this.minCustomersPerHour + 1)) + this.minCustomersPerHour);
    }
  };
  this.calcCookiesSoldPerHour = function() {
    for (var i = 0; i < hoursOpenPerDay.length; i++) {
      this.cookiesSoldPerHour.push(Math.ceil(this.customersPerHour[i] * this.avgCookiesPerCustomer));
      this.totalDailyCookiesSold += this.cookiesSoldPerHour[i];
    }
  };
  this.renderTableBody = function () {
    var tableDataDisplay = document.getElementById('businesses_reporting_js');
    for (var i = 0; i < businesses.length; i++) {
      var trEl = document.createElement('tr'); //Create a row for each business location
      var tdEl = document.createElement('td'); //Create a column for the business location name
      tdEl.textContent = businesses[i].location; //Add business location name to column
      trEl.appendChild(tdEl); //Add business location name column to row for current business location[i]
      for (var a = 0; a <= hoursOpenPerDay.length; a++) { //Create a column for each hour of the day loop
        tdEl = document.createElement('td'); //Create a column for earch hour of the day
        tdEl.textContent = businesses[i].cookiesSoldPerHour[a]; //Add hourly sales of cookies per business[i] to hourly column
        trEl.appendChild(tdEl); //Add hourly sales of cookies per business to column for current business location[i] row
      }
      tdEl.textContent = businesses[i].totalDailyCookiesSold; //Create a column for the daily total cookies sold
      trEl.appendChild(tdEl); //Add daily cookies total sold to business location row
    }
    tableDataDisplay.appendChild(trEl); //Add row for each business location to reporting table
  };
  this.calculate = function () {
    this.calcCustomersPerHour();
    this.calcCookiesSoldPerHour();
    this.renderTableBody();
  };
  businesses.push(this);
  this.calculate();
}

function renderTableHeader() {
  var tableDataDisplay = document.getElementById('businesses_reporting_js');
  var trEl = document.createElement('tr'); //Create a row for each business location
  var thEl = document.createElement('th'); //Create a table header column to hold hours of the day
  thEl.textContent = ''; //Create a blank space as the first column in the tabel header row
  trEl.appendChild(thEl); //Add blank space to the table header row
  for (var i = 0; i < hoursOpenPerDay.length; i++) {
    thEl = document.createElement('th'); //Create a table header row to hold hours of the day
    thEl.textContent = hoursOpenPerDay[i]; //Add hour of the day to the table header
    trEl.appendChild(thEl); //Add hour of the day to the table header row
  }
  thEl = document.createElement('th'); //Create a table header row for daily totals
  thEl.textContent = 'Totals!'; //Add totals to the table header row as last column
  trEl.appendChild(thEl); //Add totals to the table header row as last column
  tableDataDisplay.appendChild(trEl); //Add table header row to daily data table
};
function renderTableFooter() {
  var tableDataDisplay = document.getElementById('businesses_reporting_js');
  var trEl = document.createElement('tr'); //Create a row for each business location
  var tdEl = document.createElement('td'); //Create a column for the business location name
  tdEl.textContent = 'Totals'; //Add business location name to column
  trEl.appendChild(tdEl); //Add business location name column to row for current business location[i]
  for (var a = 0; a <= hoursOpenPerDay.length; a++) { //Create a column for each hour of the day loop
    tdEl = document.createElement('td'); //Create a column for earch hour of the day
    tdEl.textContent = salesByHour[a]; //Add hourly sales of cookies per business[i] to hourly column
    trEl.appendChild(tdEl); //Add hourly sales of cookies per business to column for current business location[i] row
  }
  tdEl.textContent = totalAllLocationsSales; //Create a column for the daily total cookies sold
  trEl.appendChild(tdEl); //Add daily cookies total sold to business location row
  tableDataDisplay.appendChild(trEl); //Add row for each business location to reporting table
};
renderTableHeader();

new Stores(23, 65, 6.3, '1st and Pike');
new Stores(3, 24, 1.2, 'SeaTac Airport');
new Stores(11, 38, 3.7, 'Seattle Center');
new Stores(20, 38, 2.3, 'Capitol Hill');
new Stores(2, 16, 4.6, 'Alki Beach');

function totalSalesCalc() {
  for (var i = 0; i < hoursOpenPerDay.length; i++) {
    var hourlyCookieSales = 0;
    for (var z = 0; z < businesses.length; z++) {
      hourlyCookieSales += businesses[z].cookiesSoldPerHour[i];
    }
    salesByHour.push(hourlyCookieSales);
  }
  for (var y = 0; y < businesses.length; y++) {
    totalAllLocationsSales += businesses[y].totalDailyCookiesSold;
  }
}
totalSalesCalc();
renderTableFooter();
<|endoftext|>


<commit_before>//app
//external modules
var express = require('express');
var toobusy = require('toobusy-js');
var ejs = require('ejs');
var passport = require('passport');
var methodOverride = require('method-override');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var compression = require('compression')
var session = require('express-session');
var SequelizeStore = require('connect-session-sequelize')(session.Store);
var fs = require('fs');
var imgur = require('imgur');
var formidable = require('formidable');
var morgan = require('morgan');
var passportSocketIo = require("passport.socketio");
var helmet = require('helmet');

//core
var config = require("./lib/config.js");
var logger = require("./lib/logger.js");
var auth = require("./lib/auth.js");
var response = require("./lib/response.js");
var models = require("./lib/models");

//server setup
if (config.usessl) {
    var ca = (function () {
        var i, len, results;
        results = [];
        for (i = 0, len = config.sslcapath.length; i < len; i++) {
            results.push(fs.readFileSync(config.sslcapath[i], 'utf8'));
        }
        return results;
    })();
    var options = {
        key: fs.readFileSync(config.sslkeypath, 'utf8'),
        cert: fs.readFileSync(config.sslcertpath, 'utf8'),
        ca: ca,
        dhparam: fs.readFileSync(config.dhparampath, 'utf8'),
        requestCert: false,
        rejectUnauthorized: false
    };
    var app = express();
    var server = require('https').createServer(options, app);
} else {
    var app = express();
    var server = require('http').createServer(app);
}

//logger
app.use(morgan('combined', {
    "stream": logger.stream
}));

//socket io
var io = require('socket.io')(server);

//others
var realtime = require("./lib/realtime.js");

//assign socket io to realtime
realtime.io = io;

//methodOverride
app.use(methodOverride('_method'));

// create application/json parser
var jsonParser = bodyParser.json();

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({
    extended: false
});

//session store
var sessionStore = new SequelizeStore({
    db: models.sequelize
});

//compression
app.use(compression());

// use hsts to tell https users stick to this
app.use(helmet.hsts({
    maxAge: 31536000 * 1000, // 365 days
    includeSubdomains: true,
    preload: true
}));

// routes without sessions
// static files
app.use('/', express.static(__dirname + '/public', { maxAge: config.staticcachetime }));
app.use('/vendor/', express.static(__dirname + '/bower_components', { maxAge: config.staticcachetime }));

//session
app.use(session({
    name: config.sessionname,
    secret: config.sessionsecret,
    resave: false, //don't save session if unmodified
    saveUninitialized: true, //always create session to ensure the origin
    cookie: {
        maxAge: config.sessionlife,
        expires: new Date(Date.now() + config.sessionlife),
    },
    store: sessionStore
}));

// session resumption
var tlsSessionStore = {};
server.on('newSession', function (id, data, cb) {
    tlsSessionStore[id.toString('hex')] = data;
    cb();
});
server.on('resumeSession', function (id, cb) {
    cb(null, tlsSessionStore[id.toString('hex')] || null);
});

//middleware which blocks requests when we're too busy
app.use(function (req, res, next) {
    if (toobusy()) {
        response.errorServiceUnavailable(res);
    } else {
        next();
    }
});

//passport
app.use(passport.initialize());
app.use(passport.session());

//serialize and deserialize
passport.serializeUser(function (user, done) {
    logger.info('serializeUser: ' + user.id);
    return done(null, user.id);
});
passport.deserializeUser(function (id, done) {
    models.User.findOne({
        where: {
            id: id
        }
    }).then(function (user) {
        logger.info('deserializeUser: ' + user.id);
        return done(null, user);
    }).catch(function (err) {
        logger.error(err);
        return done(err, null);
    });
});

// routes need sessions
//template files
app.set('views', __dirname + '/public');
//set render engine
app.engine('html', ejs.renderFile);
//get index
app.get("/", response.showIndex);
//get 403 forbidden
app.get("/403", function (req, res) {
    response.errorForbidden(res);
});
//get 404 not found
app.get("/404", function (req, res) {
    response.errorNotFound(res);
});
//get 500 internal error
app.get("/500", function (req, res) {
    response.errorInternalError(res);
});
//get status
app.get("/status", function (req, res, next) {
    realtime.getStatus(function (data) {
        res.end(JSON.stringify(data));
    });
});
//get status
app.get("/temp", function (req, res) {
    var host = req.get('host');
    if (config.alloworigin.indexOf(host) == -1)
        response.errorForbidden(res);
    else {
        var tempid = req.query.tempid;
        if (!tempid)
            response.errorForbidden(res);
        else {
            models.Temp.findOne({
                where: {
                    id: tempid
                }
            }).then(function (temp) {
                if (!temp)
                    response.errorNotFound(res);
                else {
                    res.header("Access-Control-Allow-Origin", "*");
                    res.send({
                        temp: temp.data
                    });
                    temp.destroy().catch(function (err) {
                        if (err)
                            logger.error('remove temp failed: ' + err);
                    });
                }
            }).catch(function (err) {
                logger.error(err);
                return response.errorInternalError(res);
            });
        }
    }
});
//post status
app.post("/temp", urlencodedParser, function (req, res) {
    var host = req.get('host');
    if (config.alloworigin.indexOf(host) == -1)
        response.errorForbidden(res);
    else {
        var data = req.body.data;
        if (!data)
            response.errorForbidden(res);
        else {
            if (config.debug)
                logger.info('SERVER received temp from [' + host + ']: ' + req.body.data);
            models.Temp.create({
                data: data
            }).then(function (temp) {
                if (temp) {
                    res.header("Access-Control-Allow-Origin", "*");
                    res.send({
                        status: 'ok',
                        id: temp.id
                    });
                } else
                    response.errorInternalError(res);
            }).catch(function (err) {
                logger.error(err);
                return response.errorInternalError(res);
            });
        }
    }
});
//facebook auth
if (config.facebook) {
    app.get('/auth/facebook',
        passport.authenticate('facebook'),
        function (req, res) {});
    //facebook auth callback
    app.get('/auth/facebook/callback',
        passport.authenticate('facebook', {
            failureRedirect: config.serverurl
        }),
        function (req, res) {
            res.redirect(config.serverurl);
        });
}
//twitter auth
if (config.twitter) {
    app.get('/auth/twitter',
        passport.authenticate('twitter'),
        function (req, res) {});
    //twitter auth callback
    app.get('/auth/twitter/callback',
        passport.authenticate('twitter', {
            failureRedirect: config.serverurl
        }),
        function (req, res) {
            res.redirect(config.serverurl);
        });
}
//github auth
if (config.github) {
    app.get('/auth/github',
        passport.authenticate('github'),
        function (req, res) {});
    //github auth callback
    app.get('/auth/github/callback',
        passport.authenticate('github', {
            failureRedirect: config.serverurl
        }),
        function (req, res) {
            res.redirect(config.serverurl);
        });
    //github callback actions
    app.get('/auth/github/callback/:noteId/:action', response.githubActions);
}
//dropbox auth
if (config.dropbox) {
    app.get('/auth/dropbox',
        passport.authenticate('dropbox-oauth2'),
        function (req, res) {});
    //dropbox auth callback
    app.get('/auth/dropbox/callback',
        passport.authenticate('dropbox-oauth2', {
            failureRedirect: config.serverurl
        }),
        function (req, res) {
            res.redirect(config.serverurl);
        });
}
//logout
app.get('/logout', function (req, res) {
    if (config.debug && req.isAuthenticated())
        logger.info('user logout: ' + req.user.id);
    req.logout();
    res.redirect(config.serverurl);
});
//get history
app.get('/history', function (req, res) {
    if (req.isAuthenticated()) {
        models.User.findOne({
            where: {
                id: req.user.id
            }
        }).then(function (user) {
            if (!user)
                return response.errorNotFound(res);
            var history = [];
            if (user.history)
                history = JSON.parse(user.history);
            res.send({
                history: history
            });
            if (config.debug)
                logger.info('read history success: ' + user.id);
        }).catch(function (err) {
            logger.error('read history failed: ' + err);
            return response.errorInternalError(res);
        });
    } else {
        return response.errorForbidden(res);
    }
});
//post history
app.post('/history', urlencodedParser, function (req, res) {
    if (req.isAuthenticated()) {
        if (config.debug)
            logger.info('SERVER received history from [' + req.user.id + ']: ' + req.body.history);
        models.User.update({
            history: req.body.history
        }, {
            where: {
                id: req.user.id
            }
        }).then(function (count) {
            if (!count)
                return response.errorNotFound(res);
            if (config.debug)
                logger.info("write user history success: " + req.user.id);
        }).catch(function (err) {
            logger.error('write history failed: ' + err);
            return response.errorInternalError(res);
        });
        res.end();
    } else {
        return response.errorForbidden(res);
    }
});
//get me info
app.get('/me', function (req, res) {
    if (req.isAuthenticated()) {
        models.User.findOne({
            where: {
                id: req.user.id
            }
        }).then(function (user) {
            if (!user)
                return response.errorNotFound(res);
            var profile = models.User.parseProfile(user.profile);
            res.send({
                status: 'ok',
                id: req.user.id,
                name: profile.name,
                photo: profile.photo
            });
        }).catch(function (err) {
            logger.error('read me failed: ' + err);
            return response.errorInternalError(res);
        });
    } else {
        res.send({
            status: 'forbidden'
        });
    }
});
//upload to imgur
app.post('/uploadimage', function (req, res) {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        if (err || !files.image || !files.image.path) {
            response.errorForbidden(res);
        } else {
            if (config.debug)
                logger.info('SERVER received uploadimage: ' + JSON.stringify(files.image));
            imgur.setClientId(config.imgur.clientID);
            try {
                imgur.uploadFile(files.image.path)
                    .then(function (json) {
                        if (config.debug)
                            logger.info('SERVER uploadimage success: ' + JSON.stringify(json));
                        res.send({
                            link: json.data.link
                        });
                    })
                    .catch(function (err) {
                        logger.error(err);
                        return res.send('upload image error');
                    });
            } catch (err) {
                logger.error(err);
                return res.send('upload image error');
            }
        }
    });
});
//get new note
app.get("/new", response.newNote);
//get publish note
app.get("/s/:shortid", response.showPublishNote);
//publish note actions
app.get("/s/:shortid/:action", response.publishNoteActions);
//get publish slide
app.get("/p/:shortid", response.showPublishSlide);
//get note by id
app.get("/:noteId", response.showNote);
//note actions
app.get("/:noteId/:action", response.noteActions);

//socket.io secure
io.use(realtime.secure);
//socket.io auth
io.use(passportSocketIo.authorize({
    cookieParser: cookieParser,
    key: config.sessionname,
    secret: config.sessionsecret,
    store: sessionStore,
    success: realtime.onAuthorizeSuccess,
    fail: realtime.onAuthorizeFail
}));
//socket.io heartbeat
io.set('heartbeat interval', config.heartbeatinterval);
io.set('heartbeat timeout', config.heartbeattimeout);
//socket.io connection
io.sockets.on('connection', realtime.connection);

//listen
function startListen() {
    if (config.usessl) {
        server.listen(config.port, function () {
            logger.info('HTTPS Server listening at port %d', config.port);
        });
    } else {
        server.listen(config.port, function () {
            logger.info('HTTP Server listening at port %d', config.port);
        });
    }
}

// sync db then start listen
models.sequelize.sync().then(startListen);

// log uncaught exception
process.on('uncaughtException', function (err) {
    logger.error(err);
});<commit_msg>Update to redirect url with trailing slashes<commit_after>//app
//external modules
var express = require('express');
var toobusy = require('toobusy-js');
var ejs = require('ejs');
var passport = require('passport');
var methodOverride = require('method-override');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var compression = require('compression')
var session = require('express-session');
var SequelizeStore = require('connect-session-sequelize')(session.Store);
var fs = require('fs');
var imgur = require('imgur');
var formidable = require('formidable');
var morgan = require('morgan');
var passportSocketIo = require("passport.socketio");
var helmet = require('helmet');

//core
var config = require("./lib/config.js");
var logger = require("./lib/logger.js");
var auth = require("./lib/auth.js");
var response = require("./lib/response.js");
var models = require("./lib/models");

//server setup
if (config.usessl) {
    var ca = (function () {
        var i, len, results;
        results = [];
        for (i = 0, len = config.sslcapath.length; i < len; i++) {
            results.push(fs.readFileSync(config.sslcapath[i], 'utf8'));
        }
        return results;
    })();
    var options = {
        key: fs.readFileSync(config.sslkeypath, 'utf8'),
        cert: fs.readFileSync(config.sslcertpath, 'utf8'),
        ca: ca,
        dhparam: fs.readFileSync(config.dhparampath, 'utf8'),
        requestCert: false,
        rejectUnauthorized: false
    };
    var app = express();
    var server = require('https').createServer(options, app);
} else {
    var app = express();
    var server = require('http').createServer(app);
}

//logger
app.use(morgan('combined', {
    "stream": logger.stream
}));

//socket io
var io = require('socket.io')(server);

//others
var realtime = require("./lib/realtime.js");

//assign socket io to realtime
realtime.io = io;

//methodOverride
app.use(methodOverride('_method'));

// create application/json parser
var jsonParser = bodyParser.json();

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({
    extended: false
});

//session store
var sessionStore = new SequelizeStore({
    db: models.sequelize
});

//compression
app.use(compression());

// use hsts to tell https users stick to this
app.use(helmet.hsts({
    maxAge: 31536000 * 1000, // 365 days
    includeSubdomains: true,
    preload: true
}));

// routes without sessions
// static files
app.use('/', express.static(__dirname + '/public', { maxAge: config.staticcachetime }));
app.use('/vendor/', express.static(__dirname + '/bower_components', { maxAge: config.staticcachetime }));

//session
app.use(session({
    name: config.sessionname,
    secret: config.sessionsecret,
    resave: false, //don't save session if unmodified
    saveUninitialized: true, //always create session to ensure the origin
    cookie: {
        maxAge: config.sessionlife,
        expires: new Date(Date.now() + config.sessionlife),
    },
    store: sessionStore
}));

// session resumption
var tlsSessionStore = {};
server.on('newSession', function (id, data, cb) {
    tlsSessionStore[id.toString('hex')] = data;
    cb();
});
server.on('resumeSession', function (id, cb) {
    cb(null, tlsSessionStore[id.toString('hex')] || null);
});

//middleware which blocks requests when we're too busy
app.use(function (req, res, next) {
    if (toobusy()) {
        response.errorServiceUnavailable(res);
    } else {
        next();
    }
});

//passport
app.use(passport.initialize());
app.use(passport.session());

//serialize and deserialize
passport.serializeUser(function (user, done) {
    logger.info('serializeUser: ' + user.id);
    return done(null, user.id);
});
passport.deserializeUser(function (id, done) {
    models.User.findOne({
        where: {
            id: id
        }
    }).then(function (user) {
        logger.info('deserializeUser: ' + user.id);
        return done(null, user);
    }).catch(function (err) {
        logger.error(err);
        return done(err, null);
    });
});

// redirect url with trailing slashes
app.use(function(req, res, next) {
    if ("GET" == req.method && req.path.substr(-1) == '/' && req.path.length > 1) {
        var query = req.url.slice(req.path.length);
        console.log(config.serverurl + req.path.slice(0, -1) + query);
        res.redirect(301, config.serverurl + req.path.slice(0, -1) + query);
    } else {
        next();
    }
});

// routes need sessions
//template files
app.set('views', __dirname + '/public');
//set render engine
app.engine('html', ejs.renderFile);
//get index
app.get("/", response.showIndex);
//get 403 forbidden
app.get("/403", function (req, res) {
    response.errorForbidden(res);
});
//get 404 not found
app.get("/404", function (req, res) {
    response.errorNotFound(res);
});
//get 500 internal error
app.get("/500", function (req, res) {
    response.errorInternalError(res);
});
//get status
app.get("/status", function (req, res, next) {
    realtime.getStatus(function (data) {
        res.end(JSON.stringify(data));
    });
});
//get status
app.get("/temp", function (req, res) {
    var host = req.get('host');
    if (config.alloworigin.indexOf(host) == -1)
        response.errorForbidden(res);
    else {
        var tempid = req.query.tempid;
        if (!tempid)
            response.errorForbidden(res);
        else {
            models.Temp.findOne({
                where: {
                    id: tempid
                }
            }).then(function (temp) {
                if (!temp)
                    response.errorNotFound(res);
                else {
                    res.header("Access-Control-Allow-Origin", "*");
                    res.send({
                        temp: temp.data
                    });
                    temp.destroy().catch(function (err) {
                        if (err)
                            logger.error('remove temp failed: ' + err);
                    });
                }
            }).catch(function (err) {
                logger.error(err);
                return response.errorInternalError(res);
            });
        }
    }
});
//post status
app.post("/temp", urlencodedParser, function (req, res) {
    var host = req.get('host');
    if (config.alloworigin.indexOf(host) == -1)
        response.errorForbidden(res);
    else {
        var data = req.body.data;
        if (!data)
            response.errorForbidden(res);
        else {
            if (config.debug)
                logger.info('SERVER received temp from [' + host + ']: ' + req.body.data);
            models.Temp.create({
                data: data
            }).then(function (temp) {
                if (temp) {
                    res.header("Access-Control-Allow-Origin", "*");
                    res.send({
                        status: 'ok',
                        id: temp.id
                    });
                } else
                    response.errorInternalError(res);
            }).catch(function (err) {
                logger.error(err);
                return response.errorInternalError(res);
            });
        }
    }
});
//facebook auth
if (config.facebook) {
    app.get('/auth/facebook',
        passport.authenticate('facebook'),
        function (req, res) {});
    //facebook auth callback
    app.get('/auth/facebook/callback',
        passport.authenticate('facebook', {
            failureRedirect: config.serverurl
        }),
        function (req, res) {
            res.redirect(config.serverurl);
        });
}
//twitter auth
if (config.twitter) {
    app.get('/auth/twitter',
        passport.authenticate('twitter'),
        function (req, res) {});
    //twitter auth callback
    app.get('/auth/twitter/callback',
        passport.authenticate('twitter', {
            failureRedirect: config.serverurl
        }),
        function (req, res) {
            res.redirect(config.serverurl);
        });
}
//github auth
if (config.github) {
    app.get('/auth/github',
        passport.authenticate('github'),
        function (req, res) {});
    //github auth callback
    app.get('/auth/github/callback',
        passport.authenticate('github', {
            failureRedirect: config.serverurl
        }),
        function (req, res) {
            res.redirect(config.serverurl);
        });
    //github callback actions
    app.get('/auth/github/callback/:noteId/:action', response.githubActions);
}
//dropbox auth
if (config.dropbox) {
    app.get('/auth/dropbox',
        passport.authenticate('dropbox-oauth2'),
        function (req, res) {});
    //dropbox auth callback
    app.get('/auth/dropbox/callback',
        passport.authenticate('dropbox-oauth2', {
            failureRedirect: config.serverurl
        }),
        function (req, res) {
            res.redirect(config.serverurl);
        });
}
//logout
app.get('/logout', function (req, res) {
    if (config.debug && req.isAuthenticated())
        logger.info('user logout: ' + req.user.id);
    req.logout();
    res.redirect(config.serverurl);
});
//get history
app.get('/history', function (req, res) {
    if (req.isAuthenticated()) {
        models.User.findOne({
            where: {
                id: req.user.id
            }
        }).then(function (user) {
            if (!user)
                return response.errorNotFound(res);
            var history = [];
            if (user.history)
                history = JSON.parse(user.history);
            res.send({
                history: history
            });
            if (config.debug)
                logger.info('read history success: ' + user.id);
        }).catch(function (err) {
            logger.error('read history failed: ' + err);
            return response.errorInternalError(res);
        });
    } else {
        return response.errorForbidden(res);
    }
});
//post history
app.post('/history', urlencodedParser, function (req, res) {
    if (req.isAuthenticated()) {
        if (config.debug)
            logger.info('SERVER received history from [' + req.user.id + ']: ' + req.body.history);
        models.User.update({
            history: req.body.history
        }, {
            where: {
                id: req.user.id
            }
        }).then(function (count) {
            if (!count)
                return response.errorNotFound(res);
            if (config.debug)
                logger.info("write user history success: " + req.user.id);
        }).catch(function (err) {
            logger.error('write history failed: ' + err);
            return response.errorInternalError(res);
        });
        res.end();
    } else {
        return response.errorForbidden(res);
    }
});
//get me info
app.get('/me', function (req, res) {
    if (req.isAuthenticated()) {
        models.User.findOne({
            where: {
                id: req.user.id
            }
        }).then(function (user) {
            if (!user)
                return response.errorNotFound(res);
            var profile = models.User.parseProfile(user.profile);
            res.send({
                status: 'ok',
                id: req.user.id,
                name: profile.name,
                photo: profile.photo
            });
        }).catch(function (err) {
            logger.error('read me failed: ' + err);
            return response.errorInternalError(res);
        });
    } else {
        res.send({
            status: 'forbidden'
        });
    }
});
//upload to imgur
app.post('/uploadimage', function (req, res) {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        if (err || !files.image || !files.image.path) {
            response.errorForbidden(res);
        } else {
            if (config.debug)
                logger.info('SERVER received uploadimage: ' + JSON.stringify(files.image));
            imgur.setClientId(config.imgur.clientID);
            try {
                imgur.uploadFile(files.image.path)
                    .then(function (json) {
                        if (config.debug)
                            logger.info('SERVER uploadimage success: ' + JSON.stringify(json));
                        res.send({
                            link: json.data.link
                        });
                    })
                    .catch(function (err) {
                        logger.error(err);
                        return res.send('upload image error');
                    });
            } catch (err) {
                logger.error(err);
                return res.send('upload image error');
            }
        }
    });
});
//get new note
app.get("/new", response.newNote);
//get publish note
app.get("/s/:shortid", response.showPublishNote);
//publish note actions
app.get("/s/:shortid/:action", response.publishNoteActions);
//get publish slide
app.get("/p/:shortid", response.showPublishSlide);
//get note by id
app.get("/:noteId", response.showNote);
//note actions
app.get("/:noteId/:action", response.noteActions);

//socket.io secure
io.use(realtime.secure);
//socket.io auth
io.use(passportSocketIo.authorize({
    cookieParser: cookieParser,
    key: config.sessionname,
    secret: config.sessionsecret,
    store: sessionStore,
    success: realtime.onAuthorizeSuccess,
    fail: realtime.onAuthorizeFail
}));
//socket.io heartbeat
io.set('heartbeat interval', config.heartbeatinterval);
io.set('heartbeat timeout', config.heartbeattimeout);
//socket.io connection
io.sockets.on('connection', realtime.connection);

//listen
function startListen() {
    if (config.usessl) {
        server.listen(config.port, function () {
            logger.info('HTTPS Server listening at port %d', config.port);
        });
    } else {
        server.listen(config.port, function () {
            logger.info('HTTP Server listening at port %d', config.port);
        });
    }
}

// sync db then start listen
models.sequelize.sync().then(startListen);

// log uncaught exception
process.on('uncaughtException', function (err) {
    logger.error(err);
});<|endoftext|>


<commit_before>global.$ = $;

var fs = require('fs');
var process = require('process');
var app = require('electron').remote.app;
var dialog = require('electron').remote.dialog;
var execFile = require('child_process').execFile;

var bootloader_ready = false;
var flash_in_progress = false;
var dfu_location = 'dfu/dfu-programmer';

if (process.platform == "win32") {
  dfu_location = dfu_location + '.exe'
}

fs.access(dfu_location, fs.F_OK, function(err) {
  if (err) {
    // Running in deployed mode, use the app copy
    var dfu_location = app.getAppPath() + '/' + dfu_location;
  }
});

$(document).ready(function() {
  // Handle drag-n-drop events
  $(document).on('dragenter dragover', function(event) {
    event.preventDefault();
    event.stopPropagation();
  });

  $(document).on('drop', function(event) {
    event.preventDefault();
    event.stopPropagation();

    var file = event.originalEvent.dataTransfer.files[0];
    loadHex(file.path);
  });

  $(document).on('open-file', function(event, path) {
    event.preventDefault();
    event.stopPropagation();

    loadHex(path);
  });

  // Bind actions to our buttons
  $('#flash-hex').attr('disabled','disabled');
  $('#close-window-button').bind('click', function (event) {
    window.close();
  });
  $('#load-file').bind('click', function (event) {
    loadHex(loadFile()[0]);
  });
  $('#flash-hex').bind('click', function (event) {
    disableButtons();
    sendHex($("#file-path").val(), function(success) {
      if (success) {
        sendStatus("Flashing complete!");
      } else {
        sendStatus("An error occured - please try again.");
      }
    });
  });
  $('#reset').bind('click', function (event) {
    disableButtons();
    resetChip(function(success) {
      enableButtons();
      if (success) {
        sendStatus("Reset complete!");
      } else {
        sendStatus("An error occured - please try again.");
      }
    });
  });

  // Ready to go
  execFile(dfu_location, ['--version'], function(error, stdout, stderr) {
    if (stderr.indexOf('dfu-programmer') > -1) {
      window.setTimeout(checkForBoard, 10);
      sendStatus("Select a firmware file by clicking 'Choose .hex' or drag and drop a file onto this window.");
    } else {
      sendStatus("Could not run dfu-programmer! Please report this as a bug!");
      sendStatus("
Debugging information:
");
      sendStatus(error);
      sendStatus("stdout:");
      writeStatus(stdout);
      sendStatus("stderr:");
      writeStatus(stderr);
    }
  });
});

function loadHex(filename) {
  // Load a file and prepare to flash it.
  if (filename.slice(-4) != '.hex') {
    sendStatus("Invalid firmware file: " + filename);
    return;
  }

  $("#file-path").val(filename);
  enableButtons();
  clearStatus();

  if (!bootloader_ready) sendStatus("Press RESET on your keyboard's PCB.");
}

function disableButtons() {
  $('#flash-hex').attr('disabled','disabled');
  $('#flash-hex').css('background-color', 'red');
  $('#flash-hex').css('color', 'black');
}

function enableButtons() {
  if (bootloader_ready && $('#file-path').val() != "") {
    $('#flash-hex').removeAttr('disabled');
    $('#flash-hex').css('background-color', 'green');
    $('#flash-hex').css('color', 'white');
  }
}

function clearStatus() {
  $('#status').text('');
}

function writeStatus(text) {
  $('#status').append(text);
  $('#status').scrollTop($('#status')[0].scrollHeight);
}

function sendStatus(text) {
  writeStatus('' + text + "\n");
}

function loadFile() {
  return dialog.showOpenDialog({
    properties: [ 'openFile' ],
    filters: [
      { name: 'Custom File Type', extensions: ['hex'] }
    ]
  });
}

function sendHex(file, callback) {
  flash_in_progress = true;
  eraseChip(function(success) {
    if (success) {
      // continue
      flashChip(file, function(success) {
        if (success) {
          // continue
          resetChip(function(success) {
            if (success) {
              // completed successfully
              callback(true);
            } else {
              callback(false)
            }
          });
        } else {
          // memory error / other
          callback(false);
        }
      });
    } else {
      // no device / other error
      callback(false);
    }
  });
  flash_in_progress = false;
};

/*
var escapeShell = function(cmd) {
  return ''+cmd.replace(/(["\s'$`\\\(\)])/g,'\\$1')+'';
};
*/

function eraseChip(callback) {
  sendStatus('dfu-programmer atmega32u4 erase --force');
  execFile(dfu_location, ['atmega32u4', 'erase', '--force'], function(error, stdout, stderr) {
    sendStatus(error);
    writeStatus(stdout);
    writeStatus(stderr);
    if (stderr.indexOf("no device present") > -1) {
      callback(false);
    } else {
      callback(true);
    }
  });
}

function flashChip(file, callback) {
  sendStatus('dfu-programmer atmega32u4 flash ' + file);
  execFile(dfu_location, ['atmega32u4', 'flash', file], function(error, stdout, stderr) {
    writeStatus(stdout);
    writeStatus(stderr);
    if (stderr.indexOf("no device present") > -1) {
      callback(false);
    } else {
      callback(true);
    }
  });
}

function resetChip(callback) {
  sendStatus('dfu-programmer atmega32u4 reset');
  execFile(dfu_location, ['atmega32u4', 'reset'], function(error, stdout, stderr) {
    writeStatus(stdout);
    writeStatus(stderr);
    if (stderr.indexOf("no device present") > -1) {
      callback(false);
    } else {
      callback(true);
    }
  });
}

function checkForBoard() {
  if (!flash_in_progress) {
    execFile(dfu_location, ['atmega32u4', 'get', 'bootloader-version'], function(error, stdout, stderr) {
      if (stdout.indexOf("Bootloader Version:") > -1) {
        if (!bootloader_ready && $('#file-path').val() != "") clearStatus();
        bootloader_ready = true;
        if ($('#file-path').val() != "") enableButtons();
      } else {
        bootloader_ready = false;
        disableButtons();
      }
    });
  }
  window.setTimeout(checkForBoard, 10000);
}
<commit_msg>Improve error detection - now with added non-brokenness! (#14)<commit_after>global.$ = $;

var fs = require('fs');
var process = require('process');
var app = require('electron').remote.app;
var dialog = require('electron').remote.dialog;
var execFile = require('child_process').execFile;

var bootloader_ready = false;
var flash_in_progress = false;
var dfu_location = 'dfu/dfu-programmer';

if (process.platform == "win32") {
  dfu_location = dfu_location + '.exe'
}

fs.access(dfu_location, fs.F_OK, function(err) {
  if (err) {
    // Running in deployed mode, use the app copy
    var dfu_location = app.getAppPath() + '/' + dfu_location;
  }
});

$(document).ready(function() {
  // Handle drag-n-drop events
  $(document).on('dragenter dragover', function(event) {
    event.preventDefault();
    event.stopPropagation();
  });

  $(document).on('drop', function(event) {
    event.preventDefault();
    event.stopPropagation();

    var file = event.originalEvent.dataTransfer.files[0];
    loadHex(file.path);
  });

  $(document).on('open-file', function(event, path) {
    event.preventDefault();
    event.stopPropagation();

    loadHex(path);
  });

  // Bind actions to our buttons
  $('#flash-hex').attr('disabled','disabled');
  $('#close-window-button').bind('click', function (event) {
    window.close();
  });
  $('#load-file').bind('click', function (event) {
    loadHex(loadFile()[0]);
  });
  $('#flash-hex').bind('click', function (event) {
    disableButtons();
    sendHex($("#file-path").val(), function(success) {
      if (success) {
        sendStatus("Flashing complete!");
      } else {
        sendStatus("An error occured - please try again.");
      }
    });
  });
  $('#reset').bind('click', function (event) {
    disableButtons();
    resetChip(function(success) {
      enableButtons();
      if (success) {
        sendStatus("Reset complete!");
      } else {
        sendStatus("An error occured - please try again.");
      }
    });
  });

  // Ready to go
  execFile(dfu_location, ['--version'], function(error, stdout, stderr) {
    if (stderr.indexOf('dfu-programmer') > -1) {
      window.setTimeout(checkForBoard, 10);
      sendStatus("Select a firmware file by clicking 'Choose .hex' or drag and drop a file onto this window.");
    } else {
      sendStatus("Could not run dfu-programmer! Please report this as a bug!");
      sendStatus("
Debugging information:
");
      sendStatus(error);
      sendStatus("stdout:");
      writeStatus(stdout);
      sendStatus("stderr:");
      writeStatus(stderr);
    }
  });
});

function loadHex(filename) {
  // Load a file and prepare to flash it.
  if (filename.slice(-4) != '.hex') {
    sendStatus("Invalid firmware file: " + filename);
    return;
  }

  $("#file-path").val(filename);
  enableButtons();
  clearStatus();

  if (!bootloader_ready) sendStatus("Press RESET on your keyboard's PCB.");
}

function disableButtons() {
  $('#flash-hex').attr('disabled','disabled');
  $('#flash-hex').css('background-color', 'red');
  $('#flash-hex').css('color', 'black');
}

function enableButtons() {
  if (bootloader_ready && $('#file-path').val() != "") {
    $('#flash-hex').removeAttr('disabled');
    $('#flash-hex').css('background-color', 'green');
    $('#flash-hex').css('color', 'white');
  }
}

function clearStatus() {
  $('#status').text('');
}

function writeStatus(text) {
  $('#status').append(text);
  $('#status').scrollTop($('#status')[0].scrollHeight);
}

function sendStatus(text) {
  writeStatus('' + text + "\n");
}

function loadFile() {
  return dialog.showOpenDialog({
    properties: [ 'openFile' ],
    filters: [
      { name: 'Custom File Type', extensions: ['hex'] }
    ]
  });
}

function sendHex(file, callback) {
  flash_in_progress = true;
  eraseChip(function(success) {
    if (success) {
      // continue
      flashChip(file, function(success) {
        if (success) {
          // continue
          resetChip(function(success) {
            if (success) {
              // completed successfully
              callback(true);
            } else {
              callback(false)
            }
          });
        } else {
          // memory error / other
          callback(false);
        }
      });
    } else {
      // no device / other error
      callback(false);
    }
  });
  flash_in_progress = false;
};

/*
var escapeShell = function(cmd) {
  return ''+cmd.replace(/(["\s'$`\\\(\)])/g,'\\$1')+'';
};
*/

function eraseChip(callback) {
  sendStatus('dfu-programmer atmega32u4 erase --force');
  execFile(dfu_location, ['atmega32u4', 'erase', '--force'], function(error, stdout, stderr) {
    sendStatus(error);
    writeStatus(stdout);
    writeStatus(stderr);
    var regex = /.*Success.*\r?\n|\rChecking memory from .* Empty.*/;
    if (regex.test(stderr)) {
      callback(true);
    } else {
      callback(false);
    }
  });
}

function flashChip(file, callback) {
  sendStatus('dfu-programmer atmega32u4 flash ' + file);
  execFile(dfu_location, ['atmega32u4', 'flash', file], function(error, stdout, stderr) {
    writeStatus(stdout);
    writeStatus(stderr);
    if (stderr.indexOf("Validating...  Success") > -1) {
      callback(true);
    } else {
      callback(false);
    }
  });
}

function resetChip(callback) {
  sendStatus('dfu-programmer atmega32u4 reset');
  execFile(dfu_location, ['atmega32u4', 'reset'], function(error, stdout, stderr) {
    writeStatus(stdout);
    writeStatus(stderr);
	if (stderr == "") {
	  callback(true);
    } else {
      callback(false);
    }
  });
}

function checkForBoard() {
  if (!flash_in_progress) {
    execFile(dfu_location, ['atmega32u4', 'get', 'bootloader-version'], function(error, stdout, stderr) {
      if (stdout.indexOf("Bootloader Version:") > -1) {
        if (!bootloader_ready && $('#file-path').val() != "") clearStatus();
        bootloader_ready = true;
        if ($('#file-path').val() != "") enableButtons();
      } else {
        bootloader_ready = false;
        disableButtons();
      }
    });
  }
  window.setTimeout(checkForBoard, 10000);
}
<|endoftext|>