<commit_before>/**
 * 数值处理模块
 * @module echarts/util/number
 */

define(function (require) {

    var number = {};

    var RADIAN_EPSILON = 1e-4;

    function _trim(str) {
        return str.replace(/^\s+/, '').replace(/\s+$/, '');
    }

    /**
     * Linear mapping a value from domain to range
     * @memberOf module:echarts/util/number
     * @param  {(number|Array.<number>)} val
     * @param  {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
     * @param  {Array.<number>} range  Range extent range[0] can be bigger than range[1]
     * @param  {boolean} clamp
     * @return {(number|Array.<number>}
     */
    number.linearMap = function (val, domain, range, clamp) {

        var sub = domain[1] - domain[0];

        if (sub === 0) {
            return (range[0] + range[1]) / 2;
        }
        var t = (val - domain[0]) / sub;

        if (clamp) {
            t = Math.min(Math.max(t, 0), 1);
        }

        return t * (range[1] - range[0]) + range[0];
    };

    /**
     * Convert a percent string to absolute number.
     * Returns NaN if percent is not a valid string or number
     * @memberOf module:echarts/util/number
     * @param {string|number} percent
     * @param {number} all
     * @return {number}
     */
    number.parsePercent = function(percent, all) {
        switch (percent) {
            case 'center':
            case 'middle':
                percent = '50%';
                break;
            case 'left':
            case 'top':
                percent = '0%';
                break;
            case 'right':
            case 'bottom':
                percent = '100%';
                break;
        }
        if (typeof percent === 'string') {
            if (_trim(percent).match(/%$/)) {
                return parseFloat(percent) / 100 * all;
            }

            return parseFloat(percent);
        }

        return percent == null ? NaN : +percent;
    };

    /**
     * Fix rounding error of float numbers
     * @param {number} x
     * @return {number}
     */
    number.round = function (x) {
        // PENDING
        return +(+x).toFixed(14);
    };

    number.asc = function (arr) {
        arr.sort(function (a, b) {
            return a - b;
        });
        return arr;
    };

    /**
     * Get precision
     * @param {number} val
     */
    number.getPrecision = function (val) {
        if (isNaN(val)) {
            return 0;
        }
        // It is much faster than methods converting number to string as follows
        //      var tmp = val.toString();
        //      return tmp.length - 1 - tmp.indexOf('.');
        // especially when precision is low
        var e = 1;
        var count = 0;
        while (Math.round(val * e) / e !== val) {
            e *= 10;
            count++;
        }
        return count;
    };

    /**
     * @param {Array.<number>} dataExtent
     * @param {Array.<number>} pixelExtent
     * @return {number}  precision
     */
    number.getPixelPrecision = function (dataExtent, pixelExtent) {
        var log = Math.log;
        var LN10 = Math.LN10;
        var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
        var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
        return Math.max(
            -dataQuantity + sizeQuantity,
            0
        );
    };

    // Number.MAX_SAFE_INTEGER, ie do not support.
    number.MAX_SAFE_INTEGER = 9007199254740991;

    /**
     * To 0 - 2 * PI, considering negative radian.
     * @param {number} radian
     * @return {number}
     */
    number.remRadian = function (radian) {
        var pi2 = Math.PI * 2;
        return (radian % pi2 + pi2) % pi2;
    };

    /**
     * @param {type} radian
     * @return {boolean}
     */
    number.isRadianAroundZero = function (val) {
        return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
    };

    /**
     * @param {string|Date|number} value
     * @return {number} timestamp
     */
    number.parseDate = function (value) {
        return value instanceof Date
            ? value
            : new Date(
                typeof value === 'string'
                    ? value.replace(/-/g, '/')
                    : Math.round(value)
            );
    };

    // "Nice Numbers for Graph Labels" of Graphic Gems
    /**
     * find a “nice” number approximately equal to x. Round the number if round = true, take ceiling if round = false
     * The primary observation is that the “nicest” numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
     * @param  {number} val
     * @param  {boolean} round
     * @return {number}
     */
    number.nice = function (val, round) {
        var exp = Math.floor(Math.log(val) / Math.LN10);
        var exp10 = Math.pow(10, exp);
        var f = val / exp10; // between 1 and 10
        var nf;
        if (round) {
            if (f < 1.5) { nf = 1; }
            else if (f < 2.5) { nf = 2; }
            else if (f < 4) { nf = 3; }
            else if (f < 7) { nf = 5; }
            else { nf = 10; }
        }
        else {
            if (f < 1) { nf = 1; }
            else if (f < 2) { nf = 2; }
            else if (f < 3) { nf = 3; }
            else if (f < 5) { nf = 5; }
            else { nf = 10; }
        }
        return nf * exp10;
    };

    return number;
});<commit_msg>rounding error tweak<commit_after>/**
 * 数值处理模块
 * @module echarts/util/number
 */

define(function (require) {

    var number = {};

    var RADIAN_EPSILON = 1e-4;

    function _trim(str) {
        return str.replace(/^\s+/, '').replace(/\s+$/, '');
    }

    /**
     * Linear mapping a value from domain to range
     * @memberOf module:echarts/util/number
     * @param  {(number|Array.<number>)} val
     * @param  {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
     * @param  {Array.<number>} range  Range extent range[0] can be bigger than range[1]
     * @param  {boolean} clamp
     * @return {(number|Array.<number>}
     */
    number.linearMap = function (val, domain, range, clamp) {

        var sub = domain[1] - domain[0];

        if (sub === 0) {
            return (range[0] + range[1]) / 2;
        }
        var t = (val - domain[0]) / sub;

        if (clamp) {
            t = Math.min(Math.max(t, 0), 1);
        }

        return t * (range[1] - range[0]) + range[0];
    };

    /**
     * Convert a percent string to absolute number.
     * Returns NaN if percent is not a valid string or number
     * @memberOf module:echarts/util/number
     * @param {string|number} percent
     * @param {number} all
     * @return {number}
     */
    number.parsePercent = function(percent, all) {
        switch (percent) {
            case 'center':
            case 'middle':
                percent = '50%';
                break;
            case 'left':
            case 'top':
                percent = '0%';
                break;
            case 'right':
            case 'bottom':
                percent = '100%';
                break;
        }
        if (typeof percent === 'string') {
            if (_trim(percent).match(/%$/)) {
                return parseFloat(percent) / 100 * all;
            }

            return parseFloat(percent);
        }

        return percent == null ? NaN : +percent;
    };

    /**
     * Fix rounding error of float numbers
     * @param {number} x
     * @return {number}
     */
    number.round = function (x) {
        // PENDING
        return +(+x).toFixed(10);
    };

    number.asc = function (arr) {
        arr.sort(function (a, b) {
            return a - b;
        });
        return arr;
    };

    /**
     * Get precision
     * @param {number} val
     */
    number.getPrecision = function (val) {
        if (isNaN(val)) {
            return 0;
        }
        // It is much faster than methods converting number to string as follows
        //      var tmp = val.toString();
        //      return tmp.length - 1 - tmp.indexOf('.');
        // especially when precision is low
        var e = 1;
        var count = 0;
        while (Math.round(val * e) / e !== val) {
            e *= 10;
            count++;
        }
        return count;
    };

    /**
     * @param {Array.<number>} dataExtent
     * @param {Array.<number>} pixelExtent
     * @return {number}  precision
     */
    number.getPixelPrecision = function (dataExtent, pixelExtent) {
        var log = Math.log;
        var LN10 = Math.LN10;
        var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
        var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
        return Math.max(
            -dataQuantity + sizeQuantity,
            0
        );
    };

    // Number.MAX_SAFE_INTEGER, ie do not support.
    number.MAX_SAFE_INTEGER = 9007199254740991;

    /**
     * To 0 - 2 * PI, considering negative radian.
     * @param {number} radian
     * @return {number}
     */
    number.remRadian = function (radian) {
        var pi2 = Math.PI * 2;
        return (radian % pi2 + pi2) % pi2;
    };

    /**
     * @param {type} radian
     * @return {boolean}
     */
    number.isRadianAroundZero = function (val) {
        return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
    };

    /**
     * @param {string|Date|number} value
     * @return {number} timestamp
     */
    number.parseDate = function (value) {
        return value instanceof Date
            ? value
            : new Date(
                typeof value === 'string'
                    ? value.replace(/-/g, '/')
                    : Math.round(value)
            );
    };

    // "Nice Numbers for Graph Labels" of Graphic Gems
    /**
     * find a “nice” number approximately equal to x. Round the number if round = true, take ceiling if round = false
     * The primary observation is that the “nicest” numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
     * @param  {number} val
     * @param  {boolean} round
     * @return {number}
     */
    number.nice = function (val, round) {
        var exp = Math.floor(Math.log(val) / Math.LN10);
        var exp10 = Math.pow(10, exp);
        var f = val / exp10; // between 1 and 10
        var nf;
        if (round) {
            if (f < 1.5) { nf = 1; }
            else if (f < 2.5) { nf = 2; }
            else if (f < 4) { nf = 3; }
            else if (f < 7) { nf = 5; }
            else { nf = 10; }
        }
        else {
            if (f < 1) { nf = 1; }
            else if (f < 2) { nf = 2; }
            else if (f < 3) { nf = 3; }
            else if (f < 5) { nf = 5; }
            else { nf = 10; }
        }
        return nf * exp10;
    };

    return number;
});<|endoftext|>


<commit_before>import lightBaseTheme from 'material-ui/styles/baseThemes/lightBaseTheme'
import {merge} from 'lodash'

export default merge(lightBaseTheme, {
  palette: {
    primary1Color: '#f09442',
    primary2Color: '#e95d3b',
    accent1Color: '#99dc3c',
    pickerHeaderColor: '#f09442',
    footerColor: '#336699'
  }
})
<commit_msg>Update footer color: use vscode-footer-like color<commit_after>import lightBaseTheme from 'material-ui/styles/baseThemes/lightBaseTheme'
import {merge} from 'lodash'

export default merge(lightBaseTheme, {
  palette: {
    primary1Color: '#f09442',
    primary2Color: '#e95d3b',
    accent1Color: '#99dc3c',
    pickerHeaderColor: '#f09442',
    footerColor: 'rgb(0, 122, 204)'
  }
})
<|endoftext|>


<commit_before>// commit de la branche kiesmohamed:myprojetct-alphorm+2
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'abdelkader'));
app.set('view engine', 'kies mohamed abdelkader');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('int'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// commit de la branche djazair/myproject-alphorm
app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('kies mohamed abdelkader');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
<commit_msg>commit master+2<commit_after>// commit de la branche kiesmohamed:myprojetct-alphorm+2
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'abdelkader'));
app.set('view engine', 'kies mohamed abdelkader');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('int'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// commit de la branche djazair/myproject-alphorm+2
app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('kies mohamed abdelkader');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
<|endoftext|>


<commit_before>
const randomColor = () => ({
  r: Math.random() * 255,
  g: Math.random() * 255,
  b: Math.random() * 255
});

const setNeighbours = (cell, grid) => {
  const {i, j} = cell;
  if (i > 0) {
    cell.neighbors.push(grid[i-1][j]);
    grid[i-1][j].neighbors.push(cell);
  }
  if (j > 0) {
    cell.neighbors.push(grid[i][j-1]);
    grid[i][j-1].neighbors.push(cell);
  }
}

const cellFactory = ({width, height}) => (i, j) => {
  const {r, g, b} = randomColor();
  return {
    i, j, r, g, b,
    x: i * width,
    y: j * height,
    bufferR: r,
    bufferG: g,
    bufferB: b,
    rVel: 0,
    gVel: 0,
    bVel: 0,
    bufferRVel: 0,
    bufferGVel: 0,
    bufferBVel: 0,
    neighbors: [],
    neighborPointerList: {}
  };
}

const addToList = (cell, list) => {
  const {i, j} = cell;
  if ((i === 0) && (j === 0)) {
    list.first = cell;
  } else {
    cell.next = list.first;
    list.first = cell;
  }
}

const arrangeNeighbors = (list) => {
  // TODO: this doesn't make much sense
  let cell = list.first;
  while (cell != null) {
    let numNeighbors = 1;
    cell.neighborPointerList.first = {neighbor: cell.neighbors[0]};
    for (let i = 1; i < cell.neighbors.length; i++) {
      const newPointer = {next: cell.neighborPointerList.first};
      cell.neighborPointerList.first = newPointer;
      newPointer.neighbor = cell.neighbors[i];
      ++numNeighbors;
    }
    cell.numNeighbors = numNeighbors;
    cell = cell.next;
  }
}

export const createCells = (cellSize, horizontalCells, verticalCells) => {
  const grid = [];
  const list = {};
  const makeCell = cellFactory(cellSize);
  for (let i = 0; i < horizontalCells; i++) {
    grid.push([]);
    for (let j = 0; j < verticalCells; j++) {
      const newCell = makeCell(i, j);
      setNeighbours(newCell, grid);
      //store cells in a 2D array only for the sake of setting neighbors
      grid[i].push(newCell);
      addToList(newCell, list);
    }
  }
  arrangeNeighbors(list);
  return list;
}

export const restart = list => () => {
  let cell = list.first;
  while (cell) {
    const {r, g, b} = randomColor();
    cell.bufferR = cell.r = r;
    cell.bufferG = cell.g = g;
    cell.bufferB = cell.b = b;
    cell.bufferRVel = cell.rVel = 0;
    cell.bufferGVel = cell.gVel = 0;
    cell.bufferBVel = cell.bVel = 0;
    cell = cell.next;
  }
}

const fixBoundaries = cell => {
  //bounce colors off of color cube boundaries
  if (cell.bufferR < 0) {
    cell.bufferR = 0;
    cell.bufferRVel *= -1;
  } else if (cell.bufferR > 255) {
    cell.bufferR = 255;
    cell.bufferRVel *= -1;
  }

  if (cell.bufferG < 0) {
    cell.bufferG = 0;
    cell.bufferGVel *= -1;
  } else if (cell.bufferG > 255) {
    cell.bufferG = 255;
    cell.bufferGVel *= -1;
  }
  if (cell.bufferB < 0) {
    cell.bufferB = 0;
    cell.bufferBVel *= -1;
  } else if (cell.bufferB > 255) {
    cell.bufferB = 255;
    cell.bufferBVel *= -1;
  }
}

export const tick = (list, cellSize, context, options) => () => {
  let cell = list.first;
  const {ease, minDistSquare, sepNormMag} = options;
  while (cell != null) {
    let [rAve, gAve, bAve, rVelAve, gVelAve, bVelAve, rSep, gSep, bSep]
      = new Array(9).fill(0);
    let neighborPointer = cell.neighborPointerList.first;
    while (neighborPointer != null) {
      const neighbor = neighborPointer.neighbor;
      rAve += neighbor.r;
      gAve += neighbor.g;
      bAve += neighbor.b;
      rVelAve += neighbor.rVel;
      gVelAve += neighbor.gVel;
      bVelAve += neighbor.bVel;
      const dr = cell.r - neighbor.r;
      const dg = cell.g - neighbor.g;
      const db = cell.b - neighbor.b;
      if (dr*dr + dg*dg + db*db < minDistSquare) {
        rSep += dr;
        gSep += dg;
        bSep += db;
      }
      neighborPointer = neighborPointer.next;
    }

    const f = 1/cell.numNeighbors
    rAve *= f;
    gAve *= f;
    bAve *= f;
    rVelAve *= f;
    gVelAve *= f;
    bVelAve *= f;

    //normalize separation vector
    if ((rSep !== 0) || (gSep !== 0) || (bSep !== 0)) {
      const length = Math.sqrt(rSep*rSep + gSep*gSep + bSep*bSep);
      const sepMagRecip = sepNormMag / length;
      rSep *= sepMagRecip;
      gSep *= sepMagRecip;
      bSep *= sepMagRecip;
    }

    //Update velocity by combining separation, alignment and cohesion effects. Change velocity only by 'ease' ratio.
    cell.bufferRVel += ease * (rSep + rVelAve + rAve - cell.r - cell.bufferRVel);
    cell.bufferGVel += ease * (gSep + gVelAve + gAve - cell.g - cell.bufferGVel);
    cell.bufferBVel += ease * (bSep + bVelAve + bAve - cell.b - cell.bufferBVel);

    //Code for clamping velocity commented out because in my testing, the velocity never went over the max. (But you may wish to restore this
    //code if you experiment with different parameters.)
    /*
    if ((mag = Math.sqrt(cell.bufferRVel*cell.bufferRVel + cell.bufferGVel*cell.bufferGVel + cell.bufferBVel*cell.bufferBVel))> velMax) {
      cell.bufferRVel *= (f = velMax/mag);
      cell.bufferGVel *= f;
      cell.bufferBVel *= f;
      Debugger.log("clamped");
    }
    */

    //update colors according to color velocities
    cell.bufferR += cell.bufferRVel;
    cell.bufferG += cell.bufferGVel;
    cell.bufferB += cell.bufferBVel;

    fixBoundaries(cell);

    cell = cell.next;
  }

  //now loop through again, copy buffer values and draw
  cell = list.first;
  while (cell != null) {
    cell.r = cell.bufferR;
    cell.g = cell.bufferG;
    cell.b = cell.bufferB;
    cell.rVel = cell.bufferRVel;
    cell.gVel = cell.bufferGVel;
    cell.bVel = cell.bufferBVel;
    context.fillStyle = `rgb(${~~cell.r},${~~cell.g},${~~cell.b})`;
    context.fillRect(cell.x, cell.y, cellSize.width, cellSize.height);

    cell = cell.next;
  }
}
<commit_msg>Drop array.fill from destructuring assignment on update<commit_after>
const randomColor = () => ({
  r: Math.random() * 255,
  g: Math.random() * 255,
  b: Math.random() * 255
});

const setNeighbours = (cell, grid) => {
  const {i, j} = cell;
  if (i > 0) {
    cell.neighbors.push(grid[i-1][j]);
    grid[i-1][j].neighbors.push(cell);
  }
  if (j > 0) {
    cell.neighbors.push(grid[i][j-1]);
    grid[i][j-1].neighbors.push(cell);
  }
}

const cellFactory = ({width, height}) => (i, j) => {
  const {r, g, b} = randomColor();
  return {
    i, j, r, g, b,
    x: i * width,
    y: j * height,
    bufferR: r,
    bufferG: g,
    bufferB: b,
    rVel: 0,
    gVel: 0,
    bVel: 0,
    bufferRVel: 0,
    bufferGVel: 0,
    bufferBVel: 0,
    neighbors: [],
    neighborPointerList: {}
  };
}

const addToList = (cell, list) => {
  const {i, j} = cell;
  if ((i === 0) && (j === 0)) {
    list.first = cell;
  } else {
    cell.next = list.first;
    list.first = cell;
  }
}

const arrangeNeighbors = (list) => {
  // TODO: this doesn't make much sense
  let cell = list.first;
  while (cell != null) {
    let numNeighbors = 1;
    cell.neighborPointerList.first = {neighbor: cell.neighbors[0]};
    for (let i = 1; i < cell.neighbors.length; i++) {
      const newPointer = {next: cell.neighborPointerList.first};
      cell.neighborPointerList.first = newPointer;
      newPointer.neighbor = cell.neighbors[i];
      ++numNeighbors;
    }
    cell.numNeighbors = numNeighbors;
    cell = cell.next;
  }
}

export const createCells = (cellSize, horizontalCells, verticalCells) => {
  const grid = [];
  const list = {};
  const makeCell = cellFactory(cellSize);
  for (let i = 0; i < horizontalCells; i++) {
    grid.push([]);
    for (let j = 0; j < verticalCells; j++) {
      const newCell = makeCell(i, j);
      setNeighbours(newCell, grid);
      //store cells in a 2D array only for the sake of setting neighbors
      grid[i].push(newCell);
      addToList(newCell, list);
    }
  }
  arrangeNeighbors(list);
  return list;
}

export const restart = list => () => {
  let cell = list.first;
  while (cell) {
    const {r, g, b} = randomColor();
    cell.bufferR = cell.r = r;
    cell.bufferG = cell.g = g;
    cell.bufferB = cell.b = b;
    cell.bufferRVel = cell.rVel = 0;
    cell.bufferGVel = cell.gVel = 0;
    cell.bufferBVel = cell.bVel = 0;
    cell = cell.next;
  }
}

const fixBoundaries = cell => {
  //bounce colors off of color cube boundaries
  if (cell.bufferR < 0) {
    cell.bufferR = 0;
    cell.bufferRVel *= -1;
  } else if (cell.bufferR > 255) {
    cell.bufferR = 255;
    cell.bufferRVel *= -1;
  }

  if (cell.bufferG < 0) {
    cell.bufferG = 0;
    cell.bufferGVel *= -1;
  } else if (cell.bufferG > 255) {
    cell.bufferG = 255;
    cell.bufferGVel *= -1;
  }
  if (cell.bufferB < 0) {
    cell.bufferB = 0;
    cell.bufferBVel *= -1;
  } else if (cell.bufferB > 255) {
    cell.bufferB = 255;
    cell.bufferBVel *= -1;
  }
}

export const tick = (list, cellSize, context, options) => () => {
  let cell = list.first;
  const {ease, minDistSquare, sepNormMag} = options;
  while (cell != null) {
    let [rAve, gAve, bAve, rVelAve, gVelAve, bVelAve, rSep, gSep, bSep]
      = [0, 0, 0, 0, 0, 0, 0, 0, 0];
    let neighborPointer = cell.neighborPointerList.first;
    while (neighborPointer != null) {
      const neighbor = neighborPointer.neighbor;
      rAve += neighbor.r;
      gAve += neighbor.g;
      bAve += neighbor.b;
      rVelAve += neighbor.rVel;
      gVelAve += neighbor.gVel;
      bVelAve += neighbor.bVel;
      const dr = cell.r - neighbor.r;
      const dg = cell.g - neighbor.g;
      const db = cell.b - neighbor.b;
      if (dr*dr + dg*dg + db*db < minDistSquare) {
        rSep += dr;
        gSep += dg;
        bSep += db;
      }
      neighborPointer = neighborPointer.next;
    }

    const f = 1/cell.numNeighbors
    rAve *= f;
    gAve *= f;
    bAve *= f;
    rVelAve *= f;
    gVelAve *= f;
    bVelAve *= f;

    //normalize separation vector
    if ((rSep !== 0) || (gSep !== 0) || (bSep !== 0)) {
      const length = Math.sqrt(rSep*rSep + gSep*gSep + bSep*bSep);
      const sepMagRecip = sepNormMag / length;
      rSep *= sepMagRecip;
      gSep *= sepMagRecip;
      bSep *= sepMagRecip;
    }

    //Update velocity by combining separation, alignment and cohesion effects. Change velocity only by 'ease' ratio.
    cell.bufferRVel += ease * (rSep + rVelAve + rAve - cell.r - cell.bufferRVel);
    cell.bufferGVel += ease * (gSep + gVelAve + gAve - cell.g - cell.bufferGVel);
    cell.bufferBVel += ease * (bSep + bVelAve + bAve - cell.b - cell.bufferBVel);

    //Code for clamping velocity commented out because in my testing, the velocity never went over the max. (But you may wish to restore this
    //code if you experiment with different parameters.)
    /*
    if ((mag = Math.sqrt(cell.bufferRVel*cell.bufferRVel + cell.bufferGVel*cell.bufferGVel + cell.bufferBVel*cell.bufferBVel))> velMax) {
      cell.bufferRVel *= (f = velMax/mag);
      cell.bufferGVel *= f;
      cell.bufferBVel *= f;
      Debugger.log("clamped");
    }
    */

    //update colors according to color velocities
    cell.bufferR += cell.bufferRVel;
    cell.bufferG += cell.bufferGVel;
    cell.bufferB += cell.bufferBVel;

    fixBoundaries(cell);

    cell = cell.next;
  }

  //now loop through again, copy buffer values and draw
  cell = list.first;
  while (cell != null) {
    cell.r = cell.bufferR;
    cell.g = cell.bufferG;
    cell.b = cell.bufferB;
    cell.rVel = cell.bufferRVel;
    cell.gVel = cell.bufferGVel;
    cell.bVel = cell.bufferBVel;
    context.fillStyle = `rgb(${~~cell.r},${~~cell.g},${~~cell.b})`;
    context.fillRect(cell.x, cell.y, cellSize.width, cellSize.height);

    cell = cell.next;
  }
}
<|endoftext|>


<commit_before>'use strict';

var express        = require('express')
  , passport       = require('passport')
  , OpenIDStrategy = require('passport-openid').Strategy
  , _              = require('lodash')
  , app            = express()
  , host           = process.env.HOST
  , port           = process.env.PORT || 3000
;

app.use(express.static('public'));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({ secret: 'no peeking' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);

// Passport configuration

var origin = 'http://'+ host +':'+ port;

passport.use(new OpenIDStrategy({
    returnURL: origin + '/auth/openid/return',
    realm:     origin + '/'
}, function(identifier, done) {
    findUser(identifier, done);
}));

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

passport.deserializeUser(function(id, done) {
    var user = _.find(users, { id: id });
    if (user) {
        done(null, user);
    }
    else {
        done(new Error('no such user'));
    }
});

// Passport authentication endpoints

app.post('/auth/openid', passport.authenticate('openid'));

app.get('/auth/openid/return', passport.authenticate('openid', {
    successRedirect: '/',
    failureRedirect: '/login.html'
}));

// My application endpoints

app.get('/', function(req, res) {
    var body = 'Hello, world!';
    res.setHeader('Content-Type', 'text/plain');
    res.setHeader('Content-Length', body.length);
    res.end(body);
});

app.get('/whoami', function(req, res) {
    var user = req.user
      , tmpl = '
<%= openid %>

member since <%= since %>
';
    if (user) {
        res.setHeader('Content-Type', 'text/html');
        res.end(_.template(tmpl, user));
    }
    else {
        res.redirect('/login.html');
    }
});

app.listen(port);
console.log('Listening on port 3000');
console.log('Realm is: '+ origin);

// Fancy in-memory database

var users = [], lastId = 0;

function findUser(identifier, callback) {
    var user = _.find(users, { openid: identifier });
    if (!user) {
        // new user!
        user = {
            openid: identifier,
            since: new Date(),
            id: ++lastId
        };
        users.push(user);
    }
    callback(null, user);
}
<commit_msg>Adds logout endpoint<commit_after>'use strict';

var express        = require('express')
  , passport       = require('passport')
  , OpenIDStrategy = require('passport-openid').Strategy
  , _              = require('lodash')
  , app            = express()
  , host           = process.env.HOST
  , port           = process.env.PORT || 3000
;

app.use(express.static('public'));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({ secret: 'no peeking' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);

// Passport configuration

var origin = 'http://'+ host +':'+ port;

passport.use(new OpenIDStrategy({
    returnURL: origin + '/auth/openid/return',
    realm:     origin + '/'
}, function(identifier, done) {
    findUser(identifier, done);
}));

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

passport.deserializeUser(function(id, done) {
    var user = _.find(users, { id: id });
    if (user) {
        done(null, user);
    }
    else {
        done(new Error('no such user'));
    }
});

// Passport authentication endpoints

app.post('/auth/openid', passport.authenticate('openid'));

app.get('/auth/openid/return', passport.authenticate('openid', {
    successRedirect: '/',
    failureRedirect: '/login.html'
}));

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

// My application endpoints

app.get('/', function(req, res) {
    var body = 'Hello, world!';
    res.setHeader('Content-Type', 'text/plain');
    res.setHeader('Content-Length', body.length);
    res.end(body);
});

app.get('/whoami', function(req, res) {
    var user = req.user
      , tmpl = '
<%= openid %>

member since <%= since %>
';
    if (user) {
        res.setHeader('Content-Type', 'text/html');
        res.end(_.template(tmpl, user));
    }
    else {
        res.redirect('/login.html');
    }
});

app.listen(port);
console.log('Listening on port 3000');
console.log('Realm is: '+ origin);

// Fancy in-memory database

var users = [], lastId = 0;

function findUser(identifier, callback) {
    var user = _.find(users, { openid: identifier });
    if (!user) {
        // new user!
        user = {
            openid: identifier,
            since: new Date(),
            id: ++lastId
        };
        users.push(user);
    }
    callback(null, user);
}
<|endoftext|>


<commit_before>
var MongoClient = require('mongodb').MongoClient
    , assert = require('assert');

// import express and start express app
var express = require("express")
    , app = express();

// Connection URL
var url = 'mongodb://localhost:27017/progtest';

// configuration
// PLEASE SEE ./config/project.js
// TO SET OPTIONS SUCH AS PORT AND
// API PREFIX
require('./config/progtest')(app);

var routes = require('./routes/index')(app);

console.log("Connecting to database");
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
    assert.equal(null, err);
    console.log("Connected correctly to database");
    app.set("db", db);

    console.log("Progtest API going online...");
// start application
    var port = app.get('port');
    app.listen(port);
    console.log("Progtest API online: listening on port " + port);

});

<commit_msg>Commented out mongo connect commands in app.js. Would need to set up more remote mongo dbs to connect it to which is not worth doing for the master branch<commit_after>
var MongoClient = require('mongodb').MongoClient
    , assert = require('assert');

// import express and start express app
var express = require("express")
    , app = express();

// Connection URL
var url = 'mongodb://localhost:27017/progtest';

// configuration
// PLEASE SEE ./config/project.js
// TO SET OPTIONS SUCH AS PORT AND
// API PREFIX
require('./config/progtest')(app);

var routes = require('./routes/index')(app);

console.log("Connecting to database");
// Use connect method to connect to the Server
//MongoClient.connect(url, function(err, db) {
//    assert.equal(null, err);
//    console.log("Connected correctly to database");
//    app.set("db", db);

    console.log("Progtest API going online...");
// start application
    var port = app.get('port');
    app.listen(port);
    console.log("Progtest API online: listening on port " + port);

//});

<|endoftext|>


<commit_before>var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser')
var app = express();

var wrongTries=0;
var conf={
  pass:"admin",
  users:20,
  lengthOfCodes:32,
  votes:20
}
var codes=[];

//conf
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.use(cookieParser())
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');
app.use(express.static('public'));

var test=0;
var elec=true;
var option = ["Tuna berg", "Erik bark", "Ndushi johan"];

app.get('/', function (req, res) {
  test++;
  res.render('frontend.html', {elec:elec,test:test,options:option});
});

app.get('/loginAdmin', function (req, res) {
  console.log(req.cookies.password);

  res.render('loginAdmin.html');
});
app.post('/loginAdmin', function (req, res) {

  if(req.body.pass==conf.pass){
    res.cookie('password', req.body.pass, { maxAge: 900000, httpOnly: false});
  //  res.send('OK');
    res.redirect('/admin');
  }else{
    res.send('FAIL');
  }

});

app.post('/vote', function (req, res) {
  console.log(req.body);
  //res.send(test+' Hello World!');
});
app.post('/login', function (req, res) {
  console.log(req.body);
>>>>>>> 5efc25126aacbd1fbfb5b263926ac3fb5541dbd9
  //res.send(test+' Hello World!');
});

app.get('/admin', function (req, res) {
  if(req.cookies.password!=conf.pass){
    res.redirect('/loginAdmin');
  }

  res.render('admin.html');
});
app.get('/admin/print', function (req, res) {
  if(req.cookies.password!=conf.pass){
    res.redirect('/loginAdmin');
  }
  res.render('print.html',{codes:generateCodes()});
});

var generateCodes=function(){
  for(var i=0;i<conf.users;i++){
    temp=[];
    for(var j=0;j<conf.votes;j++){
      temp.push(randomString(conf.lengthOfCodes, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'));
    }
    codes.push(temp);
  }
  return codes;
}

function randomString(length, chars) {
    var result = '';
    for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
    return result;
}

//server start stuff.
var server = app.listen(3001, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});
<commit_msg>fix merge<commit_after>var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser')
var app = express();

var wrongTries=0;
var conf={
  pass:"admin",
  users:20,
  lengthOfCodes:32,
  votes:20
}
var codes=[];

//conf
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.use(cookieParser())
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');
app.use(express.static('public'));

var test=0;
var elec=true;
var option = ["Tuna berg", "Erik bark", "Ndushi johan"];

app.get('/', function (req, res) {
  test++;
  res.render('frontend.html', {elec:elec,test:test,options:option});
});

app.get('/loginAdmin', function (req, res) {
  console.log(req.cookies.password);

  res.render('loginAdmin.html');
});
app.post('/loginAdmin', function (req, res) {

  if(req.body.pass==conf.pass){
    res.cookie('password', req.body.pass, { maxAge: 900000, httpOnly: false});
  //  res.send('OK');
    res.redirect('/admin');
  }else{
    res.send('FAIL');
  }

});

app.post('/vote', function (req, res) {
  console.log(req.body);
  //res.send(test+' Hello World!');
});
app.post('/login', function (req, res) {
  console.log(req.body);
  //res.send(test+' Hello World!');
});

app.get('/admin', function (req, res) {
  if(req.cookies.password!=conf.pass){
    res.redirect('/loginAdmin');
  }

  res.render('admin.html');
});
app.get('/admin/print', function (req, res) {
  if(req.cookies.password!=conf.pass){
    res.redirect('/loginAdmin');
  }
  res.render('print.html',{codes:generateCodes()});
});

var generateCodes=function(){
  for(var i=0;i<conf.users;i++){
    temp=[];
    for(var j=0;j<conf.votes;j++){
      temp.push(randomString(conf.lengthOfCodes, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'));
    }
    codes.push(temp);
  }
  return codes;
}

function randomString(length, chars) {
    var result = '';
    for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
    return result;
}

//server start stuff.
var server = app.listen(3001, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});
<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var _ = require('lodash');
var CronJob = require('cron').CronJob;
var log = require('log-to-file-and-console-node');
var MessageController = require('./controller/message');
var BotHandler = require('./route/botHandler');
var TelegramBot = require('node-telegram-bot-api');
var async = require('async');

var app = express();
var bot = new TelegramBot(process.env.TELEGRAM_BOT_TOKEN, {polling: true});

var connectionString = '127.0.0.1:27017/jung2bot';
if (process.env.MONGODB_URL) {
  connectionString = process.env.MONGODB_URL + 'jung2bot';
} else if (process.env.OPENSHIFT_MONGODB_DB_PASSWORD) {
  connectionString = process.env.OPENSHIFT_MONGODB_DB_USERNAME + ':' +
    process.env.OPENSHIFT_MONGODB_DB_PASSWORD + '@' +
    process.env.OPENSHIFT_MONGODB_DB_HOST + ':' +
    process.env.OPENSHIFT_MONGODB_DB_PORT + '/' +
    process.env.OPENSHIFT_APP_NAME;
}
mongoose.connect(connectionString, {db: {nativeParser: true}});

app.use(morgan('combined', {'stream': log.stream}));
app.use(bodyParser.json());

var root = require('./route/root');
app.use('/', root);

bot.onText(/\/top(t|T)en/, function (msg, match) {
  BotHandler.onTopTen(msg, bot);
});

bot.onText(/\/all(j|J)ung/, function (msg, match) {
  BotHandler.onAllJung(msg, bot);
});

bot.onText(/\/help/, function (msg, match) {
  BotHandler.onHelp(msg, bot);
});

bot.onText(/\/jung(p|P)remier(l|L)eague/, function (msg, match) {
  BotHandler.onJungPremierLeagueTable(msg, bot);
});

bot.on('message', function (msg) {
  BotHandler.onMessage(msg);
});

var job = new CronJob({
  cronTime: '00 00 18 * * 1-5',
  //cronTime: '*/5 * * * * *',
  onTick: function () {
    MessageController.getAllGroupIds().then(function (chatIds) {
      async.each(chatIds, function (chatId, callback) {
        var msg = {
          chat: {
            id: chatId
          }
        };
        bot.sendMessage(chatId, '夠鐘收工~~');
        MessageController.getTopTen(msg, true).then(function (message) {
          if (!_.isEmpty(message)) {
            bot.sendMessage(chatId, message);
          }
        });
      });
    });
  },
  start: true,
  timeZone: 'Asia/Hong_Kong'
});

module.exports = app;<commit_msg>anti spam<commit_after>'use strict';

var express = require('express');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var _ = require('lodash');
var CronJob = require('cron').CronJob;
var log = require('log-to-file-and-console-node');
var MessageController = require('./controller/message');
var BotHandler = require('./route/botHandler');
var TelegramBot = require('node-telegram-bot-api');
var async = require('async');

var app = express();
var bot = new TelegramBot(process.env.TELEGRAM_BOT_TOKEN, {polling: true});

var connectionString = '127.0.0.1:27017/jung2bot';
if (process.env.MONGODB_URL) {
  connectionString = process.env.MONGODB_URL + 'jung2bot';
} else if (process.env.OPENSHIFT_MONGODB_DB_PASSWORD) {
  connectionString = process.env.OPENSHIFT_MONGODB_DB_USERNAME + ':' +
    process.env.OPENSHIFT_MONGODB_DB_PASSWORD + '@' +
    process.env.OPENSHIFT_MONGODB_DB_HOST + ':' +
    process.env.OPENSHIFT_MONGODB_DB_PORT + '/' +
    process.env.OPENSHIFT_APP_NAME;
}
mongoose.connect(connectionString, {db: {nativeParser: true}});

app.use(morgan('combined', {'stream': log.stream}));
app.use(bodyParser.json());

var root = require('./route/root');
app.use('/', root);

bot.onText(/\/top(t|T)en/, function (msg, match) {
  BotHandler.onTopTen(msg, bot);
});

bot.onText(/\/all(j|J)ung/, function (msg, match) {
  BotHandler.onAllJung(msg, bot);
});

bot.onText(/\/help/, function (msg, match) {
  BotHandler.onHelp(msg, bot);
});

bot.onText(/\/jung(p|P)remier(l|L)eague/, function (msg, match) {
  BotHandler.onJungPremierLeagueTable(msg, bot);
});

// TODO: code refactoring required
var spamRecord = {};
var checkSpam = function (msg) {
  var chatId = msg.chat.id;
  if (!spamRecord[chatId]) {
    spamRecord[chatId] = 0;
  }
  spamRecord[chatId]++;
  // assume max conversation rate = 0.2 msg/s
  return spamRecord[chatId] < 720; // max 720 msg per hour in a group
};

var checkSpamJob = new CronJob({
  cronTime: '00 00 */1 * * *',
  onTick: function () {
    spamRecord = {};
  },
  start: true,
  timeZone: 'Asia/Hong_Kong'
});

bot.on('message', function (msg) {
  if (checkSpam(msg)) {
    BotHandler.onMessage(msg);
  }
});

var job = new CronJob({
  cronTime: '00 00 18 * * 1-5',
  //cronTime: '*/5 * * * * *',
  onTick: function () {
    MessageController.getAllGroupIds().then(function (chatIds) {
      async.each(chatIds, function (chatId, callback) {
        var msg = {
          chat: {
            id: chatId
          }
        };
        bot.sendMessage(chatId, '夠鐘收工~~');
        MessageController.getTopTen(msg, true).then(function (message) {
          if (!_.isEmpty(message)) {
            bot.sendMessage(chatId, message);
          }
        });
      });
    });
  },
  start: true,
  timeZone: 'Asia/Hong_Kong'
});

module.exports = app;<|endoftext|>


<commit_before>function timestamp(seconds) {
    var sec = Math.floor(seconds % 60);
    var min = Math.floor((seconds / 60) % 60);
    var hours = Math.floor((min / 60) % 60);

    if (sec < 10) {
        sec = "0" + sec;
    }
    if (min < 10) {
        min = "0" + min;
    }

    return (hours ? (hours + ":") : "") + min + ":" + sec;
}

function App() {
    this.user = API.getUser();
    this.registerCommands([
        {
            name: "autowoot",
            args: "[0|1]",
            desc: "get/set autowoot",
            help: "Call without parameters to get autowoot status.  Call with a 0 or 1 to disable/enable autowoot.",
            func: this.autoWoot
        },
        {
            name: "leaveafter",
            args: "[n|?|cancel]",
            desc: "leave after your next track or n track(s)",
            help: "Without arguments, leaves the DJ booth after you play your next song. " +
                  "With an int argument, leave after you have played that number of tracks. " +
                  "With '-1' or 'cancel', cancels the leaveafter command. " +
                  "With '?', prints the number of remaining tracks.",
            func: this.leaveafter
        },
        {
            name: "?",
            args: "[cmd]",
            desc: "lists info on commands",
            help: "Call without parameters to list commands or call with the name of a command to get specific help on that command.",
            func: this.help
        }
    ]);

    if (this.autoWootEnabled) {
        this.clickWoot();
    }

    if (this.leaveAfterCount || this.leaveAfterCount === 0) {
        this.addCheckLeaveListeners();
    }

    this.addHooks();
}

App.prototype = Object.create(Object.prototype, {
    constructor: App,
    commands: { value: {} },
    autoWootEnabled: {
        get: function () {
            return localStorage["auto-woot"] === "true";
        },
        set: function (val) {
            localStorage["auto-woot"] = val;
        }
    },
    isCurrentDJ: {
        get: function () {
            var djs = API.getDJs();
            if (djs.length) {
                return this.user && this.user.id === djs[0].id;
            } else {
                return false;
            }
        },
    },
    isQueued: {
        get: function () {
            var self = this;
            return API.getDJs().some(function (dj) {
                return self.user.id && self.user.id === dj.id;
            });
        },
    },
    leaveAfterCount: {
        get: function () {
            // make sure we only return an int or null
            var val = parseInt(localStorage["leaveafter"]);
            if (isNaN(val)) {
                val = null;
            };
            return val;
        },
        set: function (val) {
            localStorage["leaveafter"] = val;
        }
    }
});

App.prototype.registerCommands= function (cmds) {
    var self = this;
    cmds.forEach(function (cmd) {
        self.commands[cmd.name] = cmd;
    });
}

App.prototype.addHooks = function () {
    var self = this;
    // RM: this is probably not necessary since Backbone takes a context with the register
    function hookIt(event, fn) {
        API.on(event, function () {
            fn.apply(self, arguments);
        });
    }
    hookIt(API.CHAT_COMMAND, this.onChatCommand);
    hookIt(API.DJ_ADVANCE, this.onDJAdvance);
    API.on(API.CURATE_UPDATE, this.onCurateUpdate, this);
}

App.prototype.onCurateUpdate = function (data) {
    console.log(arguments);
    API.chatLog(data.user.username + " grabbed \"" + API.getMedia().title + "\"!");
}

App.prototype.onChatCommand = function (command) {
    var split = command.split(" ");
    var name = split[0].substring(1);
    var cmd = this.commands[name];
    var args = Array.prototype.slice.call(split, 1);

    if (cmd) {
        console.debug("executing command", cmd, "with args", args);
        try {
            cmd.func.call(this, name, args);
        } catch (e) {
            API.chatLog("error executing command", true);
            console.error("error executing command:", e);
            if (e.stack) {
                console.error("stack:\n", e.stack);
            }
        }
    } else {
        API.chatLog("No such command", true);
        this.help();
    }
}

App.prototype.onDJAdvance = function (data) {
    if (data && data.media) {
        var media = data.media;
        window.postMessage({
            action: 'notify',
            message: "Now Playing: " + media.author + " - " + media.title + " (" + timestamp(media.duration) + ")"
        }, "http://plug.dj");

        if (this.autoWootEnabled) {
            this.clickWoot();
        };
    }
}

App.prototype.autoWoot = function (cmd, args) {
    if (args.length === 1) {
        if (parseInt(args[0]) === 1) {
            this.autoWootEnabled = true;
            this.clickWoot();
        } else {
            this.autoWootEnabled = false;
        }
    }
    API.chatLog("AutoWoot: " + (this.autoWootEnabled ? "enabled" : "disabled"));
}

App.prototype.checkLeave = function () {
    if (this.leaveAfterCount === 0) {
        this.leaveAfterCount = null;
        this.removeCheckLeaveListeners();
        API.djLeave();
    }
    this.updateLeaveAfterCount();
}
App.prototype.updateLeaveAfterCount = function() {
    if (this.isCurrentDJ) {
        if (this.leaveAfterCount) {
            this.leaveAfterCount--;
            this.showLeaveAfterCount();
        }
    }
}
App.prototype.checkUpdateForLeave = function () {
    if (!this.isQueued && !this.isCurrentDJ) {
        API.chatLog("Canceling leaveafter");
        this.leaveAfterCount = null;
        this.removeCheckLeaveListeners();
    }
}
App.prototype.showLeaveAfterCount = function () {
    if (this.leaveAfterCount) {
        API.chatLog("Leaving after " + this.leaveAfterCount + " more track(s).");
    } else if (this.leaveAfterCount === 0) {
        API.chatLog("Leaving after this track.");
    } else {
        API.chatLog("leaveafter not enabled");
    }
}
App.prototype.leaveafter = function (cmd, args) {
    if (args.length === 1) {
        var leaveAfterArg = args[0];
        var leaveAfterCount = parseInt(leaveAfterArg);

        if (!isNaN(leaveAfterCount) && (leaveAfterCount >= 0)) {
            this.leaveAfterCount = leaveAfterCount;
            this.addCheckLeaveListeners();

            // RM: don't want to print a message twice...
            if (!this.isCurrentDJ) {
                this.showLeaveAfterCount();
            } else {
                this.updateLeaveAfterCount();
            }
        } else if (leaveAfterArg == "?") {
            this.showLeaveAfterCount();
        } else if ((!isNaN(leaveAfterCount) && (leaveAfterCount === -1))
                   || leaveAfterArg == "cancel") {
            this.leaveAfterCount = null;
            this.removeCheckLeaveListeners();
            API.chatLog("leaveafter cancelled.")
        } else {
            API.chatLog("Invalid argument: " + leaveAfterArg, true);
        }
    } else if (args.length === 0) {
        this.leaveAfterCount = 1;
        this.addCheckLeaveListeners();
        this.updateLeaveAfterCount();
    }
}

App.prototype.addCheckLeaveListeners = function() {
    if (!this.leaveListenersAdded) {
        this.leaveListenersAdded = true;
        API.on(API.DJ_ADVANCE, this.checkLeave, this);
        API.on(API.DJ_UPDATE, this.checkUpdateForLeave, this);
    }
}

App.prototype.removeCheckLeaveListeners = function() {
    API.off(API.DJ_ADVANCE, this.checkLeave);
    API.off(API.DJ_UPDATE, this.checkUpdateForLeave);
    this.leaveListenersAdded = false;
}

App.prototype.clickWoot = function() {
    $("#woot").click();
}

App.prototype.printCommands = function (helpCmd) {
    var self = this;

    function printHelp(cmd) {
        var hasArgs = cmd.args != null;
        API.chatLog("/" + cmd.name +
                    (hasArgs ? (" " + cmd.args) : "") +
                    " -- " + cmd.desc);
    }

    API.chatLog("Commands:");
    printHelp(this.commands[helpCmd]);
    Object.keys(this.commands).forEach(function (name) {
        if (name !== helpCmd) {
            printHelp(self.commands[name]);
        }
    });
}
App.prototype.help = function (name, args) {
    if (args.length === 1) {
        var cmd = this.commands[args[0]];
        if (cmd) {
            if (cmd.help) {
                API.chatLog(cmd.help);
            } else if (cmd.desc) {
                API.chatLog(cmd.desc);
            } else {
                API.chatLog("no help available");
            }
        }
    } else {
        this.printCommands("?");
    }
}

var app;
var apiInterval = setInterval(function () {
    if (typeof(API) !== "undefined") {
        clearInterval(apiInterval);
        app = new App();
        console.log("plug.dj script loaded");
    }
}, 1000);
<commit_msg>For Issue #1 - /brb command (named to avoid colliding with existing /afk cmd, which only goes afk): posts emote message and chat-log, sets status to AFK, leaves after next track. Up next: save off autowoot status and restore on return.<commit_after>function timestamp(seconds) {
    var sec = Math.floor(seconds % 60);
    var min = Math.floor((seconds / 60) % 60);
    var hours = Math.floor((min / 60) % 60);

    if (sec < 10) {
        sec = "0" + sec;
    }
    if (min < 10) {
        min = "0" + min;
    }

    return (hours ? (hours + ":") : "") + min + ":" + sec;
}

function App() {
    this.user = API.getUser();
    this.registerCommands([
        {
            name: "autowoot",
            args: "[0|1]",
            desc: "get/set autowoot",
            help: "Call without parameters to get autowoot status.  Call with a 0 or 1 to disable/enable autowoot.",
            func: this.autoWoot
        },
        {
            name: "leaveafter",
            args: "[n|?|cancel]",
            desc: "leave after your next track or n track(s)",
            help: "Without arguments, leaves the DJ booth after you play your next song. " +
                  "With an int argument, leave after you have played that number of tracks. " +
                  "With '-1' or 'cancel', cancels the leaveafter command. " +
                  "With '?', prints the number of remaining tracks.",
            func: this.leaveafter
        },
        {
            name : "brb",
            args : "[0|1]",
            desc : "get/set AFK status",
            help : "Call without parameters to get AFK status. Call with 0 or 1 to disable/enable AFK status",
            func : this.brb
        },
        {
            name: "?",
            args: "[cmd]",
            desc: "lists info on commands",
            help: "Call without parameters to list commands or call with the name of a command to get specific help on that command.",
            func: this.help
        }
    ]);

    if (this.autoWootEnabled) {
        this.clickWoot();
    }

    if (this.leaveAfterCount || this.leaveAfterCount === 0) {
        this.addCheckLeaveListeners();
    }

    this.addHooks();
}

App.prototype = Object.create(Object.prototype, {
    constructor: App,
    commands: { value: {} },
    autoWootEnabled: {
        get: function () {
            return localStorage["auto-woot"] === "true";
        },
        set: function (val) {
            localStorage["auto-woot"] = val;
        }
    },
    isCurrentDJ: {
        get: function () {
            var djs = API.getDJs();
            if (djs.length) {
                return this.user && this.user.id === djs[0].id;
            } else {
                return false;
            }
        },
    },
    isQueued: {
        get: function () {
            var self = this;
            return API.getDJs().some(function (dj) {
                return self.user.id && self.user.id === dj.id;
            });
        },
    },
    leaveAfterCount: {
        get: function () {
            // make sure we only return an int or null
            var val = parseInt(localStorage["leaveafter"]);
            if (isNaN(val)) {
                val = null;
            };
            return val;
        },
        set: function (val) {
            localStorage["leaveafter"] = val;
        }
    }
});

App.prototype.registerCommands= function (cmds) {
    var self = this;
    cmds.forEach(function (cmd) {
        self.commands[cmd.name] = cmd;
    });
}

App.prototype.addHooks = function () {
    var self = this;
    // RM: this is probably not necessary since Backbone takes a context with the register
    function hookIt(event, fn) {
        API.on(event, function () {
            fn.apply(self, arguments);
        });
    }
    hookIt(API.CHAT_COMMAND, this.onChatCommand);
    hookIt(API.DJ_ADVANCE, this.onDJAdvance);
    API.on(API.CURATE_UPDATE, this.onCurateUpdate, this);
}

App.prototype.onCurateUpdate = function (data) {
    console.log(arguments);
    API.chatLog(data.user.username + " grabbed \"" + API.getMedia().title + "\"!");
}

App.prototype.onChatCommand = function (command) {
    var split = command.split(" ");
    var name = split[0].substring(1);
    var cmd = this.commands[name];
    var args = Array.prototype.slice.call(split, 1);

    if (cmd) {
        console.debug("executing command", cmd, "with args", args);
        try {
            cmd.func.call(this, name, args);
        } catch (e) {
            API.chatLog("error executing command", true);
            console.error("error executing command:", e);
            if (e.stack) {
                console.error("stack:\n", e.stack);
            }
        }
    } else {
        API.chatLog("No such command", true);
        this.help();
    }
}

App.prototype.onDJAdvance = function (data) {
    if (data && data.media) {
        var media = data.media;
        window.postMessage({
            action: 'notify',
            message: "Now Playing: " + media.author + " - " + media.title + " (" + timestamp(media.duration) + ")"
        }, "http://plug.dj");

        if (this.autoWootEnabled) {
            this.clickWoot();
        };
    }
}

App.prototype.autoWoot = function (cmd, args) {
    if (args.length === 1) {
        if (parseInt(args[0]) === 1) {
            this.autoWootEnabled = true;
            this.clickWoot();
        } else {
            this.autoWootEnabled = false;
        }
    }
    API.chatLog("AutoWoot: " + (this.autoWootEnabled ? "enabled" : "disabled"));
}

App.prototype.brb  = function (cmd, args) {
    if (args.length === 1)
    {
        if (parseInt(args[0]) === 1)
        {

            API.chatLog("Going AFK");
            API.sendChat("/em Going AFK...");
            this.leaveAfterCount = 1;
            this.addCheckLeaveListeners();
            this.updateLeaveAfterCount();
            API.setStatus(API.STATUS.AFK);
        }
        else
        {
            API.chatLog("Returning from AFK");
            API.sendChat("/em Back from AFK.");
            API.setStatus(API.STATUS.AVAILABLE);
        }
    }
    else
    {
        API.chatLog("AFK: " + ((API.STATUS.AFK === API.getUser().status) ? "enabled" : "disabled"));
    }
}

App.prototype.checkLeave = function () {
    if (this.leaveAfterCount === 0) {
        this.leaveAfterCount = null;
        this.removeCheckLeaveListeners();
        API.djLeave();
    }
    this.updateLeaveAfterCount();
}
App.prototype.updateLeaveAfterCount = function() {
    if (this.isCurrentDJ) {
        if (this.leaveAfterCount) {
            this.leaveAfterCount--;
            this.showLeaveAfterCount();
        }
    }
}
App.prototype.checkUpdateForLeave = function () {
    if (!this.isQueued && !this.isCurrentDJ) {
        API.chatLog("Canceling leaveafter");
        this.leaveAfterCount = null;
        this.removeCheckLeaveListeners();
    }
}
App.prototype.showLeaveAfterCount = function () {
    if (this.leaveAfterCount) {
        API.chatLog("Leaving after " + this.leaveAfterCount + " more track(s).");
    } else if (this.leaveAfterCount === 0) {
        API.chatLog("Leaving after this track.");
    } else {
        API.chatLog("leaveafter not enabled");
    }
}
App.prototype.leaveafter = function (cmd, args) {
    if (args.length === 1) {
        var leaveAfterArg = args[0];
        var leaveAfterCount = parseInt(leaveAfterArg);

        if (!isNaN(leaveAfterCount) && (leaveAfterCount >= 0)) {
            this.leaveAfterCount = leaveAfterCount;
            this.addCheckLeaveListeners();

            // RM: don't want to print a message twice...
            if (!this.isCurrentDJ) {
                this.showLeaveAfterCount();
            } else {
                this.updateLeaveAfterCount();
            }
        } else if (leaveAfterArg == "?") {
            this.showLeaveAfterCount();
        } else if ((!isNaN(leaveAfterCount) && (leaveAfterCount === -1))
                   || leaveAfterArg == "cancel") {
            this.leaveAfterCount = null;
            this.removeCheckLeaveListeners();
            API.chatLog("leaveafter cancelled.")
        } else {
            API.chatLog("Invalid argument: " + leaveAfterArg, true);
        }
    } else if (args.length === 0) {
        this.leaveAfterCount = 1;
        this.addCheckLeaveListeners();
        this.updateLeaveAfterCount();
    }
}

App.prototype.addCheckLeaveListeners = function() {
    if (!this.leaveListenersAdded) {
        this.leaveListenersAdded = true;
        API.on(API.DJ_ADVANCE, this.checkLeave, this);
        API.on(API.DJ_UPDATE, this.checkUpdateForLeave, this);
    }
}

App.prototype.removeCheckLeaveListeners = function() {
    API.off(API.DJ_ADVANCE, this.checkLeave);
    API.off(API.DJ_UPDATE, this.checkUpdateForLeave);
    this.leaveListenersAdded = false;
}

App.prototype.clickWoot = function() {
    $("#woot").click();
}

App.prototype.printCommands = function (helpCmd) {
    var self = this;

    function printHelp(cmd) {
        var hasArgs = cmd.args != null;
        API.chatLog("/" + cmd.name +
                    (hasArgs ? (" " + cmd.args) : "") +
                    " -- " + cmd.desc);
    }

    API.chatLog("Commands:");
    printHelp(this.commands[helpCmd]);
    Object.keys(this.commands).forEach(function (name) {
        if (name !== helpCmd) {
            printHelp(self.commands[name]);
        }
    });
}
App.prototype.help = function (name, args) {
    if (args.length === 1) {
        var cmd = this.commands[args[0]];
        if (cmd) {
            if (cmd.help) {
                API.chatLog(cmd.help);
            } else if (cmd.desc) {
                API.chatLog(cmd.desc);
            } else {
                API.chatLog("no help available");
            }
        }
    } else {
        this.printCommands("?");
    }
}

var app;
var apiInterval = setInterval(function () {
    if (typeof(API) !== "undefined") {
        clearInterval(apiInterval);
        app = new App();
        console.log("plug.dj script loaded");
    }
}, 1000);
<|endoftext|>


<commit_before>var myApp = angular.module('weather', []);

myApp.controller('WeatherController', ['$scope', function($scope, $htpp) {
	$scope.currWeather = "hi";

	$http.get("http://api.wunderground.com/api/d2c25648f13d77b5/forecast/q/CA/San_Francisco.json")
	  .then(function(response){
			$scope.currWeather = response.forecast.txt_forecast.forecastday[0].fctext;
		});
}]);
<commit_msg>forgot first http<commit_after>var myApp = angular.module('weather', []);

myApp.controller('WeatherController', ['$scope', '$http', function($scope, $htpp) {
	$scope.currWeather = "hi";

	$http.get("http://api.wunderground.com/api/d2c25648f13d77b5/forecast/q/CA/San_Francisco.json")
	  .then(function(response){
			$scope.currWeather = response.forecast.txt_forecast.forecastday[0].fctext;
		});
}]);
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;
<commit_msg>Quitar el middleware de users<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;
<|endoftext|>


<commit_before>var userName = prompt("what is your name?");
var counter = 0;
//alert ("Hi there, " + userName + ". You will be asked 4 questions today (3 of them about this developer). Please answer 'Y' for yes and 'N' for No");
console.log("the user's name is " + userName);

//First question block

function firstQuestion(){
  var res1 = document.getElementById('firstAnswer');
  var questionOne = prompt("is my name Hugo?");
  questionOne = questionOne.toUpperCase();
  console.log(userName + " answered the question with " + questionOne);
     if (questionOne === 'Y' || questionOne === 'YES') {
       res1.textContent = ("you are right, " + userName + "! For the record, your answer was " + questionOne);
       counter += 1;  //counts right answer
       console.log(userName + " has answered " + counter + " questions correctly");
   } else {
     res1.textContent = ("you are wrong, " + userName + " but that's ok! For the record, your answer was " + questionOne);
   }

}
function secondQuestion(){
  var res2 = document.getElementById('secondAnswer');
  //Second question block
   var questionTwo = prompt("am I a llama?");
   questionTwo = questionTwo.toUpperCase();
   console.log(userName +" answered the question with " + questionTwo);
   if (questionTwo === 'N' || questionTwo === 'NO') {
     res2.textContent = ("you are right, " + userName + "! For the record, your answer was " + questionTwo);
     counter += 1; //counts right answer
     console.log(userName + " has answered " + counter + " questions correctly");
  } else {
   res2.textContent = ("you are wrong, " + userName + " but that's ok! For the record, your answer was " + questionTwo);
  }

}
function thirdQuestion(){
  var res3 = document.getElementById('thirdAnswer');
  //Third question block
    var questionThree = prompt("Do I like coding?");
    questionThree = questionThree.toUpperCase();
    console.log(userName + " answered the question with " + questionThree);
    if (questionThree === 'Y' || questionThree === 'YES') {
      res2.textContent = ("you are right, " + userName + "! For the record, your answer was " + questionThree);
      counter += 1; //counts right answer
      console.log(userName + " has answered " + counter + " questions correctly");
  } else {
    res2.textContent = ("you are wrong, " + userName + " but that's ok! For the record, your answer was " + questionThree);
  }

}
// function firstQuestion(){
//   var res1 = document.getElementById('firstAnswer');
//
//
// }
// function firstQuestion(){
//   var res1 = document.getElementById('firstAnswer');
//
//
// }

// var questionOne = prompt("is my name Hugo?");
// questionOne = questionOne.toUpperCase();
// console.log(userName + " answered the question with " + questionOne);
//    if (questionOne === 'Y' || questionOne === 'YES') {
//      alert ("you are right, " + userName + "! For the record, your answer was " + questionOne);
//      counter += 1;  //counts right answer
//      console.log(userName + " has answered " + counter + " questions correctly");
//  } else {
//    alert ("you are wrong, " + userName + " but that's ok! For the record, your answer was " + questionOne);
//  }
//
//Second question block
//  var questionTwo = prompt("am I a llama?");
//  questionTwo = questionTwo.toUpperCase();
//  console.log(userName +" answered the question with " + questionTwo);
//  if (questionTwo === 'N' || questionTwo === 'NO') {
//    alert ("you are right, " + userName + "! For the record, your answer was " + questionTwo);
//    counter += 1; //counts right answer
//    console.log(userName + " has answered " + counter + " questions correctly");
// } else {
//  alert ("you are wrong, " + userName + " but that's ok! For the record, your answer was " + questionTwo);
// }
//
// //Third question block
//   var questionThree = prompt("Do I like coding?");
//   questionThree = questionThree.toUpperCase();
//   console.log(userName + " answered the question with " + questionThree);
//   if (questionThree === 'Y' || questionThree === 'YES') {
//     alert ("you are right, " + userName + "! For the record, your answer was " + questionThree);
//     counter += 1; //counts right answer
//     console.log(userName + " has answered " + counter + " questions correctly");
// } else {
//   alert ("you are wrong, " + userName + " but that's ok! For the record, your answer was " + questionThree);
// }
//
// //Congrats alert prior to number question
// alert ("Congratulations, " + userName +", You've answered " + counter + " questions right so far!")
//
// //Number question block
//    var bonusQuestion = prompt("Now for something completely different: I'm thinking of a number between 1 and 10. Guess as many times as you need until you get it right. Afterwards, I'll tell you how many times you failed miserably before getting it right (no pressure)");
//    console.log(userName +" answered the question with " + bonusQuestion);
//    var numberQuestionWrongCounter = 0;
//    while (bonusQuestion != 6) {
//       numberQuestionWrongCounter += 1;
//       alert("Wrong. So, so wrong. You've guessed " + numberQuestionWrongCounter + " times so far. Please take this more seriously and try again");
//       bonusQuestion = prompt("So once again, what number am I thinking of? (between 1 and 10)");
//     }
// //Final congratulatory alert
//
// alert("You got it right, " + userName + "! Just so you know, it took you " + numberQuestionWrongCounter + " tries to get it right. So yeah, think about that for a while and feel bad.");

//firstQuestion();
secondQuestion();
<commit_msg>finished switching existing questions to functions<commit_after>var userName = prompt("what is your name?");
var counter = 0;
//alert ("Hi there, " + userName + ". You will be asked 4 questions today (3 of them about this developer). Please answer 'Y' for yes and 'N' for No");
console.log("the user's name is " + userName);

//First question block

function firstQuestion(){
  var res1 = document.getElementById('firstAnswer');
  var questionOne = prompt("is my name Hugo?");
  questionOne = questionOne.toUpperCase();
  console.log(userName + " answered the question with " + questionOne);
     if (questionOne === 'Y' || questionOne === 'YES') {
       res1.textContent = ("you are right, " + userName + "! For the record, your answer was " + questionOne);
       counter += 1;  //counts right answer
       console.log(userName + " has answered " + counter + " questions correctly");
   } else {
     res1.textContent = ("you are wrong, " + userName + " but that's ok! For the record, your answer was " + questionOne);
   }

}
function secondQuestion(){
  var res2 = document.getElementById('secondAnswer');
  //Second question block
   var questionTwo = prompt("am I a llama?");
   questionTwo = questionTwo.toUpperCase();
   console.log(userName +" answered the question with " + questionTwo);
   if (questionTwo === 'N' || questionTwo === 'NO') {
     res2.textContent = ("you are right, " + userName + "! For the record, your answer was " + questionTwo);
     counter += 1; //counts right answer
     console.log(userName + " has answered " + counter + " questions correctly");
  } else {
   res2.textContent = ("you are wrong, " + userName + " but that's ok! For the record, your answer was " + questionTwo);
  }

}
function thirdQuestion(){
  var res3 = document.getElementById('thirdAnswer');
  //Third question block
    var questionThree = prompt("Do I like coding?");
    questionThree = questionThree.toUpperCase();
    console.log(userName + " answered the question with " + questionThree);
    if (questionThree === 'Y' || questionThree === 'YES') {
      res3.textContent = ("you are right, " + userName + "! For the record, your answer was " + questionThree);
      counter += 1; //counts right answer
      console.log(userName + " has answered " + counter + " questions correctly");
  } else {
    res3.textContent = ("you are wrong, " + userName + " but that's ok! For the record, your answer was " + questionThree);
  }

}

function fourthQuestion(){
  var res4 = document.getElementById('fourthAnswer');
  //Number question block
  var bonusQuestion = prompt("Now for something completely different: I'm thinking of a number between 1 and 10. Guess as many times as you need until you get it right. Afterwards, I'll tell you how many times you failed miserably before getting it right (no pressure)");
  console.log(userName +" answered the question with " + bonusQuestion);
  var numberQuestionWrongCounter = 0;
  while (bonusQuestion != 6) {
    numberQuestionWrongCounter += 1;
    res4.textContent = ("Wrong. So, so wrong. You've guessed " + numberQuestionWrongCounter + " times so far. Please take this more seriously and try again");
    bonusQuestion = prompt("So once again, what number am I thinking of? (between 1 and 10)");
  }
  res4.textContent = ("You got it right, " + userName + "! Just so you know, it took you " + numberQuestionWrongCounter + " tries to get it right. So yeah, think about that for a while and feel bad.");
}
// function firstQuestion(){
//   var res1 = document.getElementById('firstAnswer');
//
//
// }

// var questionOne = prompt("is my name Hugo?");
// questionOne = questionOne.toUpperCase();
// console.log(userName + " answered the question with " + questionOne);
//    if (questionOne === 'Y' || questionOne === 'YES') {
//      alert ("you are right, " + userName + "! For the record, your answer was " + questionOne);
//      counter += 1;  //counts right answer
//      console.log(userName + " has answered " + counter + " questions correctly");
//  } else {
//    alert ("you are wrong, " + userName + " but that's ok! For the record, your answer was " + questionOne);
//  }
//
//Second question block
//  var questionTwo = prompt("am I a llama?");
//  questionTwo = questionTwo.toUpperCase();
//  console.log(userName +" answered the question with " + questionTwo);
//  if (questionTwo === 'N' || questionTwo === 'NO') {
//    alert ("you are right, " + userName + "! For the record, your answer was " + questionTwo);
//    counter += 1; //counts right answer
//    console.log(userName + " has answered " + counter + " questions correctly");
// } else {
//  alert ("you are wrong, " + userName + " but that's ok! For the record, your answer was " + questionTwo);
// }
//
// //Third question block
//   var questionThree = prompt("Do I like coding?");
//   questionThree = questionThree.toUpperCase();
//   console.log(userName + " answered the question with " + questionThree);
//   if (questionThree === 'Y' || questionThree === 'YES') {
//     alert ("you are right, " + userName + "! For the record, your answer was " + questionThree);
//     counter += 1; //counts right answer
//     console.log(userName + " has answered " + counter + " questions correctly");
// } else {
//   alert ("you are wrong, " + userName + " but that's ok! For the record, your answer was " + questionThree);
// }
//
// //Congrats alert prior to number question
// alert ("Congratulations, " + userName +", You've answered " + counter + " questions right so far!")
//
// //Number question block
//    var bonusQuestion = prompt("Now for something completely different: I'm thinking of a number between 1 and 10. Guess as many times as you need until you get it right. Afterwards, I'll tell you how many times you failed miserably before getting it right (no pressure)");
//    console.log(userName +" answered the question with " + bonusQuestion);
//    var numberQuestionWrongCounter = 0;
//    while (bonusQuestion != 6) {
//       numberQuestionWrongCounter += 1;
//       alert("Wrong. So, so wrong. You've guessed " + numberQuestionWrongCounter + " times so far. Please take this more seriously and try again");
//       bonusQuestion = prompt("So once again, what number am I thinking of? (between 1 and 10)");
//     }
// //Final congratulatory alert
//
//alert("You got it right, " + userName + "! Just so you know, it took you " + numberQuestionWrongCounter + " tries to get it right. So yeah, think about that for a while and feel bad.");

//firstQuestion();
//secondQuestion();
//thirdQuestion();
fourthQuestion();
<|endoftext|>


<commit_before>var express          = require('express'),
    compression      = require('compression'),
    expressValidator = require('express-validator'),
    path             = require('path'),
    fs               = require('fs');
    favicon          = require('serve-favicon'),
    logger           = require('morgan'),
    cookieParser     = require('cookie-parser'),
    bodyParser       = require('body-parser'),
    util             = require('util'),
    LRU              = require('lru-cache'),
    uuid             = require('uuid'),
    hljs             = require(path.join(__dirname,'node_modules','highlight.js','lib','index.js'));

var storage_type   = process.env.NODE_NOPASTE_STORAGE_TYPE   || 'memory';
var redis_hash_key = process.env.NODE_NOPASTE_REDIS_HASH_KEY || "node-nopaste-storage";
var lru_max_age    = process.env.NODE_NOPASTE_LRU_MAX_AGE    || 60 * 60 * 24;

var app = express();

var cache = LRU({ maxAge: lru_max_age });

var highlightjs_path    = path.join(__dirname,'node_modules','highlight.js','lib','highlight.js');
var highlightjs_css_dir = path.join(__dirname,'node_modules','highlight.js','styles');
console.log(highlightjs_css_dir);
var ghlightjs_css_files = {};
fs.readdirSync(highlightjs_css_dir).filter(function(file){
    return ( /^(school_book|hybrid|brown_paper)\.css$/.test(file) ? false : true ) && /^.*\.css$/.test(file);
}).forEach(function(file){
    var match = file.match(/^(.+)\.css$/);
    ghlightjs_css_files[match[1]] = file;
    app.get(path.join('/css',file),function(req, res, next) {
        res.append('Content-Type','text/css;');
        res.send(fs.readFileSync(path.join(highlightjs_css_dir,file)));
    });
});

var storage = (function(){
    var Storage;
    if( storage_type == 'memory' ) {
        Storage = function(){
            this.data = {};
        };
        Storage.prototype.set = function(uuid,data) {
            this.data[uuid] = data;
        };
        Storage.prototype.get = function(uuid,callback) {
            callback(null,this.data[uuid]);
        };
        return new Storage();
    } else if( storage_type == 'redis'  ) {
        Storage = function(){
            var redis   = require("redis");
            this.client = redis.createClient();
            this.redis_hash_key = redis_hash_key;
        };
        Storage.prototype.set = function(uuid,data) {
            this.client.hset(this.redis_hash_key, uuid, data);
        };
        Storage.prototype.get = function(uuid,callback) {
            this.client.hget(this.redis_hash_key,uuid,callback);
        };
        return new Storage();
    }
}())

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(compression());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(expressValidator());

app.use(function (req, res, next) {
    res.locals = {
        title: 'No Paste',
        ghlightjs_css_files: ghlightjs_css_files
    };
    next();
});

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

app.post('/add',function(req, res, next) {
    req.checkBody('data', 'Invalid data').notEmpty();

    var errors = req.validationErrors();
    if (errors) {
        res.status(400).send('There have been validation errors: ' + util.inspect(errors));
        return;
    }

    var uuid_v1 = uuid.v1();
    storage.set(uuid_v1,req.body['data']);

    res.redirect('/show?uuid=' + uuid_v1);
});

app.get('/show',function(req, res, next) {
    req.checkQuery('uuid', 'Invalid uuid').notEmpty();

    var errors = req.validationErrors();
    if (errors) {
        res.status(400).send('There have been validation errors: ' + util.inspect(errors));
        return;
    }

    var style   = req.cookies['style'] || 'default';

    var results = cache.get(req.query['uuid']);
    if( results ) {
        return res.render('show',
            { value: results['value'], language: results['language'] ,style: style });
    }

    storage.get(req.query['uuid'],function(err,data){
        if(err || !data) {
            res.status(400).send('Unexpected uuid: ' + (req.query['uuid'] || ''));
            return;
        }
        var results = hljs.highlightAuto(data);
        cache.set(req.query['uuid'],results);
        res.render('show', { value: results['value'], language: results['language'] ,style: style });
    });
});

app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
<commit_msg>Deleted console.log<commit_after>var express          = require('express'),
    compression      = require('compression'),
    expressValidator = require('express-validator'),
    path             = require('path'),
    fs               = require('fs');
    favicon          = require('serve-favicon'),
    logger           = require('morgan'),
    cookieParser     = require('cookie-parser'),
    bodyParser       = require('body-parser'),
    util             = require('util'),
    LRU              = require('lru-cache'),
    uuid             = require('uuid'),
    hljs             = require(path.join(__dirname,'node_modules','highlight.js','lib','index.js'));

var storage_type   = process.env.NODE_NOPASTE_STORAGE_TYPE   || 'memory';
var redis_hash_key = process.env.NODE_NOPASTE_REDIS_HASH_KEY || "node-nopaste-storage";
var lru_max_age    = process.env.NODE_NOPASTE_LRU_MAX_AGE    || 60 * 60 * 24;

var app = express();

var cache = LRU({ maxAge: lru_max_age });

var highlightjs_path    = path.join(__dirname,'node_modules','highlight.js','lib','highlight.js');
var highlightjs_css_dir = path.join(__dirname,'node_modules','highlight.js','styles');

var ghlightjs_css_files = {};
fs.readdirSync(highlightjs_css_dir).filter(function(file){
    return ( /^(school_book|hybrid|brown_paper)\.css$/.test(file) ? false : true ) && /^.*\.css$/.test(file);
}).forEach(function(file){
    var match = file.match(/^(.+)\.css$/);
    ghlightjs_css_files[match[1]] = file;
    app.get(path.join('/css',file),function(req, res, next) {
        res.append('Content-Type','text/css;');
        res.send(fs.readFileSync(path.join(highlightjs_css_dir,file)));
    });
});

var storage = (function(){
    var Storage;
    if( storage_type == 'memory' ) {
        Storage = function(){
            this.data = {};
        };
        Storage.prototype.set = function(uuid,data) {
            this.data[uuid] = data;
        };
        Storage.prototype.get = function(uuid,callback) {
            callback(null,this.data[uuid]);
        };
        return new Storage();
    } else if( storage_type == 'redis'  ) {
        Storage = function(){
            var redis   = require("redis");
            this.client = redis.createClient();
            this.redis_hash_key = redis_hash_key;
        };
        Storage.prototype.set = function(uuid,data) {
            this.client.hset(this.redis_hash_key, uuid, data);
        };
        Storage.prototype.get = function(uuid,callback) {
            this.client.hget(this.redis_hash_key,uuid,callback);
        };
        return new Storage();
    }
}())

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(compression());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(expressValidator());

app.use(function (req, res, next) {
    res.locals = {
        title: 'No Paste',
        ghlightjs_css_files: ghlightjs_css_files
    };
    next();
});

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

app.post('/add',function(req, res, next) {
    req.checkBody('data', 'Invalid data').notEmpty();

    var errors = req.validationErrors();
    if (errors) {
        res.status(400).send('There have been validation errors: ' + util.inspect(errors));
        return;
    }

    var uuid_v1 = uuid.v1();
    storage.set(uuid_v1,req.body['data']);

    res.redirect('/show?uuid=' + uuid_v1);
});

app.get('/show',function(req, res, next) {
    req.checkQuery('uuid', 'Invalid uuid').notEmpty();

    var errors = req.validationErrors();
    if (errors) {
        res.status(400).send('There have been validation errors: ' + util.inspect(errors));
        return;
    }

    var style   = req.cookies['style'] || 'default';

    var results = cache.get(req.query['uuid']);
    if( results ) {
        return res.render('show',
            { value: results['value'], language: results['language'] ,style: style });
    }

    storage.get(req.query['uuid'],function(err,data){
        if(err || !data) {
            res.status(400).send('Unexpected uuid: ' + (req.query['uuid'] || ''));
            return;
        }
        var results = hljs.highlightAuto(data);
        cache.set(req.query['uuid'],results);
        res.render('show', { value: results['value'], language: results['language'] ,style: style });
    });
});

app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
<|endoftext|>