<commit_before>var util = require('util')
    , EventEmitter = require('events').EventEmitter
    , MongoClient = require('mongodb').MongoClient
    , ObjectID = require('mongodb').ObjectID
    , jwt = require("jsonwebtoken");

function RestAPI() {
    this.routes = [
        { method: 'get', mount: '', handler: this._query },
        { method: 'get', mount: '/:id', handler: this._get },
        { method: 'put', mount: '', handler: this._create },
        { method: 'post', mount: '', handler: this._create },
        { method: 'post', mount: '/:id', handler: this._update },
        { method: 'delete', mount: '/:id', handler: this._remove }
    ];
}
util.inherits(RestAPI, EventEmitter);
RestAPI.prototype.getRoutes = function () {
    return this.routes;
}

RestAPI.prototype._query = function (req, res) {
    var self = this;

    self.checkAuthentification(req, function () {
        if (!req.user && !req.user.bucket) {
            return exports.sendError( res, 401, 'Unauthorized');
        }
        self.query.call(self, req.user.bucket, exports.responseCallback(res));
    });
}
RestAPI.prototype._get = function (req, res) {
    var self = this;

    self.checkAuthentification(req, function () {
        if (!req.user&& !req.user.bucket) {
            return exports.sendError( res, 401, 'Unauthorized');
        }
        if (!req.params.id) {
            exports.sendError(res, 400, 'id missing');
        } else {
            self.get.call( self, req.user.bucket, { _id: ObjectID(req.params.id) }, exports.responseCallback(res));
        }
    });
}
RestAPI.prototype._create = function (req, res) {
    var self = this;

    self.checkAuthentification(req, function () {
        if (!req.user && !req.user.bucket) {
            return exports.sendError( res, 401, 'Unauthorized');
        }
        if (!req.body) {
            exports.sendError(res, 400, 'body missing');
        } else {
            self.create.call( self, req.user.bucket, req.body, exports.responseCallback(res));
        }
    });

}
RestAPI.prototype._update = function (req, res) {

    var self = this;

    self.checkAuthentification(req,  function () {
        if (!req.user&& !req.user.bucket) {
            return exports.sendError( res, 401, 'Unauthorized');
        }
        if (!req.params.id) {
            exports.sendError(res, 400, 'id missing');
        } else if (!req.body) {
            exports.sendError(res, 400, 'body missing');
        } else {
            self.update.call( self, req.user.bucket, { _id: ObjectID(req.params.id) }, req.body, exports.responseCallback(res));
        }
    });
}
RestAPI.prototype._remove = function (req, res) {

    var self = this;

    self.checkAuthentification(req, function () {
        if (!req.user&& !req.user.bucket) {
            return exports.sendError( res, 401, 'Unauthorized');
        }

        if (!req.params.id) {
            exports.sendError(res, 400, 'id missing');
        } else {
            self.remove.call(self, req.user.bucket, { _id: ObjectID(req.params.id) }, exports.responseCallback(res));
        }
    });
};

function RestMongoAPI(uri, privateKey, collection) {
    this.mongoUri = uri;
    this.connections = {};
    this.privateKey = privateKey;
    this.collection = collection;

    RestAPI.call(this);

}

util.inherits(RestMongoAPI, RestAPI);

RestMongoAPI.prototype.checkAuthentification = function(req, cb) {

    var token;

    if (req.method === 'OPTIONS' && req.headers.hasOwnProperty('access-control-request-headers')) {
        if (req.headers['access-control-request-headers'].split(', ').indexOf('authorization') != -1) {
            return cb();
        }
    }

    if (req.headers && req.headers.authorization) {
        var parts = req.headers.authorization.split(' ');
        if (parts.length == 2) {
            var scheme = parts[0]
                , credentials = parts[1];

            if (/^Bearer$/i.test(scheme)) {
                token = credentials;
            }
        } else {
            return cb();
        }
    } else {
        return cb();
    }

    jwt.verify(token, this.privateKey, function (err, decoded) {
        if (err) return cb();

        req.user = decoded;

        return cb();
    });
}

RestMongoAPI.prototype._getBucketConnection = function( bucket, callback ) {
    var self = this;

    if( this.connections[bucket] == undefined ) {
        // Instantiate new mongo connection
        MongoClient.connect(this.mongoUri, { auto_reconnect: true }, function (err, db) {
            if (err) return self.emit('error', err);
            self.connections[bucket] = {
                db: db,
                connected_at: new Date()
            };
            self.emit('connect', db);
            db.on('error', function (err) {
                self.emit('error', err);
            });

            callback( self.connections[bucket].db );
        });
    }
    else if( callback ) {
        callback( this.connections[bucket].db );
    }
};

RestMongoAPI.prototype._return = function (err, data, isArray, cb) {
    if (!cb) {
        return;
    } else if (err) {
        cb(500, err.message ? err.message : err);
    } else if (!data) {
        cb(404);
    } else if (isArray) {
        cb(null, data);
    } else {
        cb(null, util.isArray(data) ? data[0] : data);
    }
}
RestMongoAPI.prototype.query = function (bucket, criteria, options, cb) {
    if (typeof criteria === 'function') {
        cb = criteria;
        criteria = {};
        options = {};
    } else if (typeof options === 'function') {
        cb = options;
        options = {};
    }

    var self = this;

    if (!options.limit) options.limit = 100;

    self._getBucketConnection( bucket, function(db) {
        db.collection(self.collection).find(criteria, options).toArray(function (err, data) {
            self._return(err, data, true, cb);
        });
    });
}
RestMongoAPI.prototype.get = function (bucket, criteria, options, cb) {
    if (typeof options === 'function') {
        cb = options;
        options = {};
    }
    var self = this;
    self._getBucketConnection( bucket, function(db) {
        db.collection(self.collection).findOne(criteria, options, function (err, data) {
            self._return(err, data, false, cb);
        });
    });
}
RestMongoAPI.prototype.create = function (bucket, data, options, cb) {
    if (typeof options === 'function') {
        cb = options;
        options = {};
    }
    var self = this;
    self._getBucketConnection( bucket, function(db) {
        db.collection(self.collection).insert(data, options, function (err, data) {
            self._return(err, data, false, cb);
        });
    });
}
RestMongoAPI.prototype.update = function (bucket, criteria, data, options, cb) {
    if (typeof options === 'function') {
        cb = options;
        options = { w: 1 };
    }
    delete data._id;
    var self = this;

    self._getBucketConnection( bucket, function(db) {
        db.collection(self.collection).update(criteria, data, options, function (err, _data) {
            if (criteria._id) {
                data._id = criteria._id.toString();
            }
            self._return(err, _data ? data : null, false, cb);
        });
    });
}
RestMongoAPI.prototype.remove = function (bucket, criteria, options, cb) {
    if (typeof options === 'function') {
        cb = options;
        options = {};
    }
    var self = this;

    self._getBucketConnection( bucket, function(db) {
        db.collection(self.collection).remove(criteria, options, function (err, data) {
            if (err) {
                cb(500, err.message ? err.message : err);
            } else if (!data) {
                cb(400);
            } else {
                cb(null, '');
            }
        });
    });
}

exports.use = function (express, mount, api) {
    var routes = api.getRoutes();

    function getHandler(context, f) {
        return function (req, res, next) {
            f.call(context, req, res, next);
        }
    }

    for (var i = 0; i < routes.length; i++) {
        express[routes[i].method](mount + routes[i].mount, getHandler(api, routes[i].handler));
    }
}
exports.throwError = function (code, message) {
    console.error(code, message);
    var err = new Error(message);
    err.code = code;
    throw err;
}
exports.sendError = function (res, code, message) {
    var data = {
        success: false,
        code: code,
        error: message || ''
    };
    res.jsonp(code, data);
}
exports.responseCallback = function (res) {
    var self = this;
    return function (err, data) {
        if (err) {
            self.sendError(res, err.code || parseInt(err) || 400, err.message || data);
        } else {
            res.jsonp(data);
        }
    }
}
exports.RestAPI = RestAPI;
exports.RestMongoAPI = RestMongoAPI;

<commit_msg>Refactor<commit_after>var util = require('util')
    , EventEmitter = require('events').EventEmitter
    , MongoClient = require('mongodb').MongoClient
    , ObjectID = require('mongodb').ObjectID
    , jwt = require("jsonwebtoken");

function RestAPI() {
    this.routes = [
        { method: 'get', mount: '', handler: this._query },
        { method: 'get', mount: '/:id', handler: this._get },
        { method: 'put', mount: '', handler: this._create },
        { method: 'post', mount: '', handler: this._create },
        { method: 'post', mount: '/:id', handler: this._update },
        { method: 'delete', mount: '/:id', handler: this._remove }
    ];
}
util.inherits(RestAPI, EventEmitter);
RestAPI.prototype.getRoutes = function () {
    return this.routes;
}

RestAPI.prototype._query = function (req, res) {
    var self = this;

        if (!req.user && !req.user.bucket) {
    self.resolveAuthentification(req, function () {
            return exports.sendError( res, 401, 'Unauthorized');
        }
        self.query.call(self, req.user.bucket, exports.responseCallback(res));
    });
}
RestAPI.prototype._get = function (req, res) {
    var self = this;

        if (!req.user&& !req.user.bucket) {
    self.resolveAuthentification(req, function () {
            return exports.sendError( res, 401, 'Unauthorized');
        }
        if (!req.params.id) {
            exports.sendError(res, 400, 'id missing');
        } else {
            self.get.call( self, req.user.bucket, { _id: ObjectID(req.params.id) }, exports.responseCallback(res));
        }
    });
}
RestAPI.prototype._create = function (req, res) {
    var self = this;

        if (!req.user && !req.user.bucket) {
    self.resolveAuthentification(req, function () {
            return exports.sendError( res, 401, 'Unauthorized');
        }
        if (!req.body) {
            exports.sendError(res, 400, 'body missing');
        } else {
            self.create.call( self, req.user.bucket, req.body, exports.responseCallback(res));
        }
    });

}
RestAPI.prototype._update = function (req, res) {

    var self = this;

        if (!req.user&& !req.user.bucket) {
    self.resolveAuthentification(req,  function () {
            return exports.sendError( res, 401, 'Unauthorized');
        }
        if (!req.params.id) {
            exports.sendError(res, 400, 'id missing');
        } else if (!req.body) {
            exports.sendError(res, 400, 'body missing');
        } else {
            self.update.call( self, req.user.bucket, { _id: ObjectID(req.params.id) }, req.body, exports.responseCallback(res));
        }
    });
}
RestAPI.prototype._remove = function (req, res) {

    var self = this;

        if (!req.user&& !req.user.bucket) {
    self.resolveAuthentification(req, function () {
            return exports.sendError( res, 401, 'Unauthorized');
        }

        if (!req.params.id) {
            exports.sendError(res, 400, 'id missing');
        } else {
            self.remove.call(self, req.user.bucket, { _id: ObjectID(req.params.id) }, exports.responseCallback(res));
        }
    });
};

function RestMongoAPI(uri, privateKey, collection) {
    this.mongoUri = uri;
    this.connections = {};
    this.privateKey = privateKey;
    this.collection = collection;

    RestAPI.call(this);

}

util.inherits(RestMongoAPI, RestAPI);

RestMongoAPI.prototype.resolveAuthentification = function(req, cb) {

    var token;

    if (req.method === 'OPTIONS' && req.headers.hasOwnProperty('access-control-request-headers')) {
        if (req.headers['access-control-request-headers'].split(', ').indexOf('authorization') != -1) {
            return cb();
        }
    }

    if (req.headers && req.headers.authorization) {
        var parts = req.headers.authorization.split(' ');
        if (parts.length == 2) {
            var scheme = parts[0]
                , credentials = parts[1];

            if (/^Bearer$/i.test(scheme)) {
                token = credentials;
            }
        } else {
            return cb();
        }
    } else {
        return cb();
    }

    jwt.verify(token, this.privateKey, function (err, decoded) {
        if (err) return cb();

        req.user = decoded;

        return cb();
    });
}

RestMongoAPI.prototype._getBucketConnection = function( bucket, callback ) {
    var self = this;

    if( this.connections[bucket] == undefined ) {
        // Instantiate new mongo connection
        MongoClient.connect(this.mongoUri, { auto_reconnect: true }, function (err, db) {
            if (err) return self.emit('error', err);
            self.connections[bucket] = {
                db: db,
                connected_at: new Date()
            };
            self.emit('connect', db);
            db.on('error', function (err) {
                self.emit('error', err);
            });

            callback( self.connections[bucket].db );
        });
    }
    else if( callback ) {
        callback( this.connections[bucket].db );
    }
};

RestMongoAPI.prototype._return = function (err, data, isArray, cb) {
    if (!cb) {
        return;
    } else if (err) {
        cb(500, err.message ? err.message : err);
    } else if (!data) {
        cb(404);
    } else if (isArray) {
        cb(null, data);
    } else {
        cb(null, util.isArray(data) ? data[0] : data);
    }
}
RestMongoAPI.prototype.query = function (bucket, criteria, options, cb) {
    if (typeof criteria === 'function') {
        cb = criteria;
        criteria = {};
        options = {};
    } else if (typeof options === 'function') {
        cb = options;
        options = {};
    }

    var self = this;

    if (!options.limit) options.limit = 100;

    self._getBucketConnection( bucket, function(db) {
        db.collection(self.collection).find(criteria, options).toArray(function (err, data) {
            self._return(err, data, true, cb);
        });
    });
}
RestMongoAPI.prototype.get = function (bucket, criteria, options, cb) {
    if (typeof options === 'function') {
        cb = options;
        options = {};
    }
    var self = this;
    self._getBucketConnection( bucket, function(db) {
        db.collection(self.collection).findOne(criteria, options, function (err, data) {
            self._return(err, data, false, cb);
        });
    });
}
RestMongoAPI.prototype.create = function (bucket, data, options, cb) {
    if (typeof options === 'function') {
        cb = options;
        options = {};
    }
    var self = this;
    self._getBucketConnection( bucket, function(db) {
        db.collection(self.collection).insert(data, options, function (err, data) {
            self._return(err, data, false, cb);
        });
    });
}
RestMongoAPI.prototype.update = function (bucket, criteria, data, options, cb) {
    if (typeof options === 'function') {
        cb = options;
        options = { w: 1 };
    }
    delete data._id;
    var self = this;

    self._getBucketConnection( bucket, function(db) {
        db.collection(self.collection).update(criteria, data, options, function (err, _data) {
            if (criteria._id) {
                data._id = criteria._id.toString();
            }
            self._return(err, _data ? data : null, false, cb);
        });
    });
}
RestMongoAPI.prototype.remove = function (bucket, criteria, options, cb) {
    if (typeof options === 'function') {
        cb = options;
        options = {};
    }
    var self = this;

    self._getBucketConnection( bucket, function(db) {
        db.collection(self.collection).remove(criteria, options, function (err, data) {
            if (err) {
                cb(500, err.message ? err.message : err);
            } else if (!data) {
                cb(400);
            } else {
                cb(null, '');
            }
        });
    });
}

exports.use = function (express, mount, api) {
    var routes = api.getRoutes();

    function getHandler(context, f) {
        return function (req, res, next) {
            f.call(context, req, res, next);
        }
    }

    for (var i = 0; i < routes.length; i++) {
        express[routes[i].method](mount + routes[i].mount, getHandler(api, routes[i].handler));
    }
}
exports.throwError = function (code, message) {
    console.error(code, message);
    var err = new Error(message);
    err.code = code;
    throw err;
}
exports.sendError = function (res, code, message) {
    var data = {
        success: false,
        code: code,
        error: message || ''
    };
    res.jsonp(code, data);
}
exports.responseCallback = function (res) {
    var self = this;
    return function (err, data) {
        if (err) {
            self.sendError(res, err.code || parseInt(err) || 400, err.message || data);
        } else {
            res.jsonp(data);
        }
    }
}
exports.RestAPI = RestAPI;
exports.RestMongoAPI = RestMongoAPI;

<|endoftext|>


<commit_before><commit_msg>Refactor user games ctrl; track its view<commit_after><|endoftext|>


<commit_before>'use strict';
const Ringpop = require('ringpop')
    , TChannel = require('tchannel')
    , conf = require('keef')
    , host = conf.get('channel:host')
    , port = ~~conf.get('channel:port')
    ;

const tchannel = new TChannel();
const ringpop = new Ringpop({
    app: 'timers'
  , hostPort:`${host}:${port}`
  , channel: tchannel.makeSubChannel({
      serviceName: 'ringpop'
    , trace:false
    })
});

ringpop.setupChannel();

tchannel.listen( port, host, ()=> {
  console.log('tchannel listening on ', host, port);

  ringpop.bootstrap(conf.get( 'seed' ),( err ) => {
    if( err ){
      console.error( err.stack );
      process.exit( 1 );
    }
    console.log( 'ring bootstraped', conf.get( 'seed' ) );
  });
});

module.exports = ringpop;
<commit_msg>removing some console statements<commit_after>'use strict';
const Ringpop  = require('ringpop')
    , TChannel = require('tchannel')
    , debug    = require('debug')('kronos:ring')
    , conf     = require('keef')
    , host     = conf.get('channel:host')
    , port     = ~~conf.get('channel:port')
    ;

const tchannel = new TChannel();
const ringpop = new Ringpop({
    app: 'timers'
  , hostPort:`${host}:${port}`
  , channel: tchannel.makeSubChannel({
      serviceName: 'ringpop'
    , trace:false
    })
});

ringpop.setupChannel();

tchannel.listen( port, host, ()=> {
  debug('tchannel listening on ', host, port);

  ringpop.bootstrap(conf.get( 'seed' ), ( err ) => {
    if( err ){
      console.error( err.stack );
      process.exit( 1 );
    }
    debug( 'ring bootstraped', conf.get( 'seed' ) );
  });
});

module.exports = ringpop;
<|endoftext|>


<commit_before>var _ = require('underscore')._;
var util = require('util');

var Room = function(io, roomUrl) {
  this.io = io;
  this.roomUrl = roomUrl;
  this.createdAt = calcTime(2);
  this.createAdmin = true;
  this.hasAdmin = false;
  this.cardPack = 'goat';
  this.clientCount = 0;
  this.connections = {}; // we collect the votes in here
  this.forcedReveal = false;
};

Room.prototype.info = function() {
  this.clientCount = this.getClientCount();
  this.createAdmin = this.hasAdmin === false;
  this.hasAdmin = true;
  // console.log("room info = ", this.json());
  return this.json();
};

Room.prototype.enter = function(socket, data) {
  // console.log("room entered as " + socket.id);
  if (this.connections[data.sessionId]) {
    this.connections[data.sessionId].socketId = socket.id;
  } else {
    this.connections[data.sessionId] = { sessionId: data.sessionId, socketId: socket.id, vote: null, voter: true };
  }
}

Room.prototype.leave = function(socket) {
  var connection = _.find(this.connections, function(c) { return c.socketId === socket.id } );
  if (connection && connection.sessionId) {
    connection.socketId = null;
  }
}

Room.prototype.setCardPack = function(data) {
  this.cardPack = data.cardPack;
  this.io.sockets.in(this.roomUrl).emit('card pack set');
  // console.log('card pack set');
}

Room.prototype.toggleVoter = function(data) {
  if (this.connections[data.sessionId]) {
    this.connections[data.sessionId]['voter'] = data.voter;
    if (!data.voter) {
      this.connections[data.sessionId]['vote'] = null;
    }
    // console.log("voter set to " + data.voter + " for " + data.sessionId);
  }
  this.io.sockets.in(this.roomUrl).emit('voter status changed');
}

Room.prototype.recordVote = function(socket, data) {
  if (this.connections[data.sessionId]) {
    this.connections[data.sessionId]['vote'] = data.vote;
  }
  socket.broadcast.to(this.roomUrl).emit('voted');
  // this.io.sockets.in(this.roomUrl).emit('voted');
}

Room.prototype.destroyVote = function(socket, data) {
  if (this.connections[data.sessionId]) {
    this.connections[data.sessionId]['vote'] = null;
  }
  socket.broadcast.to(this.roomUrl).emit('unvoted');
  // this.io.sockets.in(this.roomUrl).emit('unvoted');
}

Room.prototype.resetVote = function() {
  _.forEach(this.connections, function(c) {
    c.vote = null;
  })
  this.forcedReveal = false;
  this.io.sockets.in(this.roomUrl).emit('vote reset');
}

Room.prototype.forceReveal = function() {
  this.forcedReveal = true;
  this.io.sockets.in(this.roomUrl).emit('reveal');
}

Room.prototype.getClientCount = function() {
  return Object.keys(this.io.sockets.clients(this.roomUrl)).length;
}

Room.prototype.json = function() {
  return {
    roomUrl: this.roomUrl,
    createdAt: this.createdAt,
    createAdmin: this.createAdmin,
    hasAdmin: this.hasAdmin,
    cardPack: this.cardPack,
    clientCount: this.clientCount,
    connections: this.connections,
    forcedReveal: this.forcedReveal
  };
}

function calcTime(offset) {
  // create Date object for current location
  d = new Date();

  // convert to msec
  // add local time zone offset
  // get UTC time in msec
  utc = d.getTime() + (d.getTimezoneOffset() * 60000);

  // create new Date object for different place
  // using supplied offset
  nd = new Date(utc + (3600000*offset));

  // return time as a string
  return nd.toLocaleString();
}

exports.Room = Room;<commit_msg>Pedantic - swapped moved forcedReveal above the connections in the json to make the /debug_state look prettier.<commit_after>var _ = require('underscore')._;
var util = require('util');

var Room = function(io, roomUrl) {
  this.io = io;
  this.roomUrl = roomUrl;
  this.createdAt = calcTime(2);
  this.createAdmin = true;
  this.hasAdmin = false;
  this.cardPack = 'goat';
  this.clientCount = 0;
  this.connections = {}; // we collect the votes in here
  this.forcedReveal = false;
};

Room.prototype.info = function() {
  this.clientCount = this.getClientCount();
  this.createAdmin = this.hasAdmin === false;
  this.hasAdmin = true;
  // console.log("room info = ", this.json());
  return this.json();
};

Room.prototype.enter = function(socket, data) {
  // console.log("room entered as " + socket.id);
  if (this.connections[data.sessionId]) {
    this.connections[data.sessionId].socketId = socket.id;
  } else {
    this.connections[data.sessionId] = { sessionId: data.sessionId, socketId: socket.id, vote: null, voter: true };
  }
}

Room.prototype.leave = function(socket) {
  var connection = _.find(this.connections, function(c) { return c.socketId === socket.id } );
  if (connection && connection.sessionId) {
    connection.socketId = null;
  }
}

Room.prototype.setCardPack = function(data) {
  this.cardPack = data.cardPack;
  this.io.sockets.in(this.roomUrl).emit('card pack set');
  // console.log('card pack set');
}

Room.prototype.toggleVoter = function(data) {
  if (this.connections[data.sessionId]) {
    this.connections[data.sessionId]['voter'] = data.voter;
    if (!data.voter) {
      this.connections[data.sessionId]['vote'] = null;
    }
    // console.log("voter set to " + data.voter + " for " + data.sessionId);
  }
  this.io.sockets.in(this.roomUrl).emit('voter status changed');
}

Room.prototype.recordVote = function(socket, data) {
  if (this.connections[data.sessionId]) {
    this.connections[data.sessionId]['vote'] = data.vote;
  }
  socket.broadcast.to(this.roomUrl).emit('voted');
  // this.io.sockets.in(this.roomUrl).emit('voted');
}

Room.prototype.destroyVote = function(socket, data) {
  if (this.connections[data.sessionId]) {
    this.connections[data.sessionId]['vote'] = null;
  }
  socket.broadcast.to(this.roomUrl).emit('unvoted');
  // this.io.sockets.in(this.roomUrl).emit('unvoted');
}

Room.prototype.resetVote = function() {
  _.forEach(this.connections, function(c) {
    c.vote = null;
  })
  this.forcedReveal = false;
  this.io.sockets.in(this.roomUrl).emit('vote reset');
}

Room.prototype.forceReveal = function() {
  this.forcedReveal = true;
  this.io.sockets.in(this.roomUrl).emit('reveal');
}

Room.prototype.getClientCount = function() {
  return Object.keys(this.io.sockets.clients(this.roomUrl)).length;
}

Room.prototype.json = function() {
  return {
    roomUrl: this.roomUrl,
    createdAt: this.createdAt,
    createAdmin: this.createAdmin,
    hasAdmin: this.hasAdmin,
    cardPack: this.cardPack,
    clientCount: this.clientCount,
    forcedReveal: this.forcedReveal,
    connections: this.connections
  };
}

function calcTime(offset) {
  // create Date object for current location
  d = new Date();

  // convert to msec
  // add local time zone offset
  // get UTC time in msec
  utc = d.getTime() + (d.getTimezoneOffset() * 60000);

  // create new Date object for different place
  // using supplied offset
  nd = new Date(utc + (3600000*offset));

  // return time as a string
  return nd.toLocaleString();
}

exports.Room = Room;<|endoftext|>


<commit_before>JavascriptBuilder = function() {
	this.responses = [];
};

JavascriptBuilder.prototype.appendResponse = function(response) {
	this.responses.push(response);
};

JavascriptBuilder.prototype._getInitFunction = function() {
	var initFunction = function() {

        var myAppDev = angular.module('httpBackendMock', ['ngMockE2E']);

        myAppDev.run(['$httpBackend', function($httpBackend) {
            window.httpBackendContext = $httpBackend;
            window.httpBackendContext.context = {};
            var firstSync;
        }]);
    };

    return initFunction;
};

JavascriptBuilder.prototype.toString = function(init) {

	var mockFunction = '';
	this.responses.forEach(function(response) {
		mockFunction += this._buildSyncFunctionForResponse(response);
	}, this);

	if (init && init != 'undefined') {
		mockFunction = '(' + this._getInitFunction().toString().replace(/var firstSync;/, mockFunction) + ')();';
	}

	return mockFunction;
};

JavascriptBuilder.prototype._buildSyncFunctionForResponse = function(response) {
    var mockFunction =  "window.httpBackendContext." + this.buildRequestmethod(response.request) +
        "." + this.buildResponse(response) +";";

    return this.buildContextForResponse(response) + mockFunction;
};

JavascriptBuilder.prototype.buildRequestmethod = function(request) {

	var url;

	if (typeof request.url == 'string') {
		url = '"' + request.url + '"';
	} else {
		url = request.url;
	}

	return 'when' + request.method + "(" + url +")";
};

JavascriptBuilder.prototype.buildResponse = function(response) {

	if (response.isPassThrough) {
		return 'passThrough()';
	}

	return "respond(function(method, url, data) { return window.httpBackendContext.context['" + response.request.uid + "'](method, url, data);})";
};

JavascriptBuilder.prototype.buildContextForResponse = function(response) {
	if (response.isPassThrough) {
		return '';
	}

	var contextFunction = null;

	if (typeof response.data != 'function') {
		contextFunction = function () {
			return [200, data];
		};

		contextFunction = contextFunction.toString().replace(/data/, JSON.stringify(response.data));
	} else {
		contextFunction = response.data.toString();
	}

	return "window.httpBackendContext.context['" + response.request.uid + "'] = " +  contextFunction + ";";
};

module.exports = JavascriptBuilder;<commit_msg>Update javascriptbuilder.js<commit_after>JavascriptBuilder = function() {
	this.responses = [];
};

JavascriptBuilder.prototype.appendResponse = function(response) {
	this.responses.push(response);
};

JavascriptBuilder.prototype._getInitFunction = function() {
	var initFunction = function() {

        var myAppDev = angular.module('httpBackendMock', ['ngMockE2E']);

        myAppDev.run(['$httpBackend', function($httpBackend) {
            window.httpBackendContext = $httpBackend;
            window.httpBackendContext.context = {};
            var firstSync;
        }]);
    };

    return initFunction;
};

JavascriptBuilder.prototype.toString = function(init) {

	var mockFunction = '';
	this.responses.forEach(function(response) {
		mockFunction += this._buildSyncFunctionForResponse(response);
	}, this);

	if (init && init != 'undefined') {
		mockFunction = '(' + this._getInitFunction().toString().replace(/var firstSync;/, mockFunction) + ')();';
	}

	return mockFunction;
};

JavascriptBuilder.prototype._buildSyncFunctionForResponse = function(response) {
    var mockFunction =  "window.httpBackendContext." + this.buildRequestmethod(response.request) +
        "." + this.buildResponse(response) +";";

    return this.buildContextForResponse(response) + mockFunction;
};

JavascriptBuilder.prototype.buildRequestmethod = function(request) {

	var url;

	if (typeof request.url == 'string') {
		url = '"' + request.url + '"';
	} else {
		url = request.url;
	}

	return 'when' + request.method + "(" + url +")";
};

JavascriptBuilder.prototype.buildResponse = function(response) {

	if (response.isPassThrough) {
		return 'passThrough()';
	}

	return "respond(function(method, url, data, headers) { return window.httpBackendContext.context['" + response.request.uid + "'](method, url, data, headers);})";
};

JavascriptBuilder.prototype.buildContextForResponse = function(response) {
	if (response.isPassThrough) {
		return '';
	}

	var contextFunction = null;

	if (typeof response.data != 'function') {
		contextFunction = function () {
			return [200, data];
		};

		contextFunction = contextFunction.toString().replace(/data/, JSON.stringify(response.data));
	} else {
		contextFunction = response.data.toString();
	}

	return "window.httpBackendContext.context['" + response.request.uid + "'] = " +  contextFunction + ";";
};

module.exports = JavascriptBuilder;
<|endoftext|>


<commit_before>(function(global) {
    'use strict';

    if (typeof module !== 'undefined' && module.exports)
        module.exports = new Ruff();
    else
        global.ruff = new Ruff();

    function Ruff() {
        function ra(generator) {
            var events  = new Events(),
                gen     = generator();

            function nextItem(error, result) {
                var item = gen.next(result);

                if (error)
                    events.emit('error', error);
                else if (!item.done)
                    item.value(nextItem);

                if (item.done)
                    events.emit('end');
            }

            nextItem();

            return events;
        }

        function Events() {
            this._all = {};
        }

        Events.prototype.on = function(event, callback) {
            var funcs = this._all[event];

            if (funcs)
                funcs.push(callback);
            else
                this._all[event] = [callback];

            return events;
        };

        Events.prototype.emit = function(event, data) {
            var funcs = this._all[event];

            if (funcs)
                funcs.forEach(function(fn) {
                    fn(data);
                });
            else if (event === 'error')
                throw data;
        };

        return ra;
    }
})(this);
<commit_msg>fix(ruff) Events on return: events -> this<commit_after>(function(global) {
    'use strict';

    if (typeof module !== 'undefined' && module.exports)
        module.exports = new Ruff();
    else
        global.ruff = new Ruff();

    function Ruff() {
        function ra(generator) {
            var events  = new Events(),
                gen     = generator();

            function nextItem(error, result) {
                var item = gen.next(result);

                if (error)
                    events.emit('error', error);
                else if (!item.done)
                    item.value(nextItem);

                if (item.done)
                    events.emit('end');
            }

            nextItem();

            return events;
        }

        function Events() {
            this._all = {};
        }

        Events.prototype.on = function(event, callback) {
            var funcs = this._all[event];

            if (funcs)
                funcs.push(callback);
            else
                this._all[event] = [callback];

            return this;
        };

        Events.prototype.emit = function(event, data) {
            var funcs = this._all[event];

            if (funcs)
                funcs.forEach(function(fn) {
                    fn(data);
                });
            else if (event === 'error')
                throw data;
        };

        return ra;
    }
})(this);
<|endoftext|>


<commit_before>'use babel';

import { CompositeDisposable } from 'atom';
import fs from 'fs';
import path from 'path';

const PACKAGE_NAME = 'atom-language-rust';
const CONFIG = {
  STYLES: PACKAGE_NAME + '.styles',
  COLORS: PACKAGE_NAME + '.colors'
}
const STYLES_REGEX = {
  ATTRIBUTE: /(@syntax-color-attribute:\s+)[^;]+/,
  DOCUMENTATION: /(@syntax-color-documentation:\s+)[^;]+/,
  LIFETIME: /(@syntax-color-lifetime:\s+)[^;]+/,
  MACRO: /(@syntax-color-macro:\s+)[^;]+/,
  PARAMETER: /(@syntax-color-parameter:\s+)[^;]+/
};

class Rust {
  constructor() {
    this.config = {
      styles: {
        title: 'Additional Styles',
        description:
          `Provides additional styles to assist with distinguishing between
          Rust language constructs. This is made possible by taking advantage
          of non-standard scope names defined by the grammar in this package.`,
        type: 'boolean',
        default: true,
        order: 0
      },
      colors: {
        title: 'Custom Colors',
        type: 'object',
        properties: {
          attribute: {
            title: 'Attributes',
            type: 'string',
            default: ''
          },
          documentation: {
            title: 'Documentation',
            description:
              `Base color used by documentation blocks. The color of each
              supported Markdown construct is derived from it.`,
            type: 'string',
            default: ''
          },
          lifetime: {
            title: 'Lifetimes',
            type: 'string',
            default: ''
          },
          macro: {
            title: 'Macros',
            type: 'string',
            default: ''
          },
          parameter: {
            title: 'Parameters',
            type: 'string',
            default: ''
          }
        },
        order: 1
      }
    };
    this.subscriptions = new CompositeDisposable;
  }
  activate(state) {
    this.styles = this.loadStylesFile();
    this.readDefaultColors();
    this.subscriptions.add(
      atom.config.observe(CONFIG.STYLES, (this.onToggleStyles).bind(this)),
      atom.config.observe(CONFIG.COLORS, (this.onEditColors).bind(this))
    );
  }
  deactivate() {
    this.subscriptions.dispose();
    this.subscriptions = null;
  }
  onEditColors(colors) {
    // Block style reloading attempts if additional styles is disabled
    if (!atom.config.get(CONFIG.STYLES)) return;
    this.reloadStyles(colors);
  }
  onToggleStyles(enabled) {
    if (!enabled) {
      let styleElement = atom.styles.styleElementsBySourcePath[this.stylesPath];
      atom.styles.removeStyleElement(styleElement);
      if (!styleElement) {
        atom.notifications.addWarning(
          PACKAGE_NAME + ' could not find its package styles to remove'
        );
      }
      return;
    }
    this.reloadStyles(atom.config.get(CONFIG.COLORS));
  }
  loadStylesFile() {
    let package = atom.packages.getLoadedPackage(PACKAGE_NAME);
    if (!package) {
      atom.notifications.addFatalError(
        PACKAGE_NAME + ' failed to locate its own package instance'
      );
      return;
    }
    this.stylesPath = [package.path, 'styles', 'rust.less'].join(path.sep);
    let styles;
    try {
      styles = fs.readFileSync(this.stylesPath, {
        encoding: 'utf8'
      });
    } catch (e) {
      atom.notifications.addFatalError(
        PACKAGE_NAME + ' failed to read its package styles file\n' +
        e.message
      );
    }
    return styles;
  }
  readDefaultColors() {
    let styles =
      atom.themes.lessCache.cssForFile(null, this.styles);
    for (let item in STYLES_REGEX) {
      item = item.toLowerCase();
      let regex = new RegExp(item + '[^:]+:\\s+([^;]+)');
      let match = styles.match(regex);
      if (!match) continue;
      atom.config.defaultSettings[PACKAGE_NAME].colors[item] = match[1];
    }
  }
  reloadStyles(colors) {
    // Operate on a copy of the uncompiled base styles
    let styles = this.styles;
    for (let item in colors) {
      if (colors[item] === '') continue;
      styles = styles.replace(
        STYLES_REGEX[item.toUpperCase()], '$1' + colors[item]
      );
    }
    styles = atom.themes.lessCache.cssForFile(this.stylesPath, styles);
    atom.styles.addStyleSheet(styles, {
      priority: 0,
      sourcePath: this.stylesPath
    });
  }
}

export default Rust;
<commit_msg>Suppress LESS compilation errors<commit_after>'use babel';

import { CompositeDisposable } from 'atom';
import fs from 'fs';
import path from 'path';

const PACKAGE_NAME = 'atom-language-rust';
const CONFIG = {
  STYLES: PACKAGE_NAME + '.styles',
  COLORS: PACKAGE_NAME + '.colors'
}
const STYLES_REGEX = {
  ATTRIBUTE: /(@syntax-color-attribute:\s+)[^;]+/,
  DOCUMENTATION: /(@syntax-color-documentation:\s+)[^;]+/,
  LIFETIME: /(@syntax-color-lifetime:\s+)[^;]+/,
  MACRO: /(@syntax-color-macro:\s+)[^;]+/,
  PARAMETER: /(@syntax-color-parameter:\s+)[^;]+/
};

class Rust {
  constructor() {
    this.config = {
      styles: {
        title: 'Additional Styles',
        description:
          `Provides additional styles to assist with distinguishing between
          Rust language constructs. This is made possible by taking advantage
          of non-standard scope names defined by the grammar in this package.`,
        type: 'boolean',
        default: true,
        order: 0
      },
      colors: {
        title: 'Custom Colors',
        type: 'object',
        properties: {
          attribute: {
            title: 'Attributes',
            type: 'string',
            default: ''
          },
          documentation: {
            title: 'Documentation',
            description:
              `Base color used by documentation blocks. The color of each
              supported Markdown construct is derived from it.`,
            type: 'string',
            default: ''
          },
          lifetime: {
            title: 'Lifetimes',
            type: 'string',
            default: ''
          },
          macro: {
            title: 'Macros',
            type: 'string',
            default: ''
          },
          parameter: {
            title: 'Parameters',
            type: 'string',
            default: ''
          }
        },
        order: 1
      }
    };
    this.subscriptions = new CompositeDisposable;
  }
  activate(state) {
    this.styles = this.loadStylesFile();
    this.readDefaultColors();
    this.subscriptions.add(
      atom.config.observe(CONFIG.STYLES, (this.onToggleStyles).bind(this)),
      atom.config.observe(CONFIG.COLORS, (this.onEditColors).bind(this))
    );
  }
  deactivate() {
    this.subscriptions.dispose();
    this.subscriptions = null;
  }
  onEditColors(colors) {
    // Block style reloading attempts if additional styles is disabled
    if (!atom.config.get(CONFIG.STYLES)) return;
    this.reloadStyles(colors);
  }
  onToggleStyles(enabled) {
    if (!enabled) {
      let styleElement = atom.styles.styleElementsBySourcePath[this.stylesPath];
      atom.styles.removeStyleElement(styleElement);
      if (!styleElement) {
        atom.notifications.addWarning(
          PACKAGE_NAME + ' could not find its package styles to remove'
        );
      }
      return;
    }
    this.reloadStyles(atom.config.get(CONFIG.COLORS));
  }
  loadStylesFile() {
    let package = atom.packages.getLoadedPackage(PACKAGE_NAME);
    if (!package) {
      atom.notifications.addFatalError(
        PACKAGE_NAME + ' failed to locate its own package instance'
      );
      return;
    }
    this.stylesPath = [package.path, 'styles', 'rust.less'].join(path.sep);
    let styles;
    try {
      styles = fs.readFileSync(this.stylesPath, {
        encoding: 'utf8'
      });
    } catch (e) {
      atom.notifications.addFatalError(
        PACKAGE_NAME + ' failed to read its package styles file\n' +
        e.message
      );
    }
    return styles;
  }
  readDefaultColors() {
    let styles =
      atom.themes.lessCache.cssForFile(null, this.styles);
    for (let item in STYLES_REGEX) {
      item = item.toLowerCase();
      let regex = new RegExp(item + '[^:]+:\\s+([^;]+)');
      let match = styles.match(regex);
      if (!match) continue;
      atom.config.defaultSettings[PACKAGE_NAME].colors[item] = match[1];
    }
  }
  reloadStyles(colors) {
    // Operate on a copy of the uncompiled base styles
    let styles = this.styles;
    for (let item in colors) {
      if (colors[item] === '') continue;
      styles = styles.replace(
        STYLES_REGEX[item.toUpperCase()], '$1' + colors[item]
      );
    }
    try {
      styles = atom.themes.lessCache.cssForFile(this.stylesPath, styles);
    } catch (e) {
      // Suppress errors that might be caused by trying to compile invalid
      // input color values and return immediately without updating styles
      return;
    }
    atom.styles.addStyleSheet(styles, {
      priority: 0,
      sourcePath: this.stylesPath
    });
  }
}

export default Rust;
<|endoftext|>


<commit_before>/**
 * This script inserts into mongo the contents of all the .json files in the /seeds directory.
 *
 * The name of the file is the collection that the contents of that file will be inserted into.
 *      Example: This script will insert all the records in cohort.json into the collection "cohort"
 *
 * Usage: $ node seed
 *
 * @author Tom Caflisch
 */

var Q       = require('q');
var mongo   = require('mongodb').MongoClient;
var config  = require(process.cwd() + "/seed.json");
var dir     = process.cwd()+'/seeds';
var fs      = require('fs'); // Used to get all the files in a directory
var util    = require('util');
var _       = require('lodash');
var errno   = require('errno');
var path    = require('path');
var json2mongo = require('json2mongo');

/**
 * Reads the .json files from the ./seeds folder and inserts them into mongo
 */
module.exports.seed = function() {

  var listOfFiles = null;

  load_files().then(function(list) {
    listOfFiles = list;
    return getConnection();
  }).then(function(db) {
    return seed_db(db, listOfFiles);
  }).then(function () {
    console.log('----------------------');
    console.log('All done. Go play!');
  }).fail(function(err) {
    console.log('err = ', err);
  }).done();
}

/*************************
 * Private
 ************************/

/**
 * Loads all the json files from the ./seeds folder
 */
function load_files() {

  return Q.promise(function(resolve, reject, notify) {

    // Read all the files in the ./seeds folder
    fs.readdir(dir, function(err, files) {

      if(err || _.isUndefined(files)) {
        return reject('Error reading /seeds folder');
      } else {
        // Filter out everything except the .json files
        files = files.filter(function(file) {
          return path.extname(file) === '.json';
        });

        return resolve(files);
      }
    });
  });
}

/**
 * Loops through all the .json files in ./seeds and removes all the records
 *
 * @param db    - The mongo object to run queries against
 * @param list  - An array of all the .json files from the seeds folder
 */
function seed_db(db, list) {

  console.log('Seeding files from directory ' + path.resolve(dir));
  console.log('----------------------');

  return Q.promise(function(resolve, reject, notify) {

    var operations = [];

    // Loop through every file in the list
    list.forEach(function (file) {

      // Set the filename without the extension to the variable collection_name
      var collection_name = file.split(".")[0];
      var contents = null;

      // True if the current file has contents, false if it's empty
      var hasContents = fs.statSync(path.resolve(dir + '/' + file)).size > 0;

      console.log('Seeding collection ' + collection_name);

      // If the file has contents, load them
      if(hasContents) {

        contents = require(dir + '/' + file);

        // If the seed file is NOT an array
        if (!util.isArray(contents)) {
          return reject(new Error('Seed file ' + collection_name + ' does not start with an Array'));
        }
      }

      // The chain of operations to occur for each file. Drop the existing collection if it exists, create it, insert data into it
      var chain = dropCollection(db, collection_name).then(function() {
        return createCollection(db, collection_name);
      }).then(function() {
        if(contents) {
          return insert(db, collection_name, contents)
        }
      }).fail(function(err) {
        return reject(errmsg(err));
      });

      // Push the chain for each file to an array of promises
      operations.push(chain);
    });

    // When all the drop/create/inserts are complete, we're finished
    Q.allSettled(operations).then(function() {
      return resolve();
    }).fail(function(err) {
      return reject(err);
    }).fin(function() {
      db.close();
    });
  });
}

/**
 * Gets a connection to mongo
 *
 * @returns {promise|*|Q.promise}
 */
function getConnection() {

  return Q.promise(function(resolve, reject, notify) {

    var NODE_ENV = process.env.NODE_ENV;
    var connectionString = null;

    // If NODE_ENV is set and there is no key in seed.json matching, throw an error
    if(NODE_ENV && !config[NODE_ENV]) {
      return reject('No key exists in seed.json for the passed in NODE_ENV');
    }

    // If the connection string does not start with "mongodb://", add it
    if(_.startsWith(config[NODE_ENV], "mongodb://")) {
      connectionString = config[NODE_ENV];
    } else {
      connectionString = 'mongodb://' + config[NODE_ENV];
    }

    mongo.connect(connectionString, function(err, db) {

      if(err) {
        return reject(err);
      }

      resolve(db);
    });
  });
}

/**
 * Creates a collection in mongo
 *
 * @param collection
 * @returns {*}
 */
function createCollection(db, name) {

  return Q.promise(function(resolve, reject, notify) {

    db.createCollection(name, function(err, collection) {

      if(err) {
        return reject(err);
      }

      resolve();
    });
  });
}

/**
 * Drops a collection from mongo if it exists
 *
 * @param collection  - The collection to drop
 * @returns {*}
 */
function dropCollection(db, name) {

  return Q.promise(function(resolve, reject, notify) {

    // Check if the collection exists, else don't do anything
    collectionExist(db, name).then(function(exists) {

      // If the collection exists, drop it
      if(exists) {

        db.dropCollection(name, function(err, reply) {

          if(err) {
            return reject(err);
          }

          resolve();
        });
      } else {
        resolve();
      }
    });
  });
}

/**
 * Checks if a collection exists
 *
 * @param db    - The db to check if a collection exists in
 * @param name  - The name of the collection we want to see if exists
 * @returns {promise|*|Q.promise}
 */
function collectionExist(db, name) {

  return Q.promise(function(resolve, reject, notify) {

    db.collectionNames(function(err, collections) {

      if(err) {
        reject(err);
      }

      // If the collection exists in the mongo db
      if(_.findWhere(collections, {name: name})) {
        return resolve(true);
      } else {
        return resolve(false);
      }
    });
  });
}

/**
 * Inserts an array of objects into mongo
 *
 * @param db              - The db to insert into
 * @param collection_name - The collection to insert into
 * @param contents        - The contents to be inserted
 * @returns {*}
 */
function insert(db, collection_name, contents) {

  return Q.promise(function(resolve, reject, notify) {

    // If it's an empty array, there's nothing to insert
    if(contents.length !== 0) {

      var data = contents.map(function(content){
        return json2mongo(content);
      });

      db.collection(collection_name).insert(data, function(err, result) {
        if(err) {
          return reject(err);
        }

        return resolve(result);
      });
    }

    return resolve();
  });
}

/**
 * Formats error messages to display the actual error message instead of all the errno codes and what not.
 *
 * @param err         - The error object that may or may not contain an errno code
 * @returns {string}  - A simple message
 */
function errmsg(err) {

  var str = 'Error: '
  // if it's a libuv error then get the description from errno
  if (errno.errno[err.errno]) {
    str += errno.errno[err.errno].description
  } else {
    str += err.message
  }

  // if it's a `fs` error then it'll have a 'path' property
  if (err.path) {
    str += ' [' + err.path + ']'
  }
  return str
}
<commit_msg>Fixed accidental overwrite of previous fix<commit_after>/**
 * This script inserts into mongo the contents of all the .json files in the /seeds directory.
 *
 * The name of the file is the collection that the contents of that file will be inserted into.
 *      Example: This script will insert all the records in cohort.json into the collection "cohort"
 *
 * Usage: $ node seed
 *
 * @author Tom Caflisch
 */

var Q       = require('q');
var mongo   = require('mongodb').MongoClient;
var config  = require(process.cwd() + "/seed.json");
var dir     = process.cwd()+'/seeds';
var fs      = require('fs'); // Used to get all the files in a directory
var util    = require('util');
var _       = require('lodash');
var errno   = require('errno');
var path    = require('path');
var json2mongo = require('json2mongo');

/**
 * Reads the .json files from the ./seeds folder and inserts them into mongo
 */
module.exports.seed = function() {

  var listOfFiles = null;

  load_files().then(function(list) {
    listOfFiles = list;
    return getConnection();
  }).then(function(db) {
    return seed_db(db, listOfFiles);
  }).then(function () {
    console.log('----------------------');
    console.log('All done. Go play!');
  }).fail(function(err) {
    console.log('err = ', err);
  }).done();
}

/*************************
 * Private
 ************************/

/**
 * Loads all the json files from the ./seeds folder
 */
function load_files() {

  return Q.promise(function(resolve, reject, notify) {

    // Read all the files in the ./seeds folder
    fs.readdir(dir, function(err, files) {

      if(err || _.isUndefined(files)) {
        return reject('Error reading /seeds folder');
      } else {
        // Filter out everything except the .json files
        files = files.filter(function(file) {
          return path.extname(file) === '.json';
        });

        return resolve(files);
      }
    });
  });
}

/**
 * Loops through all the .json files in ./seeds and removes all the records
 *
 * @param db    - The mongo object to run queries against
 * @param list  - An array of all the .json files from the seeds folder
 */
function seed_db(db, list) {

  console.log('Seeding files from directory ' + path.resolve(dir));
  console.log('----------------------');

  return Q.promise(function(resolve, reject, notify) {

    var operations = [];

    // Loop through every file in the list
    list.forEach(function (file) {

      // Set the filename without the extension to the variable collection_name
      var collection_name = file.split(".")[0];
      var contents = null;

      // True if the current file has contents, false if it's empty
      var hasContents = fs.statSync(path.resolve(dir + '/' + file)).size > 0;

      console.log('Seeding collection ' + collection_name);

      // If the file has contents, load them
      if(hasContents) {

        contents = require(dir + '/' + file);

        // If the seed file is NOT an array
        if (!util.isArray(contents)) {
          return reject(new Error('Seed file ' + collection_name + ' does not start with an Array'));
        }
      }

      // The chain of operations to occur for each file. Drop the existing collection if it exists, create it, insert data into it
      var chain = dropCollection(db, collection_name).then(function() {
        return createCollection(db, collection_name);
      }).then(function() {
        if(contents) {
          return insert(db, collection_name, contents)
        }
      }).fail(function(err) {
        return reject(errmsg(err));
      });

      // Push the chain for each file to an array of promises
      operations.push(chain);
    });

    // When all the drop/create/inserts are complete, we're finished
    Q.allSettled(operations).then(function() {
      return resolve();
    }).fail(function(err) {
      return reject(err);
    }).fin(function() {
      db.close();
    });
  });
}

/**
 * Gets a connection to mongo
 *
 * @returns {promise|*|Q.promise}
 */
function getConnection() {

  return Q.promise(function(resolve, reject, notify) {

    var NODE_ENV = process.env.NODE_ENV;
    var connectionString = null;

    // If NODE_ENV is set and there is no key in seed.json matching, throw an error
    if(NODE_ENV && !config[NODE_ENV]) {
      return reject('No key exists in seed.json for the passed in NODE_ENV');
    }

    // If the connection string does not start with "mongodb://", add it
    if(_.startsWith(config[NODE_ENV], "mongodb://")) {
      connectionString = config[NODE_ENV];
    } else {
      connectionString = 'mongodb://' + config[NODE_ENV];
    }

    mongo.connect(connectionString, function(err, db) {

      if(err) {
        return reject(err);
      }

      resolve(db);
    });
  });
}

/**
 * Creates a collection in mongo
 *
 * @param collection
 * @returns {*}
 */
function createCollection(db, name) {

  return Q.promise(function(resolve, reject, notify) {

    db.createCollection(name, function(err, collection) {

      if(err) {
        return reject(err);
      }

      resolve();
    });
  });
}

/**
 * Drops a collection from mongo if it exists
 *
 * @param collection  - The collection to drop
 * @returns {*}
 */
function dropCollection(db, name) {

  return Q.promise(function(resolve, reject, notify) {

    // Check if the collection exists, else don't do anything
    collectionExist(db, name).then(function(exists) {

      // If the collection exists, drop it
      if(exists) {

        db.dropCollection(name, function(err, reply) {

          if(err) {
            return reject(err);
          }

          resolve();
        });
      } else {
        resolve();
      }
    });
  });
}

/**
 * Checks if a collection exists
 *
 * @param db    - The db to check if a collection exists in
 * @param name  - The name of the collection we want to see if exists
 * @returns {promise|*|Q.promise}
 */
function collectionExist(db, name) {

  return Q.promise(function(resolve, reject, notify) {

    db.collectionNames(function(err, collections) {

      if(err) {
        reject(err);
      }

      // If the collection exists in the mongo db
      if(_.findWhere(collections, {name: name})) {
        return resolve(true);
      } else {
        return resolve(false);
      }
    });
  });
}

/**
 * Inserts an array of objects into mongo
 *
 * @param db              - The db to insert into
 * @param collection_name - The collection to insert into
 * @param contents        - The contents to be inserted
 * @returns {*}
 */
function insert(db, collection_name, contents) {

  return Q.promise(function(resolve, reject, notify) {

    // If it's an empty array, there's nothing to insert
    if(contents.length !== 0) {

      var data = contents.map(function(content){
        return json2mongo(content);
      });

      db.collection(collection_name).insert(data, function(err, result) {
        if(err) {
          return reject(err);
        }

        return resolve(result);
      });
    } else {
      return resolve();
    }
  });
}

/**
 * Formats error messages to display the actual error message instead of all the errno codes and what not.
 *
 * @param err         - The error object that may or may not contain an errno code
 * @returns {string}  - A simple message
 */
function errmsg(err) {

  var str = 'Error: '
  // if it's a libuv error then get the description from errno
  if (errno.errno[err.errno]) {
    str += errno.errno[err.errno].description
  } else {
    str += err.message
  }

  // if it's a `fs` error then it'll have a 'path' property
  if (err.path) {
    str += ' [' + err.path + ']'
  }
  return str
}
<|endoftext|>


<commit_before>import React from 'react';
import AppBar from '@material-ui/core/AppBar';
import InputBase from '@material-ui/core/InputBase';
import Toolbar from '@material-ui/core/Toolbar';
import Button from '@material-ui/core/Button';
import SearchIcon from '@material-ui/icons/Search';
import { withRouter } from 'react-router-dom';
import  { Breakpoint } from 'react-socks';
import './Header.css';
import HamburgerNavMenu from '../navmenu/HamburgerNavMenu';

class Header extends React.Component {
  constructor(props) {
    super(props);

    this.handleKeyUp_ = this.handleKeyUp_.bind(this);
    this.handleChange_ = this.handleChange_.bind(this);
    this.doSearch_ = this.doSearch_.bind(this);

    const queryStringParams = new URLSearchParams(props.location.search);

    this.state = {
      search: queryStringParams.get('search') || '',
      top500: queryStringParams.get('top500') !== '0',
    };
  }

  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      const queryStringParams = new URLSearchParams(this.props.location.search);
      this.setState({
        search: queryStringParams.get('search') || '',
        top500: queryStringParams.get('top500') !== '0',
      });
    }
  }

  handleChange_(e) {
    this.setState({
      search: e.target.value,
    });
  }

  handleKeyUp_(e) {
    if (e.keyCode === 13) {
      this.doSearch_();
    }
  }

  doSearch_() {
    let nextHistory = `/?search=${this.state.search}`;
    if (!this.state.top500) {
      nextHistory += '&top500=0';
    }
    this.props.history.push(nextHistory);
  }

  renderHeaderSearch_() {
    if (!this.props.signedIn) {
      return null;
    }

    return (
      <InputBase
        placeholder='Search'
        classes={{
          root: 'header-search-root',
          input: 'header-search-input',
        }}
        inputProps={{ 'aria-label': 'search' }}
        value={this.state.search}
        onChange={this.handleChange_}
        onKeyUp={this.handleKeyUp_}
      />
    );
  }

  renderAuthButton_() {
    if (this.props.authInitializing) {
      return null;
    }

    return (
      <Button
        variant='contained'
        color='primary'
        onClick={this.props.authAction}
        className='auth-button'
        key={1}
      >
        {this.props.signedIn ? 'Log out' : 'Sign in'}
      </Button>
    );
  }

  render() {
    return (

        <AppBar position='static' className='header'>
          {/* Only renders the hamburger menu in mobile widths. */}
          <Breakpoint medium down>
            {/* Hide the menu completely while auth is initializing. Once that is done, but
              * before the user logs in, the menu will only show the 'Sign in' option. */}
            {this.props.authInitializing ?
              null : <HamburgerNavMenu signedIn={this.props.signedIn} authAction={this.props.authAction} />}
          </Breakpoint>
          <Toolbar>
            <h1 className={`header-title ${this.props.signedIn && 'signed-in'}`}>
              Barnard

            <div
              className={`header-search ${!this.props.signedIn && 'hidden'}`}>
              <SearchIcon className='header-search-icon' onClick={this.doSearch_}/>
              {this.renderHeaderSearch_()}

            {/* Only renders the logout button for desktop. In mobile widths, the auth button
              * is part of the nav menu. */}
            <Breakpoint large up>
              {this.renderAuthButton_()}
            </Breakpoint>
          </Toolbar>
        </AppBar>

    );
  }
}

export default withRouter(Header);
<commit_msg>Chnage display name barnard -> woolaroo<commit_after>import React from 'react';
import AppBar from '@material-ui/core/AppBar';
import InputBase from '@material-ui/core/InputBase';
import Toolbar from '@material-ui/core/Toolbar';
import Button from '@material-ui/core/Button';
import SearchIcon from '@material-ui/icons/Search';
import { withRouter } from 'react-router-dom';
import  { Breakpoint } from 'react-socks';
import './Header.css';
import HamburgerNavMenu from '../navmenu/HamburgerNavMenu';

class Header extends React.Component {
  constructor(props) {
    super(props);

    this.handleKeyUp_ = this.handleKeyUp_.bind(this);
    this.handleChange_ = this.handleChange_.bind(this);
    this.doSearch_ = this.doSearch_.bind(this);

    const queryStringParams = new URLSearchParams(props.location.search);

    this.state = {
      search: queryStringParams.get('search') || '',
      top500: queryStringParams.get('top500') !== '0',
    };
  }

  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      const queryStringParams = new URLSearchParams(this.props.location.search);
      this.setState({
        search: queryStringParams.get('search') || '',
        top500: queryStringParams.get('top500') !== '0',
      });
    }
  }

  handleChange_(e) {
    this.setState({
      search: e.target.value,
    });
  }

  handleKeyUp_(e) {
    if (e.keyCode === 13) {
      this.doSearch_();
    }
  }

  doSearch_() {
    let nextHistory = `/?search=${this.state.search}`;
    if (!this.state.top500) {
      nextHistory += '&top500=0';
    }
    this.props.history.push(nextHistory);
  }

  renderHeaderSearch_() {
    if (!this.props.signedIn) {
      return null;
    }

    return (
      <InputBase
        placeholder='Search'
        classes={{
          root: 'header-search-root',
          input: 'header-search-input',
        }}
        inputProps={{ 'aria-label': 'search' }}
        value={this.state.search}
        onChange={this.handleChange_}
        onKeyUp={this.handleKeyUp_}
      />
    );
  }

  renderAuthButton_() {
    if (this.props.authInitializing) {
      return null;
    }

    return (
      <Button
        variant='contained'
        color='primary'
        onClick={this.props.authAction}
        className='auth-button'
        key={1}
      >
        {this.props.signedIn ? 'Log out' : 'Sign in'}
      </Button>
    );
  }

  render() {
    return (

        <AppBar position='static' className='header'>
          {/* Only renders the hamburger menu in mobile widths. */}
          <Breakpoint medium down>
            {/* Hide the menu completely while auth is initializing. Once that is done, but
              * before the user logs in, the menu will only show the 'Sign in' option. */}
            {this.props.authInitializing ?
              null : <HamburgerNavMenu signedIn={this.props.signedIn} authAction={this.props.authAction} />}
          </Breakpoint>
          <Toolbar>
            <h1 className={`header-title ${this.props.signedIn && 'signed-in'}`}>
              Woolaroo

            <div
              className={`header-search ${!this.props.signedIn && 'hidden'}`}>
              <SearchIcon className='header-search-icon' onClick={this.doSearch_}/>
              {this.renderHeaderSearch_()}

            {/* Only renders the logout button for desktop. In mobile widths, the auth button
              * is part of the nav menu. */}
            <Breakpoint large up>
              {this.renderAuthButton_()}
            </Breakpoint>
          </Toolbar>
        </AppBar>

    );
  }
}

export default withRouter(Header);
<|endoftext|>


<commit_before>/**
 * This file is your application’s main JavaScript file. It is listed as a dependency in run.js and will
 * automatically load when run.js loads.
 *
 * Because this file has the special filename “main.js”, and because we’ve registered the “app” package in run.js,
 * whatever object this module returns can be loaded by other files simply by requiring “app” (instead of “app/main”).
 *
 * Our first dependency is to the “dojo/has” module, which allows us to conditionally execute code based on
 * configuration settings or environmental information. Unlike a normal conditional, these branches can be compiled
 * away by the build system; see “staticHasFeatures” in app.profile.js for more information.
 *
 * Our second dependency is to the special module “require”; this allows us to make additional require calls using
 * relative module IDs within the body of our define function.
 *
 * In all cases, whatever function is passed to define() is only invoked once, and the return value is cached.
 *
 * More information about everything described about the loader throughout this file can be found at
 * http://livedocs.dojotoolkit.org/loader/amd.
 */
define([ 'dojo/has', 'require' ], function (has, require) {
    var app = {};

    if (has('host-browser')) {
        /*
         * This require call’s first dependency, “./Dialog”, uses a relative module identifier; you should use this
         * type of notation for dependencies *within* a package in order to ensure the package is fully portable. It
         * works like a path, where “./” refers to the current directory and “../” refers to the parent directory. If
         * you are referring to a module in a *different* package, you should *not* use a relative module identifier.
         *
         * The second dependency is a plugin dependency; in this case, it is a dependency on the special functionality
         * of the “dojo/domReady” plugin, which waits until the DOM is ready before finishing loading.
         * The “!” after the module name indicates you want to use special plugin functionality; if you were to
         * require just “dojo/domReady”, it would load that module just like any other module, without any of the
         * special plugin functionality.
         */
        require([ 'dojo/router', 'dojo/domReady!' ], function (router, domready) {
			router.register("/something/:id", function(evt){
				evt.preventDefault();
				// Will fire when the hash matches
				// evt.params.id will contain what is passed in :id
				console.log(evt.params.id);
			});

			// Startup must be called in order to "activate" the router
			router.startup();
        });
    }
    else {
        console.log('Hello from the server!');
    }
});<commit_msg>Deleted unneeded file<commit_after><|endoftext|>