<commit_before>
//Width and height
var kCellCount = 9;
var kNewChessCount = 3;
var kMinMatchBallCount = 5;

var board_data = [];
var game_data;

var svg_sel;
var board_sel;
var cells_sel;
var chesses_sel;

var hud_sel;
var score_sel;

var kEmptyColorId = -1;
// svg.on('click', function() {
//     var coords = d3.mouse(this);
//     // console.log(coords);
// });

// https://en.wikipedia.org/wiki/Web_colors#HTML_color_names
var chess_colors = [
    "blueviolet",
    "deeppink",
    "limegreen",
    "steelblue",
    "rosybrown",
    "fuchsia",
    "orange",
];

function random_index(max_value) {
    var random = d3.randomUniform(0, max_value);
    var impl = function() {
        var id = parseInt(random());
        return id;
    }
    return impl();
}

function random_color_id() {
    return random_index(chess_colors.length);
}

function random_board_id() {
    return random_index(board_data.length);
}

function set_chess_color(selection) {
    selection
        .transition()
        .duration(500)
        .attr("stroke", function(d, i) {
            if (i === selected_board_id) {
                return "black";
            }
            else {
                return "none";
            }
        })
        .attr("fill", function(d, i) {
            if (d.color_id === kEmptyColorId) {
                return "lightgrey";
            }
            return chess_colors[d.color_id];
            })
        ;
}

function place_new_chesses() {
    for (var i=0;i<kNewChessCount;i++) {
       if (game_data.chess_count >= kCellCount * kCellCount) {
            // TODO: enter game_over state
            // new_game();
            // svg_sel.remove();
            // svg_sel = undefined;
            // resize();
            return;
        }

        var board_id = random_board_id();
        while (board_data[board_id].color_id !== kEmptyColorId) {
            board_id = random_board_id();
        }
        game_data.chess_count ++;
        board_data[board_id].color_id = random_color_id();
        game_data.graph.nodes[board_id].weight = 0;
    }
}

function check_connected_chesses(board_id) {
    function check_dir(dx, dy) {
        var center_color_id = board_data[board_id].color_id;
        var result = [];
        var x = board_data[board_id].i+dx, y = board_data[board_id].j+dy;
        while (x >=0 && x < kCellCount && y >= 0 && y < kCellCount) {
            var idx = y * kCellCount + x;
            // console.log("x" + x + "y" + y);
            if (board_data[idx].color_id != center_color_id) break;
            result.push(idx);

            x+=dx;
            y+=dy;
        }
        return result;
    }
    var results = [
        // [0, +/-1]
        check_dir(0, +1).concat(check_dir(0, -1)),
        // [+/-1, 0]
        check_dir(+1, 0).concat(check_dir(-1, 0)),
        // [+/-1, +/-1]
        check_dir(+1, +1).concat(check_dir(-1, -1)),
        // [+/-1, -/+1]
        check_dir(+1, -1).concat(check_dir(-1, +1)),
    ];

    results.forEach(function (result) {
        // console.log(result);
        if (result.length >= 4) {
            board_data[board_id].color_id = kEmptyColorId;
            game_data.graph.nodes[board_id].weight = 1;
            for (var id of result) {
                game_data.graph.nodes[id].weight = 1;
                board_data[id].color_id = kEmptyColorId;
                game_data.score++;
            }
        }
    });
}

var selected_board_id = -1;
function update_board_data(board_id) {
    if (selected_board_id === -1) {
        if (board_data[board_id].color_id !== kEmptyColorId) {
            selected_board_id = board_id;
        }
    }
    else {
        if (board_data[board_id].color_id === kEmptyColorId) {
            // move #selected_board_id -> empty slot #board_id
            var start = game_data.graph.nodes[selected_board_id];
            var end = game_data.graph.nodes[board_id];
            var result = astar.search(game_data.graph, start, end);
            console.log(result);

            if (result.length > 0) {
                // can we move the chess there?
                board_data[board_id].color_id = board_data[selected_board_id].color_id;
                board_data[selected_board_id].color_id = kEmptyColorId;

                game_data.graph.nodes[selected_board_id].weight = 1;
                game_data.graph.nodes[board_id].weight = 0;

                check_connected_chesses(board_id);
                place_new_chesses();

                selected_board_id = -1;
            }
        }
        else {
            // selecting #board_id as #selected_board_id
            selected_board_id = board_id;
        }
    }

    chesses_sel.call(set_chess_color);
}

function new_game() {
    for (var i=0;i<kCellCount;i++) {
        for (var j=0;j<kCellCount;j++) {
            board_data[j*kCellCount + i] = {
                board_id: j * kCellCount + i,
                color_id: kEmptyColorId,
            }
        }
    }

    game_data = {
        "score": 0,
        "chess_count": 0,
        "graph" : new Graph([
            [1,1,1,1,1,1,1,1,1],
            [1,1,1,1,1,1,1,1,1],
            [1,1,1,1,1,1,1,1,1],
            [1,1,1,1,1,1,1,1,1],
            [1,1,1,1,1,1,1,1,1],
            [1,1,1,1,1,1,1,1,1],
            [1,1,1,1,1,1,1,1,1],
            [1,1,1,1,1,1,1,1,1],
            [1,1,1,1,1,1,1,1,1],
        ]),
    };
}

function resize() {
    console.log("resize");
    var width = window.innerWidth, height = window.innerHeight;
    var widthMajor = true;
    var svgMajorSize = height;
    if (width < height) {
        widthMajor = false;
        svgMajorSize = width;
    }
    var kMarginSize = svgMajorSize * 0.05;
    var kBoardSize = svgMajorSize - kMarginSize * 2;
    var kCellSize = kBoardSize / kCellCount;
    var kBallRadius = kCellSize * 0.5 * 0.9;

    if (svg_sel === undefined) {
        svg_sel = d3.select("body")
                .append("svg")
                ;

        new_game();

        board_sel = svg_sel.append("g")
                        .attr("id", "board");
        hud_sel = svg_sel.append("g")
                        .attr("id", "hud");
        score_sel = hud_sel.selectAll("text")
                .data(game_data)
                .enter().append("text")
                .text(function(d) { return d.score; })
                ;

        // https://developer.mozilla.org/en-US/docs/Web/SVG/Element/rect
        cells_sel = board_sel.selectAll("rect")
            .data(board_data)
            .enter().append("rect")
                .attr("fill", "lightgrey")
                .attr("stroke", "grey")
            ;

        // https://developer.mozilla.org/en-US/docs/Web/SVG/Element/circle
        chesses_sel = board_sel.selectAll("circle")
            .data(board_data)
            .enter().append("circle")
                .attr("stroke", "none")
                .attr("stroke-width", 2)
                .call(set_chess_color)
                .on('click', function(d){
                    // http://jsfiddle.net/GordyD/0o71rhug/1/
                    var ele = d3.select(this);
                    // console.log(this);
                    // console.log(ele);
                    // console.log(ele.datum());
                    var board_id = ele.datum().board_id;
                    update_board_data(board_id);
                    // ele.call(set_chess_color);
                });
    }

    for (var i=0;i<kCellCount;i++) {
        for (var j=0;j<kCellCount;j++) {
            board_data[j*kCellCount + i].cx = (i + 0.5) * kCellSize;
            board_data[j*kCellCount + i].cy = (j + 0.5) * kCellSize;
            board_data[j*kCellCount + i].x = i * kCellSize;
            board_data[j*kCellCount + i].y = j * kCellSize;
            board_data[j*kCellCount + i].i = i;
            board_data[j*kCellCount + i].j = j;
        }
    }

    svg_sel
        .transition()
        .attr("width", svgMajorSize)
        .attr("height", svgMajorSize)
        ;

    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Text_formatting
    board_sel
        .transition()
        .attr("transform", "translate(" + kMarginSize + ", " +  kMarginSize + ")")
        ;

    if (widthMajor) {
        hud_sel
            .transition()
            .attr("transform", "translate(" + (kMarginSize * 2 + kBoardSize) + ", " +  kMarginSize + ")")
            ;
    }
    else {
        hud_sel
            .transition()
            .attr("transform", "translate(" + kMarginSize + ", " + (kMarginSize * 2 + kBoardSize) + ")")
            ;
    }

    cells_sel
        .transition()
        .attr("x", function(d, i) { return d.x; })
        .attr("y", function(d, i) { return d.y; })
        .attr("width", kCellSize)
        .attr("height", kCellSize)
        ;

    chesses_sel
        .transition()
        .attr("cx", function(d, i) { return d.cx; })
        .attr("cy", function(d, i) { return d.cy; })
        .attr("r", kBallRadius)
        ;

}

// http://stackoverflow.com/questions/11942500/how-to-make-force-layout-graph-in-d3-js-responsive-to-screen-browser-size
window.addEventListener('resize', resize);
resize();
place_new_chesses();

<commit_msg>Add "score"<commit_after>
//Width and height
var kCellCount = 9;
var kNewChessCount = 3;
var kMinMatchBallCount = 5;

var board_data = [];
var game_data;

var svg_sel;
var board_sel;
var cells_sel;
var chesses_sel;

var hud_sel;
var score_sel;

var kEmptyColorId = -1;
// svg.on('click', function() {
//     var coords = d3.mouse(this);
//     // console.log(coords);
// });

// https://en.wikipedia.org/wiki/Web_colors#HTML_color_names
var chess_colors = [
    "blueviolet",
    "deeppink",
    "limegreen",
    "steelblue",
    "rosybrown",
    "dimgray",
    "goldenrod",
];

function random_index(max_value) {
    var random = d3.randomUniform(0, max_value);
    var impl = function() {
        var id = parseInt(random());
        return id;
    }
    return impl();
}

function random_color_id() {
    return random_index(chess_colors.length);
}

function random_board_id() {
    return random_index(board_data.length);
}

function set_chess_color(selection) {
    selection
        .transition()
        .duration(500)
        .attr("stroke", function(d, i) {
            if (i === selected_board_id) {
                return "black";
            }
            else {
                return "none";
            }
        })
        .attr("fill", function(d, i) {
            if (d.color_id === kEmptyColorId) {
                return "lightgrey";
            }
            return chess_colors[d.color_id];
            })
        ;
}

function set_game_score() {
    score_sel.text(function(d) { return "score: " + d.score; })
}

function place_new_chesses() {
    for (var i=0;i<kNewChessCount;i++) {
       if (game_data.chess_count >= kCellCount * kCellCount) {
            // TODO: enter game_over state
            // new_game();
            // svg_sel.remove();
            // svg_sel = undefined;
            // resize();
            return;
        }

        var board_id = random_board_id();
        while (board_data[board_id].color_id !== kEmptyColorId) {
            board_id = random_board_id();
        }
        game_data.chess_count ++;
        board_data[board_id].color_id = random_color_id();
        game_data.graph.nodes[board_id].weight = 0;
    }
}

function check_connected_chesses(board_id) {
    function check_dir(dx, dy) {
        var center_color_id = board_data[board_id].color_id;
        var result = [];
        var x = board_data[board_id].i+dx, y = board_data[board_id].j+dy;
        while (x >=0 && x < kCellCount && y >= 0 && y < kCellCount) {
            var idx = y * kCellCount + x;
            // console.log("x" + x + "y" + y);
            if (board_data[idx].color_id != center_color_id) break;
            result.push(idx);

            x+=dx;
            y+=dy;
        }
        return result;
    }
    var results = [
        // [0, +/-1]
        check_dir(0, +1).concat(check_dir(0, -1)),
        // [+/-1, 0]
        check_dir(+1, 0).concat(check_dir(-1, 0)),
        // [+/-1, +/-1]
        check_dir(+1, +1).concat(check_dir(-1, -1)),
        // [+/-1, -/+1]
        check_dir(+1, -1).concat(check_dir(-1, +1)),
    ];

    results.forEach(function (result) {
        // console.log(result);
        if (result.length >= 4) {
            board_data[board_id].color_id = kEmptyColorId;
            game_data.graph.nodes[board_id].weight = 1;
            game_data.score++;

            for (var id of result) {
                game_data.graph.nodes[id].weight = 1;
                board_data[id].color_id = kEmptyColorId;
                game_data.score++;
            }
        }
    });
}

var selected_board_id = -1;
function update_board_data(board_id) {
    if (selected_board_id === -1) {
        if (board_data[board_id].color_id !== kEmptyColorId) {
            selected_board_id = board_id;
        }
    }
    else {
        if (board_data[board_id].color_id === kEmptyColorId) {
            // move #selected_board_id -> empty slot #board_id
            var start = game_data.graph.nodes[selected_board_id];
            var end = game_data.graph.nodes[board_id];
            var result = astar.search(game_data.graph, start, end);
            // console.log(result);

            if (result.length > 0) {
                // can we move the chess there?
                board_data[board_id].color_id = board_data[selected_board_id].color_id;
                board_data[selected_board_id].color_id = kEmptyColorId;

                game_data.graph.nodes[selected_board_id].weight = 1;
                game_data.graph.nodes[board_id].weight = 0;

                check_connected_chesses(board_id);
                place_new_chesses();

                selected_board_id = -1;
            }
        }
        else {
            // selecting #board_id as #selected_board_id
            selected_board_id = board_id;
        }
    }

    chesses_sel.call(set_chess_color);
    set_game_score();
}

function new_game() {
    for (var i=0;i<kCellCount;i++) {
        for (var j=0;j<kCellCount;j++) {
            board_data[j*kCellCount + i] = {
                board_id: j * kCellCount + i,
                color_id: kEmptyColorId,
            }
        }
    }

    game_data = {
        "score": 0,
        "chess_count": 0,
        "graph" : new Graph([
            [1,1,1,1,1,1,1,1,1],
            [1,1,1,1,1,1,1,1,1],
            [1,1,1,1,1,1,1,1,1],
            [1,1,1,1,1,1,1,1,1],
            [1,1,1,1,1,1,1,1,1],
            [1,1,1,1,1,1,1,1,1],
            [1,1,1,1,1,1,1,1,1],
            [1,1,1,1,1,1,1,1,1],
            [1,1,1,1,1,1,1,1,1],
        ]),
    };
}

function resize() {
    console.log("resize");
    var width = window.innerWidth, height = window.innerHeight;
    var widthMajor = true;
    var svgMajorSize = height;
    if (width < height) {
        widthMajor = false;
        svgMajorSize = width;
    }
    var kMarginSize = svgMajorSize * 0.05;
    var kBoardSize = svgMajorSize - kMarginSize * 2;
    var kCellSize = kBoardSize / kCellCount;
    var kBallRadius = kCellSize * 0.5 * 0.9;

    if (svg_sel === undefined) {
        svg_sel = d3.select("body")
                .append("svg")
                ;

        new_game();

        board_sel = svg_sel.append("g")
                        .attr("id", "board");
        hud_sel = svg_sel.append("g")
                        .attr("id", "hud");
        score_sel = hud_sel.selectAll("text")
            .data([game_data])
            .enter().append("text")
            .attr("font-family", "sans-serif")
            .attr("font-size", "30")
            ;

        // https://developer.mozilla.org/en-US/docs/Web/SVG/Element/rect
        cells_sel = board_sel.selectAll("rect")
            .data(board_data)
            .enter().append("rect")
                .attr("fill", "lightgrey")
                .attr("stroke", "grey")
            ;

        // https://developer.mozilla.org/en-US/docs/Web/SVG/Element/circle
        chesses_sel = board_sel.selectAll("circle")
            .data(board_data)
            .enter().append("circle")
                .attr("stroke", "none")
                .attr("stroke-width", 4)
                .call(set_chess_color)
                .on('click', function(d){
                    // http://jsfiddle.net/GordyD/0o71rhug/1/
                    var ele = d3.select(this);
                    // console.log(this);
                    // console.log(ele);
                    // console.log(ele.datum());
                    var board_id = ele.datum().board_id;
                    update_board_data(board_id);
                    // ele.call(set_chess_color);
                });
    }

    for (var i=0;i<kCellCount;i++) {
        for (var j=0;j<kCellCount;j++) {
            board_data[j*kCellCount + i].cx = (i + 0.5) * kCellSize;
            board_data[j*kCellCount + i].cy = (j + 0.5) * kCellSize;
            board_data[j*kCellCount + i].x = i * kCellSize;
            board_data[j*kCellCount + i].y = j * kCellSize;
            board_data[j*kCellCount + i].i = i;
            board_data[j*kCellCount + i].j = j;
        }
    }

    svg_sel
        .transition()
        .attr("width", width)
        .attr("height", height)
        ;

    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Text_formatting
    board_sel
        .transition()
        .attr("transform", "translate(" + kMarginSize + ", " +  kMarginSize + ")")
        ;

    if (widthMajor) {
        hud_sel
            .transition()
            .attr("transform", "translate(" + (kMarginSize * 2 + kBoardSize) + ", " +  kMarginSize * 2 + ")")
            ;
    }
    else {
        hud_sel
            .transition()
            .attr("transform", "translate(" + kMarginSize * 2 + ", " + (kMarginSize * 2 + kBoardSize) + ")")
            ;
    }

    cells_sel
        .transition()
        .attr("x", function(d, i) { return d.x; })
        .attr("y", function(d, i) { return d.y; })
        .attr("width", kCellSize)
        .attr("height", kCellSize)
        ;

    chesses_sel
        .transition()
        .attr("cx", function(d, i) { return d.cx; })
        .attr("cy", function(d, i) { return d.cy; })
        .attr("r", kBallRadius)
        ;

}

// http://stackoverflow.com/questions/11942500/how-to-make-force-layout-graph-in-d3-js-responsive-to-screen-browser-size
window.addEventListener('resize', resize);
resize();
place_new_chesses();
set_game_score();
<|endoftext|>


<commit_before>const _ = require('lodash');
const Xantrex = require("./lib/xantrex.js").Xantrex;
const schedule = require('node-schedule');
const SunCalc = require('suncalc');
const axios = require('axios');
const isBefore = require('date-fns/is_before');
const isAfter = require('date-fns/is_after');
const isSameDay = require('date-fns/is_same_day');
const format = require('date-fns/format');
let times = {};
let lastReading = {
  date: new Date()
};

const api = axios.create({
  baseURL: process.env.XANTREX_STORE_URL,
  timeout: 1000,
});

/**
 * Get sunrise and sunset times
 */
function updateTimes() {
  times = SunCalc.getTimes(new Date(), -37, 144);
  console.log('Updating times');
}

/**
 * Read from the inverter
 */
function performReading() {
  let now = new Date();
  if (isAfter(now, times.sunset)) {
    console.log('Sun has set');
  }
  else if (isBefore(now, times.sunrise)) {
    console.log('Before sunrise');
  } else {
    console.log('Getting reading');
    let xantrex = new Xantrex("/dev/ttyUSB0", 9600);
    xantrex.connect().then(
      function () {
        xantrex.getSummary().then(
          function (result) {
            console.log(result);
            if (!isSameDay(now, lastReading.date)) {
              if (result.kwhtoday > 0.5) {
                console.log('Skipping yesterday\'s reading');
              }
            } else {
              lastReading = {
                date: now,
                reading: result
              };
              api.post(
                '/sensors-xantrex/reading/',
                _.extend(result, {timestamp: format(now)})
              );
              xantrex.disconnect();
            }
          });
      }).catch(function (error) {
      console.log(error);
    });
  }
}

/**
 * init
 */
updateTimes();
performReading();

const updateTimesSchedule = schedule.scheduleJob('0 0 * * *', updateTimes);

const j = schedule.scheduleJob('* * * * *', performReading);
<commit_msg>Daemon fixes<commit_after>const _ = require('lodash');
const Xantrex = require("./lib/xantrex.js").Xantrex;
const schedule = require('node-schedule');
const SunCalc = require('suncalc');
const axios = require('axios');
const isBefore = require('date-fns/is_before');
const isAfter = require('date-fns/is_after');
const isSameDay = require('date-fns/is_same_day');
const format = require('date-fns/format');
let times = {};
let lastReading = {
  date: new Date()
};

const api = axios.create({
  baseURL: process.env.XANTREX_STORE_URL,
  timeout: 1000,
});

/**
 * Get sunrise and sunset times
 */
function updateTimes() {
  times = SunCalc.getTimes(new Date(), -37, 144);
  console.log('Updating times');
}

/**
 * Read from the inverter
 */
function performReading() {
  let now = new Date();
  if (isAfter(now, times.sunset)) {
    console.log('Sun has set');
  }
  else if (isBefore(now, times.sunrise)) {
    console.log('Before sunrise');
  } else {
    console.log('Getting reading');
    let xantrex = new Xantrex("/dev/ttyUSB0", 9600);
    xantrex.connect().then(
      function () {
        xantrex.getSummary().then(
          function (result) {
            console.log(result);
            if (!isSameDay(now, lastReading.date)) {
		    console.log(lastReading);
              if (result.kwhtoday > 0.5) {
                console.log('Skipping yesterday\'s reading');
              }
            } else {
              lastReading = {
                date: now,
                reading: result
              };
              api.post(
                '/sensors-xantrex/reading/',
                _.extend(result, {timestamp: format(now)})
              );
            }
	    xantrex.disconnect();
          });
      }).catch(function (error) {
      console.log(error);
    });
  }
}

/**
 * init
 */
updateTimes();
performReading();

const updateTimesSchedule = schedule.scheduleJob('0 0 * * *', updateTimes);

const j = schedule.scheduleJob('* * * * *', performReading);
<|endoftext|>


<commit_before>if (process.env.NODE_ENV === 'production') {
  console.log('Starting newrelic application monitoring');
  require('newrelic');
}

/**
 * Set keys and URL's
 */

var routeApiUri = process.env.ROUTING_API_URL;
var ntbApiUri = process.env.NTB_API_URL;
var ntbApiKey = process.env.NTB_API_KEY;

var dntApiKey = process.env.DNT_CONNECT_KEY;

var sessionSecret = process.env.SESSION_SECRET || "0rdisObMCVXWawtji4B2iIGIKKqlsgAOPJhcHw4IREiCf7PGnAxY2isXfXd2Is7a";

/**
 * Module dependencies
 */

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var errorHandler = require('errorhandler');
var cookieSession = require('cookie-session');
var methodOverride = require('method-override');
var DNT = require('dnt-api');
var sentry = require('./lib/sentry');

// Start app
var app = module.exports = express();

// All environments
app.set('url', process.env.APP_URL);
app.set('port', process.env.APP_PORT || 8080);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json({extended: true, limit: '10mb'}));
app.use(methodOverride());
app.use(cookieParser(sessionSecret));
app.use(cookieSession({name: 'turadmin:sess', secret: sessionSecret}));
app.use(sentry.raven.middleware.express(sentry));
app.use(errorHandler({dumpExceptions: true, showStack: true}));

app.disable('x-powered-by');
app.set('x-powered-by', false);
app.disable('etag');
app.set('etag', false);

if (app.get('env') === 'development') {
    app.set('view cache', false);
}

/**
 * Routes and middleware
 */
var userGroupsFetcher = require('./routes/userGroupsFetcher')(app, express, {api: new DNT('Turadmin/1.0', dntApiKey)});
var restProxy = require('./routes/restProxy')(app, {ntbApiUri: ntbApiUri, ntbApiKey: ntbApiKey});

require('./routes/auth')(app, {
    dntApi: new DNT('Turadmin/1.0', dntApiKey),
    userGroupsFetcher: userGroupsFetcher
});

require('./routes/termsAndConditions')(app);

require('./routes/routes-index')(app, {
    dntApi: new DNT('Turadmin/1.0', dntApiKey),
    userGroupsFetcher: userGroupsFetcher,
    restProxy: restProxy
});

require('./routes/pois-index')(app, {
    dntApi: new DNT('Turadmin/1.0', dntApiKey),
    userGroupsFetcher: userGroupsFetcher,
    restProxy: restProxy
});

require('./routes/route')(app, restProxy, {
    routeApiUri: routeApiUri,
    dntApi: new DNT('Turadmin/1.0', dntApiKey),
    userGroupsFetcher: userGroupsFetcher
});

require('./routes/poi')(app, restProxy, {
    routeApiUri: routeApiUri,
    dntApi: new DNT('Turadmin/1.0', dntApiKey),
    userGroupsFetcher: userGroupsFetcher
});

require('./routes/groups')(app, {
    dntApi: new DNT('Turadmin/1.0', dntApiKey),
    userGroupsFetcher: userGroupsFetcher,
    restProxy: restProxy
});

require('./routes/lists')(app, {
    dntApi: new DNT('Turadmin/1.0', dntApiKey),
    userGroupsFetcher: userGroupsFetcher,
    restProxy: restProxy
});

require('./routes/chown')(app, {
    dntApi: new DNT('Turadmin/1.0', dntApiKey),
    restProxy: restProxy
});

// Redirect requests to '/' to '/turer'
app.use('/', function (req, res, next) {
    "use strict";

    // We do not want to redirect requests for files or XHR's Could be replaced
    // with regexp matching all file extensions except html Also, this should be
    // in the route below, but did not get that to work, because this route also
    // caught requests for files and stuff
    var isFileRequest = !!req.url.match(/^.*\.(css|js)$/);
    var isXhr = req.xhr;

    if (isFileRequest || isXhr) {
        res.status(404).end();
    } else {
        res.redirect(301, '/turer');
    }
});

// 404 handling
// Redirect requests for invalid URL's to /
app.use(function (req, res, next) {
    "use strict";

    res.redirect(307, '/');
});

if (!module.parent) {
    app.listen(app.get('port'), function () {
        "use strict";
        console.log('Express server listening on port ' + app.get('port'));
    });
}
<commit_msg>Allow loading map files<commit_after>if (process.env.NODE_ENV === 'production') {
  console.log('Starting newrelic application monitoring');
  require('newrelic');
}

/**
 * Set keys and URL's
 */

var routeApiUri = process.env.ROUTING_API_URL;
var ntbApiUri = process.env.NTB_API_URL;
var ntbApiKey = process.env.NTB_API_KEY;

var dntApiKey = process.env.DNT_CONNECT_KEY;

var sessionSecret = process.env.SESSION_SECRET || "0rdisObMCVXWawtji4B2iIGIKKqlsgAOPJhcHw4IREiCf7PGnAxY2isXfXd2Is7a";

/**
 * Module dependencies
 */

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var errorHandler = require('errorhandler');
var cookieSession = require('cookie-session');
var methodOverride = require('method-override');
var DNT = require('dnt-api');
var sentry = require('./lib/sentry');

// Start app
var app = module.exports = express();

// All environments
app.set('url', process.env.APP_URL);
app.set('port', process.env.APP_PORT || 8080);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json({extended: true, limit: '10mb'}));
app.use(methodOverride());
app.use(cookieParser(sessionSecret));
app.use(cookieSession({name: 'turadmin:sess', secret: sessionSecret}));
app.use(sentry.raven.middleware.express(sentry));
app.use(errorHandler({dumpExceptions: true, showStack: true}));

app.disable('x-powered-by');
app.set('x-powered-by', false);
app.disable('etag');
app.set('etag', false);

if (app.get('env') === 'development') {
    app.set('view cache', false);
}

/**
 * Routes and middleware
 */
var userGroupsFetcher = require('./routes/userGroupsFetcher')(app, express, {api: new DNT('Turadmin/1.0', dntApiKey)});
var restProxy = require('./routes/restProxy')(app, {ntbApiUri: ntbApiUri, ntbApiKey: ntbApiKey});

require('./routes/auth')(app, {
    dntApi: new DNT('Turadmin/1.0', dntApiKey),
    userGroupsFetcher: userGroupsFetcher
});

require('./routes/termsAndConditions')(app);

require('./routes/routes-index')(app, {
    dntApi: new DNT('Turadmin/1.0', dntApiKey),
    userGroupsFetcher: userGroupsFetcher,
    restProxy: restProxy
});

require('./routes/pois-index')(app, {
    dntApi: new DNT('Turadmin/1.0', dntApiKey),
    userGroupsFetcher: userGroupsFetcher,
    restProxy: restProxy
});

require('./routes/route')(app, restProxy, {
    routeApiUri: routeApiUri,
    dntApi: new DNT('Turadmin/1.0', dntApiKey),
    userGroupsFetcher: userGroupsFetcher
});

require('./routes/poi')(app, restProxy, {
    routeApiUri: routeApiUri,
    dntApi: new DNT('Turadmin/1.0', dntApiKey),
    userGroupsFetcher: userGroupsFetcher
});

require('./routes/groups')(app, {
    dntApi: new DNT('Turadmin/1.0', dntApiKey),
    userGroupsFetcher: userGroupsFetcher,
    restProxy: restProxy
});

require('./routes/lists')(app, {
    dntApi: new DNT('Turadmin/1.0', dntApiKey),
    userGroupsFetcher: userGroupsFetcher,
    restProxy: restProxy
});

require('./routes/chown')(app, {
    dntApi: new DNT('Turadmin/1.0', dntApiKey),
    restProxy: restProxy
});

// Redirect requests to '/' to '/turer'
app.use('/', function (req, res, next) {
    "use strict";

    // We do not want to redirect requests for files or XHR's Could be replaced
    // with regexp matching all file extensions except html Also, this should be
    // in the route below, but did not get that to work, because this route also
    // caught requests for files and stuff
    var isFileRequest = !!req.url.match(/^.*\.(css|js|map)$/);
    var isXhr = req.xhr;

    if (isFileRequest || isXhr) {
        res.status(404).end();
    } else {
        res.redirect(301, '/turer');
    }
});

// 404 handling
// Redirect requests for invalid URL's to /
app.use(function (req, res, next) {
    "use strict";

    res.redirect(307, '/');
});

if (!module.parent) {
    app.listen(app.get('port'), function () {
        "use strict";
        console.log('Express server listening on port ' + app.get('port'));
    });
}
<|endoftext|>


<commit_before>var hours =['6am','7am','8am','9am','10am','11am','12pm','1pm','2pm','3pm','4pm','5pm','6pm','7pm','8pm']
var firstAndPike = {

  minCustPerHour: 23,
  maxCustPerHour: 65,
  avgCookiesPerHour: 6.4,
  cookiesSoldPerHour: [],
  total: 0,

  randCustPerHour: function () {
    console.log('before running loop in randCustPerHour method: ' + this.cookiesSoldPerHour);
    for(var i = 0; i< hours.length;i++){
      var randomCustomersPerHour =  Math.ceil(((Math.random()*this.maxCustPerHour - this.minCustPerHour + 1)) + this.minCustPerHour);
      var cookiesPerHour = Math.ceil(randomCustomersPerHour * this.avgCookiesPerHour);
      this.cookiesSoldPerHour.push(cookiesPerHour);
      // console.log(this.cookiesSoldPerHour);
      //Math.floor(Math.random() * (max - min + 1)) + min;
    }
    console.log('after running loop in randCustPerHour method: ' + this.cookiesSoldPerHour);
  },
  sumTotal: function() {
    for(var i=0; i < hours.length;i++) {
      var sum = this.cookiesSoldPerHour[i];
      return sum;
    }
  },
  render: function() {
    this.randCustPerHour();// before you render so that there's content to render
    var ulEl = document.createElement('ul');
    ulEl.textContent = 'Data';
    document.body.appendChild(ulEl);

    for(var i = 0; i< hours.length; i++) {
      var liEl = document.createElement('li');
      liEl.textContent = hours[i] + this.cookiesSoldPerHour[i];
      ulEl.appendChild(liEl);

    }
  }

}

firstAndPike.render();
firstAndPike.randCustPerHour();
firstAndPike.cookiesSoldPerHour;
<commit_msg>finished total<commit_after>var hours =['6am','7am','8am','9am','10am','11am','12pm','1pm','2pm','3pm','4pm','5pm','6pm','7pm','8pm']
var firstAndPike = {

  minCustPerHour: 23,
  maxCustPerHour: 65,
  avgCookiesPerHour: 6.4,
  cookiesSoldPerHour: [],

  randCustPerHour: function () {
    console.log('before running loop in randCustPerHour method: ' + this.cookiesSoldPerHour);
    for(var i = 0; i< hours.length;i++){
      var randomCustomersPerHour =  Math.ceil(((Math.random()*this.maxCustPerHour - this.minCustPerHour + 1)) + this.minCustPerHour);
      var cookiesPerHour = Math.ceil(randomCustomersPerHour * this.avgCookiesPerHour);
      this.cookiesSoldPerHour.push(cookiesPerHour);
      // console.log(this.cookiesSoldPerHour);
      //Math.floor(Math.random() * (max - min + 1)) + min;
    }
    console.log('after running loop in randCustPerHour method: ' + this.cookiesSoldPerHour);
  },
  sumTotal: function() {
    var sum =0;
    for(var i=0; i < this.cookiesSoldPerHour.length;i++) {
      sum += this.cookiesSoldPerHour[i];
    }
    return sum;
  },
  render: function() {
    this.randCustPerHour();// before you render so that there's content to render
    var ulEl = document.createElement('ul');
    ulEl.textContent = 'Data';
    document.body.appendChild(ulEl);

    for(var i = 0; i< hours.length; i++) {
      var liEl = document.createElement('li');
      liEl.textContent = hours[i] + this.cookiesSoldPerHour[i];
      ulEl.appendChild(liEl);

    }
    var pEl =document.createElement('p');
    pEl.textContent = 'Total: ' + this.sumTotal();
    document.body.appendChild(pEl);
  }

}

firstAndPike.render();
firstAndPike.randCustPerHour();
firstAndPike.cookiesSoldPerHour;
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
var sets = require('simplesets');

app.use(express.static('static'));
app.set('view engine', 'jade');

var names = [];

// Initialize whitelist and black list
var white_list = new sets.Set();
load_file(white_list, 'special_names/whitelist.txt');
var black_list = new sets.Set();
load_file(black_list, 'special_names/blacklist.txt');

function load_file(s, file) {
  fs.readFile(file, 'utf8', function(err, data) {
    if (err) {
      return console.log(err);
    }

    t = data.split("\r\n");
    for (var i = 0; i < t.length; i++) {
      s.add(t[i].toLowerCase());
    }
    console.log("Finished loading " + file);
  });
};

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

app.get('/tree', function (req, res){
  res.render('tree', {names: names});
});

app.get('/moderator', function (req, res){
  res.render('moderator', {names: names});
});

io.on('connection', function(socket){
  console.log('A user connected from: ' + socket.handshake.address);

  // Run this function when the "verify name" channel recieves an entry
  socket.on('verify name', function(msg){
    // Send start message to console
    console.log('Attempting to add name ' + msg);

    // Create variables to assess the validity of the name
    var nameElements = msg.split(" ");
    var nameOnWhiteList = false;
    var nameOnBlackList = false;
    var nameScore = 0; // Use this to verify that all of the words are valid

    // Verify that all of the separate words in the name are on the whitelist
    var i;
    var numElements = nameElements.length;

    for(i = 0; i < numElements; i++)
    {
      if(white_list.has(nameElements[i].toLowerCase()))
      {
        nameScore += 1;
      }
    }

    if(nameScore == nameElements.length)
    {
      nameOnWhiteList = true;

      // Send the name to the tree
      io.emit('add name', msg)

      console.log('The name ' + msg + ' is on the whitelist');
    }

    // Verify that the name as a whole is on the blacklist
    if (black_list.has(msg.toLowerCase())) {
      // Show unaccepted name notification
      io.emit('blacklisted name', msg);

      nameOnBlackList = true;

      console.log('The word ' + msg + ' is on the blacklist');
    }

    // Verify that the name is not on either list
    if(!nameOnWhiteList && !nameOnBlackList)
    {
      // Send the name to the moderator to verify
      io.emit('moderate name', msg)

      console.log('The name ' + msg + ' was sent to the moderator');
    }
  });

  // Send the name to the tree
  socket.on('add name', function(msg){
    // Deserialize parameter
    var nameInfo = JSON.parse(msg);

    // Check if the name is accepted by the moderator
    if(nameInfo[1])
    {

      // Add the various words in the name to the whitelist
      addWhitelistName(name);

      // Add the current name to the list of names
      names.append(msg);
    }
    else
    {
      // Add the name to the blacklist
      black_list.add(name);
    }
  });
});

function addWhitelistName(name)
{
  var nameElements = name.split(" ");
  var i;
  var numEleNames = nameElements.length;

  // Go through all of the words in the name
  for(i = 0; i < numEleNames; i++)
  {
    // Verify whether the word is greater than 3 characters
    var word = nameElements[i];
    if(word.length > 2)
    {
      // Add the current word to the whitelist
      white_list.add(word.toLowerCase());
    }
  }
}

http.listen(3000, function(){
  console.log('Listening on port 3000!');
});
<commit_msg>Server: Add debug messages<commit_after>var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
var sets = require('simplesets');

app.use(express.static('static'));
app.set('view engine', 'jade');

var names = [];

// Initialize whitelist and black list
var white_list = new sets.Set();
load_file(white_list, 'special_names/whitelist.txt');
var black_list = new sets.Set();
load_file(black_list, 'special_names/blacklist.txt');

function load_file(s, file) {
  fs.readFile(file, 'utf8', function(err, data) {
    if (err) {
      return console.log(err);
    }

    t = data.split("\r\n");
    for (var i = 0; i < t.length; i++) {
      s.add(t[i].toLowerCase());
    }
    console.log("Finished loading " + file);
  });
};

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

app.get('/tree', function (req, res){
  res.render('tree', {names: names});
});

app.get('/moderator', function (req, res){
  res.render('moderator', {names: names});
});

io.on('connection', function(socket){
  console.log('A user connected from: ' + socket.handshake.address);

  // Run this function when the "verify name" channel recieves an entry
  socket.on('verify name', function(msg){
    // Send start message to console
    console.log('Attempting to add name ' + msg);

    // Create variables to assess the validity of the name
    var nameElements = msg.split(" ");
    var nameOnWhiteList = false;
    var nameOnBlackList = false;
    var nameScore = 0; // Use this to verify that all of the words are valid

    // Verify that all of the separate words in the name are on the whitelist
    var i;
    var numElements = nameElements.length;

    for(i = 0; i < numElements; i++)
    {
      if(white_list.has(nameElements[i].toLowerCase()))
      {
        nameScore += 1;
      }
    }

    if(nameScore == nameElements.length)
    {
      nameOnWhiteList = true;

      // Send the name to the tree
      io.emit('add name', msg)

      console.log('The name ' + msg + ' is on the whitelist');
    }

    // Verify that the name as a whole is on the blacklist
    if (black_list.has(msg.toLowerCase())) {
      // Show unaccepted name notification
      io.emit('blacklisted name', msg);

      nameOnBlackList = true;

      console.log('The word ' + msg + ' is on the blacklist');
    }

    // Verify that the name is not on either list
    if(!nameOnWhiteList && !nameOnBlackList)
    {
      // Send the name to the moderator to verify
      io.emit('moderate name', msg)

      console.log('The name ' + msg + ' was sent to the moderator');
    }
  });

  // Send the name to the tree
  socket.on('add name', function(msg){
    // Deserialize parameter
    var nameInfo = JSON.parse(msg);

    // Check if the name is accepted by the moderator
    if(nameInfo[1])
    {
      console.log('The name ' + name + ' has been whitelisted');

      // Add the various words in the name to the whitelist
      addWhitelistName(name);

      // Add the current name to the list of names
      names.append(msg);
    }
    else
    {
      console.log('The name ' + name + ' has been blacklisted');

      // Add the name to the blacklist
      black_list.add(name);
    }
  });
});

function addWhitelistName(name)
{
  var nameElements = name.split(" ");
  var i;
  var numEleNames = nameElements.length;

  // Go through all of the words in the name
  for(i = 0; i < numEleNames; i++)
  {
    // Verify whether the word is greater than 3 characters
    var word = nameElements[i];
    if(word.length > 2)
    {
      // Add the current word to the whitelist
      white_list.add(word.toLowerCase());
    }
  }
}

http.listen(3000, function(){
  console.log('Listening on port 3000!');
});
<|endoftext|>


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

var app = connect()
  .use(connect.static('public'))
  .use(function(req, res){
    res.end('hello world\n');
  })

var port = Number(process.env.PORT || 5000);

console.log("Server listening on http://0.0.0.0:"+port);

http.createServer(app).listen(port);
<commit_msg>Not found code<commit_after>var http = require('http'),
    connect = require('connect');

var app = connect()
  .use(connect.static('public'))
  .use(function(req, res){
    res.statusCode = 404;
    res.end("Not found!");
  })

var port = Number(process.env.PORT || 5000);

console.log("Server listening on http://0.0.0.0:"+port);

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


<commit_before>// set up for final # of correct answers at end
var userGotQRight = 0;
var userBestPossibleScore = 7;

// greeting and start of quiz
var userName = prompt('Hi! Thanks for visiting my About Me page! What is your name?');
alert('Nice to meet you ' + userName + ', you\'re shoes are great.\n\nI\'m going to ask you five questions about me. Good luck.');

// -------------------
// questions 1-5 reworked into multidimensional array and loop
// -------------------

var quizArray = [
  [
    'Question #1: Do I have a dog?',
    'no',
    userName + '! You got it right! I am indeed dog-less.',
    'I\'m so sorry ' + userName + ', you are incorrect. I like dogs but I don\'t have any of my own.'
  ],
  [
    'Question #2: Do I like four-leaf clovers?',
    'yes',
    'You are correct ' + userName + '! May the luck be with you.',
    'Sadly, ' + userName + ' you are wrong. Better luck next time.'
  ],
  [
    'Question #3: Do I live in San Francisco?',
    'no',
    'Correct, ' + userName + '! I live in Seattle.',
    'Oh no ' + userName + ' you are so wrong! I really, really didn\'t like living there.'
  ],
  [
    'Question #4: Do I like Halloween?',
    'yes',
    userName + ' you are correct. I LOVE Halloween!',
    'You are wrong, ' + userName + '. You must be one of those Christmas-lovers.'
  ],
  [
    'Question #5: Do I like pizza?',
    'yes',
    'Duh, of course I like pizza. Want to grab a slice ' + userName + '?',
    'Gasp! You are so very very incorrect. Pizza 4evr. ' + userName + ' I\'m disappointed.'
  ]
];

for (var i = 0; i < quizArray.length; i++) {
  var userAnswer = prompt(quizArray[i][0]);
  var correctAnswer = quizArray[i][1];
  userAnswer = userAnswer.toLowerCase();
  correctAnswer = correctAnswer.toLowerCase();
  if ((userAnswer === correctAnswer) || (userAnswer === correctAnswer[0])) {
    alert(quizArray[i][2]);
    userGotQRight ++;
  } else {
    alert(quizArray[i][3]);
  }
}

// -------------------
// question 6 - guess the number
// -------------------

var myNumber = Math.floor((Math.random() * 10) + 1);
var userNumber = parseInt(prompt('I\'ve summoned a random number between 1 and 10, you have four tries to guess what it is. Good luck:'));

for (var i = 0; i < 4; i++) {
  if (i === 3){
    alert('ALL ANSWERS ARE WRONG\n\nThe secret number was ' + myNumber + '.');
    break;
  } else if (userNumber === myNumber) {
    alert('Wowsers! You guessed the secret number, it was indeed ' + myNumber + '!');
    userGotQRight ++;
    break;
  } else if (userNumber < myNumber) {
    userNumber = parseInt(prompt('Too low, enter something a wee bit higher.'));
  } else if (userNumber > myNumber) {
    userNumber = parseInt(prompt('So close, try a lower number.'));
  } else {
    // if answer is NaN let them know, don't let that count against their amount of guesses
    i--;
    userNumber = parseInt(prompt('That, my dear friend, is not a number! Try again, gimme a number.'));
  }
}

// -------------------
// question 7 - countries
// -------------------

var countriesVisited = ['England', 'Ireland', 'Wales', 'Scotland', 'Italy', 'Belgium', 'Canada'];
var countriesGuessed = prompt('Alright ' + userName + ', guess a country that I have visited, you have six tries. Go on. Enter one now:');
var gotOneRight = false;

for (var i = 0; i < 5; i++) {
  for (var j = 0; j < countriesVisited.length; j++) {
    if (countriesGuessed.toLowerCase() === countriesVisited[j].toLowerCase()) {
      gotOneRight = true;
      break;
    }
  }
  if (gotOneRight == false) {
    countriesGuessed = prompt('Sorry that was incorrect. Try again:');
  }
}

if (gotOneRight) {
  alert('Congrats! ' + countriesVisited[j] + ' is one of the places I\'ve traveled to.');
  userGotQRight ++;
} else {
  alert('Sorry, you did not guess any of the countries.');
}

// function to print out list of contries
var listOfCountries = '';
var h = 0;

function listingCountries() {
  while (h < countriesVisited.length) {
    if (h === countriesVisited.length - 1) {
      listOfCountries += 'and ' + countriesVisited[h] + '.';
      h++;
    } else {
      listOfCountries += countriesVisited[h] + ', ';
      h++;
    }
  }
  return listOfCountries;
}

alert('Here are all the countries I have visited: ' + listingCountries() + ' They are all good beer-drinking countries.');

// -------------------
// final tally of correct answers
// -------------------

function userScoreMsg() {
  var userScoreMsgString = userName + ' you got ' + userGotQRight + ' out of ' + userBestPossibleScore + ' trivia questions correct.';
  return userScoreMsgString;
}

if (userGotQRight === userBestPossibleScore) {
  alert(userScoreMsg() + ' Wow! You did great!\n\n* * * GOLD STAR * * *');
} else if (userGotQRight === 0) {
  alert(userScoreMsg() + ' I\'m disappointed, it\'s like you don\'t know me at all.');
} else if (userGotQRight <= Math.floor(userBestPossibleScore / 2)) {
  alert(userScoreMsg() + ' You tried hard but this isn\'t a victory. Here, have a door prize.');
} else {
  alert(userScoreMsg() + ' Not too bad!');
}
<commit_msg>changed #7 to for loop, rough but working<commit_after>// set up for final # of correct answers at end
var userGotQRight = 0;
var userBestPossibleScore = 7;

// greeting and start of quiz
var userName = prompt('Hi! Thanks for visiting my About Me page! What is your name?');
alert('Nice to meet you ' + userName + ', you\'re shoes are great.\n\nI\'m going to ask you five questions about me. Good luck.');

// -------------------
// questions 1-5 reworked into multidimensional array and loop
// -------------------

var quizArray = [
  [
    'Question #1: Do I have a dog?',
    'no',
    userName + '! You got it right! I am indeed dog-less.',
    'I\'m so sorry ' + userName + ', you are incorrect. I like dogs but I don\'t have any of my own.'
  ],
  [
    'Question #2: Do I like four-leaf clovers?',
    'yes',
    'You are correct ' + userName + '! May the luck be with you.',
    'Sadly, ' + userName + ' you are wrong. Better luck next time.'
  ],
  [
    'Question #3: Do I live in San Francisco?',
    'no',
    'Correct, ' + userName + '! I live in Seattle.',
    'Oh no ' + userName + ' you are so wrong! I really, really didn\'t like living there.'
  ],
  [
    'Question #4: Do I like Halloween?',
    'yes',
    userName + ' you are correct. I LOVE Halloween!',
    'You are wrong, ' + userName + '. You must be one of those Christmas-lovers.'
  ],
  [
    'Question #5: Do I like pizza?',
    'yes',
    'Duh, of course I like pizza. Want to grab a slice ' + userName + '?',
    'Gasp! You are so very very incorrect. Pizza 4evr. ' + userName + ' I\'m disappointed.'
  ]
];

// line below is on/off for testing REMOVE IT
for (var i = 0; i < 0; i++) {
// for (var i = 0; i < quizArray.length; i++) {
  var userAnswer = prompt(quizArray[i][0]);
  var correctAnswer = quizArray[i][1];
  userAnswer = userAnswer.toLowerCase();
  correctAnswer = correctAnswer.toLowerCase();
  if ((userAnswer === correctAnswer) || (userAnswer === correctAnswer[0])) {
    alert(quizArray[i][2]);
    userGotQRight ++;
  } else {
    alert(quizArray[i][3]);
  }
}

// -------------------
// function to announce that user has X number of guesses left, used in question 6 and 7
// -------------------

//not to self make sure # is a universal variable

// -------------------
// question 6 - guess the number
// -------------------

var j = 0;
var guessedTheNumber = false;
var myNumber = Math.floor((Math.random() * 10) + 1);
var userNumber = parseInt(prompt('I\'ve summoned a random number between 1 and 10, you have four tries to guess what it is. Good luck:'));

/* TEMPORARILY WALLING OFF MY ATTEMPT AT A WHILE LOOP FOR Q6
while ((j < 3) && (guessedTheNumber === false)) {
  if (userNumber === myNumber) {
    //alert Congrats
    //userGotQRight++;
    //break;
    alert('Wowsers! You guessed the secret number, it was indeed ' + myNumber + '!');
    userGotQRight ++;
    break;
  } else if (userNumber < myNumber) {
    //alert try higher number
    userNumber = parseInt(prompt('Too low, enter something a wee bit higher.'));
    j++;
  } else if (userNumber > myNumber) {
    //alert try lower number
    userNumber = parseInt(prompt('So close, try a lower number.'));
    j++;
  }
  //alert ALL GUESSES ARE WRONG
  alert('ALL GUESSES ARE WRONG\n\nThe secret number was ' + myNumber + '.');
}
*/

// the line below is on/off for testing REMOVE IT
for (var i = 0; i < 0; i++) {
// for (var i = 0; i < 4; i++) {
  if (i === 3){
    alert('ALL ANSWERS ARE WRONG\n\nThe secret number was ' + myNumber + '.');
    break;
  } else if (userNumber === myNumber) {
    alert('Wowsers! You guessed the secret number, it was indeed ' + myNumber + '!');
    userGotQRight ++;
    break;
  } else if (userNumber < myNumber) {
    userNumber = parseInt(prompt('Too low, enter something a wee bit higher.'));
  } else if (userNumber > myNumber) {
    userNumber = parseInt(prompt('So close, try a lower number.'));
  } else {
    // if answer is NaN let them know, don't let that count against their amount of guesses
    i--;
    userNumber = parseInt(prompt('That, my dear friend, is not a number! Try again, gimme a number.'));
  }
}

// -------------------
// question 7 - countries
// -------------------

var countriesVisited = ['England', 'Ireland', 'Wales', 'Scotland', 'Italy', 'Belgium', 'Canada'];
var countriesGuessed = prompt('Alright ' + userName + ', guess a country that I have visited, you have six tries. Go on. Enter one now:');
var gotOneRight = false;

// the line below is on/off for testing REMOVE IT
// for (var i = 0; i < 0; i++) {
for (var i = 0; i < 5; i++) {
  for (var j = 0; j < countriesVisited.length; j++) {
    if (countriesGuessed.toLowerCase() === countriesVisited[j].toLowerCase()) {
      gotOneRight = true;
      break;
    }
  }
  if (gotOneRight == false) {
    countriesGuessed = prompt('Sorry that was incorrect. Try again:');
  }
}

if (gotOneRight) {
  alert('Congrats! ' + countriesVisited[j] + ' is one of the places I\'ve traveled to.');
  userGotQRight ++;
} else {
  alert('Sorry, you did not guess any of the countries.');
}

// function to print out list of contries
var listOfCountries = '';

function listingCountries() {
  for (var h = 0; h < countriesVisited.length; h++) {
    if (h < countriesVisited.length - 1) {
      listOfCountries += countriesVisited[h] + ', ';
      console.log('h is ' + h + ' and string is ' + listOfCountries);
    } else {
      listOfCountries += 'and ' + countriesVisited[h] + '.';
      console.log('h is ' + h + ' and string is ' + listOfCountries);
      return listOfCountries;
    }
  }
}

/* TEMPORARY WALL OF WHILE LOOP
function listingCountries() {
  while (h < countriesVisited.length) {
    if (h === countriesVisited.length - 1) {
      listOfCountries += 'and ' + countriesVisited[h] + '.';
      h++;
    } else {
      listOfCountries += countriesVisited[h] + ', ';
      h++;
    }
  }
  return listOfCountries;
}
*/

alert('Here are all the countries I have visited: ' + listingCountries() + ' They are all good beer-drinking countries.');

// -------------------
// final tally of correct answers
// -------------------

function userScoreMsg() {
  var userScoreMsgString = userName + ' you got ' + userGotQRight + ' out of ' + userBestPossibleScore + ' trivia questions correct.';
  return userScoreMsgString;
}

if (userGotQRight === userBestPossibleScore) {
  alert(userScoreMsg() + ' Wow! You did great!\n\n* * * GOLD STAR * * *');
} else if (userGotQRight === 0) {
  alert(userScoreMsg() + ' I\'m disappointed, it\'s like you don\'t know me at all.');
} else if (userGotQRight <= Math.floor(userBestPossibleScore / 2)) {
  alert(userScoreMsg() + ' You tried hard but this isn\'t a victory. Here, have a door prize.');
} else {
  alert(userScoreMsg() + ' Not too bad!');
}
<|endoftext|>


<commit_before>var express = require('express');
var mongoose = require('mongoose');
var app = express();
var authors = require('./controller/authors');
var books = require('./controller/books');

var mongourl;
app.configure(function () {
    app.use(express.logger('dev'));     /* 'default', 'short', 'tiny', 'dev' */
    app.use(express.bodyParser());
    var tungus = require('tungus');
    mongourl = "tingodb:///tmp";
});

app.configure('local', function () {
    app.use(express.logger('dev'));     /* 'default', 'short', 'tiny', 'dev' */
    app.use(express.bodyParser());
    var mongodb = require('mongodb');
    mongourl = "mongodb://localhost/bookapp";
});

app.configure('prod', function () {
    app.use(express.logger('dev'));     /* 'default', 'short', 'tiny', 'dev' */
    app.use(express.bodyParser());
    var mongodb = require('mongodb');
    var env = JSON.parse(process.env.VCAP_SERVICES);
    mongourl = ['mongodb-1.8'][0]['credentials'];
});

mongoose.connect(mongourl);

app.get('/rest/authors', authors.list);
app.get('/rest/authors/:id', authors.read);
app.post('/rest/authors', authors.create);
app.put('/rest/authors/:id', authors.update);
app.delete('/rest/authors/:id', authors.delete);

app.get('/rest/books', books.list);
app.get('/rest/books/:id', books.read);
app.post('/rest/books', books.create);
app.put('/rest/books/:id', books.update);
app.delete('/rest/books/:id', books.delete);

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

app.listen(process.env.PORT);
console.log('Listening on port '+process.env.PORT+'...');<commit_msg>environment configuration<commit_after>var express = require('express');
var app = express();

console.log("**** ENV: "+app.get('env'));

var mongourl;
app.configure('development', function () {
    app.use(express.logger('dev'));
    useTingo = true;
    mongourl = "tingodb:///tmp";
    port = 8080
});

app.configure('cloud9', function () {
    app.use(express.logger('dev'));
    useTingo = true;
    mongourl = "tingodb:///tmp";
    port = process.env.PORT;
});

app.configure('local', function () {
    app.use(express.logger('dev'));
    useTingo = false;
    var mongodb = require('mongodb');
    mongourl = "mongodb://localhost/bookapp";
    port = 8080
});

app.configure('production', function () {
    app.use(express.logger('default'));
    useTingo = false;
    var mongodb = require('mongodb');
    var env = JSON.parse(process.env.VCAP_SERVICES);
    mongourl = ['mongodb-1.8'][0]['credentials'];
    port = process.env.VCAP_APP_PORT;
});

if (useTingo) {
    var tungus = require('tungus');
}
var mongoose = require('mongoose');
var authors = require('./controller/authors');
var books = require('./controller/books');

mongoose.connect(mongourl);

app.use(express.bodyParser());
app.get('/rest/authors', authors.list);
app.get('/rest/authors/:id', authors.read);
app.post('/rest/authors', authors.create);
app.put('/rest/authors/:id', authors.update);
app.delete('/rest/authors/:id', authors.delete);

app.get('/rest/books', books.list);
app.get('/rest/books/:id', books.read);
app.post('/rest/books', books.create);
app.put('/rest/books/:id', books.update);
app.delete('/rest/books/:id', books.delete);

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

app.listen(port);
console.log('Listening on port '+port+'...');<|endoftext|>


<commit_before>var config = require('./config.js');
var ip = config.ip;
var port = config.port;
var express = require('express');
var app = express();
var server = app.listen(port);
var ejs = require('ejs');
var bbcode = require('bbcode');
var io = require('socket.io').listen(server);
io.set('log level', 1);
var sys = require('sys')
var exec = require('child_process').exec;

app.set("view options", {layout: false});
app.use(express.json());
app.use(express.static(__dirname + '/public'));

process.on('SIGINT', function() {
  console.log( "\nShutting down from manual SIGINT (Ctrl-C), NOW." );
  io.sockets.emit('annouce', {message : 'SHUTTING DOWN, NOW!'});
  process.exit();
});

process.once('SIGUSR2', function () {
  gracefulShutdown(function () {
    process.kill(process.pid, 'SIGUSR2');
  });
});

function gracefulShutdown(kill){
  console.log( "\nShutting down from nodemon SIGUSR2 (RESTART) in 10 seconds..." );
  io.sockets.emit('annouce', {message : 'RESTARTING IN 10 SECONDS!'});
  setTimeout(function(){kill()}, 10000);
}

app.post('/gitpull', function(req, res) {
  //GitHub push hook
  res.end();
  io.sockets.emit('annouce', {message : 'SYSTEM UPDATE INITIATED...'});
  function puts(error, stdout, stderr) {sys.puts(stdout)}
  exec("git reset --hard HEAD", puts);
  exec("git pull", puts);
  var arr = req.body.commits[0].modified;
  if((arr.join(',').indexOf("app.min.js") > -1) || (arr.join(',').indexOf("app.min.css") > -1)){
    io.sockets.emit('annouce', {message : 'SYSTEM UPDATE COMPLETE, BROWSER RELOAD IS NECCESARY.'});
  } else {
    io.sockets.emit('annouce', {message : 'SYSTEM UPDATE COMPLETE, BROWSER RELOAD IS NOT NECCESARY.'});
  }
});

app.get('*', function(req, res) {
  res.render('index.ejs', {
   ip: ip
 });
});

var users = [];

process.stdin.resume();
process.stdin.setEncoding('utf8');

process.stdin.on('data', function (chunk) {
 io.sockets.emit('annouce', {message : '' + chunk.toUpperCase() + ''});
});

io.sockets.on('connection', function (socket) {
  function broadcast(data) {
    io.sockets.emit('annouce', {message : data});
  }

  function parseServerCommand(data) {
    var res = data.message.trim().split(" ");

    if(res[0].toLowerCase() == "/nick"){
      updateName(res.slice(1,res.length).join(' '));
      return;
    }

    if(res[0].toLowerCase() == "/pm"){
      if(res.length >= 3){
        if(res[1] == 'SERVER'){
          var help = "You cannot PM the server.";
          socket.emit('annouce', {message : help});
          return;
        }
        if(findUser(res[1])){
          pm(res[1], res.slice(2, res.length).join(' '));
          return;
        } else if (findUser(res.slice(1 ,3).join(' '))){
          pm(res.slice(1 ,3).join(' '), res.slice(3, res.length).join(' '));
          return;
        } else {
          var help = "User not found for command '" + res.join(' ') + "'";
          socket.emit('annouce', {message : help});
        }
      } else {
          var help = "You must add a PM message.";
          socket.emit('annouce', {message : help});
      }
    }

    if(res[0].toLowerCase() == "/disconnect"){
      socket.disconnect();
    }

    if(res[0].toLowerCase() == "/help"){
      sendHelp();
      return;
    }

    unrecognized(res[0]);
    sendHelp();
  }

  var entityMap = {
    "&": "&",
    "<": "<",
    ">": ">",
    '"': '"',
    "'": ''',
    "/": '/'
  };

  function escapeHtml(string) {
    return String(string).replace(/[&<>"'\/]/g, function (s) {
      return entityMap[s];
    });
  }

  function removeItem(arr, item) {
    for(var i = arr.length; i--;) {
      if(arr[i][0].toString() === item[0].toString()) {
        arr.splice(i, 1);
      }
    }
  }

  function findUser(user) {
    for(var i = users.length; i--;) {
      if(users[i][0] == user) {
        return true;
      }
    }
    return false;
  }

  function findSocket(user) {
    for(var i = users.length; i--;) {
      if(users[i][0] == user) {
        return users[i][1];
      }
    }
    return 0;
  }

  function pm(dest, data){
    if(dest == name){
      var help = "You cannot PM yourself.";
      socket.emit('annouce', {message : help});
      return;
    }
    data = '<to ' + dest + '> ' + data + '</span';
    io.sockets.socket(findSocket(dest)).emit('broadcast', {client : name, message : data});
    socket.emit('broadcast', {client : name, message : data});
  }

  function updateName(data){
    if(findUser(data)){
      socket.emit('annouce', {message : "The nick '" + data + "' is taken!"});
      return;
    }
    if(data.toLowerCase() == "admin" || data.toLowerCase() == "server"){
      socket.emit('annouce', {message : "That nick is reserved!"});
      return;
    }
    oldName = name;
    name = data;
    removeItem(users, [oldName, socket.id]);
    users.push([name, socket.id, true]);
    io.sockets.emit('users', users);
    socket.emit('name', {name : name});
    broadcast('' + oldName + ' has changed name to ' + data + '.');
  }

  function disconnect(data){
    socket.disconnect();
  }

  function unrecognized(data){
    var help = "Unknown command '" + data + "'.";
    socket.emit('annouce', {message : help});
  }

  function sendHelp(){
    var help = "HardOrange IRC Help - Commands:
/nick nick
/pm nick message
/clear
/disconnect
/help";
    socket.emit('annouce', {message : help});
  }

  function multiArrayIndex(arr, item){
    for(var i = 0; i < arr.length; i++) {
      if(arr[i][0].toString() == item[0].toString()) {
          return i;
       }
     }
  }

  //Set name and notify clients
  sendHelp();
  var name = 'Guest' + Math.floor(100 + Math.random() * 900);
  broadcast('' + name + ' has entered chat.');
  users.push([name, socket.id, true]);
  io.sockets.emit('users', users);
  socket.emit('name', {name : name});

  //Begin Handlers
  socket.on('broadcast', function (data) {
    if(data.message[0] == "/") {
      parseServerCommand(data);
    } else {
      bbcode.parse(escapeHtml(data.message), function(content){
        io.sockets.emit('broadcast', {client : name, message : content});
      });
    }
  });

  socket.on('status', function (data) {
    var index = multiArrayIndex(users, [name, socket.id, !data.status]);
    users[index][2] = data.status;
    io.sockets.emit('users', users);
  });

  socket.on('disconnect', function (data) {
    removeItem(users, [name, socket.id]);
    io.sockets.emit('users', users);
    broadcast('' + name + ' has exited chat.');
  });
});
<commit_msg>Added index watch<commit_after>var config = require('./config.js');
var ip = config.ip;
var port = config.port;
var express = require('express');
var app = express();
var server = app.listen(port);
var ejs = require('ejs');
var bbcode = require('bbcode');
var io = require('socket.io').listen(server);
io.set('log level', 1);
var sys = require('sys')
var exec = require('child_process').exec;

app.set("view options", {layout: false});
app.use(express.json());
app.use(express.static(__dirname + '/public'));

process.on('SIGINT', function() {
  console.log( "\nShutting down from manual SIGINT (Ctrl-C), NOW." );
  io.sockets.emit('annouce', {message : 'SHUTTING DOWN, NOW!'});
  process.exit();
});

process.once('SIGUSR2', function () {
  gracefulShutdown(function () {
    process.kill(process.pid, 'SIGUSR2');
  });
});

function gracefulShutdown(kill){
  console.log( "\nShutting down from nodemon SIGUSR2 (RESTART) in 10 seconds..." );
  io.sockets.emit('annouce', {message : 'RESTARTING IN 10 SECONDS!'});
  setTimeout(function(){kill()}, 10000);
}

app.post('/gitpull', function(req, res) {
  //GitHub push hook
  res.end();
  io.sockets.emit('annouce', {message : 'SYSTEM UPDATE INITIATED...'});
  function puts(error, stdout, stderr) {sys.puts(stdout)}
  exec("git reset --hard HEAD", puts);
  exec("git pull", puts);
  var arr = req.body.commits[0].modified;
  if((arr.join(',').indexOf("app.min.js") > -1) || (arr.join(',').indexOf("app.min.css") > -1) || (arr.join(',').indexOf("index.ejs") > -1)){
    io.sockets.emit('annouce', {message : 'SYSTEM UPDATE COMPLETE, BROWSER RELOAD IS NECCESARY.'});
  } else {
    io.sockets.emit('annouce', {message : 'SYSTEM UPDATE COMPLETE, BROWSER RELOAD IS NOT NECCESARY.'});
  }
});

app.get('*', function(req, res) {
  res.render('index.ejs', {
   ip: ip
 });
});

var users = [];

process.stdin.resume();
process.stdin.setEncoding('utf8');

process.stdin.on('data', function (chunk) {
 io.sockets.emit('annouce', {message : '' + chunk.toUpperCase() + ''});
});

io.sockets.on('connection', function (socket) {
  function broadcast(data) {
    io.sockets.emit('annouce', {message : data});
  }

  function parseServerCommand(data) {
    var res = data.message.trim().split(" ");

    if(res[0].toLowerCase() == "/nick"){
      updateName(res.slice(1,res.length).join(' '));
      return;
    }

    if(res[0].toLowerCase() == "/pm"){
      if(res.length >= 3){
        if(res[1] == 'SERVER'){
          var help = "You cannot PM the server.";
          socket.emit('annouce', {message : help});
          return;
        }
        if(findUser(res[1])){
          pm(res[1], res.slice(2, res.length).join(' '));
          return;
        } else if (findUser(res.slice(1 ,3).join(' '))){
          pm(res.slice(1 ,3).join(' '), res.slice(3, res.length).join(' '));
          return;
        } else {
          var help = "User not found for command '" + res.join(' ') + "'";
          socket.emit('annouce', {message : help});
        }
      } else {
          var help = "You must add a PM message.";
          socket.emit('annouce', {message : help});
      }
    }

    if(res[0].toLowerCase() == "/disconnect"){
      socket.disconnect();
    }

    if(res[0].toLowerCase() == "/help"){
      sendHelp();
      return;
    }

    unrecognized(res[0]);
    sendHelp();
  }

  var entityMap = {
    "&": "&",
    "<": "<",
    ">": ">",
    '"': '"',
    "'": ''',
    "/": '/'
  };

  function escapeHtml(string) {
    return String(string).replace(/[&<>"'\/]/g, function (s) {
      return entityMap[s];
    });
  }

  function removeItem(arr, item) {
    for(var i = arr.length; i--;) {
      if(arr[i][0].toString() === item[0].toString()) {
        arr.splice(i, 1);
      }
    }
  }

  function findUser(user) {
    for(var i = users.length; i--;) {
      if(users[i][0] == user) {
        return true;
      }
    }
    return false;
  }

  function findSocket(user) {
    for(var i = users.length; i--;) {
      if(users[i][0] == user) {
        return users[i][1];
      }
    }
    return 0;
  }

  function pm(dest, data){
    if(dest == name){
      var help = "You cannot PM yourself.";
      socket.emit('annouce', {message : help});
      return;
    }
    data = '<to ' + dest + '> ' + data + '</span';
    io.sockets.socket(findSocket(dest)).emit('broadcast', {client : name, message : data});
    socket.emit('broadcast', {client : name, message : data});
  }

  function updateName(data){
    if(findUser(data)){
      socket.emit('annouce', {message : "The nick '" + data + "' is taken!"});
      return;
    }
    if(data.toLowerCase() == "admin" || data.toLowerCase() == "server"){
      socket.emit('annouce', {message : "That nick is reserved!"});
      return;
    }
    oldName = name;
    name = data;
    removeItem(users, [oldName, socket.id]);
    users.push([name, socket.id, true]);
    io.sockets.emit('users', users);
    socket.emit('name', {name : name});
    broadcast('' + oldName + ' has changed name to ' + data + '.');
  }

  function disconnect(data){
    socket.disconnect();
  }

  function unrecognized(data){
    var help = "Unknown command '" + data + "'.";
    socket.emit('annouce', {message : help});
  }

  function sendHelp(){
    var help = "HardOrange IRC Help - Commands:
/nick nick
/pm nick message
/clear
/disconnect
/help";
    socket.emit('annouce', {message : help});
  }

  function multiArrayIndex(arr, item){
    for(var i = 0; i < arr.length; i++) {
      if(arr[i][0].toString() == item[0].toString()) {
          return i;
       }
     }
  }

  //Set name and notify clients
  sendHelp();
  var name = 'Guest' + Math.floor(100 + Math.random() * 900);
  broadcast('' + name + ' has entered chat.');
  users.push([name, socket.id, true]);
  io.sockets.emit('users', users);
  socket.emit('name', {name : name});

  //Begin Handlers
  socket.on('broadcast', function (data) {
    if(data.message[0] == "/") {
      parseServerCommand(data);
    } else {
      bbcode.parse(escapeHtml(data.message), function(content){
        io.sockets.emit('broadcast', {client : name, message : content});
      });
    }
  });

  socket.on('status', function (data) {
    var index = multiArrayIndex(users, [name, socket.id, !data.status]);
    users[index][2] = data.status;
    io.sockets.emit('users', users);
  });

  socket.on('disconnect', function (data) {
    removeItem(users, [name, socket.id]);
    io.sockets.emit('users', users);
    broadcast('' + name + ' has exited chat.');
  });
});
<|endoftext|>


<commit_before>const App = Object.freeze(Object.create({
  "showNav": function(nav) { nav.classList.add("active"); },

  "hideNav": function(nav) { nav.classList.remove("active"); },

  "showDiv": function(div) { div.classList.remove("invisible"); },

  "hideDiv": function(div) { div.classList.add("invisible"); },

  "toggleDiv": function(div) {
    const nodes = Array.from(document.querySelectorAll(".contentDiv"));
    nodes.forEach(this.hideDiv);
    this.showDiv(div);
  },

  "setDate": function() {
    const now = new Date();
    const date = document.querySelector("#date");
    const month = ((now.getMonth() +1) < 10) ? "" + 0 + (now.getMonth()+1) : now.getMonth()+1;
    const day = (now.getDate() < 10) ? "" + 0 + now.getDate() : now.getDate();

    date.innerHTML = day + "/" + month + "/" + now.getFullYear();
  },

  "setMoodValue": function(value) {
    document.getElementById('moodValue').innerHTML = value;
  },

  "setupEventHandlers": function() {
     // Save button event handler.
    document.getElementById("save").addEventListener("click", () => {
      const data = {};
      const now = new Date();
      const mood = document.getElementById("mood").value;
      const notes = document.getElementById("notes").value;
      const nodes = document.getElementsByClassName("emotion");
      const feelings = Array.from(nodes).filter((node) => node.checked);
      const year = now.getFullYear();
      const month = now.getMonth();
      const date = now.getDate();

      now.setTime(0);
      now.setYear(year);
      now.setMonth(month);
      now.setDate(date);

      data.id = now.getTime();
      data.date = now;
      data.mood = parseInt(mood, 10);
      data.notes = notes;
      data.feelings = feelings.map((node) => node.id);

      Jaryn.updateDiary(data, (obj) => {
        this.showHistory(obj);

        // Fix these
        //this.displayAverageMood(obj);
        //this.displayAverageFeelings(obj);
      });
    });

    // Add event handlers.
    Array.from(document.querySelectorAll(".contentDiv")).forEach((div) => {
      div.addEventListener("click", (e) => this.toggleDiv(div));
    });

    document.getElementById('mood').addEventListener('change', (event) => {
      this.setMoodValue(event.target.value);
    });

    Array.from(document.getElementsByClassName("navLink")).forEach((nav) => {
      nav.addEventListener("click", (e) => {
        const contentNodes = Array.from(document.querySelectorAll(".contentDiv"));
        const navNodes = Array.from(document.querySelectorAll(".navLink"));
        const target = nav.firstChild.getAttribute("data-target");

        contentNodes.forEach(this.hideDiv);
        navNodes.forEach(this.hideNav);

        this.showDiv(document.querySelector("#" + target));
        this.showNav(e.target.parentNode);
      });
    });
  },

  "showAverageMood": function(data) {
    const moods = document.querySelector("#averageMood").innerHTML = data;
  },

  // Figure out what to do with this!
  "showAverageFeelings": function(allEmotions) {
    const emotions = document.querySelector("#averageEmotions");
    emotions.innerHTML = allEmotions.join(", ");
  },

  "showHistory": function(data) {
    const tbody = document.querySelector("#historyTable");

    while(tbody.hasChildNodes()) tbody.removeChild(tbody.firstChild);

    console.log("Data");
    console.log(data);

    Object.keys(data).forEach((obj) => {
      const row = document.createElement('tr');
      const date = document.createElement('td');
      const mood = document.createElement('td');
      const feelings = document.createElement('td');
      const notes = document.createElement('td');

      const dt = new Date();
      dt.setTime(obj);
      const year = dt.getFullYear();
      const month = (dt.getMonth() + 1 < 10) ? "0" + (dt.getMonth() + 1) : dt.getMonth() + 1;
      const day = (dt.getDate() < 10) ? "0" + dt.getDate() : dt.getDate();

      date.innerHTML = day + "/" + month + "/" + year;
      mood.innerHTML = (data[obj]) ? data[obj].mood : "-";
      notes.innerHTML = (data[obj]) ? data[obj].notes : "-";
      feelings.innerHTML = (data[obj]) ? data[obj].feelings.reduce((p, n) => p + ", " + n) : "-";

      row.appendChild(date);
      row.appendChild(mood);
      row.appendChild(feelings);
      row.appendChild(notes);
      tbody.appendChild(row);
    });
  },

  "init": function() {
    this.setDate();
    this.setupEventHandlers();
    this.setMoodValue("5");

    Jaryn.loadConfig((conf) => {
      this.showAverageMood(conf.averageMood);
      this.showAverageFeelings(conf.averageEmotion);

      // Only read data files if config is loaded.
      Jaryn.getSevenDayHistory(d => this.showHistory(d));
    });
  }
}));

App.init();<commit_msg>Removed debug console.log lines.<commit_after>const App = Object.freeze(Object.create({
  "showNav": function(nav) { nav.classList.add("active"); },

  "hideNav": function(nav) { nav.classList.remove("active"); },

  "showDiv": function(div) { div.classList.remove("invisible"); },

  "hideDiv": function(div) { div.classList.add("invisible"); },

  "toggleDiv": function(div) {
    const nodes = Array.from(document.querySelectorAll(".contentDiv"));
    nodes.forEach(this.hideDiv);
    this.showDiv(div);
  },

  "setDate": function() {
    const now = new Date();
    const date = document.querySelector("#date");
    const month = ((now.getMonth() +1) < 10) ? "" + 0 + (now.getMonth()+1) : now.getMonth()+1;
    const day = (now.getDate() < 10) ? "" + 0 + now.getDate() : now.getDate();

    date.innerHTML = day + "/" + month + "/" + now.getFullYear();
  },

  "setMoodValue": function(value) {
    document.getElementById('moodValue').innerHTML = value;
  },

  "setupEventHandlers": function() {
     // Save button event handler.
    document.getElementById("save").addEventListener("click", () => {
      const data = {};
      const now = new Date();
      const mood = document.getElementById("mood").value;
      const notes = document.getElementById("notes").value;
      const nodes = document.getElementsByClassName("emotion");
      const feelings = Array.from(nodes).filter((node) => node.checked);
      const year = now.getFullYear();
      const month = now.getMonth();
      const date = now.getDate();

      now.setTime(0);
      now.setYear(year);
      now.setMonth(month);
      now.setDate(date);

      data.id = now.getTime();
      data.date = now;
      data.mood = parseInt(mood, 10);
      data.notes = notes;
      data.feelings = feelings.map((node) => node.id);

      Jaryn.updateDiary(data, (obj) => {
        this.showHistory(obj);

        // Fix these
        //this.displayAverageMood(obj);
        //this.displayAverageFeelings(obj);
      });
    });

    // Add event handlers.
    Array.from(document.querySelectorAll(".contentDiv")).forEach((div) => {
      div.addEventListener("click", (e) => this.toggleDiv(div));
    });

    document.getElementById('mood').addEventListener('change', (event) => {
      this.setMoodValue(event.target.value);
    });

    Array.from(document.getElementsByClassName("navLink")).forEach((nav) => {
      nav.addEventListener("click", (e) => {
        const contentNodes = Array.from(document.querySelectorAll(".contentDiv"));
        const navNodes = Array.from(document.querySelectorAll(".navLink"));
        const target = nav.firstChild.getAttribute("data-target");

        contentNodes.forEach(this.hideDiv);
        navNodes.forEach(this.hideNav);

        this.showDiv(document.querySelector("#" + target));
        this.showNav(e.target.parentNode);
      });
    });
  },

  "showAverageMood": function(data) {
    const moods = document.querySelector("#averageMood").innerHTML = data;
  },

  // Figure out what to do with this!
  "showAverageFeelings": function(allEmotions) {
    const emotions = document.querySelector("#averageEmotions");
    emotions.innerHTML = allEmotions.join(", ");
  },

  "showHistory": function(data) {
    const tbody = document.querySelector("#historyTable");

    while(tbody.hasChildNodes()) tbody.removeChild(tbody.firstChild);

    Object.keys(data).forEach((obj) => {
      const row = document.createElement('tr');
      const date = document.createElement('td');
      const mood = document.createElement('td');
      const feelings = document.createElement('td');
      const notes = document.createElement('td');

      const dt = new Date();
      dt.setTime(obj);
      const year = dt.getFullYear();
      const month = (dt.getMonth() + 1 < 10) ? "0" + (dt.getMonth() + 1) : dt.getMonth() + 1;
      const day = (dt.getDate() < 10) ? "0" + dt.getDate() : dt.getDate();

      date.innerHTML = day + "/" + month + "/" + year;
      mood.innerHTML = (data[obj]) ? data[obj].mood : "-";
      notes.innerHTML = (data[obj]) ? data[obj].notes : "-";
      feelings.innerHTML = (data[obj]) ? data[obj].feelings.reduce((p, n) => p + ", " + n) : "-";

      row.appendChild(date);
      row.appendChild(mood);
      row.appendChild(feelings);
      row.appendChild(notes);
      tbody.appendChild(row);
    });
  },

  "init": function() {
    this.setDate();
    this.setupEventHandlers();
    this.setMoodValue("5");

    Jaryn.loadConfig((conf) => {
      this.showAverageMood(conf.averageMood);
      this.showAverageFeelings(conf.averageEmotion);

      // Only read data files if config is loaded.
      Jaryn.getSevenDayHistory(d => this.showHistory(d));
    });
  }
}));

App.init();<|endoftext|>


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

var express = require('express'),
http = require('http'),
passport = require('passport'),
util = require('util'),
path = require('path'),
FacebookStrategy = require('passport-facebook').Strategy,
config = require('./config.js'),
data = require('./lib/data.js'),
mongojs = require('mongojs');
var path = require("path");

var app = express();

app.configure(function () {
	app.set('port', process.env.PORT || 3000);
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'mustache');
    app.engine('mustache', require('hogan-middleware').__express);
	app.use(express.favicon(path.join(__dirname, 'public/favicon.png')));
	app.use(express.logger('dev'));
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(express.cookieParser());
	app.use(express.session({
			secret : config.sessionsecret
		}));
	app.use(passport.initialize());
	app.use(passport.session());
	app.use(app.router);
	app.use(express.static(path.join(__dirname, 'public')));
});

// development only
if ('development' == app.get('env')) {
	app.use(express.errorHandler());
}
// passport
passport.use(new FacebookStrategy({
    clientID: config.facebookid,
    clientSecret: config.facebooksecret,
    callbackURL: "http://delta.dev.geeksoc.org/auth/facebook/callback"
  },
  function(accessToken, refreshToken, profile, done) {
    data.findOne({ facebookId: profile.id }, function (err, user) {
    if (err) return done(err);
      if (!user) return generateUserFB(profile,done);
      return done(err, user);
      }
    );
  }

));

passport.serializeUser(function(user, done) {
  done(null, user.facebookId);
});

passport.deserializeUser(function(id, done) {
  data.findOne({ facebookId: id }, function(err, user) {
    done(err, user);
  });
});

app.get('/', function (req, res) {
console.log(JSON.stringify(req.user));
res.render('index', {
		page : 'Main Page',
        theme : 'yeti',
		user : req.user
	});
});

// auth routes
app.get('/auth/facebook',
  passport.authenticate('facebook'));

app.get('/auth/facebook/callback',
  passport.authenticate('facebook', { failureRedirect: '/login' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/');
  });

app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

// API stuff
app.get('/people', function (req, res) {
  data.listAllPeople(function(e, results){
      res.send(results);
    });
  });

app.get('/people/id/:id', function (req, res) {
  var id = req.params.id;
  var objectId = mongojs.ObjectId(id);

  data.listByThing('_id', objectId, function(e, results){
      res.send(results);
    });
  });

app.get('/people/:thing/:id', function (req, res) {
  var id = req.params.id;
  var thing = req.params.thing;

  data.listByThing(thing, id, function(e, results){
      res.send(results);
    });
  });

app.post('/search', function (req, res) {
  if(!req.body.hasOwnProperty('query')) {
    res.statusCode = 400;
    return res.send('Error 400: Post syntax incorrect.');
  }
  data.listByQueryObject(req.body.query, function(e, results){
      res.send(results);
    });
  });

app.post('/people', function (req, res) {
  if(!req.body.hasOwnProperty('person')) {
    res.statusCode = 400;
    return res.send('Error 400: Post syntax incorrect.');
  }
  data.people.insert(req.body.person);
  res.statusCode = 200;
  return res.send('Inserted');
  });

app.put('/people/:id', function (req, res) {
  var id = req.params.id;
  var objectId = mongojs.ObjectId(id);

  if(!req.body.hasOwnProperty('person')) {
    res.statusCode = 400;
    return res.send('Error 400: Put syntax incorrect.');
  }

  data.people.replaceWithObject(objectId, req.body.person);
  res.statusCode = 200;
  return res.send('Updated');

  });

app.get('/map', function (req, res) {
res.render('dashboards/map', {
    page : 'Map',
    mapelement : 'map',
    datapoints: [
      {latitude: 55.8506080519, longitude: -4.26492576329, weight: 100},
        {latitude: 55.8613701277, longitude: -4.24460130892, weight: 100},
        {latitude: 55.4906916873, longitude: -4.60522901822, weight: 100},
        {latitude: 55.8651840586, longitude: -4.2216469545 , weight: 100}
      ]

  });
});

function generateUserFB(profile,done){
var user = { facebookId: profile.id , name: profile.name}
data.addPerson(user);
data.findOne(user, function (err, user) {
    if (err) return done(err);
      if (!user) return done(null,false);
      return done(err, user);
      }
    );

}

http.createServer(app).listen(app.get('port'), function () {
	console.log('Express server listening on port ' + app.get('port'));
});
<commit_msg>See what we are getting<commit_after>
/**
 * Module dependencies.
 */

var express = require('express'),
http = require('http'),
passport = require('passport'),
util = require('util'),
path = require('path'),
FacebookStrategy = require('passport-facebook').Strategy,
config = require('./config.js'),
data = require('./lib/data.js'),
mongojs = require('mongojs');
var path = require("path");

var app = express();

app.configure(function () {
	app.set('port', process.env.PORT || 3000);
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'mustache');
    app.engine('mustache', require('hogan-middleware').__express);
	app.use(express.favicon(path.join(__dirname, 'public/favicon.png')));
	app.use(express.logger('dev'));
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(express.cookieParser());
	app.use(express.session({
			secret : config.sessionsecret
		}));
	app.use(passport.initialize());
	app.use(passport.session());
	app.use(app.router);
	app.use(express.static(path.join(__dirname, 'public')));
});

// development only
if ('development' == app.get('env')) {
	app.use(express.errorHandler());
}
// passport
passport.use(new FacebookStrategy({
    clientID: config.facebookid,
    clientSecret: config.facebooksecret,
    callbackURL: "http://delta.dev.geeksoc.org/auth/facebook/callback"
  },
  function(accessToken, refreshToken, profile, done) {
    data.findOne({ facebookId: profile.id }, function (err, user) {
    if (err) return done(err);
      if (!user) return generateUserFB(profile,done);
      return done(err, user);
      }
    );
  }

));

passport.serializeUser(function(user, done) {
  done(null, user.facebookId);
});

passport.deserializeUser(function(id, done) {
  data.findOne({ facebookId: id }, function(err, user) {
    done(err, user);
  });
});

app.get('/', function (req, res) {
console.log(JSON.stringify(req.user));
res.render('index', {
		page : 'Main Page',
        theme : 'yeti',
		user : req.user
	});
});

// auth routes
app.get('/auth/facebook',
  passport.authenticate('facebook'));

app.get('/auth/facebook/callback',
  passport.authenticate('facebook', { failureRedirect: '/login' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/');
  });

app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

// API stuff
app.get('/people', function (req, res) {
  data.listAllPeople(function(e, results){
      res.send(results);
    });
  });

app.get('/people/id/:id', function (req, res) {
  var id = req.params.id;
  var objectId = mongojs.ObjectId(id);

  data.listByThing('_id', objectId, function(e, results){
      res.send(results);
    });
  });

app.get('/people/:thing/:id', function (req, res) {
  var id = req.params.id;
  var thing = req.params.thing;

  data.listByThing(thing, id, function(e, results){
      res.send(results);
    });
  });

app.post('/search', function (req, res) {
  if(!req.body.hasOwnProperty('query')) {
    res.statusCode = 400;
    return res.send('Error 400: Post syntax incorrect.');
  }
  data.listByQueryObject(req.body.query, function(e, results){
      res.send(results);
    });
  });

app.post('/people', function (req, res) {
  if(!req.body.hasOwnProperty('person')) {
    res.statusCode = 400;
    return res.send('Error 400: Post syntax incorrect.');
  }
  data.people.insert(req.body.person);
  res.statusCode = 200;
  return res.send('Inserted');
  });

app.put('/people/:id', function (req, res) {
  var id = req.params.id;
  var objectId = mongojs.ObjectId(id);

  if(!req.body.hasOwnProperty('person')) {
    res.statusCode = 400;
    return res.send('Error 400: Put syntax incorrect.');
  }

  data.people.replaceWithObject(objectId, req.body.person);
  res.statusCode = 200;
  return res.send('Updated');

  });

app.get('/map', function (req, res) {
res.render('dashboards/map', {
    page : 'Map',
    mapelement : 'map',
    datapoints: [
      {latitude: 55.8506080519, longitude: -4.26492576329, weight: 100},
        {latitude: 55.8613701277, longitude: -4.24460130892, weight: 100},
        {latitude: 55.4906916873, longitude: -4.60522901822, weight: 100},
        {latitude: 55.8651840586, longitude: -4.2216469545 , weight: 100}
      ]

  });
});

function generateUserFB(profile,done){
console.log(JOSN.stringify(profile));
var user = { facebookId: profile.id , name: profile.name}
data.addPerson(user);
data.findOne(user, function (err, user) {
    if (err) return done(err);
      if (!user) return done(null,false);
      return done(err, user);
      }
    );

}

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


<commit_before>var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var jsonParser = bodyParser.json();

app.use(bodyParser.json());

app.get('/', function (req, res) {
    res.send('Slack Commands!');
});

app.post('/github', jsonParser, function (req, res) {
    res.json(req.body);
});

app.listen(80, function () {
    console.log('Example app listening on port 80!')
});
<commit_msg>Port using ENV var<commit_after>var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var jsonParser = bodyParser.json();

app.use(bodyParser.json());

app.get('/', function (req, res) {
    res.send('Slack Commands!');
});

app.post('/github', jsonParser, function (req, res) {
    res.json(req.body);
});

app.listen(process.env.PORT || 3000, function () {
    console.log(`Example app listening on port ${process.env.PORT}!`)
});
<|endoftext|>


<commit_before>var RssCreator = require('./rss.grabber');
var util = require('util');
var db = require("mongojs").connect("ubuntu-vmware/gemeindedb");
var gemeindeMetaData = db.collection("gemeinde.metadata");

function collectUrls(callback) {
	var result = {};
	gemeindeMetaData.find().forEach(function(err, doc) {
		if (doc) {
			var feed = doc.feed;
			if (feed.indexOf('untergruppenbach') != -1 || feed.indexOf('no_cache') != -1)
				result[doc.feed] = doc._id;
		} else {
			callback(result);
		}
	});
}

collectUrls(function(urlMap) {
	var urls = [];

	for ( var key in urlMap) {
		urls.push(key);
		console.log(key);
	}

	var grabber = new RssCreator(urls);

	var gemeindeNewsItem = db.collection("gemeinde.newsitem");
	gemeindeNewsItem.ensureIndex("link", {
		unique : true
	});
	grabber.grab(function(result) {
		for ( var url in result) {
			console.log(url);
			var res = result[url];

			var id = urlMap[url];

			if (util.isArray(res)) {
				for ( var x = 0; x < res.length; x++) {
					var feed = res[x];
					if (feed.title) {
						feed.metaDataId = id;
						gemeindeNewsItem.save(feed, {
							safe : true
						}, function(err, doc) {
							if (err)
								console.error(err);
						});
					}
				}

			} else {
				console.log(res);
			}
		}
	});
});

console.log("ok");
<commit_msg>added clean DB close<commit_after>var RssCreator = require('./rss.grabber');
var util = require('util');
var db = require("mongojs").connect("ubuntu-vmware/gemeindedb");
var gemeindeMetaData = db.collection("gemeinde.metadata");

function collectUrls(callback) {
	var result = {};
	gemeindeMetaData.find().forEach(function(err, doc) {
		if (doc) {
			var feed = doc.feed;
			if (feed.indexOf('untergruppenbach') != -1 || feed.indexOf('no_cache') != -1)
				result[doc.feed] = doc._id;
		} else {
			callback(result);
		}
	});
}

collectUrls(function(urlMap) {
	var urls = [];

	console.log("Collecting URLs to process");
	for ( var key in urlMap) {
		urls.push(key);
		console.log(key);
	}

	var grabber = new RssCreator(urls);

	var gemeindeNewsItem = db.collection("gemeinde.newsitem");
	gemeindeNewsItem.ensureIndex("link", {
		unique : true
	});

	function saveNewsItems(newsItems) {
		var newsItemsSaved = 0;
		var duplicates = 0;
		for ( var x = 0; x < newsItems.length; x++) {
			gemeindeNewsItem.save(newsItems[x], {
				safe : true
			}, function(err, doc) {
				newsItemsSaved++;
				if (err) {
					if (err.err && err.err.indexOf('duplicate key') != -1) {
						duplicates++;
					} else
						console.error(err);
				}
				if (newsItemsSaved >= newsItems.length) {
					db.close();
					console.log(newsItemsSaved + " items processed. " + duplicates
							+ " duplicates. Closing DB connection.");
				}
			});
		}
	}

	grabber.grab(function(result) {
		var newsItems = [];
		for ( var url in result) {
			var res = result[url];
			var id = urlMap[url];
			if (util.isArray(res)) {
				for ( var x = 0; x < res.length; x++) {
					var newsItem = res[x];
					if (newsItem.title) {
						newsItem.metaDataId = id;
						newsItems.push(newsItem);
					}
				}
			} else {
				console.log(res);
			}
		}
		saveNewsItems(newsItems);
	});
});
<|endoftext|>