<commit_before>/**
 * bootstrap.js
 * Loads the configurations, setup Express, the routes, starts the database
 * connection while setting up the models and starts the application.
 *
 * @author  Jason Valdron <jason@valdron.ca>
 * @package valdron
 */

(function(){
  'use strict';

  // Load up the depencencies.
  var async = require('async'),
      fs = require('fs'),
      path = require('path'),
      walker = require('walk');

  // Export the main app function.
  module.exports = function(callback){

    var app = require('express')(),
        server = require('http').createServer(app);

    // We want to setup our logger first, then the configs.
    async.series([

      // Setup the Winston, our logger.
      function(next){

        var winston = require('winston');

        // Create new transport and handlers for the logger.
        var transports = [
          new winston.transports.Console({
            colorize: true,
            timestamp: true,
            level: 'info'
          }),
          new winston.transports.File({
            filename: path.join(process.cwd(), 'log', 'debug.log'),
            level: 'data',
            maxsize: 2 * 1024 * 1024
          })
        ];

        var exceptionHandlers = [
          new winston.transports.Console({
            colorize: true,
            timestamp: true
          }),
          new winston.transports.File({
            filename: path.join(process.cwd(), 'log', 'exceptions.log'),
            maxsize: 2 * 1024 * 1024
          })
        ];

        // Make sure we have a logs directory, we use synchronous because we're
        // at startup, so blocking isn't a big problem.
        if (!fs.existsSync(path.join(process.cwd(), 'log'))) {
          fs.mkdirSync(path.join(process.cwd(), 'log'), 511); // 0777 in decimal
        }

        // Create our logger and make it global to the application.
        app.logger = new winston.Logger({
            transports: transports,
            exceptionHandlers: exceptionHandlers
        });

        app.logger.info('Logger initialized!');

        return next();

      },

      // Load up our configs.
      function(next){

        app.logger.info('Loading config files...');

        if (fs.existsSync(path.join(process.cwd(), 'config', process.env.NODE_ENV + '.js'))) {

          // Load the environment specific config.
          app.config = require(path.join(process.cwd(), 'config', process.env.NODE_ENV))();

        } else {

          app.config = {};

          if (process.env.DATABASE_URL) {

            // Get our connection information.
            var info = process.env.DATABASE_URL.match(/([A-z].+):\/\/(.*)/);

            app.config.db = {
             driver: info[1],
             url: process.env.DATABASE_URL
            };

          }

          // Import the CDN URL from the configs.
          if (process.env.CDN_URL) app.config.url = {
            cdn: process.env.CDN_URL
          };

        }

        return next();

      },

    ], function(){

      // Let's configure some stuff parallel-ly.
      async.parallel([

        // Favicon.
        function(done){

          app.logger.info('Serving up the favicon...');

          // Setup our Favicon.
          app.use(require('serve-favicon')(path.join(process.cwd(), 'public', 'img', 'favicon.ico')));

          return done();

        },

        // Express configuration (Jade, view compiler).
        function(done){

            app.logger.info('Setting up our Jade views...');

            // Setup Jade.
            app.set('views', path.join(process.cwd(), 'views'));
            app.set('view engine', 'jade');
            app.locals.config = app.config;
            app.locals.environment = process.env.NODE_ENV;
            app.locals.version = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package.json'))).version;

            // Trust out the X-Forwarded-* header fields, usally required when behind a load balance.
            app.enable('trust proxy');
            app.disable('x-powered-by');

            // View cache.
            if (process.env.NODE_ENV !== 'development') {

                app.logger.info('Caching up those views...');

                // We want to cache our views.
                app.enable('view cache');

            }

          return done();

        },

        // Parsers.
        function(done){

          app.logger.info('Setting up the body parser...');

          // Parse forms and JSON requests.
          app.use(require('body-parser').urlencoded({ extended: false }));
          app.use(require('body-parser').json());

          return done();

        },

        // LESS/JS on-the-fly compilers (middlewares).
        function(done){

          // Development environment configuration.
          if (process.env.NODE_ENV === 'development') {

            app.logger.info('Setting up LESS middleware...');

            // Use the LESS middleware.
            app.use(require('less-middleware')(path.join(process.cwd(), 'assets', 'css'), {
              force: true,
              dest: path.join(process.cwd(), 'public'),
              preprocess: {
                path: function(pathname, req){
                  return pathname.replace('/css/', '/');
                }
              }
            }, null, {
              compress: false
            }));

            app.logger.info('Setting up the JavaScript merger...');

            // Use the UglifyJS middleware.
            app.use(require(path.join(process.cwd(), 'lib', 'middlewares', 'merge-js'))({
              src: path.join(process.cwd(), 'assets'),
              match: /\/js\/(.*).js/g
            }));

            app.logger.info('Setting up JSON middleware...');

            // Use the JSON middlware for the locales.
            app.use(require(path.join(process.cwd(), 'lib', 'middlewares', 'json'))({
              dest: path.join(process.cwd(), 'public'),
              src: path.join(process.cwd(), 'assets'),
              match: /\/locales\/(.*).json/g
            }));

            // Serve out static files.
            app.use(require('serve-static')(path.join(process.cwd(), 'public')));

          }

          return done();

        },

        function(done){

          app.logger.info('Setting up ORM (Caminte) to connect to ' + app.config.db.host + ' using ' + app.config.db.username + '...');

          var Schema = require('caminte').Schema;

          // Setting up the database.
          app.db = new Schema(app.config.db.driver, app.config.db);

          return done();

        }

      ], function(){

        // Create an empty object to store the models.
        app.db.models = {};
        var models = [];

        var walk = walker.walk(path.join(process.cwd(), 'models'));

        // Loop through all the models.
        walk.on('file', function(root, file, next){

          // Remove the extension.
          models[path.join(root, file.name)] = file.name.substr(0, file.name.indexOf('.'));
          return next();

        });

        // Done loading the models.
        walk.on('end', function(){

          async.series([

            function(next){

              app.logger.info('Loading models...');

              async.each(Object.keys(models), function(path, done){

                // Load the model.
                app.db.models[models[path]] = require(path).model(app.db, app);
                app.logger.info('- Model %s loaded!', models[path]);

                return done();

              }, next);

            },

            function(next){

              app.logger.info('Creating model associations...');

              async.each(Object.keys(models), function(path, done){

                // Load the model.
                var model = require(path);

                // Associate the model.
                if (model.associate) {
                    model.associate.call(app.db.models[models[path]], app.db);
                    app.logger.info('- Model %s associated!', models[path]);
                }

                return done();

              }, next);

            },

            // Load up the controllers.
            function(next){

              app.logger.info('Loading controllers...');

              var walk = walker.walk(path.join(process.cwd(), 'controllers'));

              // Loop through all the controllers.
              walk.on('file', function(root, file, next){

                  // Load the router.
                  var route = require(root + '/' + file.name)(app);
                  app.logger.info('- Controller %s loaded!', file.name);

                  return next();

              });

              // Done loading the controllers.
              walk.on('end', next);

            }

          ], function(){

            async.series([

              // 404 page.
              function(next){

                  // Setup our 404 page.
                  app.use(function(req, res, next){

                      res.status(404);

                      if (req.accepts('html')) return res.redirect('/#/errors/404');
                      if (req.accepts('json')) return res.send({ error: 'Not found' });
                      return res.type('txt').send('Not found');

                  });

                  return next();

              }

            ], function(){

              // Listen for incoming HTTP requests.
              server.listen(process.env.PORT || 3000);

              // Trigger the callback and pass the app.
              return callback(app, server);

            }); // ], function(){

          }); // ], function(){

        }); // walk.on('end', function(){

      }); // ], function(){

    }); // function(next){

  };

})();<commit_msg>Revert "Added DB logging"<commit_after>/**
 * bootstrap.js
 * Loads the configurations, setup Express, the routes, starts the database
 * connection while setting up the models and starts the application.
 *
 * @author  Jason Valdron <jason@valdron.ca>
 * @package valdron
 */

(function(){
  'use strict';

  // Load up the depencencies.
  var async = require('async'),
      fs = require('fs'),
      path = require('path'),
      walker = require('walk');

  // Export the main app function.
  module.exports = function(callback){

    var app = require('express')(),
        server = require('http').createServer(app);

    // We want to setup our logger first, then the configs.
    async.series([

      // Setup the Winston, our logger.
      function(next){

        var winston = require('winston');

        // Create new transport and handlers for the logger.
        var transports = [
          new winston.transports.Console({
            colorize: true,
            timestamp: true,
            level: 'info'
          }),
          new winston.transports.File({
            filename: path.join(process.cwd(), 'log', 'debug.log'),
            level: 'data',
            maxsize: 2 * 1024 * 1024
          })
        ];

        var exceptionHandlers = [
          new winston.transports.Console({
            colorize: true,
            timestamp: true
          }),
          new winston.transports.File({
            filename: path.join(process.cwd(), 'log', 'exceptions.log'),
            maxsize: 2 * 1024 * 1024
          })
        ];

        // Make sure we have a logs directory, we use synchronous because we're
        // at startup, so blocking isn't a big problem.
        if (!fs.existsSync(path.join(process.cwd(), 'log'))) {
          fs.mkdirSync(path.join(process.cwd(), 'log'), 511); // 0777 in decimal
        }

        // Create our logger and make it global to the application.
        app.logger = new winston.Logger({
            transports: transports,
            exceptionHandlers: exceptionHandlers
        });

        app.logger.info('Logger initialized!');

        return next();

      },

      // Load up our configs.
      function(next){

        app.logger.info('Loading config files...');

        if (fs.existsSync(path.join(process.cwd(), 'config', process.env.NODE_ENV + '.js'))) {

          // Load the environment specific config.
          app.config = require(path.join(process.cwd(), 'config', process.env.NODE_ENV))();

        } else {

          app.config = {};

          if (process.env.DATABASE_URL) {

            // Get our connection information.
            var info = process.env.DATABASE_URL.match(/([A-z].+):\/\/(.*)/);

            app.config.db = {
             driver: info[1],
             url: process.env.DATABASE_URL
            };

          }

          // Import the CDN URL from the configs.
          if (process.env.CDN_URL) app.config.url = {
            cdn: process.env.CDN_URL
          };

        }

        return next();

      },

    ], function(){

      // Let's configure some stuff parallel-ly.
      async.parallel([

        // Favicon.
        function(done){

          app.logger.info('Serving up the favicon...');

          // Setup our Favicon.
          app.use(require('serve-favicon')(path.join(process.cwd(), 'public', 'img', 'favicon.ico')));

          return done();

        },

        // Express configuration (Jade, view compiler).
        function(done){

            app.logger.info('Setting up our Jade views...');

            // Setup Jade.
            app.set('views', path.join(process.cwd(), 'views'));
            app.set('view engine', 'jade');
            app.locals.config = app.config;
            app.locals.environment = process.env.NODE_ENV;
            app.locals.version = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package.json'))).version;

            // Trust out the X-Forwarded-* header fields, usally required when behind a load balance.
            app.enable('trust proxy');
            app.disable('x-powered-by');

            // View cache.
            if (process.env.NODE_ENV !== 'development') {

                app.logger.info('Caching up those views...');

                // We want to cache our views.
                app.enable('view cache');

            }

          return done();

        },

        // Parsers.
        function(done){

          app.logger.info('Setting up the body parser...');

          // Parse forms and JSON requests.
          app.use(require('body-parser').urlencoded({ extended: false }));
          app.use(require('body-parser').json());

          return done();

        },

        // LESS/JS on-the-fly compilers (middlewares).
        function(done){

          // Development environment configuration.
          if (process.env.NODE_ENV === 'development') {

            app.logger.info('Setting up LESS middleware...');

            // Use the LESS middleware.
            app.use(require('less-middleware')(path.join(process.cwd(), 'assets', 'css'), {
              force: true,
              dest: path.join(process.cwd(), 'public'),
              preprocess: {
                path: function(pathname, req){
                  return pathname.replace('/css/', '/');
                }
              }
            }, null, {
              compress: false
            }));

            app.logger.info('Setting up the JavaScript merger...');

            // Use the UglifyJS middleware.
            app.use(require(path.join(process.cwd(), 'lib', 'middlewares', 'merge-js'))({
              src: path.join(process.cwd(), 'assets'),
              match: /\/js\/(.*).js/g
            }));

            app.logger.info('Setting up JSON middleware...');

            // Use the JSON middlware for the locales.
            app.use(require(path.join(process.cwd(), 'lib', 'middlewares', 'json'))({
              dest: path.join(process.cwd(), 'public'),
              src: path.join(process.cwd(), 'assets'),
              match: /\/locales\/(.*).json/g
            }));

            // Serve out static files.
            app.use(require('serve-static')(path.join(process.cwd(), 'public')));

          }

          return done();

        },

        function(done){

          app.logger.info('Setting up ORM (Caminte)...');

          var Schema = require('caminte').Schema;

          // Setting up the database.
          app.db = new Schema(app.config.db.driver, app.config.db);

          return done();

        }

      ], function(){

        // Create an empty object to store the models.
        app.db.models = {};
        var models = [];

        var walk = walker.walk(path.join(process.cwd(), 'models'));

        // Loop through all the models.
        walk.on('file', function(root, file, next){

          // Remove the extension.
          models[path.join(root, file.name)] = file.name.substr(0, file.name.indexOf('.'));
          return next();

        });

        // Done loading the models.
        walk.on('end', function(){

          async.series([

            function(next){

              app.logger.info('Loading models...');

              async.each(Object.keys(models), function(path, done){

                // Load the model.
                app.db.models[models[path]] = require(path).model(app.db, app);
                app.logger.info('- Model %s loaded!', models[path]);

                return done();

              }, next);

            },

            function(next){

              app.logger.info('Creating model associations...');

              async.each(Object.keys(models), function(path, done){

                // Load the model.
                var model = require(path);

                // Associate the model.
                if (model.associate) {
                    model.associate.call(app.db.models[models[path]], app.db);
                    app.logger.info('- Model %s associated!', models[path]);
                }

                return done();

              }, next);

            },

            // Load up the controllers.
            function(next){

              app.logger.info('Loading controllers...');

              var walk = walker.walk(path.join(process.cwd(), 'controllers'));

              // Loop through all the controllers.
              walk.on('file', function(root, file, next){

                  // Load the router.
                  var route = require(root + '/' + file.name)(app);
                  app.logger.info('- Controller %s loaded!', file.name);

                  return next();

              });

              // Done loading the controllers.
              walk.on('end', next);

            }

          ], function(){

            async.series([

              // 404 page.
              function(next){

                  // Setup our 404 page.
                  app.use(function(req, res, next){

                      res.status(404);

                      if (req.accepts('html')) return res.redirect('/#/errors/404');
                      if (req.accepts('json')) return res.send({ error: 'Not found' });
                      return res.type('txt').send('Not found');

                  });

                  return next();

              }

            ], function(){

              // Listen for incoming HTTP requests.
              server.listen(process.env.PORT || 3000);

              // Trigger the callback and pass the app.
              return callback(app, server);

            }); // ], function(){

          }); // ], function(){

        }); // walk.on('end', function(){

      }); // ], function(){

    }); // function(next){

  };

})();<|endoftext|>


<commit_before>"use strict"

/**
* [collectionName description]
* @type {String}
*/
var collectionName = 'Jobs'

/**
* [description]
* @param  {[type]} dbs  [description]
* @param  {[type]} opts [description]
* @param  {[type]} _cb  [description]
* @return {[type]}      [description]
*/
module.exports.get = (dbs, opts, _cb) => {

  dbs.mongo.collection(collectionName).find(opts.query, opts.proj, opts.opts, (err, cursor) => {
    if (err) return _cb(err, cursor)

    if (opts.transform.indexOf('array') > -1) {
      cursor.toArray((err, res) => {
        _cb(err, res)
      })
    } else {
      _cb(err, cursor)
    }
  })

}

/**
 * [description]
 * @param  {[type]} dbs  [description]
 * @param  {[type]} opts [description]
 * @param  {[type]} _cb  [description]
 * @return {[type]}      [description]
 */
module.exports.findOne = (dbs, opts, _cb) => {

  dbs.mongo.collection(collectionName).findOne(opts.query, opts.proj, () => {
    console.log(arguments);
    _cb(err, result)
  })

}
<commit_msg>remove logging<commit_after>"use strict"

/**
* [collectionName description]
* @type {String}
*/
var collectionName = 'Jobs'

/**
* [description]
* @param  {[type]} dbs  [description]
* @param  {[type]} opts [description]
* @param  {[type]} _cb  [description]
* @return {[type]}      [description]
*/
module.exports.get = (dbs, opts, _cb) => {

  dbs.mongo.collection(collectionName).find(opts.query, opts.proj, opts.opts, (err, cursor) => {
    if (err) return _cb(err, cursor)

    if (opts.transform.indexOf('array') > -1) {
      cursor.toArray((err, res) => {
        _cb(err, res)
      })
    } else {
      _cb(err, cursor)
    }
  })

}

/**
 * [description]
 * @param  {[type]} dbs  [description]
 * @param  {[type]} opts [description]
 * @param  {[type]} _cb  [description]
 * @return {[type]}      [description]
 */
module.exports.findOne = (dbs, opts, _cb) => {

  dbs.mongo.collection(collectionName).findOne(opts.query, opts.proj, (err, result) => {
    _cb(err, result)
  })

}
<|endoftext|>


<commit_before>/**
 * Alias for document.getElementById.
 * @param {Number} id
 * @return {*} DOMElement
 */
var $ = function(id){
    return document.getElementById(id);
}

/**
 * Debug function.
 */
function _debug(){
    if (debug){

        var text = '';

        for (var i = 0; i < arguments.length; i++){
            if (arguments[i] === null){
                text += ' null';
            }else if (typeof(arguments[i]) === "undefined"){
                text += ' undefined';
            }else if (arguments[i].message && arguments[i].name){
                text += ' '+arguments[i];
            }else{
                text += ' '+arguments[i].toSource();
            }
        }

        try{
            gSTB.Debug(text);
        }catch(e){
            console&&console.log&&console.log(text);
        }
    }
}

/**
 * Module loader.
 */

/*function load_module(module){

    _debug('load_module', module);

    try{

        var head = document.getElementsByTagName("head")[0];

        var _script = document.createElement('script');
        _script.type = "text/javascript";
        _script.src  = module + ".js";

        var _style = document.createElement('link');
        _style.type = "text/css";
        _style.rel = "stylesheet";
        _style.href = module + ".css";

        head.appendChild(_script);
        _debug('append', _script.src);
        head.appendChild(_style);
        _debug('append', _style.href);
    }catch(e){
        _debug(e);
    }
}*/

/**
 * DOM element creating functions
 */

function create_dom_element(type, class_name, parent){

    var dom_element = document.createElement(type);

    if (class_name){
        dom_element.addClass(class_name);
    }

    var parent = parent || document.body

    if (parent){
        parent.appendChild(dom_element);
    }

    return dom_element;
}

function create_inline_element(class_name, parent){

    return create_dom_element('span', class_name, parent);
}

function create_block_element(class_name, parent){

    return create_dom_element('div', class_name, parent);
}

/**
 * Custom prototype metods.
 */

HTMLElement.prototype.show = function(){
    try{
        this.style.display = 'block';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.hide = function(){
    try{
        this.style.display = 'none';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.isHidden = function(){
    try{
        if (this.style.display == 'none'){
            return true;
        }else{
            return false;
        }
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.moveX = function(to_x){
    try{
        this.style.left = parseInt(to_x)+'px';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.moveY = function(to_y){
    try{
        this.style.top = parseInt(to_y)+'px';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.offsetX = function(offset_x){
    try{
        this.style.left = parseInt(this.offsetLeft)+offset_x+'px';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.offsetY = function(offset_y){
    try{
        this.style.top = parseInt(this.offsetTop)+offset_y+'px';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.setClass = function(class_name){
    try{
        this.className = class_name;
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.delClass = function(){
    try{
        this.className = '';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.addClass = function(class_name){
    try{
        if (!this.className){
            this.setClass(class_name);
        }else{
            var new_class_name = this.className;
            new_class_name += " ";
            new_class_name += class_name;
            this.setClass(new_class_name);
        }
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.removeClass = function(class_name){
    try{
        if (this.className.indexOf(class_name) >= 0){
            this.className.replace(/(class_name)/g, '').replace(/((\s)+)/g, ' ');
        }
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.replaceClass = function(from, to){
    try{
        if (this.className.indexOf(from) >= 0 ){
            this.className.replace(/(from)/g, to);
        }
    }catch(e){
        _debug(e);
    }
}

String.prototype.clearnl = function(){
    return this.replace(/(\n(\r)?)/g, '');
}

if (typeof Object.prototype.toSource != 'function'){

    Object.prototype.toSource = function() {
        var con = this.constructor;
        if(con == String) {
            //return '"' + this + '"';
            return this;
        } else if(con == Number) {
            return this;
        } else if(con == Array) {
            var res = '[';
            for(var i=0,len=this.length;i<len;i++) {
                if(i == len-1)
                    res += this[i].toSource() + ']';
                else
                    res += this[i].toSource() + ', ';
            }
            return res;
        } else if(con == RegExp) {
            return this;
        } else if(con == Object) {
            var res = '{';
            var i=0;
            for(var j in this) {
                if (this.hasOwnProperty(j)){
                    if(j != 'toSource') {
                        if(i == 0) {
                            res += j + ':' + this[j].toSource(1);
                        } else {
                            res += ', ' + j + ':' + this[j].toSource(1);
                        }
                        i++;
                    }
                }
            }
            res += '}';
            if(arguments.length) {
                return res;
            } else {
                return '(' + res + ')';
            }
        }else if(con == Boolean){
            return this;
        }
    }

}

Object.prototype.clone = function() {

    var newObj = (this instanceof Array) ? [] : {};

    for (i in this) {

        if (this.hasOwnProperty(i)){
            //_debug(i);

            if (i == 'clone') continue;

            if (this[i] && typeof this[i] == "object") {
                newObj[i] = this[i].clone();
            }else{
                newObj[i] = this[i];
            }
        }
    }
    return newObj;
}

Array.prototype.getIdxById = function(id){
    for (var i=0; i<this.length; i++){
        if (this[i].hasOwnProperty('id')){
            if (this[i].id == id){
                return i;
            }
        }
    }
    return null;
}

Array.prototype.getIdxByVal = function(what, eq){
    for (var i=0; i<this.length; i++){
        if (this[i].hasOwnProperty(what)){
            if (this[i][what] == eq){
                return i;
            }
        }
    }
    return null;
}

Array.prototype.getIdxByNumber = function(number){
    for (var i=0; i<this.length; i++){
        if (this[i].hasOwnProperty('number')){
            if (this[i].number == number){
                return i;
            }
        }
    }
    return null;
}

Array.prototype.inArray = function (value){
    for (var i=0; i < this.length; i++){
        if (this[i] === value){
            return true;
        }
    }
    return false;
}

Math.__proto__.isEven = function(x){
    return !(x % 2);
}

Math.__proto__.isOdd = function(x){
    return !Math.isEven(x);
}

function empty(val){

    var type = typeof(val);

    if (type == 'string' && val == ''){
        return true;
    }else if (type == 'undefined'){
        return true;
    }else{
        if (type == 'object'){
            for(var p in val){
                if (val.hasOwnProperty(p)){
                    return false;
                }
            }

            return true;
        }
    }

    return false;
}<commit_msg>"Add dummy _log"<commit_after>/**
 * Alias for document.getElementById.
 * @param {Number} id
 * @return {*} DOMElement
 */
var $ = function(id){
    return document.getElementById(id);
}

/**
 * Debug function.
 */
function _debug(){
    if (debug){

        var text = '';

        for (var i = 0; i < arguments.length; i++){
            if (arguments[i] === null){
                text += ' null';
            }else if (typeof(arguments[i]) === "undefined"){
                text += ' undefined';
            }else if (arguments[i].message && arguments[i].name){
                text += ' '+arguments[i];
            }else{
                text += ' '+arguments[i].toSource();
            }
        }

        try{
            gSTB.Debug(text);
        }catch(e){
            console&&console.log&&console.log(text);
        }
    }
}

function _log(action, param, type){
    /*var tmp_type;
    var cur_place_num = 0;

    if (typeof(type) == 'undefined'){
        tmp_type = 0
    }else{
        tmp_type = cur_place_num
    }

    stb.load(
        {
            "type"   : "stb",
            "action" : "log",
            "real_action" : action,
            "tmp_type" : tmp_type,
            "param"  : param
        },

        function(result){

        }
    )*/
}

/**
 * Module loader.
 */

/*function load_module(module){

    _debug('load_module', module);

    try{

        var head = document.getElementsByTagName("head")[0];

        var _script = document.createElement('script');
        _script.type = "text/javascript";
        _script.src  = module + ".js";

        var _style = document.createElement('link');
        _style.type = "text/css";
        _style.rel = "stylesheet";
        _style.href = module + ".css";

        head.appendChild(_script);
        _debug('append', _script.src);
        head.appendChild(_style);
        _debug('append', _style.href);
    }catch(e){
        _debug(e);
    }
}*/

/**
 * DOM element creating functions
 */

function create_dom_element(type, class_name, parent){

    var dom_element = document.createElement(type);

    if (class_name){
        dom_element.addClass(class_name);
    }

    var parent = parent || document.body

    if (parent){
        parent.appendChild(dom_element);
    }

    return dom_element;
}

function create_inline_element(class_name, parent){

    return create_dom_element('span', class_name, parent);
}

function create_block_element(class_name, parent){

    return create_dom_element('div', class_name, parent);
}

/**
 * Custom prototype metods.
 */

HTMLElement.prototype.show = function(){
    try{
        this.style.display = 'block';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.hide = function(){
    try{
        this.style.display = 'none';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.isHidden = function(){
    try{
        if (this.style.display == 'none'){
            return true;
        }else{
            return false;
        }
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.moveX = function(to_x){
    try{
        this.style.left = parseInt(to_x)+'px';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.moveY = function(to_y){
    try{
        this.style.top = parseInt(to_y)+'px';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.offsetX = function(offset_x){
    try{
        this.style.left = parseInt(this.offsetLeft)+offset_x+'px';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.offsetY = function(offset_y){
    try{
        this.style.top = parseInt(this.offsetTop)+offset_y+'px';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.setClass = function(class_name){
    try{
        this.className = class_name;
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.delClass = function(){
    try{
        this.className = '';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.addClass = function(class_name){
    try{
        if (!this.className){
            this.setClass(class_name);
        }else{
            var new_class_name = this.className;
            new_class_name += " ";
            new_class_name += class_name;
            this.setClass(new_class_name);
        }
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.removeClass = function(class_name){
    try{
        if (this.className.indexOf(class_name) >= 0){
            this.className.replace(/(class_name)/g, '').replace(/((\s)+)/g, ' ');
        }
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.replaceClass = function(from, to){
    try{
        if (this.className.indexOf(from) >= 0 ){
            this.className.replace(/(from)/g, to);
        }
    }catch(e){
        _debug(e);
    }
}

String.prototype.clearnl = function(){
    return this.replace(/(\n(\r)?)/g, '');
}

if (typeof Object.prototype.toSource != 'function'){

    Object.prototype.toSource = function() {
        var con = this.constructor;
        if(con == String) {
            //return '"' + this + '"';
            return this;
        } else if(con == Number) {
            return this;
        } else if(con == Array) {
            var res = '[';
            for(var i=0,len=this.length;i<len;i++) {
                if(i == len-1)
                    res += this[i].toSource() + ']';
                else
                    res += this[i].toSource() + ', ';
            }
            return res;
        } else if(con == RegExp) {
            return this;
        } else if(con == Object) {
            var res = '{';
            var i=0;
            for(var j in this) {
                if (this.hasOwnProperty(j)){
                    if(j != 'toSource') {
                        if(i == 0) {
                            res += j + ':' + this[j].toSource(1);
                        } else {
                            res += ', ' + j + ':' + this[j].toSource(1);
                        }
                        i++;
                    }
                }
            }
            res += '}';
            if(arguments.length) {
                return res;
            } else {
                return '(' + res + ')';
            }
        }else if(con == Boolean){
            return this;
        }
    }

}

Object.prototype.clone = function() {

    var newObj = (this instanceof Array) ? [] : {};

    for (i in this) {

        if (this.hasOwnProperty(i)){
            //_debug(i);

            if (i == 'clone') continue;

            if (this[i] && typeof this[i] == "object") {
                newObj[i] = this[i].clone();
            }else{
                newObj[i] = this[i];
            }
        }
    }
    return newObj;
}

Array.prototype.getIdxById = function(id){
    for (var i=0; i<this.length; i++){
        if (this[i].hasOwnProperty('id')){
            if (this[i].id == id){
                return i;
            }
        }
    }
    return null;
}

Array.prototype.getIdxByVal = function(what, eq){
    for (var i=0; i<this.length; i++){
        if (this[i].hasOwnProperty(what)){
            if (this[i][what] == eq){
                return i;
            }
        }
    }
    return null;
}

Array.prototype.getIdxByNumber = function(number){
    for (var i=0; i<this.length; i++){
        if (this[i].hasOwnProperty('number')){
            if (this[i].number == number){
                return i;
            }
        }
    }
    return null;
}

Array.prototype.inArray = function (value){
    for (var i=0; i < this.length; i++){
        if (this[i] === value){
            return true;
        }
    }
    return false;
}

Math.__proto__.isEven = function(x){
    return !(x % 2);
}

Math.__proto__.isOdd = function(x){
    return !Math.isEven(x);
}

function empty(val){

    var type = typeof(val);

    if (type == 'string' && val == ''){
        return true;
    }else if (type == 'undefined'){
        return true;
    }else{
        if (type == 'object'){
            for(var p in val){
                if (val.hasOwnProperty(p)){
                    return false;
                }
            }

            return true;
        }
    }

    return false;
}<|endoftext|>


<commit_before>/**
 * zooming - Image zooming with pure JavaScript.
 * @version v0.2.0
 * @link https://github.com/kingdido999/zooming
 * @license MIT
 */

+function() { 'use strict'

  function Zooming() {
    this._scaleBase = 1.0
    this._target = null // Zoomable target
    this._body = document.body
    this._lastScrollPosition = null
    this._scrollThreshold = 40

    this._handleClick = this._handleClick.bind(this)
    this._handleKeyDown = this._handleKeyDown.bind(this)
    this._handleScroll = this._handleScroll.bind(this)
  }

  Zooming.prototype = {
    init: function() {
      this._body.addEventListener('click', this._handleClick)

      var zoomableImages = document.querySelectorAll('img[data-action="zoom"]')
      for (var i = 0; i < zoomableImages.length; i++) {
        setCursorStyle(zoomableImages[i], 'zoom-in')
      }
    },

    _handleClick: function(event) {
      var target = event.target
      if (!target) return

      if (target.tagName !== 'IMG'){
          $(".ace-thumbnails > li ").css("overflow","hidden");
          this._close();
      }

      if (!target.hasAttribute('data-action')) return

      switch (target.getAttribute('data-action')) {
        case 'zoom':
          this._zoom(target);
          $(".ace-thumbnails > li ").css("overflow","visible");
          break
        case 'close':
          this._close();
          $(".ace-thumbnails > li ").css("overflow","hidden");
          break
        default:
          $(".ace-thumbnails > li ").css("overflow","hidden");
          break
      }
    },

    _handleKeyDown: function(event) {
      if (event.keyCode === 27) this._close() // Esc
    },

    _handleScroll: function() {
      var scrollTop = window.pageYOffset ||
      (document.documentElement || this._body.parentNode || this._body).scrollTop

      if (this._lastScrollPosition === null) this._lastScrollPosition = scrollTop

      var deltaY = this._lastScrollPosition - scrollTop

      if (Math.abs(deltaY) >= this._scrollThreshold) {
        this._lastScrollPosition = null
        this._close()
      }
    },

    _zoom: function(target) {
      // Avoid zooming multiple times
      if (this._target) return

      this._target = new Zoomable(target)
      this._target.zoomIn()

      document.addEventListener('keydown', this._handleKeyDown)
      document.addEventListener('scroll', this._handleScroll)
    },

    _close: function() {
      if (!this._target) return

      this._target.zoomOut()
      this._target = null

      document.removeEventListener('keydown', this._handleKeyDown)
      document.removeEventListener('scroll', this._handleScroll)
    }
  }

  /**
   * The zoomable image.
   */
  function Zoomable(img) {
    this._scaleBase = 1.0
    this._image = img
    this._src = img.getAttribute('src')
    this._dataOriginal = img.getAttribute('data-original')
    this._overlay = null // An overlay that whites out the body
    this._body = document.body
    this._zoomImage = this._zoomImage.bind(this)
    this._handleTransitionEnd = this._handleTransitionEnd.bind(this)

    this._styles = {
      image: {
        width: '',
        height: '',
        transform: '',
        zoomIn: {
          'position': 'relative',
          'z-index': 666,
          '-webkit-transition': 'all 300ms',
               '-o-transition': 'all 300ms',
                  'transition': 'all 300ms'
        },
        zoomOut: {
          'position': '',
          'z-index': '',
          '-webkit-transition': '',
               '-o-transition': '',
                  'transition': ''
        }
      },
      overlay: {
        'z-index': 233,
        'background': '#fff',
        'position': 'fixed',
        'top': 0,
        'left': 0,
        'right': 0,
        'bottom': 0,
        'filter': 'alpha(opacity=0)',
        'opacity': 0,
        '-webkit-transition': 'opacity 300ms',
             '-o-transition': 'opacity 300ms',
                'transition': 'opacity 300ms'
      }
    }
  }

  Zoomable.prototype = {
    zoomIn: function() {
      var img = new Image()

      img.onload = (function() {
        // If data-orginal is present, set image css width and height explicitly
        // so the transformed source image is correctly displayed
        if (this._dataOriginal) {
          // Save the original image width and height styles if present
          this._styles.image.width = this._image.style.width
          this._styles.image.height = this._image.style.height

          var rect = this._image.getBoundingClientRect();

          setStyles(this._image, {
            'width': rect.width + 'px',
            'height': rect.height + 'px'
          })

          // Use data-original as image src
          this._image.setAttribute('src', this._dataOriginal)
        }

        this._calculateZoom()
        this._zoomImage()
      }).bind(this)

      img.src = this._src
    },

    _calculateZoom: function() {
      var rect = this._image.getBoundingClientRect()

      var windowCenter = {
        x: window.innerWidth / 2,
        y: window.innerHeight / 2
      }

      var imgHalfWidth = rect.width / 2
      var imgHalfHeight = rect.height / 2

      var imgCenter = {
        x: rect.left + imgHalfWidth,
        y: rect.top + imgHalfHeight
      }

      // The vector to translate image to the window center
      var translate = {
        x: windowCenter.x - imgCenter.x,
        y: windowCenter.y - imgCenter.y
      }

      // The distance between image edge and window edge
      var distFromImageEdgeToWindowEdge = {
        x: windowCenter.x - imgHalfWidth,
        y: windowCenter.y - imgHalfHeight
      }

      // The additional scale is based on the smaller value of
      // scaling horizontally and scaling vertically
      var scaleHorizontally = distFromImageEdgeToWindowEdge.x / imgHalfWidth
      var scaleVertically = distFromImageEdgeToWindowEdge.y / imgHalfHeight
      var scale = this._scaleBase + Math.min(scaleHorizontally, scaleVertically);

      var my_scale= this._image.getAttribute('data-scale');
      var my_scale_w = scale*Number(my_scale);
      if(isNaN(my_scale_w)){
          my_scale_w = scale;
          alert(my_scale_w);
      }
      // Translate the image to window center, then scale the image
      this._styles.image.transform =
        'translate(' + translate.x + 'px,' + translate.y + 'px) ' +
        'scale(' + my_scale_w + ',' + scale + ')';
    },

    _zoomImage: function() {
      // Repaint before animating, fix Safari image flickring issue
      this._image.offsetWidth

      setStyles(this._image, this._styles.image.zoomIn)
      this._image.addEventListener('transitionend', this._handleTransitionEnd)

      // Create an overlay, it does not white out at this point
      this._overlay = document.createElement('div')
      setStyles(this._overlay, this._styles.overlay)
      this._body.appendChild(this._overlay)

      // Use setTimeout to apply correct overlay opacity transition when
      // zooming in, otherwise the transition effect won't trigger.
      window.setTimeout((function() {
        // Now whites out the overlay
        setStyles(this._overlay, {
          'filter': "alpha(opacity=100)",
          'opacity': 1
        })
      }).bind(this), 30)

      this._transform()
    },

    zoomOut: function() {
      this._image.addEventListener('transitionend', this._handleTransitionEnd)

      // Remove the overlay
      setStyles(this._overlay, {
        'filter': "alpha(opacity=0)",
        'opacity': 0
      })

      this._styles.image.transform = ''
      this._transform()
    },

    _transform: function() {
      setStyles(this._image, {
        '-webkit-transform': this._styles.image.transform,
        '-ms-transform': this._styles.image.transform,
        'transform': this._styles.image.transform,
      })
    },

    _handleTransitionEnd: function(event) {
      switch (this._image.getAttribute('data-action')) {
        case 'close':
          if (this._dataOriginal) {
            setStyles(this._image, {
              'width': this._styles.width,
              'height': this._styles.height
            })

            // Restore the old image src
            this._image.setAttribute('src', this._src)
          }
          this._body.removeChild(this._overlay)
          setStyles(this._image, this._styles.image.zoomOut)
          setCursorStyle(this._image, 'zoom-in')
          this._image.setAttribute('data-action', 'zoom')
          break
        case 'zoom':
          setCursorStyle(this._image, 'zoom-out')
          this._image.setAttribute('data-action', 'close')
          break
        default:
          break
      }
      this._image.removeEventListener('transitionend', this._handleTransitionEnd)
    }
  }

  function setStyles(element, styles) {
    for (var prop in styles) {
      element.style[prop] = styles[prop]
    }
  }

  function setCursorStyle(element, style) {
    element.style.cursor = style
    element.style.cursor = '-webkit-' + style
    element.style.cursor = '-moz-' + style
  }

  document.addEventListener('DOMContentLoaded', function() {
    new Zooming().init()
  })
}()
<commit_msg>zooming change<commit_after>/**
 * zooming - Image zooming with pure JavaScript.
 * @version v0.2.0
 * @link https://github.com/kingdido999/zooming
 * @license MIT
 */

+function() { 'use strict'

  function Zooming() {
    this._scaleBase = 1.0
    this._target = null // Zoomable target
    this._body = document.body
    this._lastScrollPosition = null
    this._scrollThreshold = 40

    this._handleClick = this._handleClick.bind(this)
    this._handleKeyDown = this._handleKeyDown.bind(this)
    this._handleScroll = this._handleScroll.bind(this)
  }

  Zooming.prototype = {
    init: function() {
      this._body.addEventListener('click', this._handleClick)

      var zoomableImages = document.querySelectorAll('img[data-action="zoom"]')
      for (var i = 0; i < zoomableImages.length; i++) {
        setCursorStyle(zoomableImages[i], 'zoom-in')
      }
    },

    _handleClick: function(event) {
      var target = event.target
      if (!target) return

      if (target.tagName !== 'IMG'){
          $(".ace-thumbnails > li ").css("overflow","hidden");
          this._close();
      }

      if (!target.hasAttribute('data-action')) return

      switch (target.getAttribute('data-action')) {
        case 'zoom':
          this._zoom(target);
          $(".ace-thumbnails > li ").css("overflow","visible");
          break
        case 'close':
          this._close();
          $(".ace-thumbnails > li ").css("overflow","hidden");
          break
        default:
          $(".ace-thumbnails > li ").css("overflow","hidden");
          break
      }
    },

    _handleKeyDown: function(event) {
      if (event.keyCode === 27) this._close() // Esc
    },

    _handleScroll: function() {
      var scrollTop = window.pageYOffset ||
      (document.documentElement || this._body.parentNode || this._body).scrollTop

      if (this._lastScrollPosition === null) this._lastScrollPosition = scrollTop

      var deltaY = this._lastScrollPosition - scrollTop

      if (Math.abs(deltaY) >= this._scrollThreshold) {
        this._lastScrollPosition = null
        this._close()
      }
    },

    _zoom: function(target) {
      // Avoid zooming multiple times
      if (this._target) return

      this._target = new Zoomable(target)
      this._target.zoomIn()

      document.addEventListener('keydown', this._handleKeyDown)
      document.addEventListener('scroll', this._handleScroll)
    },

    _close: function() {
      if (!this._target) return

      this._target.zoomOut()
      this._target = null

      document.removeEventListener('keydown', this._handleKeyDown)
      document.removeEventListener('scroll', this._handleScroll)
    }
  }

  /**
   * The zoomable image.
   */
  function Zoomable(img) {
    this._scaleBase = 1.0
    this._image = img
    this._src = img.getAttribute('src')
    this._dataOriginal = img.getAttribute('data-original')
    this._overlay = null // An overlay that whites out the body
    this._body = document.body
    this._zoomImage = this._zoomImage.bind(this)
    this._handleTransitionEnd = this._handleTransitionEnd.bind(this)

    this._styles = {
      image: {
        width: '',
        height: '',
        transform: '',
        zoomIn: {
          'position': 'relative',
          'z-index': 666,
          '-webkit-transition': 'all 300ms',
               '-o-transition': 'all 300ms',
                  'transition': 'all 300ms'
        },
        zoomOut: {
          'position': '',
          'z-index': '',
          '-webkit-transition': '',
               '-o-transition': '',
                  'transition': ''
        }
      },
      overlay: {
        'z-index': 233,
        'background': '#fff',
        'position': 'fixed',
        'top': 0,
        'left': 0,
        'right': 0,
        'bottom': 0,
        'filter': 'alpha(opacity=0)',
        'opacity': 0,
        '-webkit-transition': 'opacity 300ms',
             '-o-transition': 'opacity 300ms',
                'transition': 'opacity 300ms'
      }
    }
  }

  Zoomable.prototype = {
    zoomIn: function() {
      var img = new Image()

      img.onload = (function() {
        // If data-orginal is present, set image css width and height explicitly
        // so the transformed source image is correctly displayed
        if (this._dataOriginal) {
          // Save the original image width and height styles if present
          this._styles.image.width = this._image.style.width
          this._styles.image.height = this._image.style.height

          var rect = this._image.getBoundingClientRect();

          setStyles(this._image, {
            'width': rect.width + 'px',
            'height': rect.height + 'px'
          })

          // Use data-original as image src
          this._image.setAttribute('src', this._dataOriginal)
        }

        this._calculateZoom()
        this._zoomImage()
      }).bind(this)

      img.src = this._src
    },

    _calculateZoom: function() {
      var rect = this._image.getBoundingClientRect()

      var windowCenter = {
        x: window.innerWidth / 2,
        y: window.innerHeight / 2
      }

      var imgHalfWidth = rect.width / 2
      var imgHalfHeight = rect.height / 2

      var imgCenter = {
        x: rect.left + imgHalfWidth,
        y: rect.top + imgHalfHeight
      }

      // The vector to translate image to the window center
      var translate = {
        x: windowCenter.x - imgCenter.x,
        y: windowCenter.y - imgCenter.y
      }

      // The distance between image edge and window edge
      var distFromImageEdgeToWindowEdge = {
        x: windowCenter.x - imgHalfWidth,
        y: windowCenter.y - imgHalfHeight
      }

      // The additional scale is based on the smaller value of
      // scaling horizontally and scaling vertically
      var scaleHorizontally = distFromImageEdgeToWindowEdge.x / imgHalfWidth
      var scaleVertically = distFromImageEdgeToWindowEdge.y / imgHalfHeight
      var scale = this._scaleBase + Math.min(scaleHorizontally, scaleVertically);

      var my_scale= this._image.getAttribute('data-scale');
      var my_scale_w = scale*Number(my_scale);
      if(isNaN(my_scale_w)){
          my_scale_w = scale;
          alert(my_scale_w);
      }
	  if(my_scale_w<=0){
		my_scale_w = scale;
	  }
      // Translate the image to window center, then scale the image
      this._styles.image.transform =
        'translate(' + translate.x + 'px,' + translate.y + 'px) ' +
        'scale(' + my_scale_w + ',' + scale + ')';
    },

    _zoomImage: function() {
      // Repaint before animating, fix Safari image flickring issue
      this._image.offsetWidth

      setStyles(this._image, this._styles.image.zoomIn)
      this._image.addEventListener('transitionend', this._handleTransitionEnd)

      // Create an overlay, it does not white out at this point
      this._overlay = document.createElement('div')
      setStyles(this._overlay, this._styles.overlay)
      this._body.appendChild(this._overlay)

      // Use setTimeout to apply correct overlay opacity transition when
      // zooming in, otherwise the transition effect won't trigger.
      window.setTimeout((function() {
        // Now whites out the overlay
        setStyles(this._overlay, {
          'filter': "alpha(opacity=100)",
          'opacity': 1
        })
      }).bind(this), 30)

      this._transform()
    },

    zoomOut: function() {
      this._image.addEventListener('transitionend', this._handleTransitionEnd)

      // Remove the overlay
      setStyles(this._overlay, {
        'filter': "alpha(opacity=0)",
        'opacity': 0
      })

      this._styles.image.transform = ''
      this._transform()
    },

    _transform: function() {
      setStyles(this._image, {
        '-webkit-transform': this._styles.image.transform,
        '-ms-transform': this._styles.image.transform,
        'transform': this._styles.image.transform,
      })
    },

    _handleTransitionEnd: function(event) {
      switch (this._image.getAttribute('data-action')) {
        case 'close':
          if (this._dataOriginal) {
            setStyles(this._image, {
              'width': this._styles.width,
              'height': this._styles.height
            })

            // Restore the old image src
            this._image.setAttribute('src', this._src)
          }
          this._body.removeChild(this._overlay)
          setStyles(this._image, this._styles.image.zoomOut)
          setCursorStyle(this._image, 'zoom-in')
          this._image.setAttribute('data-action', 'zoom')
          break
        case 'zoom':
          setCursorStyle(this._image, 'zoom-out')
          this._image.setAttribute('data-action', 'close')
          break
        default:
          break
      }
      this._image.removeEventListener('transitionend', this._handleTransitionEnd)
    }
  }

  function setStyles(element, styles) {
    for (var prop in styles) {
      element.style[prop] = styles[prop]
    }
  }

  function setCursorStyle(element, style) {
    element.style.cursor = style
    element.style.cursor = '-webkit-' + style
    element.style.cursor = '-moz-' + style
  }

  document.addEventListener('DOMContentLoaded', function() {
    new Zooming().init()
  })
}()
<|endoftext|>


<commit_before>var pg = require('pg');
var Joi = require('joi');
var DB = require('../db');
var Hapi = require('hapi');
var Util = require('util');
var _ = require('../libs/underscore.1.6.0.min')

function createSubscriberResultList (rows) {
  var subs = [];

  _.each(rows, function(row) {
    var email = row.email;
    var id = row.id;
    var subscribeDate = row.subscribe_date;

    var data = { email: email, id: id, subscribeDate: subscribeDate };

    subs.push(data);
  });

  return subs;
}

exports.list = {
  handler: function(request, reply) {
    pg.connect(DB.connectionString, function(err, client) {
      if (err) {
        console.log(err);
      }

      client.query('SELECT * FROM subscribers;', function(error, result) {

        if (error) {
          console.error('Error listing subscribers.', error);
          reply(Hapi.error.internal('Error listing subscribers', error));
        }

        var subs = createSubscriberResultList(result.rows);
        console.log(subs);

        client.end();

        reply({
          subscribers: subs
        });
      });
    });
  }
};

exports.add = {
  validate: {
    payload: {
      email: Joi.string().email()
    }
  },
  handler: function (request, reply) {
    var email = request.payload.email;
    console.log("User requested a Subscribe: " + email);

    pg.connect(DB.connectionString, function(err, client) {
      if (err) {
        console.log(err);
      }

      var data = [];
      data.push(email);

      client.query('INSERT INTO subscribers (email, subscribe_date) VALUES ($1, CURRENT_TIMESTAMP) RETURNING id;', data, function(err, result) {
        if (err) {
          console.error(Util.format('Error saving [%s] email address.', email), error);

          reply(Hapi.error.internal('Error saving your email address. This has been logged and will be fixed shortly.', error));
          return;
        }

        var subscriberID = result.rows[0].id;

        console.log("Subscribe Completed for " + email + ", ID: " + subscriberID);

        client.end();

        reply("OK");
      });
    });
  }
};
<commit_msg>Abstract handlers into separate functions.<commit_after>var pg = require('pg');
var Joi = require('joi');
var DB = require('../db');
var Hapi = require('hapi');
var Util = require('util');
var _ = require('../libs/underscore.1.6.0.min')

var SELECT_ALL_SUBSCRIBERS_SQL = 'SELECT * FROM subscribers;';
var INSERT_NEW_SUBSCRIBER_SQL = 'INSERT INTO subscribers (email, subscribe_date) VALUES ($1, CURRENT_TIMESTAMP) RETURNING id;';

function createSubscriberResultList (rows) {
  var subs = [];

  _.each(rows, function(row) {
    var email = row.email;
    var id = row.id;
    var subscribeDate = row.subscribe_date;

    var data = { email: email, id: id, subscribeDate: subscribeDate };

    subs.push(data);
  });

  return subs;
}

var listSubscribersRouteHandler = function(request, reply) {
  pg.connect(DB.connectionString, function(err, client) {
    if (err) {
      console.log(err);
    }

    client.query(SELECT_ALL_SUBSCRIBERS_SQL, function(error, result) {
      if (error) {
        console.error('Error listing subscribers.', error);
        reply(Hapi.error.internal('Error listing subscribers', error));
      }

      var subs = createSubscriberResultList(result.rows);
      console.log(subs);

      client.end();

      reply( { subscribers: subs } );
    });
  });
}

var addSubscriberRouteHandler = function (request, reply) {
  var email = request.payload.email;
  console.log("User requested a Subscribe: " + email);

  pg.connect(DB.connectionString, function(err, client) {
    if (err) {
      console.log(err);
    }

    var data = [];
    data.push(email);

    client.query(INSERT_NEW_SUBSCRIBER_SQL, data, function(err, result) {
      if (err) {
        console.error(Util.format('Error saving [%s] email address.', email), error);

        reply(Hapi.error.internal('Error saving your email address. This has been logged and will be fixed shortly.', error));
        return;
      }

      var subscriberID = result.rows[0].id;

      console.log("Subscribe Completed for " + email + ", ID: " + subscriberID);

      client.end();

      reply("OK");
    });
  });
}

exports.list = {
  handler: listSubscribersRouteHandler
};

exports.add = {
  validate: {
    payload: {
      email: Joi.string().email()
    }
  },
  handler: addSubscriberRouteHandler
};
<|endoftext|>


<commit_before>'use strict';

var cleanstatusdb = {
  name: 'cleanstatusdb'
  , label: 'Clean Mongo status database'
  , pluginType: 'admin'
};

function init() {
  return cleanstatusdb;
}

module.exports = init;

cleanstatusdb.actions = [
    {
        name: 'Delete all documents from devicestatus collection'
      , description: 'This task removes all documents from devicestatus collection. Useful when uploader battery status is not properly updated.'
      , buttonLabel: 'Delete all documents'
      , confirmText: 'Delete all documents from devicestatus collection?'
    }
  ];

cleanstatusdb.actions[0].init = function init(client, callback) {
  var translate = client.translate;
  var $status = $('#admin_' + cleanstatusdb.name + '_0_status');

  $status.hide().text(translate('Loading database ...')).fadeIn('slow');
  $.ajax('/api/v1/devicestatus.json?count=500', {
    headers: client.headers()
    , success: function (records) {
      var recs = (records.length === 500 ? '500+' : records.length);
      $status.hide().text(translate('Database contains %1 records',{ params: [recs] })).fadeIn('slow');
    }
    , error: function () {
      $status.hide().text(translate('Error loading database')).fadeIn('slow');
    }
  }).done(function () { if (callback) { callback(); } });
};

cleanstatusdb.actions[0].code =  function deleteRecords(client, callback) {
  var translate = client.translate;
  var $status = $('#admin_' + cleanstatusdb.name + '_0_status');

  if (!client.hashauth.isAuthenticated()) {
    alert(translate('Your device is not authenticated yet'));
    if (callback) {
      callback();
    }
    return;
  };

  $status.hide().text(translate('Deleting records ...')).fadeIn('slow');
  $.ajax({
      method: 'DELETE'
    , url: '/api/v1/devicestatus/*'
    , headers: client.headers()
  }).done(function success () {
    $status.hide().text(translate('All records removed ...')).fadeIn('slow');
    if (callback) {
      callback();
    }
  }).fail(function fail() {
    $status.hide().text(translate('Error')).fadeIn('slow');
    if (callback) {
      callback();
    }
  });
};
<commit_msg>Added new option to delete up to a certain number of days worth of devicestatus collection records.<commit_after>'use strict';

var moment = require('moment');

var cleanstatusdb = {
  name: 'cleanstatusdb'
  , label: 'Clean Mongo status database'
  , pluginType: 'admin'
};

function init() {
  return cleanstatusdb;
}

module.exports = init;

cleanstatusdb.actions = [
    {
        name: 'Delete all documents from devicestatus collection'
      , description: 'This task removes all documents from devicestatus collection. Useful when uploader battery status is not properly updated.'
      , buttonLabel: 'Delete all documents'
      , confirmText: 'Delete all documents from devicestatus collection?'
    }
    , {
        name: 'Delete all documents from devicestatus collection older than 30 days'
      , description: 'This task removes all documents from devicestatus collection that are older than 30 days. Useful when uploader battery status is not properly updated.'
      , buttonLabel: 'Delete old documents'
      , confirmText: 'Delete old documents from devicestatus collection?'
    }
  ];

cleanstatusdb.actions[0].init = function init(client, callback) {
  var translate = client.translate;
  var $status = $('#admin_' + cleanstatusdb.name + '_0_status');

  $status.hide().text(translate('Loading database ...')).fadeIn('slow');
  $.ajax('/api/v1/devicestatus.json?count=500', {
    headers: client.headers()
    , success: function (records) {
      var recs = (records.length === 500 ? '500+' : records.length);
      $status.hide().text(translate('Database contains %1 records',{ params: [recs] })).fadeIn('slow');
    }
    , error: function () {
      $status.hide().text(translate('Error loading database')).fadeIn('slow');
    }
  }).done(function () { if (callback) { callback(); } });
};

cleanstatusdb.actions[0].code =  function deleteRecords(client, callback) {
  var translate = client.translate;
  var $status = $('#admin_' + cleanstatusdb.name + '_0_status');

  if (!client.hashauth.isAuthenticated()) {
    alert(translate('Your device is not authenticated yet'));
    if (callback) {
      callback();
    }
    return;
  };

  $status.hide().text(translate('Deleting records ...')).fadeIn('slow');
  $.ajax({
      method: 'DELETE'
    , url: '/api/v1/devicestatus/*'
    , headers: client.headers()
  }).done(function success () {
    $status.hide().text(translate('All records removed ...')).fadeIn('slow');
    if (callback) {
      callback();
    }
  }).fail(function fail() {
    $status.hide().text(translate('Error')).fadeIn('slow');
    if (callback) {
      callback();
    }
  });

cleanstatusdb.actions[1].init = function init(client, callback) {
  var translate = client.translate;
  var $status = $('#admin_' + cleanstatusdb.name + '_1_status');

  $status.hide();

  var numDays =  '
'
      + ''
      + translate('Number of Days to Keep:')
      + '  <input id="admin_devicestatus_days" value="30" size="3" min="1" max="365"/>'
      + '';

  $('#admin_' + cleanstatusdb.name + '_1_html').html(numDays);

  if (callback) { callback(); }
};

cleanstatusdb.actions[1].code =  function deleteOldRecords(client, callback) {
  var translate = client.translate;
  var $status = $('#admin_' + cleanstatusdb.name + '_1_status');
  var numDays = Number($('#admin_devicestatus_days').val());

  if (isNaN(numDays) || (numDays <= 0)) {
    alert(translate('%1 is not a valid number', { params: [$('#admin_devicestatus_days').val()] }));
    if (callback) {
      callback();
    }
    return;
  }
  var endDate = moment().subtract(numDays, 'days');
  var dateStr = endDate.format('YYYY-MM-DD');

  if (!client.hashauth.isAuthenticated()) {
    alert(translate('Your device is not authenticated yet'));
    if (callback) {
      callback();
    }
    return;
  }

  $status.hide().text(translate('Deleting records ...')).fadeIn('slow');
  $.ajax({
      method: 'DELETE'
    , url: '/api/v1/devicestatus/' + dateStr
    , headers: client.headers()
    , success: function (retVal) {
      $status.hide().text(translate('%1 records deleted',{ params: [retVal.n] })).fadeIn('slow');
    }
  }).done(function success () {
    if (callback) {
      callback();
    }
  }).fail(function fail() {
    $status.hide().text(translate('Error')).fadeIn('slow');
    if (callback) {
      callback();
    }
  });

};
<|endoftext|>


<commit_before>const assert = require('assert')
const CNako3 = require('../../src/cnako3')

describe('plugin_test', () => {
  const nako = new CNako3()
  // nako.logger.addListener('trace', ({ browserConsole }) => { console.log(...browserConsole) })
  nako.silent = true
  const cmp = (code, res) => {
    nako.logger.debug('code=' + code)
    const ret = nako.run(code)
    assert.strictEqual(ret.log, res)
  }
  it('「取り込む」', () => {
    cmp('!「nadesiko3-hoge」を取り込む。\n3と5をHOGE足して、表示。', '8')
  })
})
<commit_msg>nadesiko3-hogeの依存排除におけるテストのエラーを修正<commit_after>const assert = require('assert')
const CNako3 = require('../../src/cnako3')
const path = require('path')
describe('plugin_test', () => {
  const nako = new CNako3()
  // nako.logger.addListener('trace', ({ browserConsole }) => { console.log(...browserConsole) })
  nako.silent = true
  const cmp = (code, res) => {
    nako.logger.debug('code=' + code)
    const ret = nako.run(code)
    assert.strictEqual(ret.log, res)
  }
  it('「取り込む」', () => {
    const plug = path.join(__dirname, '..', '..', 'src', 'plugin_keigo.js')
    cmp(`!「${plug}」を取り込む。\n拝啓。お世話になっております。礼節レベル取得して表示。`, '1')
  })
})

<|endoftext|>


<commit_before>var Economy = require('../economy');

 module.exports = {
        dicestart: 'startdice',
        startdice: function(target, room, user) {
                 if (!this.canTalk()) return this.sendReply("You can not start dice games while unable to speak.");
                 if (!target) return this.sendReply('Usage: /startdice <bet>');
                 if (isNaN(Number(target))) return this.sendReply('/startdice - <bet> must be a number greater than 0');
                 target = Math.round(Number(target));
                 if (target < 1) return this.sendReply('/startdice - You can not bet less than one buck.');
                 if (target > 500) return this.sendReply('/startdice - You can\'t bet more than 500 bucks.');
                 var self = this;
                         if (!room.dice) room.dice = {};
                         if (!room.dice.status) room.dice.status = 0;
                         if (room.dice.status > 0) return self.sendReply('/startdice - There is already a game started in here!');
                         room.dice.status = 1;
                         room.dice.bet = target;
                         room.dice.startTime = Date.now();
                         room.addRaw('

' + Tools.escapeHTML(user.name) + ' has started a dice game for ' + target +
                                 ' ' + ((target === 1) ? " buck." : " bucks.") + '.
 <button name="send" value="/joindice">Click to join.</button>

');
                         room.update();
        },

        joindice: function(target, room, user) {
                if (!this.canTalk()) return this.sendReply("You may not join dice games while unable to speak.");
                 if (!room.dice) return this.sendReply('There is no dice game in it\'s signup phase in this room.');
                 if (room.dice.status !== 1) return this.sendReply('There is no dice game in it\'s signup phase in this room.');
                 var self = this;
                 room.dice.status = 2;
                 Economy.get(user.name).then(function(userMoney){
                         if (userMoney < room.dice.bet) {
                                 self.sendReply('You don\'t have enough bucks to join this game.');
                                 return room.dice.status = 1;
                         }
                 });
                         if (!room.dice.player1) {
                                 room.dice.player1 = user.userid;
                                 room.dice.status = 1;
                                 room.addRaw('' + Tools.escapeHTML(user.name) + ' has joined the dice game.');
                                 return room.update();
                         }
                         if (room.dice.player1 === user.userid) return room.dice.status = 1;
                         if (room.dice.player1 !== user.userid) {
                                 room.dice.player2 = user.userid;
                                 if (!Users.get(room.dice.player1).userid) {
                                         room.addRaw("Player 1 seems to be missing... game ending.");
                                         delete room.dice.player1;
                                         delete room.dice.player2;
                                         delete room.dice.bet;
                                         delete room.dice.startTime;
                                         room.update();
                                         return false;
                                 }
                                 if (!Users.get(room.dice.player2).userid) {
                                         room.addRaw("Player 2 seems to be missing... game ending.");
                                         delete room.dice.player1;
                                         delete room.dice.player2;
                                         delete room.dice.bet;
                                         delete room.dice.startTime;
                                         room.update();
                                         return false;
                                 }
                                 if (room.dice.player1 !== Users.get(room.dice.player1).userid) {
                                         room.addRaw('Player 1 has changed names, game ending.');
                                         room.dice.status = 0;
                                         delete room.dice.player1;
                                         delete room.dice.player2;
                                         delete room.dice.bet;
                                         delete room.dice.startTime;
                                         room.update();
                                         return false;
                                 }
                                 room.addRaw('' + Tools.escapeHTML(user.name) + ' has joined the dice game.');
                                 room.update();
                                 var firstNumber = Math.floor(6 * Math.random()) + 1;
                                 var secondNumber = Math.floor(6 * Math.random()) + 1;
                                 var firstName = Users.get(room.dice.player1).name;
                                 var secondName = Users.get(room.dice.player2).name;
                                 firstMoney = Economy.get(toId(firstName));
                                 secondMoney = Economy.get(toId(secondName));
                                                 if (firstMoney < room.dice.bet) {
                                                        room.dice.status = 0;
                                                         delete room.dice.player1;
                                                         delete room.dice.player2;
                                                         delete room.dice.bet;
                                                         delete room.dice.startTime;
                                                         room.addRaw('' + Tools.escapeHTML(firstName) + ' no longer has enough bucks to play, game ending.');
                                                         return room.update();
                                                 }
                                                 if (secondMoney < room.dice.bet) {
                                                        room.dice.status = 0;
                                                         delete room.dice.player1;
                                                         delete room.dice.player2;
                                                         delete room.dice.bet;
                                                         delete room.dice.startTime;
                                                         room.addRaw('' + Tools.escapeHTML(secondName) + ' no longer has enough bucks to play, game ending.');
                                                         return room.update();
                                                 }
                                                 var output = '
Game has two players, starting now.
';
                                                 output += 'Rolling the dice.
';
                                                 output += Tools.escapeHTML(firstName) + ' has rolled a ' + firstNumber + '.
';
                                                 output += Tools.escapeHTML(secondName) + ' has rolled a ' + secondNumber + '.
';
                                                while (firstNumber === secondNumber) {
                                                        output += 'Tie... rolling again.
';
                                                         firstNumber = Math.floor(6 * Math.random()) + 1;
                                                         secondNumber = Math.floor(6 * Math.random()) + 1;
                                                         output += Tools.escapeHTML(firstName) + ' has rolled a ' + firstNumber + '.
';
                                                         output += Tools.escapeHTML(secondName) + ' has rolled a ' + secondNumber + '.
';
                                                }
                                                var betMoney = room.dice.bet;
                                                 if (firstNumber > secondNumber) {
                                                         output += '' + Tools.escapeHTML(firstName) + ' has won ' + betMoney + ' ' + ((betMoney === 1) ? " buck." : " bucks.") + '.
'
                                                         output += 'Better luck next time ' + Tools.escapeHTML(secondName) + '!';
                                                         Economy.give(toId(firstName),betMoney);
                                                         Economy.take(toId(secondName),betMoney);
                                                         room.dice.status = 0;
                                                         delete room.dice.player1;
                                                         delete room.dice.player2;
                                                         delete room.dice.bet;
                                                         delete room.dice.startTime;
                                                 }
                                                 if (secondNumber > firstNumber) {
                                                         output += '' + Tools.escapeHTML(secondName) + ' has won ' + betMoney + ' ' + ((betMoney === 1) ? " buck." : " bucks.") + '.
';
                                                         output += 'Better luck next time ' + Tools.escapeHTML(firstName) + '!';
                                                         Economy.take(toId(firstName),betMoney);
                                                         Economy.give(toId(secondName),betMoney);
                                                         room.dice.status = 0;
                                                         delete room.dice.player1;
                                                         delete room.dice.player2;
                                                         delete room.dice.bet;
                                                         delete room.dice.startTime;
                                                 }
                                                 output += '
';
                                                 room.addRaw(output);
                                                 room.update();
                         }
        },

        enddice: function (target, room, user) {
                if (!user.can('broadcast',null,room)) return this.sendReply('/enddice - Access denied.');
                if (!room.dice) return this.sendReply('/enddice - There is no dice game in this room.');
                if (room.dice.status === 0) return this.sendReply('/enddice - There is no dice game in this room.');
                if ((Date.now() - room.dice.startTime) < 60000 && !user.can('broadcast', null, room)) return this.sendReply('Regular users may not end a dice game within the first minute of it starting.');
                room.dice = {};
                room.dice.status = 0;
                return room.addRaw('' + Tools.escapeHTML(user.name) + ' ended the dice game.');
        },

        dicehelp: function (target, room, user) {
                if (!this.canBroadcast()) return;
                this.sendReplyBox(
                        'Dice game commands:
' +
                        '/startdice <bet> - Starts a game.
' +
                        '/joindice - Joins the game.
' +
                        '/enddice - Forcibly ends the game.'
                        );
        }
};
<commit_msg>Update casino.js<commit_after>var Economy = require('../economy');

 module.exports = {
        dicestart: 'startdice',
        startdice: function(target, room, user) {
                 if (!this.canTalk()) return this.sendReply("You can not start dice games while unable to speak.");
                 if (!target) return this.sendReply('Usage: /startdice <bet>');
                 if (isNaN(Number(target))) return this.sendReply('/startdice - <bet> must be a number greater than 0');
                 target = Math.round(Number(target));
                 if (target < 1) return this.sendReply('/startdice - You can not bet less than one buck.');
                 if (target > 500) return this.sendReply('/startdice - You can\'t bet more than 500 bucks.');
                 var self = this;
                         if (!room.dice) room.dice = {};
                         if (!room.dice.status) room.dice.status = 0;
                         if (room.dice.status > 0) return self.sendReply('/startdice - There is already a game started in here!');
                         room.dice.status = 1;
                         room.dice.bet = target;
                         room.dice.startTime = Date.now();
                         room.addRaw('

' + Tools.escapeHTML(user.name) + ' has started a dice game for ' + target +
                                 ' ' + ((target === 1) ? " buck." : " bucks.") + '.
 <button name="send" value="/joindice">Click to join.</button>

');
                         room.update();
        },

        joindice: function(target, room, user) {
                if (!this.canTalk()) return this.sendReply("You may not join dice games while unable to speak.");
                 if (!room.dice) return this.sendReply('There is no dice game in it\'s signup phase in this room.');
                 if (room.dice.status !== 1) return this.sendReply('There is no dice game in it\'s signup phase in this room.');
                 var self = this;
                 room.dice.status = 2;
                 Economy.get(user.name).then(function(userMoney){
                         if (userMoney < room.dice.bet) {
                                 self.sendReply('You don\'t have enough bucks to join this game.');
                                 return room.dice.status = 1;
                         }
                         if (!room.dice.player1) {
                                 room.dice.player1 = user.userid;
                                 room.dice.status = 1;
                                 room.addRaw('' + Tools.escapeHTML(user.name) + ' has joined the dice game.');
                                 return room.update();
                         }
                         if (room.dice.player1 === user.userid) return room.dice.status = 1;
                         if (room.dice.player1 !== user.userid) {
                                 room.dice.player2 = user.userid;
                                 if (!Users.get(room.dice.player1).userid) {
                                         room.addRaw("Player 1 seems to be missing... game ending.");
                                         delete room.dice.player1;
                                         delete room.dice.player2;
                                         delete room.dice.bet;
                                         delete room.dice.startTime;
                                         room.update();
                                         return false;
                                 }
                                 if (!Users.get(room.dice.player2).userid) {
                                         room.addRaw("Player 2 seems to be missing... game ending.");
                                         delete room.dice.player1;
                                         delete room.dice.player2;
                                         delete room.dice.bet;
                                         delete room.dice.startTime;
                                         room.update();
                                         return false;
                                 }
                                 if (room.dice.player1 !== Users.get(room.dice.player1).userid) {
                                         room.addRaw('Player 1 has changed names, game ending.');
                                         room.dice.status = 0;
                                         delete room.dice.player1;
                                         delete room.dice.player2;
                                         delete room.dice.bet;
                                         delete room.dice.startTime;
                                         room.update();
                                         return false;
                                 }
                                 room.addRaw('' + Tools.escapeHTML(user.name) + ' has joined the dice game.');
                                 room.update();
                                 var firstNumber = Math.floor(6 * Math.random()) + 1;
                                 var secondNumber = Math.floor(6 * Math.random()) + 1;
                                 var firstName = Users.get(room.dice.player1).name;
                                 var secondName = Users.get(room.dice.player2).name;
                                 firstMoney = Economy.get(toId(firstName));
                                 secondMoney = Economy.get(toId(secondName));
                                                 if (firstMoney < room.dice.bet) {
                                                        room.dice.status = 0;
                                                         delete room.dice.player1;
                                                         delete room.dice.player2;
                                                         delete room.dice.bet;
                                                         delete room.dice.startTime;
                                                         room.addRaw('' + Tools.escapeHTML(firstName) + ' no longer has enough bucks to play, game ending.');
                                                         return room.update();
                                                 }
                                                 if (secondMoney < room.dice.bet) {
                                                        room.dice.status = 0;
                                                         delete room.dice.player1;
                                                         delete room.dice.player2;
                                                         delete room.dice.bet;
                                                         delete room.dice.startTime;
                                                         room.addRaw('' + Tools.escapeHTML(secondName) + ' no longer has enough bucks to play, game ending.');
                                                         return room.update();
                                                 }
                                                 var output = '
Game has two players, starting now.
';
                                                 output += 'Rolling the dice.
';
                                                 output += Tools.escapeHTML(firstName) + ' has rolled a ' + firstNumber + '.
';
                                                 output += Tools.escapeHTML(secondName) + ' has rolled a ' + secondNumber + '.
';
                                                while (firstNumber === secondNumber) {
                                                        output += 'Tie... rolling again.
';
                                                         firstNumber = Math.floor(6 * Math.random()) + 1;
                                                         secondNumber = Math.floor(6 * Math.random()) + 1;
                                                         output += Tools.escapeHTML(firstName) + ' has rolled a ' + firstNumber + '.
';
                                                         output += Tools.escapeHTML(secondName) + ' has rolled a ' + secondNumber + '.
';
                                                }
                                                var betMoney = room.dice.bet;
                                                 if (firstNumber > secondNumber) {
                                                         output += '' + Tools.escapeHTML(firstName) + ' has won ' + betMoney + ' ' + ((betMoney === 1) ? " buck." : " bucks.") + '.
'
                                                         output += 'Better luck next time ' + Tools.escapeHTML(secondName) + '!';
                                                         Economy.give(toId(firstName),betMoney);
                                                         Economy.take(toId(secondName),betMoney);
                                                         room.dice.status = 0;
                                                         delete room.dice.player1;
                                                         delete room.dice.player2;
                                                         delete room.dice.bet;
                                                         delete room.dice.startTime;
                                                 }
                                                 if (secondNumber > firstNumber) {
                                                         output += '' + Tools.escapeHTML(secondName) + ' has won ' + betMoney + ' ' + ((betMoney === 1) ? " buck." : " bucks.") + '.
';
                                                         output += 'Better luck next time ' + Tools.escapeHTML(firstName) + '!';
                                                         Economy.take(toId(firstName),betMoney);
                                                         Economy.give(toId(secondName),betMoney);
                                                         room.dice.status = 0;
                                                         delete room.dice.player1;
                                                         delete room.dice.player2;
                                                         delete room.dice.bet;
                                                         delete room.dice.startTime;
                                                 }
                                                 output += '
';
                                                 room.addRaw(output);
                                                 room.update();
                         }
                 });
        },

        enddice: function (target, room, user) {
                if (!user.can('broadcast',null,room)) return this.sendReply('/enddice - Access denied.');
                if (!room.dice) return this.sendReply('/enddice - There is no dice game in this room.');
                if (room.dice.status === 0) return this.sendReply('/enddice - There is no dice game in this room.');
                if ((Date.now() - room.dice.startTime) < 60000 && !user.can('broadcast', null, room)) return this.sendReply('Regular users may not end a dice game within the first minute of it starting.');
                room.dice = {};
                room.dice.status = 0;
                return room.addRaw('' + Tools.escapeHTML(user.name) + ' ended the dice game.');
        },

        dicehelp: function (target, room, user) {
                if (!this.canBroadcast()) return;
                this.sendReplyBox(
                        'Dice game commands:
' +
                        '/startdice <bet> - Starts a game.
' +
                        '/joindice - Joins the game.
' +
                        '/enddice - Forcibly ends the game.'
                        );
        }
};
<|endoftext|>


<commit_before>var Lab = require('lab');
var Code = require('code');

var server = require('../').hapi;

var lab = exports.lab = Lab.script();

var sessionA = {
  id: 'john.doe',
  name: 'John Doe',
};

var changesSessionA = {
  name: 'Jane Doe'
};

var credentials = {
  id: 'john.doe',
  name: 'John Doe',
  participations: [{
    role: 'development-team',
    event: '1000-sinfo'
  }]
};

lab.experiment('Session', function() {

  lab.test('Create', function(done) {
    var options = {
      method: 'POST',
      url: '/api/sessions',
      credentials: credentials,
      payload: sessionA
    };

    server.inject(options, function(response) {
      var result = response.result;

      Code.expect(response.statusCode).to.equal(201);
      Code.expect(result).to.be.instanceof(Object);
      Code.expect(result.id).to.equal(sessionA.id);
      Code.expect(result.name).to.equal(sessionA.name);

      done();
    });
  });

  lab.test('List all', function(done) {
    var options = {
      method: 'GET',
      url: '/api/sessions',
      credentials: credentials,
    };

    server.inject(options, function(response) {
      var result = response.result;

      Code.expect(response.statusCode).to.equal(200);
      Code.expect(result).to.be.instanceof(Array);
      Code.expect(result[0].id).to.be.string;
      Code.expect(result[0].name).to.be.string;

      done();
    });
  });

  lab.test('Get one', function(done) {
    var options = {
      method: 'GET',
      url: '/api/sessions/'+sessionA.id,
      credentials: credentials,
    };

    server.inject(options, function(response) {
      var result = response.result;

      Code.expect(response.statusCode).to.equal(200);
      Code.expect(result).to.be.instanceof(Object);
      Code.expect(result.id).to.equal(sessionA.id);
      Code.expect(result.name).to.equal(sessionA.name);

      done();
    });
  });

  lab.test('Update', function(done) {
    var options = {
      method: 'PUT',
      url: '/api/sessions/'+sessionA.id,
      credentials: credentials,
      payload: changesSessionA
    };

    server.inject(options, function(response) {
      var result = response.result;

      Code.expect(response.statusCode).to.equal(200);
      Code.expect(result).to.be.instanceof(Object);
      Code.expect(result.id).to.equal(sessionA.id);
      Code.expect(result.name).to.equal(changesSessionA.name);

      done();
    });
  });

  lab.test('Delete', function(done) {
    var options = {
      method: 'DELETE',
      url: '/api/sessions/'+sessionA.id,
      credentials: credentials,
    };

    server.inject(options, function(response) {
      var result = response.result;

      Code.expect(response.statusCode).to.equal(200);
      Code.expect(result).to.be.instanceof(Object);
      Code.expect(result.id).to.equal(sessionA.id);
      Code.expect(result.name).to.equal(changesSessionA.name);

      done();
    });
  });

});
<commit_msg>fix tests<commit_after>var Lab = require('lab');
var Code = require('code');

var server = require('../').hapi;

var lab = exports.lab = Lab.script();

var sessionA = {
  id: 'john.doe',
  name: 'John Doe',
  event: 'test-event'
};

var sessionId = sessionA.id + '-' + sessionA.event

var changesSessionA = {
  name: 'Jane Doe'
};

var credentials = {
  id: 'john.doe',
  name: 'John Doe',
  participations: [{
    role: 'development-team',
    event: '1000-sinfo'
  }]
};

lab.experiment('Session', function() {

  lab.test('Create', function(done) {
    var options = {
      method: 'POST',
      url: '/api/sessions',
      credentials: credentials,
      payload: sessionA
    };

    server.inject(options, function(response) {
      var result = response.result;

      Code.expect(response.statusCode).to.equal(201);
      Code.expect(result).to.be.instanceof(Object);
      Code.expect(result.id).to.equal(sessionId);
      Code.expect(result.name).to.equal(sessionA.name);

      done();
    });
  });

  lab.test('List all', function(done) {
    var options = {
      method: 'GET',
      url: '/api/sessions',
      credentials: credentials,
    };

    server.inject(options, function(response) {
      var result = response.result;

      Code.expect(response.statusCode).to.equal(200);
      Code.expect(result).to.be.instanceof(Array);
      Code.expect(result[0].id).to.be.string;
      Code.expect(result[0].name).to.be.string;

      done();
    });
  });

  lab.test('Get one', function(done) {
    var options = {
      method: 'GET',
      url: '/api/sessions/'+sessionId,
      credentials: credentials,
    };

    server.inject(options, function(response) {
      var result = response.result;

      Code.expect(response.statusCode).to.equal(200);
      Code.expect(result).to.be.instanceof(Object);
      Code.expect(result.id).to.equal(sessionId);
      Code.expect(result.name).to.equal(sessionA.name);

      done();
    });
  });

  lab.test('Update', function(done) {
    var options = {
      method: 'PUT',
      url: '/api/sessions/'+sessionId,
      credentials: credentials,
      payload: changesSessionA
    };

    server.inject(options, function(response) {
      var result = response.result;

      Code.expect(response.statusCode).to.equal(200);
      Code.expect(result).to.be.instanceof(Object);
      Code.expect(result.id).to.equal(sessionId);
      Code.expect(result.name).to.equal(changesSessionA.name);

      done();
    });
  });

  lab.test('Delete', function(done) {
    var options = {
      method: 'DELETE',
      url: '/api/sessions/'+sessionId,
      credentials: credentials,
    };

    server.inject(options, function(response) {
      var result = response.result;

      Code.expect(response.statusCode).to.equal(200);
      Code.expect(result).to.be.instanceof(Object);
      Code.expect(result.id).to.equal(sessionId);
      Code.expect(result.name).to.equal(changesSessionA.name);

      done();
    });
  });

});
<|endoftext|>


<commit_before>'use strict'

var debug = require('debug')('rascal:tasks:createConnection')
var format = require('util').format
var _ = require('lodash')
var amqplib = require('amqplib/callback_api')

module.exports = _.curry(function(config, ctx, next) {

    debug(format('Connecting to broker using url: %s', config.connection.loggableUrl))

    amqplib.connect(config.connection.url, function(err, connection) {
        if (err) return next(err, config, ctx)

        ctx.connection = connection

        /*
         * If an error occurs during initialisation (e.g. if checkExchanges fails),
         * and no error handler has been bound to the connection, then the error will bubble up
         * to the UncaughtException handler, potentially crashing the node process.
         *
         * By adding an error handler now, we ensure that instead of being emitted as events
         * errors will be passed via the callback chain, so they can still be handled by the caller
         *
         * This error handle is removed in the vhost after the initialiation has complete
         */
        connection.on('error', function(err) {
            debug(format('Received error: %s', err.message))
        })

        next(null, config, ctx)
    })
})<commit_msg>Disabling possible EventEmitter memory leak detected on connections<commit_after>'use strict'

var debug = require('debug')('rascal:tasks:createConnection')
var format = require('util').format
var _ = require('lodash')
var amqplib = require('amqplib/callback_api')

module.exports = _.curry(function(config, ctx, next) {

    debug(format('Connecting to broker using url: %s', config.connection.loggableUrl))

    amqplib.connect(config.connection.url, function(err, connection) {
        if (err) return next(err, config, ctx)

        ctx.connection = connection
        ctx.connection.setMaxListeners(0)

        /*
         * If an error occurs during initialisation (e.g. if checkExchanges fails),
         * and no error handler has been bound to the connection, then the error will bubble up
         * to the UncaughtException handler, potentially crashing the node process.
         *
         * By adding an error handler now, we ensure that instead of being emitted as events
         * errors will be passed via the callback chain, so they can still be handled by the caller
         *
         * This error handle is removed in the vhost after the initialiation has complete
         */
        connection.on('error', function(err) {
            debug(format('Received error: %s', err.message))
        })

        next(null, config, ctx)
    })
})<|endoftext|>