<commit_before>var Windshaft = require('node_modules/windshaft');
var _         = require('node_modules/underscore');

var pointQuery = "(SELECT id, species_guess, iconic_taxon_id, taxon_id, latitude, longitude, geom FROM observations " +
  "WHERE taxon_id = {{taxon_id}}" +
  " AND id != {{obs_id}}) as points";

var defaultStylePoints = "#observations [zoom >=9]{" +
  // "marker-fill: " + iNaturalist.Map.ICONIC_TAXON_COLORS[OBSERVATION.iconic_taxon.name] + ";" +
  "marker-fill: {{taxon_color}}; " +
  "marker-opacity: 1;" +
  "marker-width: 8;" +
  "marker-line-color: white;" +
  "marker-line-width: 2;" +
  "marker-line-opacity: 0.9;" +
  "marker-placement: point;" +
  "marker-type: ellipse;" +
  "marker-allow-overlap: true;}";

var gridQuery = "(SELECT cnt, taxon_id, ST_Envelope(" +
  "ST_GEOMETRYFROMTEXT('LINESTRING('||(st_xmax(the_geom)-({{seed}}/2))||' '||(st_ymax(the_geom)-({{seed}}/2))||'," +
  "'||(st_xmax(the_geom)+({{seed}}/2))||' '||(st_ymax(the_geom)+({{seed}}/2))||')',4326)) as geom FROM " +
  "(SELECT count(*) as cnt, o.taxon_id, t.ancestry,  ST_SnapToGrid(geom, 0+({{seed}}/2), 75+({{seed}}/2), {{seed}}, {{seed}}) as the_geom FROM " +
  "observations o, taxa t  " +
  "WHERE o.taxon_id=t.id AND taxon_id={{taxon_id}} OR '/' || t.ancestry || '/' LIKE '%/{{taxon_id}}/%' " +
  "GROUP By taxon_id, ancestry, ST_SnapToGrid(geom, 0+({{seed}}/2), 75+({{seed}}/2), {{seed}}, {{seed}})) snap_grid ) as obs_grid";

var defaultStyleGrid = "#observations [zoom <9]{ " +
  "polygon-fill:#EFF3FF; " +
  "polygon-opacity:0.6; " +
  "line-opacity:1; " +
  "line-color:#FFFFFF; " +
  "[cnt>=5] { polygon-fill: {{taxon_color}}; polygon-opacity:1.0;  } " +
  "[cnt<5]  { polygon-fill: {{taxon_color}}; polygon-opacity:0.8;  } " +
  "[cnt<4]  { polygon-fill: {{taxon_color}}; polygon-opacity:0.6;  } " +
  "[cnt<3]  { polygon-fill: {{taxon_color}}; polygon-opacity:0.4;  } " +
  "[cnt<2]  { polygon-fill: {{taxon_color}}; polygon-opacity:0.2;  } }";

var config = {
  // base_url: '/database/:dbname/table/:table',
  base_url: '/:table/:endpoint',
  base_url_notable: '/:endpoint',
  grainstore: {

    // all this db connection config should be moved to a config file that lives outside the repo
    datasource: {
      user:'kueda',
      host: 'localhost',
      port: 5432,
      geometry_field: 'geom',
      srid: 4326
    }

  }, //see grainstore npm for other options
  redis: {host: '127.0.0.1', port: 6379},
  enable_cors: true,
  req2params: function(req, callback){
    // this is in case you want to test sql parameters eg ...png?sql=select * from my_table limit 10
    req.params =  _.extend({}, req.params);
    _.extend(req.params, req.query);

    req.params.dbname = 'inaturalist_development_srid';

    if(req.params.endpoint == 'grid' ){   //Grid endpoint
      var seed = 16/Math.pow(2,parseInt(req.params.z));
      if(seed > 4){
        seed = 4;
      }else if (seed == 1){
        seed = 0.99;
      }
      req.params.sql = gridQuery;
      if(req.params.taxon_id){
        req.params.sql = req.params.sql.replace(/\{\{taxon_id\}\}/g,req.params.taxon_id);
      }else{
        req.params.sql = req.params.sql.replace(/\{\{taxon_id\}\}/g,'-1');
      }
      req.params.sql = req.params.sql.replace(/\{\{seed\}\}/g, seed);
      if(!req.params.style){
        req.params.style = defaultStyleGrid;
      }
      if(req.params.taxon_color && req.params.taxon_color != 'undefined'){
        req.params.style = req.params.style.replace(/\{\{taxon_color\}\}/g,req.params.taxon_color);
      }else{
        //Boring blue
        req.params.style = req.params.style.replace(/\{\{taxon_color\}\}/g,'#FBB7ED');
      }
    }else if(req.params.endpoint == 'points'){  //Points endpoint
      req.params.sql = pointQuery;
      if(req.params.taxon_id){
        req.params.sql = req.params.sql.replace(/\{\{taxon_id\}\}/g,req.params.taxon_id);
      }else{
        req.params.sql = req.params.sql.replace(/\{\{taxon_id\}\}/g,'-1');
      }
      if(req.params.obs_id){
        req.params.sql = req.params.sql.replace(/\{\{obs_id\}\}/g,req.params.obs_id);
      }else{
        req.params.sql = req.params.sql.replace(/\{\{obs_id\}\}/g,'-1');
      }
      if(!req.params.style){
        req.params.style = defaultStylePoints;
      }
      if(req.params.taxon_color && req.params.taxon_color != 'undefined'){
  req.params.style = req.params.style.replace(/\{\{taxon_color\}\}/g,req.params.taxon_color);
      }else{
        //Boring pink
  req.params.style = req.params.style.replace(/\{\{taxon_color\}\}/g,'#1E90FF');
      }
    }
  // send the finished req object on
  var x = parseInt(req.params.x),
    y = parseInt(req.params.y),
    z = parseInt(req.params.z),
    numTiles = Math.pow(2,z),
    maxCoord = numTiles - 1

    x = x >= 0 ? x : maxCoord + x
    y = y >= 0 ? y : maxCoord + y
    if (x > maxCoord) {x = x % numTiles}
    if (y > maxCoord) {y = y % numTiles}
    if (x < -1*maxCoord) {x = Math.abs(x) % numTiles}
    if (y < -1*maxCoord) {y = Math.abs(y) % numTiles}
    req.params.x = ''+x
    req.params.y = ''+y
    req.params.z = ''+z

    callback(null,req);
  },
  beforeTileRender: function(req, res, callback) {
    callback(null);
  }
};

// Initialize tile server on port 4000
var ws = new Windshaft.Server(config);

ws.listen(4000);

console.log("map tiles are now being served out of: http://localhost:4000" + config.base_url + '/:z/:x/:y');
<commit_msg>Latest version of windshaft server script. Requires some cleanup<commit_after>var Windshaft = require('../lib/windshaft');
var _         = require('underscore');
var conf      = require('./config');

var pointQuery = "(SELECT o.id, o.species_guess, o.iconic_taxon_id, o.taxon_id, o.latitude, o.longitude, o.geom, " +
  "o.positional_accuracy, o.captive, o.quality_grade FROM " +
  "observations o, taxa t " +
  "WHERE o.taxon_id = t.id AND ( o.taxon_id = {{taxon_id}} OR '/' || t.ancestry || '/' LIKE '%/{{taxon_id}}/%' ) " +
  " AND o.id != {{obs_id}}) as points";

//Don't like hardcoding taxon colors here
/*var defaultStylePoints =
  "#observations [zoom >=9]{" +
  "marker-fill: {{taxon_color}}; " +
  "marker-opacity: 1;" +
  "marker-width: 8;" +
  "marker-line-color: white;" +
  "marker-line-width: 2;" +
  "marker-line-opacity: 0.9;" +
  "marker-placement: point;" +
  "marker-type: ellipse;" +
  "marker-allow-overlap: true; " +
  "[taxon_id=2] { marker-fill: #1E90FF; marker-width: 32; marker-file: url(images/animalia-75px.png); } " +
  "[taxon_id=3] { marker-fill: #1E90FF; marker-width: 32; marker-file: url(images/actinopterygii-75px.png); } " +
  "[taxon_id=5] { marker-fill: #1E90FF; marker-width: 32; marker-file: url(images/aves-75px.png); } " +
  "[taxon_id=6] { marker-fill: #1E90FF; marker-width: 32; marker-file: url(images/reptilia-75px.png); } " +
  "[taxon_id=7] { marker-fill: #1E90FF; marker-width: 32; marker-file: url(images/amphibia-75px.png); } " +
  "[taxon_id=8] { marker-fill: #1E90FF; marker-width: 32; marker-file: url(images/mammalia-75px.png); } " +
  "[taxon_id=9] { marker-fill: #FF4500; marker-width: 32; marker-file: url(images/arachnida-75px.png); } " +
  "[taxon_id=11] { marker-fill: #FF4500; marker-width: 32; marker-file: url(images/insecta-75px.png); } " +
  "[taxon_id=12] { marker-fill: #73AC13; marker-width: 32; marker-file: url(images/plantae-75px.png); } " +
  "[taxon_id=13] { marker-fill: #FF1493; marker-width: 32; marker-file: url(images/fungi-75px.png); } " +
  "[taxon_id=14] { marker-fill: #8B008B; marker-width: 32; marker-file: url(images/protozoa-75px.png); } " +
  "[taxon_id=15] { marker-fill: #FF4500; marker-width: 32; marker-file: url(images/mollusca-75px.png); } " +
  "[taxon_id=16] { marker-fill: #993300; marker-width: 32; marker-file: url(images/chromista-75px.png); } " +
  "}";*/

var defaultStylePoints =
  "#observations [zoom >=9]{" +
  "marker-fill: {{taxon_color}}; " +
  "marker-opacity: 1;" +
  "marker-width: 8;" +
  "marker-line-color: white;" +
  "marker-line-width: 2;" +
  "marker-line-opacity: 0.9;" +
  "marker-placement: point;" +
  "marker-type: ellipse;" +
  "marker-allow-overlap: true; " +
  "[taxon_id=2] { marker-fill: #1E90FF; } " +
  "[taxon_id=3] { marker-fill: #1E90FF; } " +
  "[taxon_id=5] { marker-fill: #1E90FF; } " +
  "[taxon_id=6] { marker-fill: #1E90FF; } " +
  "[taxon_id=7] { marker-fill: #1E90FF; } " +
  "[taxon_id=8] { marker-fill: #1E90FF; } " +
  "[taxon_id=9] { marker-fill: #FF4500; } " +
  "[taxon_id=11] { marker-fill: #FF4500; } " +
  "[taxon_id=12] { marker-fill: #73AC13; } " +
  "[taxon_id=13] { marker-fill: #FF1493; } " +
  "[taxon_id=14] { marker-fill: #8B008B; } " +
  "[taxon_id=15] { marker-fill: #FF4500; } " +
  "[taxon_id=16] { marker-fill: #993300; } " +
  "}";

var gridQuery = "(SELECT cnt, taxon_id, ST_Envelope(" +
  "ST_GEOMETRYFROMTEXT('LINESTRING('||(st_xmax(the_geom)-({{seed}}/2))||' '||(st_ymax(the_geom)-({{seed}}/2))||'," +
  "'||(st_xmax(the_geom)+({{seed}}/2))||' '||(st_ymax(the_geom)+({{seed}}/2))||')',4326)) as geom FROM " +
  "(SELECT count(*) as cnt, o.taxon_id, t.ancestry,  ST_SnapToGrid(geom, 0+({{seed}}/2), 75+({{seed}}/2), {{seed}}, {{seed}}) as the_geom FROM " +
  "observations o, taxa t  " +
  "WHERE o.taxon_id=t.id AND (taxon_id={{taxon_id}} OR '/' || t.ancestry || '/' LIKE '%/{{taxon_id}}/%') " +
  "GROUP By taxon_id, ancestry, ST_SnapToGrid(geom, 0+({{seed}}/2), 75+({{seed}}/2), {{seed}}, {{seed}})) snap_grid ) as obs_grid";

var defaultStyleGrid =
  "#observations [zoom <9]{ " +
  "polygon-fill:#EFF3FF; " +
  "polygon-opacity:0.6; " +
  "line-opacity:1; " +
  "line-color:#FFFFFF; " +
  //Labels test
/*  "::labels{" +
  " text-name: '[cnt]';" +
  " text-face-name:'Arial Bold';" +
  " text-allow-overlap: false;" +
  "}" +*/
  "[cnt>=25] { polygon-fill: {{taxon_color}}; polygon-opacity:1.0;  } " +
  "[cnt<20]  { polygon-fill: {{taxon_color}}; polygon-opacity:0.8;  } " +
  "[cnt<15]  { polygon-fill: {{taxon_color}}; polygon-opacity:0.6;  } " +
  "[cnt<10]  { polygon-fill: {{taxon_color}}; polygon-opacity:0.4;  } " +
  "[cnt<5]  { polygon-fill: {{taxon_color}}; polygon-opacity:0.2;  } }";

var config = {
  // base_url: '/database/:dbname/table/:table',
  base_url: '/:table/:endpoint',
  base_url_notable: '/:endpoint',
  grainstore: {
    datasource: {
      user: conf.database.user,
      host: conf.database.host,
      port: conf.database.port,
      geometry_field: conf.database.geometry_field,
      srid: conf.database.srid
    }
  }, //see grainstore npm for other options
  redis: {host: conf.redis.host, port: conf.redis.port},
  enable_cors: true,
  req2params: function(req, callback){
    // this is in case you want to test sql parameters eg ...png?sql=select * from my_table limit 10
    req.params =  _.extend({}, req.params);
    _.extend(req.params, req.query);

    req.params.dbname = conf.database.database_name;

    if(req.params.endpoint == 'grid' ){		//Grid endpoint
      var seed = 16/Math.pow(2,parseInt(req.params.z));
      if(seed > 4){
        seed = 4;
      }else if (seed == 1){
        seed = 0.99;
      }
      req.params.sql = gridQuery;
      if(req.params.taxon_id){
        req.params.sql = req.params.sql.replace(/\{\{taxon_id\}\}/g,req.params.taxon_id);
      }else{
        req.params.sql = req.params.sql.replace(/\{\{taxon_id\}\}/g,'-1');
      }
      req.params.sql = req.params.sql.replace(/\{\{seed\}\}/g, seed);
      if(!req.params.style){
        req.params.style = defaultStyleGrid;
      }
      if(req.params.taxon_color && req.params.taxon_color != 'undefined'){
        req.params.style = req.params.style.replace(/\{\{taxon_color\}\}/g,req.params.taxon_color);
      }else{
        //Boring blue
        req.params.style = req.params.style.replace(/\{\{taxon_color\}\}/g,'#FBB7ED');
      }
    }else if(req.params.endpoint == 'points'){	//Points endpoint
      req.params.sql = pointQuery;
      if(req.params.taxon_id){
        req.params.sql = req.params.sql.replace(/\{\{taxon_id\}\}/g,req.params.taxon_id);
      }else{
        req.params.sql = req.params.sql.replace(/\{\{taxon_id\}\}/g,'-1');
      }
      if(req.params.obs_id){
        req.params.sql = req.params.sql.replace(/\{\{obs_id\}\}/g,req.params.obs_id);
      }else{
        req.params.sql = req.params.sql.replace(/\{\{obs_id\}\}/g,'-1');
      }
      if(!req.params.style){
        req.params.style = defaultStylePoints;
      }
      if(req.params.taxon_color && req.params.taxon_color != 'undefined'){
	req.params.style = req.params.style.replace(/\{\{taxon_color\}\}/g,req.params.taxon_color);
      }else{
        //Boring pink
	req.params.style = req.params.style.replace(/\{\{taxon_color\}\}/g,'#1E90FF');
      }
    }
  // send the finished req object on
  var x = parseInt(req.params.x),
    y = parseInt(req.params.y),
    z = parseInt(req.params.z),
    numTiles = Math.pow(2,z),
    maxCoord = numTiles - 1

    x = x >= 0 ? x : maxCoord + x
    y = y >= 0 ? y : maxCoord + y
    if (x > maxCoord) {x = x % numTiles}
    if (y > maxCoord) {y = y % numTiles}
    if (x < -1*maxCoord) {x = Math.abs(x) % numTiles}
    if (y < -1*maxCoord) {y = Math.abs(y) % numTiles}
    req.params.x = ''+x
    req.params.y = ''+y
    req.params.z = ''+z

    callback(null,req);
  },
  beforeTileRender: function(req, res, callback) {
    callback(null);
  }
};

// Initialize tile server on port 4000
var ws = new Windshaft.Server(config);

ws.listen(4000);

console.log("map tiles are now being served out of: http://localhost:4000" + config.base_url + '/:z/:x/:y');
<|endoftext|>


<commit_before>var express = require('express'),
    path = require('path'),
    fs = require('fs'),
    favicon = require('static-favicon'),
    logger = require('morgan'),
    cookieParser = require('cookie-parser'),
    bodyParser = require('body-parser'),
    _s = require('underscore.string'),
    moment = require('moment'),
    marked = require('marked'),
    validator = require('validator'),
    extend = require('extend'),
    raneto = require('raneto-core'),
    config = require('./config'),
    app = express();

// Setup views
app.set('views', path.join(__dirname, 'views'));
app.set('layout', 'layout');
app.set('view engine', 'html');
app.enable('view cache');
app.engine('html', require('hogan-express'));

// Setup Express
app.use(favicon(__dirname +'/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// Setup config
extend(raneto.config, config);

// Handle all requests
app.all('*', function(req, res, next) {
    if(req.query.search){
        var searchQuery = validator.toString(validator.escape(_s.stripTags(req.query.search))).trim(),
            searchResults = raneto.doSearch(searchQuery),
            pageListSearch = raneto.getPages('');

        return res.render('search', {
            config: config,
            pages: pageListSearch,
            search: searchQuery,
            searchResults: searchResults,
            body_class: 'page-search'
        });
    }
    else if(req.params[0]){
        var slug = req.params[0];
        if(slug == '/') slug = '/index';

        var pageList = raneto.getPages(slug),
            filePath = path.normalize(raneto.config.content_dir + slug);
        if(!fs.existsSync(filePath)) filePath += '.md';

        if(slug == '/index' && !fs.existsSync(filePath)){
            return res.render('home', {
                config: config,
                pages: pageList,
                body_class: 'page-home'
            });
        } else {
            fs.readFile(filePath, 'utf8', function(err, content) {
                if(err){
                    err.status = '404';
                    err.message = 'Whoops. Looks like this page doesn\'t exist.';
                    return next(err);
                }

                // Process Markdown files
                if(path.extname(filePath) == '.md'){
                    // File info
                    var stat = fs.lstatSync(filePath);
                    // Meta
                    var meta = raneto.processMeta(content);
                    content = raneto.stripMeta(content);
                    if(!meta.title) meta.title = raneto.slugToTitle(filePath);
                    // Content
                    content = raneto.processVars(content);
                    var html = marked(content);

                    return res.render('page', {
                        config: config,
                        pages: pageList,
                        meta: meta,
                        content: html,
                        body_class: 'page-'+ raneto.cleanString(slug),
                        last_modified: moment(stat.mtime).format('Do MMM YYYY')
                    });
                } else {
                    // Serve static file
                    res.sendfile(filePath);
                }
            });
        }
    } else {
        next();
    }
});

// Handle any errors
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        config: config,
        status: err.status,
        message: err.message,
        error: {},
        body_class: 'page-error'
    });
});

module.exports = app;
<commit_msg>highlight.js doesn't use the 'lang-' prefix<commit_after>var express = require('express'),
    path = require('path'),
    fs = require('fs'),
    favicon = require('static-favicon'),
    logger = require('morgan'),
    cookieParser = require('cookie-parser'),
    bodyParser = require('body-parser'),
    _s = require('underscore.string'),
    moment = require('moment'),
    marked = require('marked'),
    validator = require('validator'),
    extend = require('extend'),
    raneto = require('raneto-core'),
    config = require('./config'),
    app = express();

// Setup views
app.set('views', path.join(__dirname, 'views'));
app.set('layout', 'layout');
app.set('view engine', 'html');
app.enable('view cache');
app.engine('html', require('hogan-express'));

// Setup Express
app.use(favicon(__dirname +'/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// Setup config
extend(raneto.config, config);

// Handle all requests
app.all('*', function(req, res, next) {
    if(req.query.search){
        var searchQuery = validator.toString(validator.escape(_s.stripTags(req.query.search))).trim(),
            searchResults = raneto.doSearch(searchQuery),
            pageListSearch = raneto.getPages('');

        return res.render('search', {
            config: config,
            pages: pageListSearch,
            search: searchQuery,
            searchResults: searchResults,
            body_class: 'page-search'
        });
    }
    else if(req.params[0]){
        var slug = req.params[0];
        if(slug == '/') slug = '/index';

        var pageList = raneto.getPages(slug),
            filePath = path.normalize(raneto.config.content_dir + slug);
        if(!fs.existsSync(filePath)) filePath += '.md';

        if(slug == '/index' && !fs.existsSync(filePath)){
            return res.render('home', {
                config: config,
                pages: pageList,
                body_class: 'page-home'
            });
        } else {
            fs.readFile(filePath, 'utf8', function(err, content) {
                if(err){
                    err.status = '404';
                    err.message = 'Whoops. Looks like this page doesn\'t exist.';
                    return next(err);
                }

                // Process Markdown files
                if(path.extname(filePath) == '.md'){
                    // File info
                    var stat = fs.lstatSync(filePath);
                    // Meta
                    var meta = raneto.processMeta(content);
                    content = raneto.stripMeta(content);
                    if(!meta.title) meta.title = raneto.slugToTitle(filePath);
                    // Content
                    content = raneto.processVars(content);
                    marked.setOptions({
                    	langPrefix: ''
                    });
                    var html = marked(content);

                    return res.render('page', {
                        config: config,
                        pages: pageList,
                        meta: meta,
                        content: html,
                        body_class: 'page-'+ raneto.cleanString(slug),
                        last_modified: moment(stat.mtime).format('Do MMM YYYY')
                    });
                } else {
                    // Serve static file
                    res.sendfile(filePath);
                }
            });
        }
    } else {
        next();
    }
});

// Handle any errors
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        config: config,
        status: err.status,
        message: err.message,
        error: {},
        body_class: 'page-error'
    });
});

module.exports = app;
<|endoftext|>


<commit_before>'use strict';

//Cookie store constructor
function CookieStore (location, minCustomers, maxCustomers, avgCookies,hourlyAvg, totalOfHour){
  this.location = location;
  this.minCustomers = minCustomers;
  this.maxCustomers = maxCustomers;
  this.avgCookies = avgCookies;
  this.hourlyAvg = hourlyAvg || [];
  this.totalOfDay = 0;
  this.totalOfHour = 0;
}

//Average cookies per hour
CookieStore.prototype.getAvgCookieCount = function(){
  for (var hours = 0; hours < time.length; hours++){
    var cookiesPerHour =  Math.floor(Math.random() * ((this.maxCustomers - this.minCustomers + 1) + this.minCustomers) * this.avgCookies);
    this.hourlyAvg.push(cookiesPerHour);
    this.totalOfDay += cookiesPerHour;
  }
};

//User store data
CookieStore.prototype.appendTable = function(tableEl){
  var userStore = document.createElement('tr');
  var storeName = document.createElement('td');
  storeName.textContent = this.location;
  userStore.appendChild(storeName);

  for(var j = 0; j < this.hourlyAvg.length; j++) {

  }
}
  tableEl.appendChild(userStore);
};

//Cookie Stores
var firstAndPike = new CookieStore('1st and Pike',23,65,6.3);
var seatac = new CookieStore('Seatac Airport',3,24,1.2);
var seattleCenter = new CookieStore('Seattle Center',11,38,3.7);
var capitolHill = new CookieStore('Capitol Hill',20,38,2.3);
var alki = new CookieStore('Alki',2,16,4.6);

//Cookie store Array
var stores = [firstAndPike,seatac,seattleCenter,capitolHill,alki];

//Time Array
var time = ['6am','7am','8am','9am','10am','11am','12pm','1pm','2pm','3pm','4pm','5pm','6pm','7pm','8pm'];

firstAndPike.getAvgCookieCount();
seatac.getAvgCookieCount();
seattleCenter.getAvgCookieCount();
capitolHill.getAvgCookieCount();
alki.getAvgCookieCount();

console.log(firstAndPike.totalOfDay);
//Table html node
var tableEl = document.createElement('table');

//Table Row for store time
var timeEl = document.createElement('tr');
tableEl.appendChild(timeEl);

//blank header over store names
var storeHrs = document.createElement('th');
storeHrs.textContent = ' ';
tableEl.appendChild(storeHrs);

//lists store hours
for (var t = 0; t < time.length; t++){
  var storeTime = document.createElement('th');
  storeTime.textContent = time[t];
  tableEl.appendChild(storeTime);
}

//table header for daily location totals
var totalCount = document.createElement('th');
totalCount.textContent = 'Daily Location Total';
tableEl.appendChild(totalCount);

//table of store names
for ( var i = 0; i < stores.length; i++){
  var currentStore = stores[i];

  //creates rows for each store
  var rowEl = document.createElement('tr');
  tableEl.appendChild(rowEl);

  //lists store names as headers
  var nameEl = document.createElement('th');
  nameEl.textContent = currentStore.location;
  rowEl.appendChild(nameEl);

  //table of average cookie sales per hour
  for(var ii = 0; ii < time.length; ii++){
    var salesEl = document.createElement('td');
    salesEl.textContent = currentStore.hourlyAvg[ii];
    rowEl.appendChild(salesEl);
  };

  //total cookies sold for the day
  var totalDaysCookies = document.createElement('td');
  totalDaysCookies.textContent = currentStore.totalOfDay;
  rowEl.appendChild(totalDaysCookies);
};

//table row for totals/hr
var dayTotalEl = document.createElement('tr');
tableEl.appendChild(dayTotalEl);

//table header for totals/hr
//var daySalesEl = document.createElement('th');
//daySalesEl.textContent = 'Totals';
//tableEl.appendChild(daySalesEl);

document.getElementById('stores').appendChild(tableEl);

//Set up variable for User to input Cookie store parameters
var userInputStoreForm = document.getElementById('cookie-store-form');

//Event Listener
userInputStoreForm.addEventListener('submit', handleSubmit);

function handleSubmit(event) {
  event.preventDefault();
  event.stopPropagation();

  var storeName = event.target.cookieStoreName.value;
  var minCustomers = parseInt(event.target.minCust.value);
  var maxCustomers = parseInt(event.target.maxCust.value);
  var avgCookies = parseInt(event.target.avgCookies.value);

  //Adding user store information from Form
  var store = new CookieStore(location, minCustomers, maxCustomers, avgCookies);
  store.getAvgCookieCount();
  stores.push(store);
  var newStores = document.getElementById('tableEl');
  store.appendTable(newStores);
}
<commit_msg>amended results table<commit_after>'use strict';

// console.log(firstAndPike.totalOfDay);
//Table html node
var tableEl = document.createElement('table');
console.log(tableEl);
//Cookie store constructor
function CookieStore (location, minCustomers, maxCustomers, avgCookies,hourlyAvg, totalOfHour){
  this.location = location;
  this.minCustomers = minCustomers;
  this.maxCustomers = maxCustomers;
  this.avgCookies = avgCookies;
  this.hourlyAvg = hourlyAvg || [];
  this.totalOfDay = 0;
  this.totalOfHour = 0;
}

//Average cookies per hour
CookieStore.prototype.getAvgCookieCount = function(){
  for (var hours = 0; hours < time.length; hours++){
    var cookiesPerHour =  Math.floor(Math.floor(Math.random() * ((this.maxCustomers - this.minCustomers + 1)) + this.minCustomers) * this.avgCookies);
    this.hourlyAvg.push(cookiesPerHour);
    this.totalOfDay += cookiesPerHour;
  }
};

//User store data
CookieStore.prototype.appendTable = function(){
  var userStore = document.createElement('tr');
  var storeName = document.createElement('td');
  storeName.textContent = this.location;
  userStore.appendChild(storeName);

  for(var j = 0; j < this.hourlyAvg.length; j++) {
    var newCookie = document.createElement('td');
    newCookie.textContent = this.hourlyAvg[j];
    userStore.appendChild(newCookie);
  }
  var totalDaysCookies = document.createElement('td');
  totalDaysCookies.textContent = currentStore.totalOfDay;
  userStore.appendChild(totalDaysCookies);

  console.log(userStore);
  console.log(tableEl);
  tableEl.appendChild(userStore);
};

//Cookie Stores
var firstAndPike = new CookieStore('1st and Pike',23,65,6.3);
var seatac = new CookieStore('Seatac Airport',3,24,1.2);
var seattleCenter = new CookieStore('Seattle Center',11,38,3.7);
var capitolHill = new CookieStore('Capitol Hill',20,38,2.3);
var alki = new CookieStore('Alki',2,16,4.6);

//Cookie store Array
var stores = [firstAndPike,seatac,seattleCenter,capitolHill,alki];

//Time Array
var time = ['6am','7am','8am','9am','10am','11am','12pm','1pm','2pm','3pm','4pm','5pm','6pm','7pm','8pm'];

firstAndPike.getAvgCookieCount();
seatac.getAvgCookieCount();
seattleCenter.getAvgCookieCount();
capitolHill.getAvgCookieCount();
alki.getAvgCookieCount();

//Table Row for store time
var timeEl = document.createElement('tr');
tableEl.appendChild(timeEl);

//blank header over store names
var storeHrs = document.createElement('th');
storeHrs.textContent = ' ';
tableEl.appendChild(storeHrs);

//lists store hours
for (var t = 0; t < time.length; t++){
  var storeTime = document.createElement('th');
  storeTime.textContent = time[t];
  tableEl.appendChild(storeTime);
}

//table header for daily location totals
var totalCount = document.createElement('th');
totalCount.textContent = 'Daily Location Total';
tableEl.appendChild(totalCount);

//table of store names
for ( var i = 0; i < stores.length; i++){
  var currentStore = stores[i];

  //creates rows for each store
  var rowEl = document.createElement('tr');
  tableEl.appendChild(rowEl);

  //lists store names as headers
  var nameEl = document.createElement('th');
  nameEl.textContent = currentStore.location;
  rowEl.appendChild(nameEl);

  //table of average cookie sales per hour
  for(var ii = 0; ii < time.length; ii++){
    var salesEl = document.createElement('td');
    salesEl.textContent = currentStore.hourlyAvg[ii];
    rowEl.appendChild(salesEl);
  };

  //total cookies sold for the day
  var totalDaysCookies = document.createElement('td');
  totalDaysCookies.textContent = currentStore.totalOfDay;
  rowEl.appendChild(totalDaysCookies);
};

//table row for totals/hr
var dayTotalEl = document.createElement('tr');
tableEl.appendChild(dayTotalEl);

//table header for totals/hr
//var daySalesEl = document.createElement('th');
//daySalesEl.textContent = 'Totals';
//tableEl.appendChild(daySalesEl);

document.getElementById('stores').appendChild(tableEl);

//Set up variable for User to input Cookie store parameters
var userInputStoreForm = document.getElementById('cookie-store-form');

//Event Listener
userInputStoreForm.addEventListener('submit', handleSubmit);

function handleSubmit(event) {
  event.preventDefault();
  event.stopPropagation();

  var storeName = event.target.cookieStoreName.value;
  var minCustomers = parseInt(event.target.minCust.value);
  var maxCustomers = parseInt(event.target.maxCust.value);
  var avgCookies = parseInt(event.target.avgCookies.value);

  console.log(storeName);
  console.log(minCustomers);
  console.log(maxCustomers);
  console.log(avgCookies);

  //Adding user store information from Form
  var store = new CookieStore(storeName, minCustomers, maxCustomers, avgCookies);
  store.getAvgCookieCount();
  stores.push(store);
  var newStores = document.getElementById('tableEl');
  store.appendTable(newStores);
}
<|endoftext|>


<commit_before>var express    = require('express')
  , imageable  = require("imageable")
  , connect    = require('connect')
  , http       = require("http")
  , fs         = require("fs")
  , app        = module.exports = express.createServer()
  , configFile = __dirname + "/" + (process.env.CONFIG || "config/config.example.json")
  , config     = JSON.parse(fs.readFileSync(configFile))
  , airbrake   = (config.airbrake ? require("airbrake").createClient(config.airbrake) : null)

// Configuration
app.configure(function(){
  connect.logger.token('date', function(){ return imageable.Logger.formatDate(new Date()) })

  app.use(connect.logger({ immediate: true, format: "\\n:date :method | :status | :url (via :referrer)" }))
  app.use(express.bodyParser())
  app.use(express.methodOverride())
  app.use(imageable(config, {
    after: function(_, _, err, req) {
      if(err && airbrake) {
        err.session = req.headers
        airbrake.notify(err, function(err, url){
          err && console.log(err)
        })
      }
    }
  }))
  app.use(app.router)
})

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }))
})

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

// Routes
app.get('/', function(req, res, next) {
  res.send('This is not the page you are looking for.')
})

app.get('/favicon.ico', function(req, res) {
  res.send('')
})

// Only listen on $ node app.js
if (!module.parent) {
  app.listen(process.env.PORT || 3000)
  console.log("Express server listening on port %d", app.address().port)
}
<commit_msg>reverted usage of config.example.json<commit_after>var express    = require('express')
  , imageable  = require("imageable")
  , connect    = require('connect')
  , http       = require("http")
  , fs         = require("fs")
  , app        = module.exports = express.createServer()
  , configFile = __dirname + "/" + (process.env.CONFIG || "config/config.json")
  , config     = JSON.parse(fs.readFileSync(configFile))
  , airbrake   = (config.airbrake ? require("airbrake").createClient(config.airbrake) : null)

// Configuration
app.configure(function(){
  connect.logger.token('date', function(){ return imageable.Logger.formatDate(new Date()) })

  app.use(connect.logger({ immediate: true, format: "\\n:date :method | :status | :url (via :referrer)" }))
  app.use(express.bodyParser())
  app.use(express.methodOverride())
  app.use(imageable(config, {
    after: function(_, _, err, req) {
      if(err && airbrake) {
        err.session = req.headers
        airbrake.notify(err, function(err, url){
          err && console.log(err)
        })
      }
    }
  }))
  app.use(app.router)
})

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }))
})

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

// Routes
app.get('/', function(req, res, next) {
  res.send('This is not the page you are looking for.')
})

app.get('/favicon.ico', function(req, res) {
  res.send('')
})

// Only listen on $ node app.js
if (!module.parent) {
  app.listen(process.env.PORT || 3000)
  console.log("Express server listening on port %d", app.address().port)
}
<|endoftext|>


<commit_before>var express = require('express');
var mongo = require('mongodb');

var mongoUri = process.env.MONGOLAB_URI ||
  process.env.MONGOHQ_URL ||
  'mongodb://localhost/newspull';

mongo.Db.connect(mongoUri, function (err, db) {
    console.log('success!');
});

var app = express();
app.use(express.logger());
app.use(express.errorHandler());
app.use(express.static(__dirname + '/static'));

app.get('/', function(req, res){
    res.send('Hello World');
});

var port = parseInt(process.env.PORT, 10) || 3000;
app.listen(port);
console.log('Listening on port ' + port);

<commit_msg>put db connection in a promise<commit_after>var express = require('express'),
    mongo = require('mongodb'),
    Q = require('q');

var mongoUri = process.env.MONGOLAB_URI ||
  process.env.MONGOHQ_URL ||
  'mongodb://localhost/newspull';

var dbQ = Q.defer(),
    dbPromise = dbQ.promise;

mongo.Db.connect(mongoUri, function (err, db) {
    dbQ.resolve(db);
});

var app = express();
app.use(express.logger());
app.use(express.errorHandler());
app.use(express.static(__dirname + '/static'));

app.get('/', function(req, res) {
    dbPromise.done(function(db) {
        console.log(db);
        res.send('Hello World');
    });
});

var port = parseInt(process.env.PORT, 10) || 3000;
app.listen(port);
console.log('Listening on port ' + port);

<|endoftext|>


<commit_before>/**
 * Copyright 2015 IBM Corp. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

var
  express = require('express'),
  app     = express(),
  port    = require('./config/app-info').port,
  logger  = require('winston');

// Bootstrap application settings
require('./config/express')(app);

// Add routes to app
require('./router')(app);

// error-handler settings
require('./config/error-handler')(app);

app.listen(port);
logger.info('Listening at:', port);
<commit_msg>fix spacing in app.js<commit_after>/**
 * Copyright 2015 IBM Corp. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

var express = require('express'),
    app     = express(),
    port    = require('./config/app-info').port,
    logger  = require('winston');

// Bootstrap application settings
require('./config/express')(app);

// Add routes to app
require('./router')(app);

// error-handler settings
require('./config/error-handler')(app);

app.listen(port);
logger.info('Listening at:', port);
<|endoftext|>


<commit_before>// Server demo. Run this with node to start your server.
// Copyright © 2011-2013 Thaddee Tyl, Jan Keromnes. All rights reserved.
// Code covered by the LGPL license.

// Let's rock'n'roll!
var camp = require('./lib/camp.js').start({
      port: +process.argv[2],
      secure: process.argv[3] === 'yes',
      debug: +process.argv[4],
    })
  , ajax = camp.ajax

// Templating demo
camp.route('/template.html', function(data, match, end) {
  end({    // Try http://localhost/template.html?title=Hello&info=[Redacted].
    title: data.title || 'Success'
  , info: data.info || 'This document has been templated!'
  })
})

// Doctor demo
var replies = ['Ok.', 'Oh⁉', 'Is that so?', 'How interesting!'
              ,'Hm…', 'What do you mean?', 'So say we all.']
ajax.on('doctor', function(data, end) {
  replies.push(data.text)
  end({reply:replies[Math.floor(Math.random() * replies.length)]})
})

// Chat demo
var chat = camp.eventSource('all')
ajax.on('talk', function(data, end) {chat.send(data); end()})

// WebSocket chat demo
camp.wsBroadcast('chat', function(data, end) {end(data)})

// Not found demo
camp.notfound(/.*\.lol$/, function(data, match, end, ask) {
  end(null, { template: '/404.html' })
})

<commit_msg>Silly basic auth example.<commit_after>// Server demo. Run this with node to start your server.
// Copyright © 2011-2013 Thaddee Tyl, Jan Keromnes. All rights reserved.
// Code covered by the LGPL license.

// Let's rock'n'roll!
var camp = require('./lib/camp.js').start({
      port: +process.argv[2],
      secure: process.argv[3] === 'yes',
      debug: +process.argv[4],
    })
  , ajax = camp.ajax

// Templating demo
camp.route('/template.html', function(data, match, end) {
  end({    // Try http://localhost/template.html?title=Hello&info=[Redacted].
    title: data.title || 'Success'
  , info: data.info || 'This document has been templated!'
  })
})

// Doctor demo
var replies = ['Ok.', 'Oh⁉', 'Is that so?', 'How interesting!'
              ,'Hm…', 'What do you mean?', 'So say we all.']
ajax.on('doctor', function(data, end) {
  replies.push(data.text)
  end({reply:replies[Math.floor(Math.random() * replies.length)]})
})

// Chat demo
var chat = camp.eventSource('all')
ajax.on('talk', function(data, end) {chat.send(data); end()})

// WebSocket chat demo
camp.wsBroadcast('chat', function(data, end) {end(data)})

// Not found demo
camp.notfound(/.*\.lol$/, function(data, match, end) {
  end(null, { template: '/404.html' })
})

// Basic authentication demo.
camp.route(/^\/secret$/, function(data, match, end, ask) {
  if (ask.username && ask.password
    && ask.username === 'Caesar' && ask.password === '1234') {
    end(null, {template: streamFromString('Congrats, you found it!')})
  } else {
    ask.res.statusCode = 401;
    ask.res.setHeader('WWW-Authenticate', 'Basic')
    end(null, {template: streamFromString('Congrats, you found it!')})
  }
})

var stream = require('stream')
function streamFromString(str) {
  var newStream = new stream.Readable()
  newStream._read = function() { newStream.push(str); newStream.push(null) }
  return newStream
}
<|endoftext|>


<commit_before>/*
Name:         overheid.io
Description:  Access overheid.io endpoints like OpenKvK, RDW and BAG with node.js
Author:       Franklin van de Meent (https://frankl.in)
Source code:  https://github.com/fvdm/nodejs-overheid.io
Feedback:     https://github.com/fvdm/nodejs-overheid.io/issues
License:      Unlicense (Public Domain) - see LICENSE file
              (https://github.com/fvdm/nodejs-overheid.io/raw/master/LICENSE)
*/

var http = require ('httpreq');

var defaults = {
  timeout: 5000
};

function fixParams (obj) {
  var key;
  var nw = [];
  var k;
  var i;

  if (obj) {
    for (key in obj) {
      if (obj [key] instanceof Array) {
        for (i = 0; i < obj [key] .length; i++) {
          nw.push (key + '[]=' + encodeURIComponent (obj [key] [i]));
        }
      } else if (obj [key] instanceof Object) {
        for (k in obj [key]) {
          nw.push (key + '[' + k + ']=' + encodeURIComponent (obj [key] [k]));
        }
      } else {
        nw.push (key + '=' + encodeURIComponent (obj [key]));
      }
    }
  }
  return nw.length ? '?' + nw.join ('&') : '';
}

module.exports = function (config) {
  return function (request) {
    var options = {
      url: 'https://overheid.io/api/' + (request.dataset || config.dataset),
      method: 'GET',
      headers: {
        'ovio-api-key': config.apikey || '',
        'User-Agent': 'overheid.io (https://github.com/fvdm/nodejs-overheid.io)'
      },
      timeout: request.timeout || config.timeout || defaults.timeout
    };

    options.url += request.path ? '/' + request.path : '';
    options.url += fixParams (request.params);

    http.doRequest (options, function (err, res) {
      var data = res && res.body || null;
      var error = null;

      if (err) {
        error = new Error ('request failed');
        error.error = err;
        error.body = data;
        request.callback (error);
        return;
      }

      try {
        data = JSON.parse (data);

        if (Object.keys (data) .length === 1 && Object.keys (data.headers) .length === 0) {
          error = new Error ('no result');
          request.callback (error);
          return;
        }
      } catch (e) {
        error = new Error ('invalid response');
        error.error = e;
        error.code = res.statusCode;
        error.body = data;
        request.callback (error);
        return;
      }

      if (res.statusCode >= 300) {
        error = new Error ('API error');
        error.code = res.statusCode;
        error.text = data.error || null;
        request.callback (error);
        return;
      }

      request.callback (null, data);
    });
  };
};
<commit_msg>Refactor(errors): Moved common errors to doError()<commit_after>/*
Name:         overheid.io
Description:  Access overheid.io endpoints like OpenKvK, RDW and BAG with node.js
Author:       Franklin van de Meent (https://frankl.in)
Source code:  https://github.com/fvdm/nodejs-overheid.io
Feedback:     https://github.com/fvdm/nodejs-overheid.io/issues
License:      Unlicense (Public Domain) - see LICENSE file
              (https://github.com/fvdm/nodejs-overheid.io/raw/master/LICENSE)
*/

var http = require ('httpreq');

var defaults = {
  timeout: 5000
};

function doError (msg, err, res, callback) {
  var error = new Error (msg);

  error.error = err;
  error.code = res && res.statusCode;
  error.body = res && res.body;
  callback (error);
}

function fixParams (obj) {
  var key;
  var nw = [];
  var k;
  var i;

  if (obj) {
    for (key in obj) {
      if (obj [key] instanceof Array) {
        for (i = 0; i < obj [key] .length; i++) {
          nw.push (key + '[]=' + encodeURIComponent (obj [key] [i]));
        }
      } else if (obj [key] instanceof Object) {
        for (k in obj [key]) {
          nw.push (key + '[' + k + ']=' + encodeURIComponent (obj [key] [k]));
        }
      } else {
        nw.push (key + '=' + encodeURIComponent (obj [key]));
      }
    }
  }
  return nw.length ? '?' + nw.join ('&') : '';
}

module.exports = function (config) {
  return function (request) {
    var options = {
      url: 'https://overheid.io/api/' + (request.dataset || config.dataset),
      method: 'GET',
      headers: {
        'ovio-api-key': config.apikey || '',
        'User-Agent': 'overheid.io (https://github.com/fvdm/nodejs-overheid.io)'
      },
      timeout: request.timeout || config.timeout || defaults.timeout
    };

    options.url += request.path ? '/' + request.path : '';
    options.url += fixParams (request.params);

    http.doRequest (options, function (err, res) {
      var data = res && res.body || null;
      var error;

      if (err) {
        doError ('request failed', err, res, request.callback);
        return;
      }

      try {
        data = JSON.parse (data);

        if (Object.keys (data) .length === 1 && Object.keys (data.headers) .length === 0) {
          error = new Error ('no result');
          request.callback (error);
          return;
        }
      } catch (e) {
        doError ('invalid response', e, res, request.callback);
        return;
      }

      if (res.statusCode >= 300) {
        error = new Error ('API error');
        error.code = res.statusCode;
        error.text = data.error || null;
        request.callback (error);
        return;
      }

      request.callback (null, data);
    });
  };
};
<|endoftext|>


<commit_before>'use strict';

/*
 * Express Dependencies
 */
var express = require('express');
var app = express();
var port = 3000;

// mongodb setup and models imported
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/TranscribeMe/');
var User = require('./models/user.js');
var Note = require('./models/note.js');
var Message = require('./models/message.js');

// Using Handlebars for templating
var exphbs = require('express3-handlebars');
var hbs;

// configure app to use bodyParser() which will this will let us get the data from a POST
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// For gzip compression
app.use(express.compress());

// authentication package
var passport = require('passport');
var localStrategy = require('passport-local').Strategy;

passport.use(new localStrategy(
  function (username, password, done) {
    User.findOne({ username: username }, function (err, user) {
      if (err) { return done(err); }
      if (!user) {
        return done(null, false, { message: 'Incorrect username.' });
      }
      if (!user.validPassword(password)) {
        return done(null, false, { message: 'Incorrect password.' });
      }
      return done(null, user);
    });
  }
));

/*
 * Config for Production and Development
 */
if (process.env.NODE_ENV === 'production') {
    // Set the default layout and locate layouts and partials
    app.engine('handlebars', exphbs({
        defaultLayout: 'main',
        layoutsDir: 'dist/views/layouts/',
        partialsDir: 'dist/views/partials/'
    }));

    // Locate the views
    app.set('views', __dirname + '/dist/views');

    // Locate the assets
    app.use(express.static(__dirname + '/dist/assets'));

} else {
    app.engine('handlebars', exphbs({
        // Default Layout and locate layouts and partials
        defaultLayout: 'main',
        layoutsDir: 'views/layouts/',
        partialsDir: 'views/partials/'
    }));

    // Locate the views
    app.set('views', __dirname + '/views');

    // Locate the assets
    app.use(express.static(__dirname + '/assets'));
}

// Set Handlebars
app.set('view engine', 'handlebars');

/*
 * Middle-ware
 */
// check if the test cases should be triggered
app.use(function (req, res, next) {
    res.locals.showTests = app.get('env') !== 'production' && req.query.test === '1';
    next();
});

/*
 * GET Routes
 */

// Index Page
app.get('/', function (req, res, next) {
    res.render('index');
});
// About Page
app.get('/about', function (req, res, next) {
    res.render('about', {
        pageTestScript: '/qa/about-tests.js'
    });
});
// Contact Page
app.get('/contact', function (req, res, next) {
    res.render('contact', {
        pageTestScript: '/qa/contact-tests.js'
    });
});
// Schedule Page
app.get('/schedule', function (req, res, next) {
    res.render('schedule', {
        pageTestScript: '/qa/schedule-tests.js'
    });
});
// Notes Page
app.get('/notes', function (req, res, next) {
    res.render('notes', {
        pageTestScript: '/qa/notes-tests.js'
    });
});
// Login Page
app.get('/login', function (req, res, next) {
    res.render('login', {
        pageTestScript: '/qa/login-tests.js'
    });
});

/*
 * POST Routes
 */

// process login request
app.post('/login',
    passport.authenticate('local', {    successRedirect: '/',
                                        failureRedirect: '/login',
                                        failureFlash: true })
);
// process contact form submission
app.post('/contact', function (req, res, next) {
    // create new message instance
    var message = new Message({
            name        : req.body.name,
            email       : req.body.email,
            message     : req.body.message,
            created_on  : Date.now(),
            pending     : true,
        });
    // save the message and check for errors
    message.save(function(err) {
        if (err) {
            res.send(err);
        }
        res.json({ message: 'Message created!' });
    });
    // send the user back to the home page
    res.redirect('/');
});

// custom 404 page
app.use(function (req, res) {
    res.status(404);
    res.render('404');
});
// custom 505 page
app.use(function (req, res) {
    res.status(500);
    res.render('500');
});

// Start up the server / logging errors to output
app.listen(process.env.PORT || port);
console.log('Express started on port ' + port);
console.log('http://localhost:'+port);<commit_msg>pointed connection string to the correct local MongoDB. Messages are logging again.<commit_after>'use strict';

/*
 * Express Dependencies
 */
var express = require('express');
var app = express();
var port = 3000;

// mongodb setup and models imported
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test/');
var User = require('./models/user.js');
var Note = require('./models/note.js');
var Message = require('./models/message.js');

// Using Handlebars for templating
var exphbs = require('express3-handlebars');
var hbs;

// configure app to use bodyParser() which will this will let us get the data from a POST
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// For gzip compression
app.use(express.compress());

// authentication package
var passport = require('passport');
var localStrategy = require('passport-local').Strategy;

passport.use(new localStrategy(
  function (username, password, done) {
    User.findOne({ username: username }, function (err, user) {
      if (err) { return done(err); }
      if (!user) {
        return done(null, false, { message: 'Incorrect username.' });
      }
      if (!user.validPassword(password)) {
        return done(null, false, { message: 'Incorrect password.' });
      }
      return done(null, user);
    });
  }
));

/*
 * Config for Production and Development
 */
if (process.env.NODE_ENV === 'production') {
    // Set the default layout and locate layouts and partials
    app.engine('handlebars', exphbs({
        defaultLayout: 'main',
        layoutsDir: 'dist/views/layouts/',
        partialsDir: 'dist/views/partials/'
    }));

    // Locate the views
    app.set('views', __dirname + '/dist/views');

    // Locate the assets
    app.use(express.static(__dirname + '/dist/assets'));

} else {
    app.engine('handlebars', exphbs({
        // Default Layout and locate layouts and partials
        defaultLayout: 'main',
        layoutsDir: 'views/layouts/',
        partialsDir: 'views/partials/'
    }));

    // Locate the views
    app.set('views', __dirname + '/views');

    // Locate the assets
    app.use(express.static(__dirname + '/assets'));
}

// Set Handlebars
app.set('view engine', 'handlebars');

/*
 * Middle-ware
 */
// check if the test cases should be triggered
app.use(function (req, res, next) {
    res.locals.showTests = app.get('env') !== 'production' && req.query.test === '1';
    next();
});

/*
 * GET Routes
 */

// Index Page
app.get('/', function (req, res, next) {
    res.render('index');
});
// About Page
app.get('/about', function (req, res, next) {
    res.render('about', {
        pageTestScript: '/qa/about-tests.js'
    });
});
// Contact Page
app.get('/contact', function (req, res, next) {
    res.render('contact', {
        pageTestScript: '/qa/contact-tests.js'
    });
});
// Schedule Page
app.get('/schedule', function (req, res, next) {
    res.render('schedule', {
        pageTestScript: '/qa/schedule-tests.js'
    });
});
// Notes Page
app.get('/notes', function (req, res, next) {
    res.render('notes', {
        pageTestScript: '/qa/notes-tests.js'
    });
});
// Login Page
app.get('/login', function (req, res, next) {
    res.render('login', {
        pageTestScript: '/qa/login-tests.js'
    });
});

/*
 * POST Routes
 */

// process login request
app.post('/login',
    passport.authenticate('local', {    successRedirect: '/',
                                        failureRedirect: '/login',
                                        failureFlash: true })
);
// process contact form submission
app.post('/contact', function (req, res, next) {
    // create new message instance
    var message = new Message({
            name        : req.body.name,
            email       : req.body.email,
            message     : req.body.message,
            created_on  : Date.now(),
            pending     : true,
        });
    // save the message and check for errors
    message.save(function(err) {
        if (err) {
            res.send(err);
        }
        res.json({ message: 'Message created!' });
    });
    // send the user back to the home page
    res.redirect('/');
});

// custom 404 page
app.use(function (req, res) {
    res.status(404);
    res.render('404');
});
// custom 505 page
app.use(function (req, res) {
    res.status(500);
    res.render('500');
});

// Start up the server / logging errors to output
app.listen(process.env.PORT || port);
console.log('Express started on port ' + port);
console.log('http://localhost:'+port);<|endoftext|>


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

var app = express();

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

app.listen(process.env.PORT || 5000);

module.exports = app;
<commit_msg>Changed from Hello World to Hello Jenkins<commit_after>var express = require('express');

var app = express();

app.get('/', function (req, res) {
  res.send('hello jenkins');
});

app.listen(process.env.PORT || 5000);

module.exports = app;
<|endoftext|>


<commit_before>var express   = require('express')
  , imageable = require("imageable")
  , app       = module.exports = express.createServer()
  , fs        = require("fs")
  , config    = JSON.parse(fs.readFileSync(__dirname + "/config/config.json"))
  , http      = require("http")

// Configuration
app.configure(function(){
  app.use(express.bodyParser())
  app.use(express.methodOverride())
  app.use(imageable(config, {
    before: function() { return +new Date() },
    after: function(start) {
      var duration = +new Date() - start
      config.hasOwnProperty('hummingBird') && http.get(config.hummingBird)
    }
  }))
  app.use(app.router)
})

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }))
})

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

// Routes
app.get('/', function(req, res, next) {
  res.send('This is not the page you are looking for.')
})

// Only listen on $ node app.js
if (!module.parent) {
  app.listen(process.env.PORT || 3000)
  console.log("Express server listening on port %d", app.address().port)
}
<commit_msg>logging + no hummingbird<commit_after>var express   = require('express')
  , imageable = require("imageable")
  , app       = module.exports = express.createServer()
  , fs        = require("fs")
  , config    = JSON.parse(fs.readFileSync(__dirname + "/config/config.json"))
  , http      = require("http")

// Configuration
app.configure(function(){
  app.use(express.logger({ format: ':method :url' }));
  app.use(express.bodyParser())
  app.use(express.methodOverride())
  app.use(imageable(config, {
    before: function() { return +new Date() },
    after: function(start) {
      var duration = +new Date() - start
    }
  }))
  app.use(app.router)
})

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }))
})

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

// Routes
app.get('/', function(req, res, next) {
  res.send('This is not the page you are looking for.')
})

// Only listen on $ node app.js
if (!module.parent) {
  app.listen(process.env.PORT || 3000)
  console.log("Express server listening on port %d", app.address().port)
}
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var express = require('express')
  , lessonRoutes = require('./routes/lessonRoutes')
  , lessonlistRoutes = require('./routes/lessonlistRoutes')
  , http = require('http')
  , appDb = require('./lib/appDb')
  , isBadSql = require('./lib/is-bad-sql')
  , crypto = require('crypto')
  , fs = require('fs')
  , path = require('path')
  , banHammer = require('./lib/banHammer')
  , postgrator = require('postgrator');

/* ============================================================
    load some environment variables if they are not present
	This really should be outside the app,
	and in a separate app running script... but...
=============================================================== */
if (!process.env.NODE_ENV || !process.env.DATABASE_URL) {
	console.log('Environment variable is missing - loading the .env');
	try {
		var envFile = fs.readFileSync(__dirname + '/.env', 'utf8');
		var envSettings = envFile.replace(/\r/g, '').split('\n');
		envSettings.forEach(function(setting) {
			keyvalue = setting.split('=');
			if (keyvalue.length == 2) {
				console.log('setting process.env.' + keyvalue[0] + ' = ' + keyvalue[1]);
				process.env[keyvalue[0]] = keyvalue[1];
			}
		});
	} catch (err) {
		console.log(err);
	}
}

/* ============================================================
    Postgrator stuff
=============================================================== */
if (!process.env.NODE_ENV) console.log('NODE_ENV not set');
if (!process.env.DATABASE_URL) console.log('DATABASE_URL not set');

postgrator.setMigrationDirectory(__dirname + '/migrations');
postgrator.setConnectionString(process.env.DATABASE_URL);
postgrator.migrate('012');

/* ============================================================
    Some Middleware
=============================================================== */
var editorsOnly = function (req, res, next) {
	if (req.session && req.session.isSignedIn) {
		next();
	} else {
		res.redirect('/signin');
	}
};

/* ============================================================
    Express Setup and stuff
=============================================================== */

var app = express();

app.configure(function(){
	app.set('port', process.env.PORT || 3000);
	app.set('views', __dirname + '/views');
	app.set('view engine', 'ejs');

	app.use(express.favicon());
	app.use(express.logger('dev'));
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(express.cookieParser('your secret here'));
	app.use(express.session());

	app.use(banHammer.handleBannedPeople);

	app.use(app.router);
	app.use(require('less-middleware')({ src: __dirname + '/public' }));
	app.use(express.static(path.join(__dirname, 'public')));

});

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

/* ============================================================
    PreCalc
	Basically a cache of all the lesson data.
	Should be refreshed each time a lesson or lessonlist is changed/added

	it looks like:
	precalc.lessonlists: [
		{
			listid: n,
			listname: '',
			listDescription: '',
			lessons: [
				{
					listid,
					listname,
					listdescription,
					listseq,
					lessonid,
					lessontitle,
					lessondescription,
					lessonseq
				}
			]
		}
	]
=============================================================== */

var precalc = {
	lessonLists: [],
	refreshLessonLists: function () {

		var sql = "SELECT ll.lessonlist_id AS listId, ll.name AS listName, ll.description AS listDescription, ll.seq AS listSeq, l.lesson_id AS lessonId, l.title AS lessonTitle, l.description AS lessonDescription, l.seq AS lessonSeq FROM lesson l JOIN lessonlist ll ON l.lessonlist_id = ll.lessonlist_id ORDER BY ll.seq, l.seq";

		appDb.query(sql, [], function(err, results) {
			if (err) {
				console.log('precalc.refreshLessonLists() failure to run query');
				precalc.lessonLists = [];
			} else {
				var lessonLists = [];
				var lessonListCounter = -1;

				for (i = 0; i < results.length; i++) {
					var lesson = results[i];

					if (lessonLists[lessonListCounter] && lessonLists[lessonListCounter].listname == lesson.listname) {
						lessonLists[lessonListCounter].lessons.push(lesson);

					} else {
						// we've approached a new list. Increment the lessonListcounter
						lessonListCounter = lessonListCounter + 1;
						// if currentList has lessons
						lessonLists[lessonListCounter] = {};
						lessonLists[lessonListCounter].listid = lesson.listid;
						lessonLists[lessonListCounter].listname = lesson.listname;
						lessonLists[lessonListCounter].listDescription = lesson.listdescription;
						lessonLists[lessonListCounter].lessons = [];
						lessonLists[lessonListCounter].lessons.push(lesson);
					}
				}

				precalc.lessonLists = lessonLists;
			}
		});

	}
};
precalc.refreshLessonLists();

/* ============================================================
    Some glocals?
=============================================================== */
var everyonesLinks = [
	{
		text: 'Lessons',
		url: '/'
	}, {
		text: 'About',
		url: '/about'
	}, {
		text: 'More SQL Resources',
		url: '/more-sql-resources'
	}
];
var editorsLinks = [
	{
		text: 'Lessons',
		url: '/'
	}, {
		text: 'superquery',
		url: '/superquery'
	}, {
		text: 'editor',
		url: '/edit'
	}, {
		text: 'sign out',
		url: '/signout'
	}
];
app.locals.links = everyonesLinks;
app.locals.title = 'Learn some SQL'; // Default title if none is provided
app.locals.makeTable = function (columns, rows) {
	var html = '
'
	html = html + '

';
	for (var c = 0; c < columns; c++) {
		html = html + '   	';
	}

	// close table header row, start body
	html = html + '

';

	for (var r = 0; r < rows; r++) {
		var rowHtml = '
'
		for (var c = 0; c < columns; c++) {
			rowHtml = rowHtml + ' 	';
		}
		rowHtml = rowHtml + '
';
		html = html + rowHtml;
	}

	// clost body and table
	html = html + '

';
	return html;
};

/* ============================================================
    The Routes
=============================================================== */

//app.get('/', routes.index);
app.get('/', function(req, res){
	//console.log('remoteAddress: ' + req.connection.remoteAddress);
	res.locals.title = 'Learn some SQL';
	res.locals.lessonLists = precalc.lessonLists;
	res.render('index', {});
});

app.get('/about', function(req, res) {
	res.render('About', {});
});
app.get('/more-sql-resources', function(req, res) {
	res.locals.title = 'More SQL Resources | Learn some SQL';
	res.render('more-sql-resources');
});

app.get('/signout', function(req, res) {
	req.session.destroy();
	app.locals.links = everyonesLinks;
	res.redirect('/');
});

app.get('/signin', function(req, res) {
	res.locals.title = 'Are you Rick? | Learn some SQL';
	res.locals.message = false;
	res.render('sign-in');
});

app.post('/signin', function(req, res) {

	var message = false;

	if (req.session.attempts === undefined) {
		req.session.attempts = 0;
	}

	if (req.body.passphrase === 'yes') {
		req.session.isSignedIn = true;
		req.session.attempts = 0;
		app.locals.links = editorsLinks;
		res.redirect('/edit');
	} else {
		req.session.isSignedIn = false;
		req.session.attempts = req.session.attempts + 1;
		if (req.session.attempts === 1) {
			message = "That's not the passphrase";
		} else if (req.session.attempts > 1) {
			message = "That's not the passphrase either";
		}
		res.render('sign-in', {
			title: 'Learn some SQL',
			message: message,
			session: req.session
		});
	}

});

// mostly a client-side driven page
app.get('/lessonlist/edit', [editorsOnly], function (req, res) {
	res.locals.lessonLists = precalc.lessonLists;
	res.render('lesson-list-editor', {title: 'Edit some SQL'});
});
app.get('/edit', [editorsOnly], function (req, res) {
	res.locals.lessonLists = precalc.lessonLists;
	res.render('lesson-list-editor', {title: 'Edit some SQL'});
});

app.get('/migrate/:version', [editorsOnly], function (req, res) {
	var version = req.params.version;

	postgrator.setMigrationDirectory(__dirname + '/migrations');
	postgrator.setConnectionString(process.env.DATABASE_URL);
	postgrator.migrate(version, function(err, migrations) {
		if (err) {
			res.send(err)
			console.log('error running the migration');
			console.log(err);
		}
		res.send(migrations);
	});
});

/*
 *	Lists
 *
 *****************************************************************************/
lessonlistRoutes.setPrecalc(precalc); // this adds a reference to the precalc object from within lessonRoutes module
app.get('/lessonlist', lessonlistRoutes.getAll);
app.post('/lessonlist/id/:id', lessonlistRoutes.save);

/*
 *	Lesson
 *
 *****************************************************************************/
lessonRoutes.setPrecalc(precalc); // this adds a reference to the precalc object from within lessonRoutes module
app.put('/lesson', lessonRoutes.create);
app.get('/lesson', lessonRoutes.getAll);
app.get('/lesson/unlisted', lessonRoutes.getUnlisted);
app.get('/lesson/listid/:id', lessonRoutes.getByListId);
app.get('/lesson/:id/:format?', lessonRoutes.getByLessonId);
app.get('/edit/lesson/:id?', lessonRoutes.editById);
app.post('/lesson/:id', lessonRoutes.save);

/*
 *	AJAXy things
 *
 *****************************************************************************/

var checkBadSql = function (req, res, next) {

	var sqlQuery = req.body.sqlQuery || '';

	if (isBadSql(sqlQuery)) {

		// take note of the offenders remoteAddress (IP Address)
		// After so many attacks, they should be silenced.
		// We can't do this on the session object, because it'll reset on browser close/change.
		var offense = banHammer.recordOffense(req);

		// 403 == forbidden
		res.send(403, offense.message);
	} else {
		next();
	}

};

app.post('/query', checkBadSql, function(req, res) {

	var sqlQuery = req.body.sqlQuery || '';

	if (isBadSql(sqlQuery)) {
		// 403 is forbidden
		res.send(403, 'That kind of SQL is not allowed. Try anything else funny and you will be banned.');
	} else {

		if (sqlQuery.trim().length > 0) {

			appDb.query(sqlQuery, [], function(err, results) {
				if (err) {
					// 400 is bad request
					res.send(400, 'Query failed because
' + err.message);
				} else {
					res.send({
						results: results
					});
				}
			});

		} else {
			res.send(400, 'Query was not provided');
		}

	}

});

app.get('/req', function(req, res) {
	res.send({
		ip: req.ip,
		ips: req.ips,
		remoteAddress: req.connection.remoteAddress
	});
});

app.get('/superquery', [editorsOnly], function (req, res) {
	res.render('super-query', {title: 'Edit some SQL'});
});

app.post('/superquery', [editorsOnly], function (req, res) {
	var sqlQuery = req.body.sqlQuery || '';

	if (sqlQuery.trim().length > 0) {

		appDb.query(sqlQuery, [], function(err, results) {
			if (err) {
				// 400 is bad request
				res.send(400, 'Query failed because
' + err.message);
			} else {
				res.send({
					results: results
				});
			}
		});

	} else {
		res.send(400, 'Query was not provided');
	}

});

/*
 *	Error Routes and Stuff
 *
 *****************************************************************************/
// A Route for Creating a 500 Error (Useful to keep around)
app.get('/500', function(req, res){
	throw new Error('This is a 500 Error');
});

// A Route for Creating a 404 Error (Useful to keep around)
app.get('/404', function(req, res){
	throw new NotFound();
});

//app.get('/*', function(req, res){
	//throw new NotFound();
//});

function NotFound(msg){
    this.name = 'NotFound';
    Error.call(this, msg);
    Error.captureStackTrace(this, arguments.callee);
}

/* ============================================================
    The Server
=============================================================== */

http.createServer(app).listen(app.get('port'), function(){
	console.log("Express server listening on port " + app.get('port'));
});
<commit_msg>/query route to format dates before sending to client<commit_after>
/**
 * Module dependencies.
 */

var express = require('express')
  , lessonRoutes = require('./routes/lessonRoutes')
  , lessonlistRoutes = require('./routes/lessonlistRoutes')
  , http = require('http')
  , appDb = require('./lib/appDb')
  , isBadSql = require('./lib/is-bad-sql')
  , crypto = require('crypto')
  , fs = require('fs')
  , path = require('path')
  , banHammer = require('./lib/banHammer')
  , moment = require('moment')
  , postgrator = require('postgrator');

/* ============================================================
    load some environment variables if they are not present
	This really should be outside the app,
	and in a separate app running script... but...
=============================================================== */
if (!process.env.NODE_ENV || !process.env.DATABASE_URL) {
	console.log('Environment variable is missing - loading the .env');
	try {
		var envFile = fs.readFileSync(__dirname + '/.env', 'utf8');
		var envSettings = envFile.replace(/\r/g, '').split('\n');
		envSettings.forEach(function(setting) {
			keyvalue = setting.split('=');
			if (keyvalue.length == 2) {
				console.log('setting process.env.' + keyvalue[0] + ' = ' + keyvalue[1]);
				process.env[keyvalue[0]] = keyvalue[1];
			}
		});
	} catch (err) {
		console.log(err);
	}
}

/* ============================================================
    Postgrator stuff
=============================================================== */
if (!process.env.NODE_ENV) console.log('NODE_ENV not set');
if (!process.env.DATABASE_URL) console.log('DATABASE_URL not set');

postgrator.setMigrationDirectory(__dirname + '/migrations');
postgrator.setConnectionString(process.env.DATABASE_URL);
postgrator.migrate('012');

/* ============================================================
    Some Middleware
=============================================================== */
var editorsOnly = function (req, res, next) {
	if (req.session && req.session.isSignedIn) {
		next();
	} else {
		res.redirect('/signin');
	}
};

/* ============================================================
    Express Setup and stuff
=============================================================== */

var app = express();

app.configure(function(){
	app.set('port', process.env.PORT || 3000);
	app.set('views', __dirname + '/views');
	app.set('view engine', 'ejs');

	app.use(express.favicon());
	app.use(express.logger('dev'));
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(express.cookieParser('your secret here'));
	app.use(express.session());

	app.use(banHammer.handleBannedPeople);

	app.use(app.router);
	app.use(require('less-middleware')({ src: __dirname + '/public' }));
	app.use(express.static(path.join(__dirname, 'public')));

});

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

/* ============================================================
    PreCalc
	Basically a cache of all the lesson data.
	Should be refreshed each time a lesson or lessonlist is changed/added

	it looks like:
	precalc.lessonlists: [
		{
			listid: n,
			listname: '',
			listDescription: '',
			lessons: [
				{
					listid,
					listname,
					listdescription,
					listseq,
					lessonid,
					lessontitle,
					lessondescription,
					lessonseq
				}
			]
		}
	]
=============================================================== */

var precalc = {
	lessonLists: [],
	refreshLessonLists: function () {

		var sql = "SELECT ll.lessonlist_id AS listId, ll.name AS listName, ll.description AS listDescription, ll.seq AS listSeq, l.lesson_id AS lessonId, l.title AS lessonTitle, l.description AS lessonDescription, l.seq AS lessonSeq FROM lesson l JOIN lessonlist ll ON l.lessonlist_id = ll.lessonlist_id ORDER BY ll.seq, l.seq";

		appDb.query(sql, [], function(err, results) {
			if (err) {
				console.log('precalc.refreshLessonLists() failure to run query');
				precalc.lessonLists = [];
			} else {
				var lessonLists = [];
				var lessonListCounter = -1;

				for (i = 0; i < results.length; i++) {
					var lesson = results[i];

					if (lessonLists[lessonListCounter] && lessonLists[lessonListCounter].listname == lesson.listname) {
						lessonLists[lessonListCounter].lessons.push(lesson);

					} else {
						// we've approached a new list. Increment the lessonListcounter
						lessonListCounter = lessonListCounter + 1;
						// if currentList has lessons
						lessonLists[lessonListCounter] = {};
						lessonLists[lessonListCounter].listid = lesson.listid;
						lessonLists[lessonListCounter].listname = lesson.listname;
						lessonLists[lessonListCounter].listDescription = lesson.listdescription;
						lessonLists[lessonListCounter].lessons = [];
						lessonLists[lessonListCounter].lessons.push(lesson);
					}
				}

				precalc.lessonLists = lessonLists;
			}
		});

	}
};
precalc.refreshLessonLists();

/* ============================================================
    Some glocals?
=============================================================== */
var everyonesLinks = [
	{
		text: 'Lessons',
		url: '/'
	}, {
		text: 'About',
		url: '/about'
	}, {
		text: 'More SQL Resources',
		url: '/more-sql-resources'
	}
];
var editorsLinks = [
	{
		text: 'Lessons',
		url: '/'
	}, {
		text: 'superquery',
		url: '/superquery'
	}, {
		text: 'editor',
		url: '/edit'
	}, {
		text: 'sign out',
		url: '/signout'
	}
];
app.locals.links = everyonesLinks;
app.locals.title = 'Learn some SQL'; // Default title if none is provided
app.locals.makeTable = function (columns, rows) {
	var html = '
'
	html = html + '

';
	for (var c = 0; c < columns; c++) {
		html = html + '   	';
	}

	// close table header row, start body
	html = html + '

';

	for (var r = 0; r < rows; r++) {
		var rowHtml = '
'
		for (var c = 0; c < columns; c++) {
			rowHtml = rowHtml + ' 	';
		}
		rowHtml = rowHtml + '
';
		html = html + rowHtml;
	}

	// clost body and table
	html = html + '

';
	return html;
};

/* ============================================================
    The Routes
=============================================================== */

//app.get('/', routes.index);
app.get('/', function(req, res){
	//console.log('remoteAddress: ' + req.connection.remoteAddress);
	res.locals.title = 'Learn some SQL';
	res.locals.lessonLists = precalc.lessonLists;
	res.render('index', {});
});

app.get('/about', function(req, res) {
	res.render('About', {});
});
app.get('/more-sql-resources', function(req, res) {
	res.locals.title = 'More SQL Resources | Learn some SQL';
	res.render('more-sql-resources');
});

app.get('/signout', function(req, res) {
	req.session.destroy();
	app.locals.links = everyonesLinks;
	res.redirect('/');
});

app.get('/signin', function(req, res) {
	res.locals.title = 'Are you Rick? | Learn some SQL';
	res.locals.message = false;
	res.render('sign-in');
});

app.post('/signin', function(req, res) {

	var message = false;

	if (req.session.attempts === undefined) {
		req.session.attempts = 0;
	}

	if (req.body.passphrase === 'yes') {
		req.session.isSignedIn = true;
		req.session.attempts = 0;
		app.locals.links = editorsLinks;
		res.redirect('/edit');
	} else {
		req.session.isSignedIn = false;
		req.session.attempts = req.session.attempts + 1;
		if (req.session.attempts === 1) {
			message = "That's not the passphrase";
		} else if (req.session.attempts > 1) {
			message = "That's not the passphrase either";
		}
		res.render('sign-in', {
			title: 'Learn some SQL',
			message: message,
			session: req.session
		});
	}

});

// mostly a client-side driven page
app.get('/lessonlist/edit', [editorsOnly], function (req, res) {
	res.locals.lessonLists = precalc.lessonLists;
	res.render('lesson-list-editor', {title: 'Edit some SQL'});
});
app.get('/edit', [editorsOnly], function (req, res) {
	res.locals.lessonLists = precalc.lessonLists;
	res.render('lesson-list-editor', {title: 'Edit some SQL'});
});

app.get('/migrate/:version', [editorsOnly], function (req, res) {
	var version = req.params.version;

	postgrator.setMigrationDirectory(__dirname + '/migrations');
	postgrator.setConnectionString(process.env.DATABASE_URL);
	postgrator.migrate(version, function(err, migrations) {
		if (err) {
			res.send(err)
			console.log('error running the migration');
			console.log(err);
		}
		res.send(migrations);
	});
});

/*
 *	Lists
 *
 *****************************************************************************/
lessonlistRoutes.setPrecalc(precalc); // this adds a reference to the precalc object from within lessonRoutes module
app.get('/lessonlist', lessonlistRoutes.getAll);
app.post('/lessonlist/id/:id', lessonlistRoutes.save);

/*
 *	Lesson
 *
 *****************************************************************************/
lessonRoutes.setPrecalc(precalc); // this adds a reference to the precalc object from within lessonRoutes module
app.put('/lesson', lessonRoutes.create);
app.get('/lesson', lessonRoutes.getAll);
app.get('/lesson/unlisted', lessonRoutes.getUnlisted);
app.get('/lesson/listid/:id', lessonRoutes.getByListId);
app.get('/lesson/:id/:format?', lessonRoutes.getByLessonId);
app.get('/edit/lesson/:id?', lessonRoutes.editById);
app.post('/lesson/:id', lessonRoutes.save);

/*
 *	AJAXy things
 *
 *****************************************************************************/

var checkBadSql = function (req, res, next) {

	var sqlQuery = req.body.sqlQuery || '';

	if (isBadSql(sqlQuery)) {

		// take note of the offenders remoteAddress (IP Address)
		// After so many attacks, they should be silenced.
		// We can't do this on the session object, because it'll reset on browser close/change.
		var offense = banHammer.recordOffense(req);

		// 403 == forbidden
		res.send(403, offense.message);
	} else {
		next();
	}

};

app.post('/query', checkBadSql, function(req, res) {

	var sqlQuery = req.body.sqlQuery || '';

	if (isBadSql(sqlQuery)) {
		// 403 is forbidden
		res.send(403, 'That kind of SQL is not allowed. Try anything else funny and you will be banned.');
	} else {

		if (sqlQuery.trim().length > 0) {

			appDb.query(sqlQuery, [], function(err, results) {
				if (err) {
					// 400 is bad request
					res.send(400, 'Query failed because
' + err.message);
				} else {
					// Before we send results, we should change the dates
					// to strings formatted to how we want them to be.
					for (row in results) {
						for (column in results[row]) {
							var field = results[row][column];
							if (field instanceof Date) {
								var m = moment.utc(field);
								results[row][column] = m.format('MM/DD/YYYY HH:mm:SS');
							}
						}
					}
					res.send({
						results: results
					});
				}
			});

		} else {
			res.send(400, 'Query was not provided');
		}

	}

});

app.get('/req', function(req, res) {
	res.send({
		ip: req.ip,
		ips: req.ips,
		remoteAddress: req.connection.remoteAddress
	});
});

app.get('/superquery', [editorsOnly], function (req, res) {
	res.render('super-query', {title: 'Edit some SQL'});
});

app.post('/superquery', [editorsOnly], function (req, res) {
	var sqlQuery = req.body.sqlQuery || '';

	if (sqlQuery.trim().length > 0) {

		appDb.query(sqlQuery, [], function(err, results) {
			if (err) {
				// 400 is bad request
				res.send(400, 'Query failed because
' + err.message);
			} else {
				res.send({
					results: results
				});
			}
		});

	} else {
		res.send(400, 'Query was not provided');
	}

});

/*
 *	Error Routes and Stuff
 *
 *****************************************************************************/
// A Route for Creating a 500 Error (Useful to keep around)
app.get('/500', function(req, res){
	throw new Error('This is a 500 Error');
});

// A Route for Creating a 404 Error (Useful to keep around)
app.get('/404', function(req, res){
	throw new NotFound();
});

//app.get('/*', function(req, res){
	//throw new NotFound();
//});

function NotFound(msg){
    this.name = 'NotFound';
    Error.call(this, msg);
    Error.captureStackTrace(this, arguments.callee);
}

/* ============================================================
    The Server
=============================================================== */

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


<commit_before>var fs = require('fs')
var path = require('path')
var util = require('util')
var mqtt = require('mqtt');
var express = require('express')
var morgan = require('morgan')
var bodyParser = require('body-parser')
var parameterize = require('parameterize');

var config = require('./config/config.json');

var harmonyHubDiscover = require('harmonyhubjs-discover')
var harmony = require('harmonyhubjs-client')

var harmonyHubClient
var harmonyActivitiesCache = {}
var harmonyActivityUpdateInterval = 1*60*1000 // 1 minute
var harmonyActivityUpdateTimer

var harmonyState
var harmonyStateUpdateInterval = 5*1000 // 5 seconds
var harmonyStateUpdateTimer

var mqttClient = mqtt.connect(config.mqtt_host);
var TOPIC_NAMESPACE = "harmony-api"

var app = express()
app.use(bodyParser.urlencoded({ extended: false }))
app.use(express.static(path.join(__dirname, 'public')));

var logFormat = "'[:date[iso]] - :remote-addr - :method :url :status :response-time ms - :res[content-length]b'"
app.use(morgan(logFormat))

// Middleware
// Check to make sure we have a harmonyHubClient to connect to
var hasHarmonyHubClient = function(req, res, next) {
  if (hasHarmonyHubClient) {
    next()
  }else{
    res.status(500).json({message: "Can not connect to hub."})
  }
}
app.use(hasHarmonyHubClient)

var discover = new harmonyHubDiscover(61991)

discover.on('online', function(hubInfo) {
  // Triggered when a new hub was found
  console.log('Hub discovered ' + hubInfo.ip + '.')

  if (hubInfo.ip) {
    console.log('Stopping discovery.')
    discover.stop()

    harmony(hubInfo.ip).then(startProcessing)
  }

})

if (config['hub_ip']) {
  // Connect to hub:
  console.log('Connecting to Harmony hub at ' + config['hub_ip'])
  harmony(config['hub_ip']).then(startProcessing)
}else{
  // Look for hubs:
  console.log('Starting discovery.')
  discover.start()
}

// mqtt api

mqttClient.on('connect', function () {
  mqttClient.subscribe(TOPIC_NAMESPACE + '/command/+')
});

mqttClient.on('message', function (topic, message) {
  var commandPattern = new RegExp(/command\/(.*)/);
  var commandMatches = topic.match(commandPattern);

  if (commandMatches) {
    var action = commandMatches[1]
    var state = message.toString()

    if (action === 'start_activity') {
      activity = activityByName(state)

      if (activity) {
        startActivity(activity.id)
      }
    } else if (action === 'off') {
      off()
    }

  }

});

function startProcessing(harmonyClient){
  harmonyHubClient = harmonyClient

  // update the list of activities
  updateActivities()
  // then do it on the set interval
  clearInterval(harmonyActivityUpdateTimer)
  harmonyActivityUpdateTimer = setInterval(function(){ updateActivities() }, harmonyActivityUpdateInterval)

  // update the list of activities on the set interval
  clearInterval(harmonyStateUpdateTimer)
  harmonyStateUpdateTimer = setInterval(function(){ updateState() }, harmonyStateUpdateInterval)
}

function updateActivities(){
  if (!harmonyHubClient) { return }
  console.log('Updating activities.')

  harmonyHubClient.getActivities().then(function(activities){
    foundActivities = {}
    activities.some(function(activity) {
      foundActivities[activity.id] = {id: activity.id, slug: parameterize(activity.label).replace(/-/g, '_'), label:activity.label, isAVActivity: activity.isAVActivity}
    })

    harmonyActivitiesCache = foundActivities
  })
}

function updateState(){
  if (!harmonyHubClient) { return }
  console.log('Updating state.')

  var previousActivityName = currentActivityName()

  harmonyHubClient.getCurrentActivity().then(function(activityId){
    data = {off: true}

    activity = harmonyActivitiesCache[activityId]

    if (activityId != -1 && activity) {
      data = {off: false, current_activity: activity}
    }else{
      data = {off: true}
    }

    harmonyState = data

    // publish state if it has changed
    activityName = currentActivityName()

    if (activityName != previousActivityName) {
      state = parameterize(activityName).replace(/-/g, '_')
      publish('state', state, {retain: true});
    }

  })
}

function cachedHarmonyActivities(){
  return Object.keys(harmonyActivitiesCache).map(function(key) {
    return harmonyActivitiesCache[key]
  })
}

function currentActivity(){
  if (!harmonyHubClient || !harmonyState) { return null}

  return harmonyState.off ? 'off' : harmonyState.current_activity.label
}

function activityByName(activityName){
  var activity
  cachedHarmonyActivities().some(function(a) {
    if(a.label === activityName) {
      activity = a
      return true
    }
  })

  return activity
}

function activityBySlug(activitySlug){
  var activity
  cachedHarmonyActivities().some(function(a) {
    if(a.slug === activitySlug) {
      activity = a
      return true
    }
  })

  return activity
}

function off(){
  if (!harmonyHubClient) { return }

  harmonyHubClient.turnOff().then(function(){
    updateState()
  })
}

function startActivity(activityId){
  if (!harmonyHubClient) { return }

  harmonyHubClient.startActivity(activityId).then(function(){
    updateState()
  })
}

function publish(topic, message, options){
  topic = TOPIC_NAMESPACE + "/" + topic
  mqttClient.publish(topic, message, options);
}

app.get('/_ping', function(req, res){
  res.send('OK');
})

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

app.get('/activities', function(req, res){
  res.json({activities: cachedHarmonyActivities()})
})

app.get('/status', function(req, res){
  res.json(harmonyState)
})

app.put('/off', function(req, res){
  off()

  res.json({message: "ok"})
})

app.post('/start_activity', function(req, res){
  activity = activityByName(req.body.activity_name)

  if (activity) {
    startActivity(activity.id)

    res.json({message: "ok"})
  }else{
    res.status(404).json({message: "Not Found"})
  }
})

app.listen(process.env.PORT || 8282)
<commit_msg>always return the current activity<commit_after>var fs = require('fs')
var path = require('path')
var util = require('util')
var mqtt = require('mqtt');
var express = require('express')
var morgan = require('morgan')
var bodyParser = require('body-parser')
var parameterize = require('parameterize');

var config = require('./config/config.json');

var harmonyHubDiscover = require('harmonyhubjs-discover')
var harmony = require('harmonyhubjs-client')

var harmonyHubClient
var harmonyActivitiesCache = {}
var harmonyActivityUpdateInterval = 1*60*1000 // 1 minute
var harmonyActivityUpdateTimer

var harmonyState
var harmonyStateUpdateInterval = 5*1000 // 5 seconds
var harmonyStateUpdateTimer

var mqttClient = mqtt.connect(config.mqtt_host);
var TOPIC_NAMESPACE = "harmony-api"

var app = express()
app.use(bodyParser.urlencoded({ extended: false }))
app.use(express.static(path.join(__dirname, 'public')));

var logFormat = "'[:date[iso]] - :remote-addr - :method :url :status :response-time ms - :res[content-length]b'"
app.use(morgan(logFormat))

// Middleware
// Check to make sure we have a harmonyHubClient to connect to
var hasHarmonyHubClient = function(req, res, next) {
  if (hasHarmonyHubClient) {
    next()
  }else{
    res.status(500).json({message: "Can not connect to hub."})
  }
}
app.use(hasHarmonyHubClient)

var discover = new harmonyHubDiscover(61991)

discover.on('online', function(hubInfo) {
  // Triggered when a new hub was found
  console.log('Hub discovered ' + hubInfo.ip + '.')

  if (hubInfo.ip) {
    console.log('Stopping discovery.')
    discover.stop()

    harmony(hubInfo.ip).then(startProcessing)
  }

})

if (config['hub_ip']) {
  // Connect to hub:
  console.log('Connecting to Harmony hub at ' + config['hub_ip'])
  harmony(config['hub_ip']).then(startProcessing)
}else{
  // Look for hubs:
  console.log('Starting discovery.')
  discover.start()
}

// mqtt api

mqttClient.on('connect', function () {
  mqttClient.subscribe(TOPIC_NAMESPACE + '/command/+')
});

mqttClient.on('message', function (topic, message) {
  var commandPattern = new RegExp(/command\/(.*)/);
  var commandMatches = topic.match(commandPattern);

  if (commandMatches) {
    var action = commandMatches[1]
    var state = message.toString()

    if (action === 'start_activity') {
      activity = activityByName(state)

      if (activity) {
        startActivity(activity.id)
      }
    } else if (action === 'off') {
      off()
    }

  }

});

function startProcessing(harmonyClient){
  harmonyHubClient = harmonyClient

  // update the list of activities
  updateActivities()
  // then do it on the set interval
  clearInterval(harmonyActivityUpdateTimer)
  harmonyActivityUpdateTimer = setInterval(function(){ updateActivities() }, harmonyActivityUpdateInterval)

  // update the list of activities on the set interval
  clearInterval(harmonyStateUpdateTimer)
  harmonyStateUpdateTimer = setInterval(function(){ updateState() }, harmonyStateUpdateInterval)
}

function updateActivities(){
  if (!harmonyHubClient) { return }
  console.log('Updating activities.')

  harmonyHubClient.getActivities().then(function(activities){
    foundActivities = {}
    activities.some(function(activity) {
      foundActivities[activity.id] = {id: activity.id, slug: parameterize(activity.label).replace(/-/g, '_'), label:activity.label, isAVActivity: activity.isAVActivity}
    })

    harmonyActivitiesCache = foundActivities
  })
}

function updateState(){
  if (!harmonyHubClient) { return }
  console.log('Updating state.')

  var previousActivityName = currentActivityName()

  harmonyHubClient.getCurrentActivity().then(function(activityId){
    data = {off: true}

    activity = harmonyActivitiesCache[activityId]

    if (activityId != -1 && activity) {
      data = {off: false, current_activity: activity}
    }else{
      data = {off: true}
    }

    harmonyState = data

    // publish state if it has changed
    activityName = currentActivityName()

    if (activityName != previousActivityName) {
      state = parameterize(activityName).replace(/-/g, '_')
      publish('state', state, {retain: true});
    }

  })
}

function cachedHarmonyActivities(){
  return Object.keys(harmonyActivitiesCache).map(function(key) {
    return harmonyActivitiesCache[key]
  })
}

function currentActivity(){
  if (!harmonyHubClient || !harmonyState) { return null}

  return harmonyState.current_activity
}

function activityByName(activityName){
  var activity
  cachedHarmonyActivities().some(function(a) {
    if(a.label === activityName) {
      activity = a
      return true
    }
  })

  return activity
}

function activityBySlug(activitySlug){
  var activity
  cachedHarmonyActivities().some(function(a) {
    if(a.slug === activitySlug) {
      activity = a
      return true
    }
  })

  return activity
}

function off(){
  if (!harmonyHubClient) { return }

  harmonyHubClient.turnOff().then(function(){
    updateState()
  })
}

function startActivity(activityId){
  if (!harmonyHubClient) { return }

  harmonyHubClient.startActivity(activityId).then(function(){
    updateState()
  })
}

function publish(topic, message, options){
  topic = TOPIC_NAMESPACE + "/" + topic
  mqttClient.publish(topic, message, options);
}

app.get('/_ping', function(req, res){
  res.send('OK');
})

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

app.get('/activities', function(req, res){
  res.json({activities: cachedHarmonyActivities()})
})

app.get('/status', function(req, res){
  res.json(harmonyState)
})

app.put('/off', function(req, res){
  off()

  res.json({message: "ok"})
})

app.post('/start_activity', function(req, res){
  activity = activityByName(req.body.activity_name)

  if (activity) {
    startActivity(activity.id)

    res.json({message: "ok"})
  }else{
    res.status(404).json({message: "Not Found"})
  }
})

app.listen(process.env.PORT || 8282)
<|endoftext|>