<commit_before>var async = require('async')
  , crypto = require('crypto')
  , cache = require('memjs').Client.create()
  , Location = require('../models/Location')
  ;

exports.index = function(req, res){
  var query = {};
  var latitude = parseFloat(req.query.latitude);
  var longitude = parseFloat(req.query.longitude);

  var geoKey = "geoPoints.all";
  if(latitude && longitude){
    query = {'geoPoint': [longitude, latitude]};
    geoKey = Location.geoHash(longitude, latitude);
  }

  // Need to look up cached location ID from queried
  // geoPoint. Can't store the location based on the
  // geoPoint directly because we need to invalidate the
  // cached location when new reports are added, and we do
  // that by ID.
  async.waterfall([

    // look up location id by geoKey
    function(callback) {
      console.log('geoKey: ', geoKey);
      cache.get(geoKey, function(err, locationKey){
        if (locationKey) {
          locationKey = locationKey.toString();
        }
        callback(err, geoKey, locationKey);
      });
    },

    // get location from id
    function(geoKey, locationKey, callback) {
      console.log('locationKey: ', locationKey);
      if (locationKey) {
        cache.get(locationKey, callback);
      } else {
        callback("No cached value for geoKey: " + geoKey);
      }
    }

  // final callback
  ], function(err, cached){
    if (err) console.error(err);

    // if all has gone well, return cached location info
    if (!err && cached) {
      console.log('returned cached result');
      cached = JSON.parse(cached.toString());
      res.json({'locations': cached});
      return;

    // else look up location info in Mongo and and cache it in memcached.
    } else {
      console.log('not cached');
      Location.find(query).populate('reports').exec(function(err, locations){
        var locId = locations.length === 1 ? locations[0]._id : 'all';
        var locationKey = 'locations.' + locId;
        cache.set(geoKey, locationKey);
        cache.set(locationKey, JSON.stringify(locations));
        res.json({'locations': locations});
        return;
      })
    }
  })
};
<commit_msg>Set cached data expiration to 1 hour<commit_after>var async = require('async')
  , crypto = require('crypto')
  , cache = require('memjs').Client.create()
  , Location = require('../models/Location')
  ;

exports.index = function(req, res){
  var query = {};
  var latitude = parseFloat(req.query.latitude);
  var longitude = parseFloat(req.query.longitude);

  var geoKey = "geoPoints.all";
  if(latitude && longitude){
    query = {'geoPoint': [longitude, latitude]};
    geoKey = Location.geoHash(longitude, latitude);
  }

  // Need to look up cached location ID from queried
  // geoPoint. Can't store the location based on the
  // geoPoint directly because we need to invalidate the
  // cached location when new reports are added, and we do
  // that by ID.
  async.waterfall([

    // look up location id by geoKey
    function(callback) {
      console.log('geoKey: ', geoKey);
      cache.get(geoKey, function(err, locationKey){
        if (locationKey) {
          locationKey = locationKey.toString();
        }
        callback(err, geoKey, locationKey);
      });
    },

    // get location from id
    function(geoKey, locationKey, callback) {
      console.log('locationKey: ', locationKey);
      if (locationKey) {
        cache.get(locationKey, callback);
      } else {
        callback("No cached value for geoKey: " + geoKey);
      }
    }

  // final callback
  ], function(err, cached){
    if (err) console.error(err);

    // if all has gone well, return cached location info
    if (!err && cached) {
      console.log('returned cached result');
      cached = JSON.parse(cached.toString());
      res.json({'locations': cached});
      return;

    // else look up location info in Mongo and and cache it in memcached.
    } else {
      console.log('not cached');
      Location.find(query).populate('reports').exec(function(err, locations){
        var locId = locations.length === 1 ? locations[0]._id : 'all';
        var locationKey = 'locations.' + locId;
        cache.set(geoKey, locationKey, null, 3600);
        cache.set(locationKey, JSON.stringify(locations), null, 3600);
        res.json({'locations': locations});
        return;
      })
    }
  })
};
<|endoftext|>


<commit_before>'use strict';

module.exports = require('dbjs').Boolean.create('YesNo', {
	trueString: 'Yes',
	falseString: 'No'
});
<commit_msg>Update up to changes in dbjs<commit_after>'use strict';

module.exports = require('dbjs').Boolean.create('YesNo', {
	trueLabel: 'Yes',
	falseLabel: 'No'
});
<|endoftext|>


<commit_before>(function(module) {

	"use strict";

	var Inigo = require("__buttercup/classes/InigoGenerator.js"),
		commandTools = require("__buttercup/tools/command.js"),
		searching = require("__buttercup/tools/searching.js"),
		entry = require("__buttercup/tools/entry.js");

	var VALID_COMMAND_EXP = 			/^[a-z]{3}[ ].+$/;

	var commandClasses = {
		cen: require("__buttercup/classes/commands/command.cen.js"),
		cgr: require("__buttercup/classes/commands/command.cgr.js"),
		cmm: require("__buttercup/classes/commands/command.cmm.js"),
		dea: require("__buttercup/classes/commands/command.dea.js"),
		dem: require("__buttercup/classes/commands/command.dem.js"),
		den: require("__buttercup/classes/commands/command.den.js"),
		dga: require("__buttercup/classes/commands/command.dga.js"),
		dgr: require("__buttercup/classes/commands/command.dgr.js"),
		fmt: require("__buttercup/classes/commands/command.fmt.js"),
		men: require("__buttercup/classes/commands/command.men.js"),
		mgr: require("__buttercup/classes/commands/command.mgr.js"),
		pad: require("__buttercup/classes/commands/command.pad.js"),
		sea: require("__buttercup/classes/commands/command.sea.js"),
		sem: require("__buttercup/classes/commands/command.sem.js"),
		sep: require("__buttercup/classes/commands/command.sep.js"),
		sga: require("__buttercup/classes/commands/command.sga.js"),
		tgr: require("__buttercup/classes/commands/command.tgr.js")
	};

	/**
	 * Westley. Archive object dataset and history manager. Handles parsing and
	 * revenge for the princess.
	 * @class Westley
	 */
	var Westley = function() {
		this.clear();
	};

	/**
	 * Clear the dataset and history
	 * @returns {Westley} Returns self
	 * @memberof Westley
	 */
	Westley.prototype.clear = function() {
		this._dataset = {};
		this._history = [];
		this._cachedCommands = {};
		return this;
	};

	/**
	 * Execute a command - stored in history and modifies the dataset
	 * @param {String} command The command to execute
	 * @returns {Westley} Returns self
	 * @memberof Westley
	 */
	Westley.prototype.execute = function(command) {
		if (!VALID_COMMAND_EXP.test(command)) {
			throw new Error("Invalid command");
		}
		var commandComponents = commandTools.extractCommandComponents(command),
			commandKey = commandComponents.shift();

		var commandObject = this._getCommandForKey(commandKey);

		this._history.push(command);
		commandObject.execute.apply(commandObject, [this._dataset].concat(commandComponents));
		return this;
	};

	/**
	 * Gets a command by its key from the cache with its dependencies injected
	 * @param {String} commandKey The key of the command
	 * @returns {Command} Returns the command
	 * @memberof Westley
	 */
	Westley.prototype._getCommandForKey = function(commandKey) {
		// If the command doesn't exist in the cache
		if (this._cachedCommands[commandKey] === undefined) {
			// Get the command object and inject its dependencies
			var requirement = new (commandClasses[commandKey])();

			if (requirement.injectSearching !== undefined) {
				requirement.injectSearching(searching);
			}

			if (requirement.injectEntry !== undefined) {
				requirement.injectEntry(entry);
			}

			// Store it in the cache
			this._cachedCommands[commandKey] = requirement;
		}

		return this._cachedCommands[commandKey];
	};

	/**
	 * Insert a padding in the archive (used for delta tracking)
	 * @returns {Westley} Returns self
	 * @memberof Westley
	 */
	Westley.prototype.pad = function() {
		this.execute(Inigo.generatePaddingCommand());
		return this;
	};

	/**
	 * Get the core dataset
	 * @returns {Object}
	 * @memberof Westley
	 */
	Westley.prototype.getDataset = function() {
		return this._dataset;
	};

	/**
	 * Get the history (deltas)
	 * @returns {String[]}
	 * @memberof Westley
	 */
	Westley.prototype.getHistory = function() {
		return this._history;
	};

	module.exports = Westley;

})(module);
<commit_msg>Finish code review fixes<commit_after>(function(module) {

	"use strict";

	var Inigo = require("__buttercup/classes/InigoGenerator.js"),
		commandTools = require("__buttercup/tools/command.js"),
		searching = require("__buttercup/tools/searching.js"),
		entry = require("__buttercup/tools/entry.js");

	var VALID_COMMAND_EXP = 			/^[a-z]{3}[ ].+$/;

	var commandClasses = {
		cen: require("__buttercup/classes/commands/command.cen.js"),
		cgr: require("__buttercup/classes/commands/command.cgr.js"),
		cmm: require("__buttercup/classes/commands/command.cmm.js"),
		dea: require("__buttercup/classes/commands/command.dea.js"),
		dem: require("__buttercup/classes/commands/command.dem.js"),
		den: require("__buttercup/classes/commands/command.den.js"),
		dga: require("__buttercup/classes/commands/command.dga.js"),
		dgr: require("__buttercup/classes/commands/command.dgr.js"),
		fmt: require("__buttercup/classes/commands/command.fmt.js"),
		men: require("__buttercup/classes/commands/command.men.js"),
		mgr: require("__buttercup/classes/commands/command.mgr.js"),
		pad: require("__buttercup/classes/commands/command.pad.js"),
		sea: require("__buttercup/classes/commands/command.sea.js"),
		sem: require("__buttercup/classes/commands/command.sem.js"),
		sep: require("__buttercup/classes/commands/command.sep.js"),
		sga: require("__buttercup/classes/commands/command.sga.js"),
		tgr: require("__buttercup/classes/commands/command.tgr.js")
	};

	/**
	 * Westley. Archive object dataset and history manager. Handles parsing and
	 * revenge for the princess.
	 * @class Westley
	 */
	var Westley = function() {
		this.clear();
	};

	/**
	 * Clear the dataset and history
	 * @returns {Westley} Returns self
	 * @memberof Westley
	 */
	Westley.prototype.clear = function() {
		this._dataset = {};
		this._history = [];
		this._cachedCommands = {};
		return this;
	};

	/**
	 * Execute a command - stored in history and modifies the dataset
	 * @param {String} command The command to execute
	 * @returns {Westley} Returns self
	 * @memberof Westley
	 */
	Westley.prototype.execute = function(command) {
		if (!VALID_COMMAND_EXP.test(command)) {
			throw new Error("Invalid command");
		}
		var commandComponents = commandTools.extractCommandComponents(command),
			commandKey = commandComponents.shift();

		var commandObject = this._getCommandForKey(commandKey);

		this._history.push(command);
		commandObject.execute.apply(commandObject, [this._dataset].concat(commandComponents));
		return this;
	};

	/**
	 * Gets a command by its key from the cache with its dependencies injected
	 * @param {String} commandKey The key of the command
	 * @returns {Command} Returns the command
	 * @memberof Westley
	 */
	Westley.prototype._getCommandForKey = function(commandKey) {
		// If the command doesn't exist in the cache
		if (this._cachedCommands[commandKey] === undefined) {
			// Get the command object and inject its dependencies
			var requirement = new (commandClasses[commandKey])();

			if (requirement.injectSearching !== undefined) {
				requirement.injectSearching(searching);
			}

			if (requirement.injectEntry !== undefined) {
				requirement.injectEntry(entry);
			}

			// Store it in the cache
			this._cachedCommands[commandKey] = requirement;
		}

		return this._cachedCommands[commandKey];
	};

	/**
	 * Insert a padding in the archive (used for delta tracking)
	 * @returns {Westley} Returns self
	 * @memberof Westley
	 */
	Westley.prototype.pad = function() {
		this.execute(Inigo.generatePaddingCommand());
		return this;
	};

	/**
	 * Get the core dataset
	 * @returns {Object}
	 * @memberof Westley
	 */
	Westley.prototype.getDataset = function() {
		return this._dataset;
	};

	/**
	 * Get the history (deltas)
	 * @returns {String[]}
	 * @memberof Westley
	 */
	Westley.prototype.getHistory = function() {
		return this._history;
	};

	module.exports = Westley;

})(module);
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import Categories from './Categories.js'
import $ from 'jquery';

class ItemForm extends React.Component {
  constructor(){
    super();
    this.handleSubmit = this.handleSubmit.bind(this);
    this.getItemnameRef = this.getItemnameRef.bind(this);
    this.getCategoryRef = this.getCategoryRef.bind(this);
    this.getMessageRef = this.getMessageRef.bind(this);
    this.getUrlRef = this.getUrlRef.bind(this);
    this.state = {
      itemname: '',
      category: '',
      message: '',
      url: ''
    }
  }

  getItemnameRef(ref){
    this.itemnameRef = ref;
  }

  getCategoryRef(ref){
    this.categoryRef = ref;
  }

  getMessageRef(ref){
    this.messageRef = ref;
  }

  getUrlRef(ref){
    this.urlRef = ref;
  }

  handleSubmit(e){
    e.preventDefault();
    let username = this.props.userInfo.username;
    let itemname = this.itemnameRef.value;
    let category = this.categoryRef.value;
    let url = this.urlRef.value;
    let message = this.messageRef.value;
    let self = this;

    $.ajax({
      url: '/wishlist',
      type: 'POST',
      contentType: 'application/json',
      dataType:'json',
      data: JSON.stringify({
        username: username,
        wishname: itemname,
        category: category,
        link: url,
        description: message
      }),
      success: function(data){
        self.props.updateWishlist(data);
      },
      error: function(err){
        console.log('error posting to wishlist: ', err);
      }
    });

    this.itemnameRef.value = '';
    this.categoryRef.value = '';
    this.urlRef.value = '';
    this.messageRef.value = '';
  }

  render(){
    return (
      <form ref='form'>
        Item
          <input type='text' name='itemname' className='form-control' placeholder='Item Name' ref={this.getItemnameRef} />

          Category
          <input type='text' name='category' className='form-control' placeholder='Category' ref={this.getCategoryRef} />

        <Categories getCategoryRef={this.getCategoryRef} />

          Message
          <input type='text' name='message' className='form-control' placeholder='Message' ref={this.getMessageRef} />

          Link
          <input type='url' name='url' className='form-control' placeholder='Enter URL Here' ref={this.getUrlRef} />

        <button type='submit' className='btn btn-primary' onClick={this.handleSubmit}>Submit</button>
      </form>
    )
  }
}

export default ItemForm;
<commit_msg>[pull] fixes merge conflict<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import Categories from './Categories.js'
import $ from 'jquery';

class ItemForm extends React.Component {
  constructor(){
    super();
    this.handleSubmit = this.handleSubmit.bind(this);
    this.getItemnameRef = this.getItemnameRef.bind(this);
    this.getCategoryRef = this.getCategoryRef.bind(this);
    this.getMessageRef = this.getMessageRef.bind(this);
    this.getUrlRef = this.getUrlRef.bind(this);
    this.state = {
      itemname: '',
      category: '',
      message: '',
      url: ''
    }
  }

  getItemnameRef(ref){
    this.itemnameRef = ref;
  }

  getCategoryRef(ref){
    this.categoryRef = ref;
    console.log(ref);
  }

  getMessageRef(ref){
    this.messageRef = ref;
  }

  getUrlRef(ref){
    this.urlRef = ref;
  }

  handleSubmit(e){
    e.preventDefault();
    let username = this.props.userInfo.username;
    let itemname = this.itemnameRef.value;
    let category = this.categoryRef.value;
    let url = this.urlRef.value;
    let message = this.messageRef.value;
    let self = this;

    $.ajax({
      url: '/wishlist',
      type: 'POST',
      contentType: 'application/json',
      dataType:'json',
      data: JSON.stringify({
        username: username,
        wishname: itemname,
        category: category,
        link: url,
        description: message
      }),
      success: function(data){
        self.props.updateWishlist(data);
      },
      error: function(err){
        console.log('error posting to wishlist: ', err);
      }
    });

    this.itemnameRef.value = '';
    this.categoryRef.value = '';
    this.urlRef.value = '';
    this.messageRef.value = '';
  }

  render(){
    return (
      <form ref='form'>
        Item
          <input type='text' name='itemname' className='form-control' placeholder='Item Name' ref={this.getItemnameRef} />

          Category
          <input type='text' name='category' className='form-control' placeholder='Category' ref={this.getCategoryRef} />

        <Categories getCategoryRef={this.getCategoryRef} />

          Message
          <input type='text' name='message' className='form-control' placeholder='Message' ref={this.getMessageRef} />

          Link
          <input type='url' name='url' className='form-control' placeholder='Enter URL Here' ref={this.getUrlRef} />

        <button type='submit' className='btn btn-primary' onClick={this.handleSubmit}>Submit</button>
      </form>
    )
  }
}

export default ItemForm;
<|endoftext|>


<commit_before>module.exports = function(app, auth) {
  var moment = require('moment')
    , Location = require('../models/location')
    , Token = require('../models/token')
    , Role = require('../models/role')
    , Team = require('../models/team')
    , access = require('../access')
    , generate_kml = require('../utilities/generate_kml');

  var p***REMOVED***port = auth.p***REMOVED***port;

  var validateLocation = function(req, res, next) {
    var data = req.body;

    // See if the client provieded a timestamp,
    // if not, set it to now.
    var timestamp = data.timestamp;
    if (!timestamp) {
      timestamp = new Date();
    } else {
      timestamp = moment.utc(timestamp).toDate();
    }

    var location = data.location;
    if (!location) return res.send(400, "Missing required parameter 'location'.");

    location.properties = location.properties || {};
    location.properties.createdOn = location.properties.updatedOn = timestamp;
    location.properties.user = req.user._id;

    console.log(JSON.stringify(location));
    req.location = location;

    next();
  }

  // get locations
  // Will only return locations for the teams that the user is a part of
  // TODO only one team for PDC, need to implement multiple teams later
  app.get(
    '/api/locations',
    p***REMOVED***port.authenticate('bearer'),
    access.hasPermission('READ_LOCATION'),
    function(req, res) {
      var limit = req.param('limit');
      limit = limit ? limit : 1;

      Location.getLocations(req.user, limit, function(err, locations) {
        res.json(locations);
      });
    }
  );

  app.get(
    '/api/locations/export',
    //p***REMOVED***port.authenticate('bearer'),
    //access.hasPermission('READ_LOCATION'),
    function(req, res) {
      res.writeHead(200,{"Content-Type": "application/vnd.google-earth.kml+xml"});
      res.write(generate_kml.generateKMLHeader());
      res.write(generate_kml.generateKMLDocument());
      res.write(generate_kml.generatePlacemark('point1', 'localhost', 39.83636818,-105.646844,3332.199951));
      res.write(generate_kml.generateKMLDocumentClose());
      res.end(generate_kml.generateKMLClose());
    }
  );

  // create a new location for a specific user
  app.post(
    '/api/locations',
    p***REMOVED***port.authenticate('bearer'),
    access.hasPermission('CREATE_LOCATION'),
    validateLocation,
    function(req, res) {
      Location.createLocation(req.user, req.location, function(err, location) {
        if (err) {
          return res.send(400, err);
        }

        res.json(location);
      });
    }
  );

  // update time on a location
  app.put(
    '/api/locations',
    p***REMOVED***port.authenticate('bearer'),
    access.hasPermission('UPDATE_LOCATION'),
    function(req, res) {
      var timestamp = req.param('timestamp');
      if (!timestamp) timestamp = new Date();

      Location.updateLocation(req.user, timestamp, function(err, location) {
        res.json(location);
      });
    }
  );
}<commit_msg>- timestamp is no longer an optional parameter for location posts.<commit_after>module.exports = function(app, auth) {
  var moment = require('moment')
    , Location = require('../models/location')
    , Token = require('../models/token')
    , Role = require('../models/role')
    , Team = require('../models/team')
    , access = require('../access')
    , generate_kml = require('../utilities/generate_kml');

  var p***REMOVED***port = auth.p***REMOVED***port;

  var validateLocation = function(req, res, next) {
    var data = req.body;

    var location = data.location;
    if (!location) return res.send(400, "Missing required parameter 'location'.");

    location.properties = location.properties || {};
    location.properties.createdOn = location.properties.updatedOn = moment.utc(data.timestamp).toDate();
    location.properties.user = req.user._id;

    console.log(JSON.stringify(location));
    req.location = location;

    next();
  }

  // get locations
  // Will only return locations for the teams that the user is a part of
  // TODO only one team for PDC, need to implement multiple teams later
  app.get(
    '/api/locations',
    p***REMOVED***port.authenticate('bearer'),
    access.hasPermission('READ_LOCATION'),
    function(req, res) {
      var limit = req.param('limit');
      limit = limit ? limit : 1;

      Location.getLocations(req.user, limit, function(err, locations) {
        res.json(locations);
      });
    }
  );

  app.get(
    '/api/locations/export',
    //p***REMOVED***port.authenticate('bearer'),
    //access.hasPermission('READ_LOCATION'),
    function(req, res) {
      res.writeHead(200,{"Content-Type": "application/vnd.google-earth.kml+xml"});
      res.write(generate_kml.generateKMLHeader());
      res.write(generate_kml.generateKMLDocument());
      res.write(generate_kml.generatePlacemark('point1', 'localhost', 39.83636818,-105.646844,3332.199951));
      res.write(generate_kml.generateKMLDocumentClose());
      res.end(generate_kml.generateKMLClose());
    }
  );

  // create a new location for a specific user
  app.post(
    '/api/locations',
    p***REMOVED***port.authenticate('bearer'),
    access.hasPermission('CREATE_LOCATION'),
    validateLocation,
    function(req, res) {
      Location.createLocation(req.user, req.location, function(err, location) {
        if (err) {
          return res.send(400, err);
        }

        res.json(location);
      });
    }
  );

  // update time on a location
  app.put(
    '/api/locations',
    p***REMOVED***port.authenticate('bearer'),
    access.hasPermission('UPDATE_LOCATION'),
    function(req, res) {
      var data = req.body;

      // See if the client provieded a timestamp,
      // if not, set it to now.
      var timestamp = data.timestamp;
      if (!timestamp) {
        timestamp = new Date();
      } else {
        timestamp = moment.utc(timestamp).toDate();
      }

      Location.updateLocation(req.user, timestamp, function(err, location) {
        res.json(location);
      });
    }
  );
}<|endoftext|>


<commit_before>var data = require("../courses.json");
var query = {};

setInterval(function() {
    if(hasQuery()) {
    	var isLive = data["courses"][query["course"]]["current"]["isLive"];
    	if(!isLive)
    		return;
        data["courses"][query["course"]]["current"]["elapsed"]++;
    }
}, 1000);

function hasQuery() {
    return "course" in query && typeof query["course"] != "undefined";
}

exports.liveLecture = function(req, res) {
	query = req.query;
	if(!hasQuery() || !(query["course"] in data["courses"])) {
        res.redirect('/classes');
        return;
    }
	var info = data["courses"][req.query["course"]]["current"];
    res.render('professor', info);
};

exports.checkLive = function(req,res) {
	var info = data["courses"][req.query["course"]]["current"];
	var toggler = { "status" : info["isLive"]};
    res.send(toggler);
};

exports.record = function(req,res) {
	var course = data["courses"][req.query["course"]];
	course["current"]["isLive"] = !course["current"]["isLive"];
	if(!course["current"]["isLive"]){
		if(req.query["pause"] == "true"){
			res.redirect("/professor?course="+req.query["course"]);
			return;
		}
		var tmp = {};
		tmp["id"] = new Date().getTime();
		tmp["marks"] = course["current"]["marks"];
		tmp["name"] = "Lecture "+(course["archive"].length+1);
		course["archive"].unshift(tmp);
		course["current"] = {
			"marks" : [],
			"elapsed" : 0,
			"isLive" : false,
			"timeString" : "0:00:00"
		};

		console.log(course["archive"]);
	}
	res.redirect("/professor?course="+req.query["course"]);
};<commit_msg>date fixed<commit_after>var data = require("../courses.json");
var query = {};

setInterval(function() {
    if(hasQuery()) {
    	var isLive = data["courses"][query["course"]]["current"]["isLive"];
    	if(!isLive)
    		return;
        data["courses"][query["course"]]["current"]["elapsed"]++;
    }
}, 1000);

function hasQuery() {
    return "course" in query && typeof query["course"] != "undefined";
}

exports.liveLecture = function(req, res) {
	query = req.query;
	if(!hasQuery() || !(query["course"] in data["courses"])) {
        res.redirect('/classes');
        return;
    }
	var info = data["courses"][req.query["course"]]["current"];
    res.render('professor', info);
};

exports.checkLive = function(req,res) {
	var info = data["courses"][req.query["course"]]["current"];
	var toggler = { "status" : info["isLive"]};
    res.send(toggler);
};

exports.record = function(req,res) {
	var course = data["courses"][req.query["course"]];
	course["current"]["isLive"] = !course["current"]["isLive"];
	if(!course["current"]["isLive"]){
		if(req.query["pause"] == "true"){
			res.redirect("/professor?course="+req.query["course"]);
			return;
		}
		var tmp = {};
		tmp["id"] = (new Date()).toLocaleDateString();;
		tmp["marks"] = course["current"]["marks"];
		tmp["name"] = "Lecture "+(course["archive"].length+1);
		course["archive"].unshift(tmp);
		course["current"] = {
			"marks" : [],
			"elapsed" : 0,
			"isLive" : false,
			"timeString" : "0:00:00"
		};

		console.log(course["archive"]);
	}
	res.redirect("/professor?course="+req.query["course"]);
};<|endoftext|>


<commit_before>if(!Package['iron-router']) return;

//track whether inside the ironRouter or not
//useful for identifying this inside the Meteor.subscribe
var insideIronRouter = false;
var RouteController = FastRender.RouteController = Package['iron-router'].RouteController;

var originalRun = RouteController.prototype.run;
RouteController.prototype.run = function() {
  if(FastRender.enabled) {
    insideIronRouter = true;
    originalRun.call(this);
    insideIronRouter = false;
  } else {
    originalRun.call(this);
  }
};

var originalSubscribe = Meteor.subscribe;
Meteor.subscribe = function(subscription) {
  var condition =
    FastRender.enabled &&
    //need to inside the ironRouter
    insideIronRouter &&
    //path loaded from the server and the local Router path should be the same
    Router.current().path == __fast_render_config.serverRoutePath &&
    //subscription not yet actually loaded (this may call multiple times)
    !__fast_render_config.loadedSubscriptions[subscription]

  if(condition) {
    Log('APPLY_IR_SUB_CORRECTIONS', subscription);
    originalSubscribe.apply(this, arguments);

    //ironRouter call .ready() and and if it's true he think subscription is completed
    return {
      ready: function() {
        return true;
      }
    }
  } else {
    return originalSubscribe.apply(this, arguments);
  }
};<commit_msg>fixed some iron-router based weird behaviour with subscriptions<commit_after>if(!Package['iron-router']) return;

//track whether inside the ironRouter or not
//useful for identifying this inside the Meteor.subscribe
var insideIronRouter = false;
var RouteController = FastRender.RouteController = Package['iron-router'].RouteController;

var originalRun = RouteController.prototype.run;
RouteController.prototype.run = function() {
  if(FastRender.enabled) {
    insideIronRouter = true;
    originalRun.call(this);
    insideIronRouter = false;
  } else {
    originalRun.call(this);
  }
};

var originalSubscribe = Meteor.subscribe;
Meteor.subscribe = function(subscription) {
  var condition =
    FastRender.enabled &&
    //need to inside the ironRouter
    insideIronRouter &&
    //path loaded from the server and the local Router path should be the same
    //We can't simply use Router.current().path, it will give some weird deps behaviour
    //which will result subscriptions stop everytime even they are not meant to
    getPath() == __fast_render_config.serverRoutePath &&
    //subscription not yet actually loaded (this may call multiple times)
    !__fast_render_config.loadedSubscriptions[subscription]

  if(condition) {
    Log('APPLY_IR_SUB_CORRECTIONS', subscription);
    originalSubscribe.apply(this, arguments);

    //ironRouter call .ready() and and if it's true he think subscription is completed
    return {
      ready: function() {
        return true;
      }
    }
  } else {
    return originalSubscribe.apply(this, arguments);
  }
};

function getPath() {
  return '/' + location.href.replace(/^.*\//, '');
}<|endoftext|>


<commit_before>module.exports = [

  // 1. replace single file with local one
  {
    pattern: 'homepage.js',      // Match url you wanna replace
    responder:  "/home/goddyzhao/workspace/homepage.js"
  },

  // 2. replace single file with web file
  {
    pattern: 'homepage.js',      // Match url you wanna replace
    responder:  "http://www.anotherwebsite.com/assets/js/homepage2.js"
  },

  // 3. replace combo file with src with absolute file path
  {
    pattern: 'group/homepageTileFramework.*.js',
    responder: [
      '/home/goddyzhao/workspace/webapp/ui/homepage/js/a.js',
      '/home/goddyzhao/workspace/webapp/ui/homepage/js/b.js',
      '/home/goddyzhao/workspace/webapp/ui/homepage/js/c.js'
    ]
  },

  // 4. replace combo file with src with relative file path and specified dir
  {
    pattern: 'group/homepageTileFramework.*.js',
    responder: {
      dir: '/home/goddyzhao/workspace/webapp/ui/homepage/js',
      src: [
        'a.js',
        'b.js',
        'c.js'
      ]
    }
  },

  // 5. Map server image directory to local image directory
  {
    pattern: 'ui/homepage/img',  // must be a string
    responder: '/home/goddyzhao/image/' //must be a absolute directory path
  },

  // 6. Write responder with regular expression variables like $1, $2
  {
    pattern: /https?:\/\/[\w\.]*(?::\d+)?\/ui\/(.*)_dev\.(\w+)/,
    reponder: 'http://localhost/proxy/$1.$2'
  },

  // 7. Map server image directory to local image directory with regular expression
  // This simple rule can replace multiple directories to corresponding locale ones
  // For Example,
  //   http://host:port/ui/a/img/... => /home/a/image/...
  //   http://host:port/ui/b/img/... => /home/b/image/...
  //   http://host:port/ui/c/img/... => /home/c/image/...
  //   ...
  {
    pattern: /ui\/(.*)\/img\//,
    responder: '/home/$1/image/'
  }
];<commit_msg>fix grammar issue<commit_after>module.exports = [

  // 1. replace single file with local one
  {
    pattern: 'homepage.js',      // Match url you wanna replace
    responder:  "/home/goddyzhao/workspace/homepage.js"
  },

  // 2. replace single file with web file
  {
    pattern: 'homepage.js',      // Match url you wanna replace
    responder:  "http://www.anotherwebsite.com/assets/js/homepage2.js"
  },

  // 3. replace combo file with src with absolute file path
  {
    pattern: 'group/homepageTileFramework.*.js',
    responder: [
      '/home/goddyzhao/workspace/webapp/ui/homepage/js/a.js',
      '/home/goddyzhao/workspace/webapp/ui/homepage/js/b.js',
      '/home/goddyzhao/workspace/webapp/ui/homepage/js/c.js'
    ]
  },

  // 4. replace combo file with src with relative file path and specified dir
  {
    pattern: 'group/homepageTileFramework.*.js',
    responder: {
      dir: '/home/goddyzhao/workspace/webapp/ui/homepage/js',
      src: [
        'a.js',
        'b.js',
        'c.js'
      ]
    }
  },

  // 5. Map server image directory to local image directory
  {
    pattern: 'ui/homepage/img',  // must be a string
    responder: '/home/goddyzhao/image/' //must be a absolute directory path
  },

  // 6. Write responder with regular expression variables like $1, $2
  {
    pattern: /https?:\/\/[\w\.]*(?::\d+)?\/ui\/(.*)_dev\.(\w+)/,
    responder: 'http://localhost/proxy/$1.$2'
  },

  // 7. Map server image directory to local image directory with regular expression
  // This simple rule can replace multiple directories to corresponding locale ones
  // For Example,
  //   http://host:port/ui/a/img/... => /home/a/image/...
  //   http://host:port/ui/b/img/... => /home/b/image/...
  //   http://host:port/ui/c/img/... => /home/c/image/...
  //   ...
  {
    pattern: /ui\/(.*)\/img\//,
    responder: '/home/$1/image/'
  }
];<|endoftext|>


<commit_before>var Nanocomponent = require('nanocomponent')
var objectValues = require('object-values')
var objectKeys = require('object-keys')
var html = require('choo/html')
var xtend = require('xtend')

module.exports = class Dropdown extends Nanocomponent {
  constructor () {
    super()
    this.state = {
      options: { },
      value: ''
    }
  }

  load (element) {
    if (!this.state.value && this.state.default) {
      this.oninput({ value: this.state.default })
    }
  }

  createElement (props, emit) {
    var self = this
    this.state = xtend(this.state, props.field)
    this.oninput = props.oninput

    return html`

          <select
            name="${this.state.key}"
            class="c12"
            type="tags"
            onchange=${onInput}
          />${options()}</select>

    `

    function options () {
      return objectKeys(self.state.options).map(function (option) {
        return html`
          <option
            value="${option}"
            ${self.state.value === option ? 'selected' : ''}
          >
            ${self.state.options[option].title || self.state.options[option]}
          </option>
        `
      })
    }

    function onInput (event) {
      props.oninput({ value: event.target.value })
    }
  }

  update (props) {
    var shouldUpdate = false

    // new value
    if (props.field.value !== this.state.value) {
      shouldUpdate = true
    }

    // new options
    if (
      objectKeys(props.field.options).length !==
      objectKeys(this.state.options).length
    ) {
      shouldUpdate = true
    }

    // if (props.field.value && props.field.value !== this.state.value) {
    //   this.state.value = props.value
    // }

    return shouldUpdate
  }
}
<commit_msg>cleamup<commit_after>var Nanocomponent = require('nanocomponent')
var objectValues = require('object-values')
var objectKeys = require('object-keys')
var html = require('choo/html')
var xtend = require('xtend')
var path = require('path')

module.exports = class Dropdown extends Nanocomponent {
  constructor () {
    super()
    this.state = {
      options: { },
      value: ''
    }
  }

  load (element) {
    if (!this.state.value && this.state.default) {
      this.oninput({ value: this.state.default })
    }
  }

  createElement (props, emit) {
    var self = this
    this.state = xtend(this.state, props.field)
    this.oninput = props.oninput

    return html`

          <select
            name="${this.state.key}"
            class="c12"
            type="tags"
            onchange=${onInput}
          />${options()}</select>

    `

    function options () {
      return objectKeys(self.state.options).map(function (option) {
        return html`
          <option
            value="${option}"
            ${self.state.value === option ? 'selected' : ''}
          >
            ${self.state.options[option].title || self.state.options[option]}
          </option>
        `
      })
    }

    function onInput (event) {
      props.oninput({ value: event.target.value })
    }
  }

  update (props) {
    var shouldUpdate = false

    // new value
    if (props.field.value !== this.state.value) {
      shouldUpdate = true
    }

    // new options
    if (
      objectKeys(props.field.options).length !==
      objectKeys(this.state.options).length
    ) {
      shouldUpdate = true
    }

    // if (props.field.value && props.field.value !== this.state.value) {
    //   this.state.value = props.value
    // }

    return shouldUpdate
  }
}
<|endoftext|>


<commit_before>'use strict';

let express = require('express');
let here = require('here').here;
let router = express.Router();

const HTML_HEAD = here(/*
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
*/);

const HTML_IE = here(/*
<!--[if lt IE 9]>
<script src="//cdn.jsdelivr.net/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<link rel="shortcut icon" href="">
*/);

const HTML_TAIL = here(/*
</head>
<body>
</body>
</html>
*/);

router.get('/html5', (req, res, next) => {
  if (validation(req.query)) {
    let template = '', ie = req.query.ie;
    if (ie == 0 || ie === undefined) {
      template = `${HTML_HEAD}${HTML_TAIL}`;
    } else {
      template = `${HTML_HEAD}${HTML_IE}${HTML_TAIL}`;
    }
    res.json({ "html5-template": template });
  } else {
    writeError(res);
  }
});

const DDL_SCHEMA = here(/*
CREATE SCHEMA <__new_schema__> DEFAULT CHARACTER SET <__collation__>;
*/);

const DDL_CREATE = here(/*
CREATE TABLE <__new_table__> (
  `id` INT NOT NULL AUTO_INCREMENT COMMENT '',
  `name` VARCHAR(45) NULL COMMENT '',
  `create_date` DATETIME NULL COMMENT '',
  PRIMARY KEY (`id`)  COMMENT '')
ENGINE = InnoDB
DEFAULT CHARACTER SET = <__collation__>;
*/);

const DDL_INSERT = here(/*
INSERT INTO <__new_table__> (`name`, `create_date`) VALUES ('hoge', now());
*/);

const DDL_UPDATE = here(/*
UPDATE <__new_table__> SET `name`='fuga', `create_date`=now() WHERE `id`='1';
*/);

router.get('/mysql_ddl/:type', (req, res, next) => {
  let type = req.params.type, template = '';
  switch (type) {
    case 'schema':
      template = DDL_SCHEMA.replace(/<__new_schema__>/g, req.query.schema).replace(/<__collation__>/g, req.query.collation);
      break;
    case 'create':
      template = replace_new_table(DDL_CREATE, req.query).replace(/<__collation__>/g, req.query.collation);
      break;
    case 'insert':
      template = replace_new_table(DDL_INSERT, req.query);
      break;
    case 'update':
      template = replace_new_table(DDL_UPDATE, req.query);
      break;
    default:
      break;
  }
  res.json({ "mysql-ddl-template": template });
});

function replace_new_table(target, q) {
  return target.replace(/<__new_table__>/g, q.table);
}

function validation(query) {
  let ie = query.ie;
  if (ie != 0 && ie != 1 && ie !== undefined) {
    return false;
  }

  return true;
}

function writeError(res) {
  res.json({ "error": "argment error" });
}

module.exports = router;
<commit_msg>Update templates.js<commit_after>'use strict';

let express = require('express');
let here = require('here').here;
let router = express.Router();

const HTML_HEAD = here(/*
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
*/);

const HTML_IE = here(/*
<!--[if lt IE 9]>
<script src="//cdn.jsdelivr.net/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<link rel="shortcut icon" href="">
*/);

const HTML_TAIL = here(/*
</head>
<body>
</body>
</html>
*/);

router.get('/html5', (req, res, next) => {
  if (validationIe(req.query)) {
    let template = '', ie = req.query.ie;
    if (ie == 0 || ie === undefined) {
      template = `${HTML_HEAD}${HTML_TAIL}`;
    } else {
      template = `${HTML_HEAD}${HTML_IE}${HTML_TAIL}`;
    }
    res.json({ "html5-template": template });
  } else {
    writeError(res);
  }
});

const DDL_SCHEMA = here(/*
CREATE SCHEMA <__new_schema__> DEFAULT CHARACTER SET <__collation__>;
*/);

const DDL_CREATE = here(/*
CREATE TABLE <__new_table__> (
  `id` INT NOT NULL AUTO_INCREMENT COMMENT '',
  `name` VARCHAR(45) NULL COMMENT '',
  `create_date` DATETIME NULL COMMENT '',
  PRIMARY KEY (`id`)  COMMENT '')
ENGINE = InnoDB
DEFAULT CHARACTER SET = <__collation__>;
*/);

const DML_INSERT = here(/*
INSERT INTO <__new_table__> (`name`, `create_date`) VALUES ('hoge', now());
*/);

const DML_UPDATE = here(/*
UPDATE <__new_table__> SET `name`='fuga', `create_date`=now() WHERE `id`='1';
*/);

const DDL_ADD_COLUMN = here(/*
ALTER TABLE <__new_table__>
ADD COLUMN `update_date` DATETIME NULL DEFAULT NULL COMMENT '' AFTER `create_date`;
*/);

const DDL_ADD_INDEX = here(/*
ALTER TABLE <__new_table__>
ADD INDEX `id_name_idx` (`id` ASC, `name` ASC)  COMMENT '';
*/);

router.get('/mysql_ddl/:type', (req, res, next) => {
  let type = req.params.type, template = '';
  switch (type) {
    case 'schema':
      template = DDL_SCHEMA.replace(/<__new_schema__>/g, req.query.schema).replace(/<__collation__>/g, req.query.collation);
      break;
    case 'create':
      template = replace_new_table(DDL_CREATE, req).replace(/<__collation__>/g, req.query.collation);
      break;
    case 'insert':
      template = replace_new_table(DML_INSERT, req);
      break;
    case 'update':
      template = replace_new_table(DML_UPDATE, req);
      break;
    case 'column':
      template = replace_new_table(DDL_ADD_COLUMN, req);
      break;
    case 'index':
      template = replace_new_table(DDL_ADD_INDEX, req);
      break;
    default:
      break;
  }
  res.json({ "mysql-ddl-template": template });
});

function replace_new_table(target, req) {
  return target.replace(/<__new_table__>/g, req.query.table);
}

function validationIe(query) {
  let ie = query.ie;
  if (ie != 0 && ie != 1 && ie !== undefined) {
    return false;
  }

  return true;
}

function writeError(res) {
  res.json({ "error": "argment error" });
}

module.exports = router;
<|endoftext|>


<commit_before>module.exports = function($parent, options) {
    get_page('chatterbox', function(page) {
        var event_bus = require('../../../shared/event_bus');

        $parent.append(page.$container);

        var show_notification = function(message) {

            if (app.hidden) {
                if (app.settings.notify === true) {
                    var n = new Notification(message);

                    n.onclick = function() {
                        window.focus();
                        n.close();
                    };

                    setTimeout(function() {
                        n.close();
                    }, 2500);
                }

                // Do the favicon thing.
                if (app.new_message_alert !== true) {
                    $('#favicon').attr('href', '/images/favicon-alert.png');
                    app.new_message_alert = true;

                    $(window).one('focus', function() {
                        app.new_message_alert = false;
                        $('#favicon').attr('href', '/images/favicon-normal.png');
                    });
                }
            }

        };

        var append_custom = function($blargh, append_options) {
            append_options = $.extend({
                room_id: null
            }, append_options);

            if (typeof($blargh) == "string") {
                $blargh = $('
' + $blargh + '
');
            }

            var $chat = page.$("div[room_id='" + append_options.room_id + "']");
            $chat.append($blargh);

            show_notification("New multi-line message received!");

            if (app.settings.scroll_lock !== true) {
                $blargh[0].scrollIntoView(false);
            }
        };

        var append_system = function(message, append_options) {
            append_options = $.extend({
                room_id: null,
                class_name: null
            }, append_options);

            if (append_options.room_id == null) {
                return;
            }

            var $chat = page.$("div[room_id='" + append_options.room_id + "']");
            var $message = $('
[' + moment().format("h:mm:ss A") + ']' + message + '
');
            $message.addClass(append_options.class_name);
            $chat.append($message);

            show_notification(message);

            if (app.settings.scroll_lock !== true) {
                $message[0].scrollIntoView(false);
            }
        };

        var append_chat = function(data) {
            if (data.room_id == null) {
                return;
            }

            var $chat = page.$("div[room_id='" + data.room_id + "']");
            var message = data.message;

            var lines = message.split('
');
            message = '';

            lines.forEach(function(line) {
                var parts = line.split(/\s/);

                // Consider a more robust link parser (heh!)
                for (var i = 0; i < parts.length; i++) {
                    parts[i] = parts[i].replace(/(http.*)/, function(url) {
                        return '' + url + '';
                    });
                }

                if (message == '') {
                    message = parts.join(' ');
                }
                else {
                    message += '
' + parts.join(' ');
                }

            });

            var this_fucking_guy = app.world.user_settings[data.username];
            this_fucking_guy = $.extend(true, {
                outfit: {
                    chat: {
                        bg_color: 'white',
                        fg_color: 'black',
                        font_family: 'Verdana',
                        font_size: 14,
                        username_color: 'blue'
                    }
                }
            }, this_fucking_guy);

            var outfit = this_fucking_guy.outfit.chat;

            var $message = $('
[' + moment().format("h:mm:ss A") + ']' + data.username + ': ' + message + '
');
            $message.css({background: outfit.bg_color, color: outfit.fg_color, fontFamily: outfit.font_family, fontSize: outfit.font_size + 'px'});
            $message.find('.username').css({color: outfit.username_color});
            $message.find('a').css({color: outfit.username_color});

            $chat.append($message);
            show_notification(data.username + ": " + data.message);

            if (app.settings.scroll_lock !== true) {
                $message[0].scrollIntoView(false);
            }
        };

        event_bus.on('users.roams_the_earth', function(event) {
            append_system(event.username + " roams the earth.", {class_name: 'happy', room_id: event.room_id})
        });

        event_bus.on('users.has_gone_to_a_better_place', function(event) {
            append_system(event.username + " has gone to a better place.", {class_name: 'sad', room_id: event.room_id})
        });

        event_bus.on('blargher.send', function(params) {
            var room_id = app.get_active_room(true);
            page.send('blargh', {message: params.message, room_id: room_id});
        });

        event_bus.on('tom_clancy.change_room_name', function(params) {
            page.send('change_room_name', params);
        });

        event_bus.on('ws.disconnect', function() {
            if (app.disconnected === true) {
                return;
            }

            app.disconnected = true;

            $("
Disconnected from server
").dialog({
                title: "Oh shit",
                modal: true,
                buttons: {
                    'Ok': function() {
                        $(this).dialog('close');
                    }
                },
                close: function() {
                    app.disconnected = false;
                    window.location = '/';
                    $(this).destroy();
                }
            });
        });

        page.listen('chat', function(data) {
            append_chat(data);
        });

        page.listen('blargh', function(data) {
            var $blargh = $('
');
            $blargh.append('
' + data.username + ' x
');
            $blargh.append('
');
            var $body = $blargh.find('.body');
            $body.text(data.message);

            append_custom($blargh, {room_id: data.room_id});
        });

        page.listen('change_room_name', function(data) {
            append_system(data.blame + ' changed the room name to ' + data.new_name, {room_id: data.room_id, class_name: 'wup'});
            app.rename_room_tab(data.room_id, data.new_name);
        });

        page.$("#composer").on('keypress', function(e) {
            if (e.which === 13) {
                var message = $(this).val();

                if (message.length > 0) {
                    var room_id = app.get_active_room(true);
                    page.send('chat', {message: message, room_id: room_id});
                }

                $(this).val('');
            }
        });

        var lobby = options.lobby;
        app.add_room_tab(options.lobby, {focus: true});
        app.ready = true;

        if (lobby.recent_messages.length > 0) {
            var $blargh = $('
');
            $blargh.append('
Recent Messages x
');
            $blargh.append('
');
            var $body = $blargh.find('.body');

            lobby.recent_messages.forEach(function(mess) {
                $body.append('
[' + moment(mess.timestamp).format('hh:mm:ss A') + '] ' + mess.message + '
');
            });

            append_custom($blargh, {room_id: lobby.id});
        }
    });

    return {};
};<commit_msg>Pas de probleme<commit_after>module.exports = function($parent, options) {
    get_page('chatterbox', function(page) {
        var event_bus = require('../../../shared/event_bus');

        $parent.append(page.$container);

        var show_notification = function(message) {

            if (app.hidden) {
                if (app.settings.notify === true) {
                    var n = new Notification(message);

                    n.onclick = function() {
                        window.focus();
                        n.close();
                    };

                    setTimeout(function() {
                        n.close();
                    }, 2500);
                }

                // Do the favicon thing.
                if (app.new_message_alert !== true) {
                    $('#favicon').attr('href', '/images/favicon-alert.png');
                    app.new_message_alert = true;

                    $(window).one('focus', function() {
                        app.new_message_alert = false;
                        $('#favicon').attr('href', '/images/favicon-normal.png');
                    });
                }
            }

        };

        var append_custom = function($blargh, append_options) {
            append_options = $.extend({
                room_id: null
            }, append_options);

            if (typeof($blargh) == "string") {
                $blargh = $('
' + $blargh + '
');
            }

            var $chat = page.$("div[room_id='" + append_options.room_id + "']");
            $chat.append($blargh);

            show_notification("New multi-line message received!");

            if (app.settings.scroll_lock !== true) {
                $blargh[0].scrollIntoView();
            }
        };

        var append_system = function(message, append_options) {
            append_options = $.extend({
                room_id: null,
                class_name: null
            }, append_options);

            if (append_options.room_id == null) {
                return;
            }

            var $chat = page.$("div[room_id='" + append_options.room_id + "']");
            var $message = $('
[' + moment().format("h:mm:ss A") + ']' + message + '
');
            $message.addClass(append_options.class_name);
            $chat.append($message);

            show_notification(message);

            if (app.settings.scroll_lock !== true) {
                $message[0].scrollIntoView();
            }
        };

        var append_chat = function(data) {
            if (data.room_id == null) {
                return;
            }

            var $chat = page.$("div[room_id='" + data.room_id + "']");
            var message = data.message;

            var lines = message.split('
');
            message = '';

            lines.forEach(function(line) {
                var parts = line.split(/\s/);

                // Consider a more robust link parser (heh!)
                for (var i = 0; i < parts.length; i++) {
                    parts[i] = parts[i].replace(/(http.*)/, function(url) {
                        return '' + url + '';
                    });
                }

                if (message == '') {
                    message = parts.join(' ');
                }
                else {
                    message += '
' + parts.join(' ');
                }

            });

            var this_fucking_guy = app.world.user_settings[data.username];
            this_fucking_guy = $.extend(true, {
                outfit: {
                    chat: {
                        bg_color: 'white',
                        fg_color: 'black',
                        font_family: 'Verdana',
                        font_size: 14,
                        username_color: 'blue'
                    }
                }
            }, this_fucking_guy);

            var outfit = this_fucking_guy.outfit.chat;

            var $message = $('
[' + moment().format("h:mm:ss A") + ']' + data.username + ': ' + message + '
');
            $message.css({background: outfit.bg_color, color: outfit.fg_color, fontFamily: outfit.font_family, fontSize: outfit.font_size + 'px'});
            $message.find('.username').css({color: outfit.username_color});
            $message.find('a').css({color: outfit.username_color});

            $chat.append($message);
            show_notification(data.username + ": " + data.message);

            if (app.settings.scroll_lock !== true) {
                $message[0].scrollIntoView();
            }
        };

        event_bus.on('users.roams_the_earth', function(event) {
            append_system(event.username + " roams the earth.", {class_name: 'happy', room_id: event.room_id})
        });

        event_bus.on('users.has_gone_to_a_better_place', function(event) {
            append_system(event.username + " has gone to a better place.", {class_name: 'sad', room_id: event.room_id})
        });

        event_bus.on('blargher.send', function(params) {
            var room_id = app.get_active_room(true);
            page.send('blargh', {message: params.message, room_id: room_id});
        });

        event_bus.on('tom_clancy.change_room_name', function(params) {
            page.send('change_room_name', params);
        });

        event_bus.on('ws.disconnect', function() {
            if (app.disconnected === true) {
                return;
            }

            app.disconnected = true;

            $("
Disconnected from server
").dialog({
                title: "Oh shit",
                modal: true,
                buttons: {
                    'Ok': function() {
                        $(this).dialog('close');
                    }
                },
                close: function() {
                    app.disconnected = false;
                    window.location = '/';
                    $(this).destroy();
                }
            });
        });

        page.listen('chat', function(data) {
            append_chat(data);
        });

        page.listen('blargh', function(data) {
            var $blargh = $('
');
            $blargh.append('
' + data.username + ' x
');
            $blargh.append('
');
            var $body = $blargh.find('.body');
            $body.text(data.message);

            append_custom($blargh, {room_id: data.room_id});
        });

        page.listen('change_room_name', function(data) {
            append_system(data.blame + ' changed the room name to ' + data.new_name, {room_id: data.room_id, class_name: 'wup'});
            app.rename_room_tab(data.room_id, data.new_name);
        });

        page.$("#composer").on('keypress', function(e) {
            if (e.which === 13) {
                var message = $(this).val();

                if (message.length > 0) {
                    var room_id = app.get_active_room(true);
                    page.send('chat', {message: message, room_id: room_id});
                }

                $(this).val('');
            }
        });

        var lobby = options.lobby;
        app.add_room_tab(options.lobby, {focus: true});
        app.ready = true;

        if (lobby.recent_messages.length > 0) {
            var $blargh = $('
');
            $blargh.append('
Recent Messages x
');
            $blargh.append('
');
            var $body = $blargh.find('.body');

            lobby.recent_messages.forEach(function(mess) {
                $body.append('
[' + moment(mess.timestamp).format('hh:mm:ss A') + '] ' + mess.message + '
');
            });

            append_custom($blargh, {room_id: lobby.id});
        }
    });

    return {};
};<|endoftext|>


<commit_before>let path = require('path');

let transform = {};

// only add babel-jest transformer if babel-jest is a top-level dependency
try {
  require.resolve('babel-jest');

  let jestConfigModule = module;
  while (jestConfigModule.parent) {
    if (path.basename(jestConfigModule.filename) !== 'jest.config.js') {
      jestConfigModule = jestConfigModule.parent;
      continue;
    }
    break;
  }

  let topPackageJson = path.join(path.dirname(jestConfigModule.filename), 'package.json');
  // eslint-disable-next-line global-require
  let topPackage = require(topPackageJson);

  if (!topPackage.devDependencies['babel-jest']) {
    throw new Error(`babel-jest is not a dev dependency in ${topPackageJson}`);
  }

  transform['^.+\\.js$'] = 'babel-jest';

  if (topPackage.devDependencies['@babel/preset-typescript']) {
    transform['^.+\\.ts$'] = 'babel-jest';
  }
} catch (_err) {
  // console.log(_err);
}

module.exports = {
  // FIXME coverage is disabled due to https://github.com/facebook/jest/issues/3959
  collectCoverage: false,
  collectCoverageFrom: [
    '**/lib/**/*.js'
  ],
  coverageReporters: [
    'json',
    'html',
    'lcov',
    'text'
  ],
  notify: false,
  testEnvironment: 'node',
  testMatch: [
    '**/test/**/*.test.js'
  ],
  transform
};
<commit_msg>style<commit_after>let path = require('path');

let sfConfig = {
  // FIXME coverage is disabled due to https://github.com/facebook/jest/issues/3959
  collectCoverage: false,
  collectCoverageFrom: [
    '**/lib/**/*.js'
  ],
  coverageReporters: [
    'json',
    'html',
    'lcov',
    'text'
  ],
  transformIgnorePatterns: [
    '.*/node_modules/.*'
  ],
  notify: false,
  testEnvironment: 'node',
  testMatch: [
    '**/test/**/*.test.js'
  ],
  transform: {}
};

// only add babel-jest transformer if babel-jest is a top-level dependency
try {
  require.resolve('babel-jest');

  let jestConfigModule = module;
  while (jestConfigModule.parent) {
    if (path.basename(jestConfigModule.filename) !== 'jest.config.js') {
      jestConfigModule = jestConfigModule.parent;
      continue;
    }
    break;
  }

  let topPackageJson = path.join(path.dirname(jestConfigModule.filename), 'package.json');
  // eslint-disable-next-line global-require
  let topPackage = require(topPackageJson);

  if (!topPackage.devDependencies['babel-jest']) {
    throw new Error(`babel-jest is not a dev dependency in ${topPackageJson}`);
  }

  sfConfig.transform['^.+\\.js$'] = 'babel-jest';

  if (topPackage.devDependencies['@babel/preset-typescript']) {
    sfConfig.transform['^.+\\.ts$'] = 'babel-jest';
  }
} catch (_err) {
  // console.log(_err);
}

module.exports = sfConfig;
<|endoftext|>


<commit_before>/**
 * Roguelike Universe
 * Author: Xavier Ho <contact@xavierho.com>
 * https://github.com/Spaxe/roguelike-universe
 */
import BVG from "bvg";
import { promise, ratio, getJSON } from "./util";

const server_url = 'http://localhost:8002/api/v1';
const start_year = 1970, end_year = 2020;
const fx = ratio.bind(ratio, start_year, end_year);

document.addEventListener('DOMContentLoaded', () => {

  let bvg = BVG.create('#container');
  let focus = bvg.group({});
  let width = bvg.tag().clientWidth;
  let height = bvg.tag().clientHeight;
  let GUI_game = document.getElementById('game');
  let selection = 'Dungeon';

  loadRoguelikeRelationsAll().then( relations => {

    // Draw timeline
    for (let i = start_year + 1; i < end_year; i++) {
      bvg.text(i.toString().substr(2, 4),
               (fx(i) - 0.005) * width,
               height / 2 + 3
      );
    }

    // Populate game titles
    relations.forEach( game => {
      let option = document.createElement('option');
      option.value = game.title;
      option.setAttribute('data-year', game.year);
      option.innerHTML = `${game.title} (${game.year})`;
      GUI_game.appendChild(option);
    });

    // Bind selection
    GUI_game.addEventListener('change', event => {
      selection = event.target.value;
      drawSelection(selection);
    });

    // Draw influence arcs
    relations.forEach( ({title, year, inspiredBy, inspirationTo, otherInspiredBy, otherInspirationTo}) => {

      inspiredBy.forEach( r => {
        let args = arcYeartoYear(year, r.year);
        args[0] *= width; args[1] *= height; args[2] *= height; args[3] *= height;
        bvg.arc(...args).stroke(0, 0, 0, 0.2);
      });
      inspirationTo.forEach( r => {
        let args = arcYeartoYear(r.year, year);
        args[0] *= width; args[1] *= height; args[2] *= height; args[3] *= height;
        bvg.arc(...args).stroke(0, 0, 0, 0.2);
      });
      otherInspiredBy.forEach( r => {
        let args = arcYeartoYear(year, r.year, 1.0);
        args[0] *= width; args[1] *= height; args[2] *= height; args[3] *= height;
        bvg.arc(...args).stroke(0, 0, 0, 0.05);
      });
      otherInspirationTo.forEach( r => {
        let args = arcYeartoYear(r.year, year, 1.0);
        args[0] *= width; args[1] *= height; args[2] *= height; args[3] *= height;
        bvg.arc(...args).stroke(0, 0, 0, 0.05);
      });

    });

    let drawSelection = (selection) => {
      focus.tag().innerHTML = '';

      for (let i = 0; i < relations.length; i++) {
        const relation = relations[i];
        if (relation.title === selection) {

          focus.text(selection, fx(relation.year) * width, 0.095 * height)
            .fill(0);

          focus.line({
            x1: fx(relation.year) * width,
            y1: height * 0.1,
            x2: fx(relation.year) * width,
            y2: height * 0.9
          }).strokeWidth(2).stroke(0, 0, 0, 0.5);

          relation.inspiredBy.forEach( r => {
            let args = arcYeartoYear(relation.year, r.year);
            args[0] *= width; args[1] *= height; args[2] *= height; args[3] *= height;
            focus.arc(...args).stroke(0, 0, 0, 1).strokeWidth(3);
          });
          relation.inspirationTo.forEach( r => {
            let args = arcYeartoYear(r.year, relation.year);
            args[0] *= width; args[1] *= height; args[2] *= height; args[3] *= height;
            focus.arc(...args).stroke(0, 0, 0, 1).strokeWidth(3);
          });
          relation.otherInspiredBy.forEach( r => {
            let args = arcYeartoYear(relation.year, r.year, 1.0);
            args[0] *= width; args[1] *= height; args[2] *= height; args[3] *= height;
            focus.arc(...args).stroke(0, 0, 0, 1).strokeWidth(3);
          });
          relation.otherInspirationTo.forEach( r => {
            let args = arcYeartoYear(r.year, relation.year, 1.0);
            args[0] *= width; args[1] *= height; args[2] *= height; args[3] *= height;
            focus.arc(...args).stroke(0, 0, 0, 1).strokeWidth(3);
          });

          return;
        }
      }
    };

    // Fire event to start
    GUI_game.value = selection;
    drawSelection(selection);

  });

});

const loadRoguelikeRelationsAll = () => {

  return getJSON(`${server_url}/roguelike/relations-all`);

};

let arcYeartoYear = (a, b, invert=-1.0) => {

  let x_a = fx(a, start_year, end_year);
  let x_b = fx(b, start_year, end_year);
  let x = (x_a + x_b) / 2;
  let y = 0.5 + 0.01 * invert;
  let rx = Math.abs(x_b - x_a) / 2;
  let ry = rx;
  let startAngle = 0;
  let endAngle = Math.PI * invert;
  return [x, y, rx, ry, startAngle, endAngle];

};
<commit_msg>Relation prototype<commit_after>/**
 * Roguelike Universe
 * Author: Xavier Ho <contact@xavierho.com>
 * https://github.com/Spaxe/roguelike-universe
 */
import BVG from "bvg";
import { promise, ratio, getJSON } from "./util";

const server_url = 'http://localhost:8002/api/v1';
const start_year = 1970, end_year = 2020;
const fx = ratio.bind(ratio, start_year, end_year);

document.addEventListener('DOMContentLoaded', () => {

  let bvg = BVG.create('#container');
  let focus = bvg.group({});
  let width = bvg.tag().clientWidth;
  let height = bvg.tag().clientHeight;
  let GUI_game = document.getElementById('game');
  let selection = 'Dungeon';

  loadRoguelikeRelationsAll().then( relations => {

    // Draw timeline
    bvg.text('year',
             0.001 * width,
             height / 2 + 3);
    for (let i = start_year + 2; i < end_year; i++) {
      bvg.text(i.toString().substr(2, 4),
               (fx(i) - 0.005) * width,
               height / 2 + 3
      );
    }

    // Populate game titles
    relations.forEach( game => {
      let option = document.createElement('option');
      option.value = game.title;
      option.setAttribute('data-year', game.year);
      option.innerHTML = `${game.title} (${game.year})`;
      GUI_game.appendChild(option);
    });

    // Bind selection
    GUI_game.addEventListener('change', event => {
      selection = event.target.value;
      drawSelection(selection);
    });

    // Draw influence arcs
    relations.forEach( ({title, year, inspiredBy, inspirationTo, otherInspiredBy, otherInspirationTo}) => {

      inspiredBy.forEach( r => {
        drawArc(bvg, year, r.year, -1.0, 0.1);
      });
      inspirationTo.forEach( r => {
        drawArc(bvg, r.year, year, -1.0, 0.1);
      });
      otherInspiredBy.forEach( r => {
        drawArc(bvg, year, r.year, 1.0, 0.05);
      });
      otherInspirationTo.forEach( r => {
        drawArc(bvg, r.year, year, 1.0, 0.05);
      });

    });

    let drawSelection = (selection) => {
      focus.tag().innerHTML = '';

      for (let i = 0; i < relations.length; i++) {
        const relation = relations[i];
        if (relation.title === selection) {

          focus.text(selection, fx(relation.year) * width, 0.095 * height)
            .fill(0);

          focus.line({
            x1: fx(relation.year) * width,
            y1: height * 0.1,
            x2: fx(relation.year) * width,
            y2: height * 0.9
          }).strokeWidth(2).stroke(0, 0, 0, 0.5);

          relation.inspiredBy.forEach( r => {
            drawArc(focus, relation.year, r.year, -1, 1, 3);
          });
          relation.inspirationTo.forEach( r => {
            drawArc(focus, r.year, relation.year, -1, 1, 3);
          });
          relation.otherInspiredBy.forEach( r => {
            drawArc(focus, relation.year, r.year, 1, 1, 3);
          });
          relation.otherInspirationTo.forEach( r => {
            drawArc(focus, r.year, relation.year, 1, 1, 3);
          });

          return;
        }
      }
    };

    // Fire event to start
    GUI_game.value = selection;
    drawSelection(selection);

  });

  let drawArc = (g, yearA, yearB, invert=-1.0, opacity=1, strokeWidth=1) => {
    let args = arcYeartoYear(yearA, yearB, invert);
    args[0] *= width; args[1] *= height; args[2] *= height; args[3] *= height;
    g.arc(...args).stroke(0, 0, 0, opacity).strokeWidth(strokeWidth);
  }

});

const loadRoguelikeRelationsAll = () => {

  return getJSON(`${server_url}/roguelike/relations-all`);

};

let arcYeartoYear = (a, b, invert=-1.0) => {

  let x_a = fx(a, start_year, end_year);
  let x_b = fx(b, start_year, end_year);
  let x = (x_a + x_b) / 2;
  let y = 0.5 + 0.01 * invert;
  let rx = Math.abs(x_b - x_a) / 2;
  let ry = rx;
  let startAngle = 0;
  let endAngle = Math.PI * invert;
  return [x, y, rx, ry, startAngle, endAngle];

};

<|endoftext|>


<commit_before>import * as constants from '../constants/dataset';

function createDatasetRequest(dataset) {
  return {
    type: constants.CREATE_DATASET_REQUEST,
    dataset,
  }
}

function createDatasetSuccess(dataset) {
  debugger;
  return {
    type: constants.CREATE_DATASET_SUCCESS,
    dataset,
  }
}

function createDatasetFailure(error, dataset) {
  debugger;
  return {
    type: constants.CREATE_DATASET_FAILURE,
    dataset,
  }
}

export function createDataset(dataset) {
  return (dispatch, getState) => {
    dispatch(createDatasetRequest(dataset));
    fetch('/api/datasets', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(dataset),
    }).then(response => {
      return response.json();
    }).then(dataset => {
      dispatch(createDatasetSuccess(dataset))
    }).catch(error => {
      dispatch(createDatasetFailure(error, dataset));
    });
  };
}

// Currently only name
export function saveDatasetSettings(id, { name }) {
  return {
    type: constants.SAVE_SETTINGS,
    dataset: {
      id,
      name,
    },
  };
}

// Only name for now.
export function defineDatasetSettings({ name }) {
  return {
    type: constants.DEFINE_DATASET_SETTINGS,
    dataset: { name }
  }
}

export function selectDataSource(dataSource) {
  return {
    type: constants.SELECT_DATA_SOURCE,
    dataSource,
  }
}

export function nextPage() {
  return {
    type: constants.NEXT_PAGE,
  }
}

export function previousPage() {
  return {
    type: constants.PREVIOUS_PAGE,
  }
}

export function defineDataSource(dataSource) {
  return {
    type: constants.DEFINE_DATA_SOURCE,
    dataSource,
  }
}

function createDataSourceRequest(fetchId) {
  return {
    type: constants.CREATE_DATA_SOURCE_REQUEST,
    fetchId,
  }
}

function createDataSourceSuccess(fetchId, importId) {
  return {
    type: constants.CREATE_DATA_SOURCE_SUCCESS,
    fetchId,
    importId,
  }
}

function createDataSourceFailure(fetchId) {
  return {
    type: constants.CREATE_DATA_SOURCE_FAILURE,
    fetchId,
  }
}

let _fetchId = 0;
function nextFetchId() {
  return _fetchId++;
}

// Poll each second.
const pollingInterval = 1000;

export function createDataSource(dataSource) {
  const fetchId = nextFetchId();
  return (dispatch, getState) => {
    dispatch(createDataSourceRequest(fetchId));
    fetch('/api/datasource', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: dataSource,
    }).then(response => {
      if (response.status !== 200) {
        throw new Error('');
      }
      return response.json();
    }).then(response => {
      dispatch(createDataSourceSuccess(fetchId, response.id));
      // Start polling for when the dataset is available

    }).catch(error => {
      dispatch(createDataSourceFailure(fetchId));
    })
  }
}
<commit_msg>[#33] More work on client/server interaction when creating a dataset<commit_after>import * as constants from '../constants/dataset';

function fetchDatasetRequest(id) {
  return {
    type: constants.FETCH_DATASET_REQUEST,
    id,
  }
}

const pollInteval = 1000;
function fetchDatasetSuccess(dataset) {
  return (dispatch, getState) => {
    if (dataset.state === 'PENDING') {
      setTimeout(() => fetchDataset(dataset.id), pollInteval);
    }
    dispatch({
      type: constants.FETCH_DATASET_SUCCESS,
      dataset,
    });
  }
}

function fetchDatasetFailure(id) {
  return {
    type: constants.FETCH_DATASET_FAILURE,
    id,
  }
}

function fetchDataset(id) {
  return (dispatch, getState) => {
    dispatch(fetchDatasetRequest(id));
    fetch(`/api/datasets/${id}`, {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' },
    })
    .then(response => response.json())
    .then(dataset => dispatch(fetchDatasetSuccess(dataset)))
    .catch(error => dispatch(fetchDatasetFailure(error, id)))
  }
}

function createDatasetRequest(dataset) {
  return {
    type: constants.CREATE_DATASET_REQUEST,
    dataset,
  }
}

function createDatasetSuccess(dataset) {
  return (dispatch, getState) => {
    dispatch({
      type: constants.CREATE_DATASET_SUCCESS,
      dataset,
    })
    dispatch(fetchDataset(dataset.id));
  }
}

function createDatasetFailure(error, dataset) {
  return {
    type: constants.CREATE_DATASET_FAILURE,
    dataset,
  }
}

export function createDataset(dataset) {
  return (dispatch, getState) => {
    dispatch(createDatasetRequest(dataset));
    fetch('/api/datasets', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(dataset),
    })
    .then(response => response.json())
    .then(dataset => dispatch(createDatasetSuccess(dataset)))
    .catch(error => dispatch(createDatasetFailure(error, dataset)))
  }
}

// Currently only name
export function saveDatasetSettings(id, { name }) {
  return {
    type: constants.SAVE_SETTINGS,
    dataset: {
      id,
      name,
    },
  };
}

// Only name for now.
// TODO: save to server.
export function defineDatasetSettings({ name }) {
  return {
    type: constants.DEFINE_DATASET_SETTINGS,
    dataset: { name }
  }
}

export function selectDataSource(dataSource) {
  return {
    type: constants.SELECT_DATA_SOURCE,
    dataSource,
  }
}

export function nextPage() {
  return {
    type: constants.NEXT_PAGE,
  }
}

export function previousPage() {
  return {
    type: constants.PREVIOUS_PAGE,
  }
}

export function defineDataSource(dataSource) {
  return {
    type: constants.DEFINE_DATA_SOURCE,
    dataSource,
  }
}

function createDataSourceRequest(fetchId) {
  return {
    type: constants.CREATE_DATA_SOURCE_REQUEST,
    fetchId,
  }
}

function createDataSourceSuccess(fetchId, importId) {
  return {
    type: constants.CREATE_DATA_SOURCE_SUCCESS,
    fetchId,
    importId,
  }
}

function createDataSourceFailure(fetchId) {
  return {
    type: constants.CREATE_DATA_SOURCE_FAILURE,
    fetchId,
  }
}
<|endoftext|>


<commit_before>var bullets    = require("./bullets")
var weapons    = require("../config/weapon")

module.exports = function updatePlayer (dt, ent) {
  var angle = ent.euler.y
  var sinAngle = Math.sin(angle)
  var cosAngle = Math.cos(angle)
  var speed = ent.speed || 2

  if (ent.control.forward || ent.control.backward) {
    var multiplier = ent.control.forward ? 1 : -1
    ent.position.x += sinAngle * speed * dt * multiplier
    ent.position.z -= cosAngle * speed * dt * multiplier
  }

  if (ent.control.strafeleft || ent.control.straferight) {
    var multiplier = ent.control.straferight ? 1 : -1
    ent.position.x += cosAngle * speed * dt * multiplier
    ent.position.z += sinAngle * speed * dt * multiplier
  }

  ent.updateRotation()

  // Queue up packets to send - we'll clear this once sent
  if (this.conn.connected)
    ent.addSnapshot(this.conn.getServerTime(), ent.control)

  var weapon = ent.weapon.active === "primary" ? ent.weapon.primary : ent.weapon.secondary
  if (weapon) return
  var weaponStats = weapons[weapon.id]
  weapon.shotTimer -= dt
  if (ent.control.shoot && (!ent.lastControl.shoot || weaponStats.automatic) && weapon.shotTimer <= 0 && weapon.ammunition > 0) {
    weapon.shotTimer = 1 / weaponStats.firerate
    this.add(bullets.create(this.genLocalId(), ent, "normal"))
    weapon.ammunition--
  }
}
<commit_msg>forgot !<commit_after>var bullets    = require("./bullets")
var weapons    = require("../config/weapon")

module.exports = function updatePlayer (dt, ent) {
  var angle = ent.euler.y
  var sinAngle = Math.sin(angle)
  var cosAngle = Math.cos(angle)
  var speed = ent.speed || 2

  if (ent.control.forward || ent.control.backward) {
    var multiplier = ent.control.forward ? 1 : -1
    ent.position.x += sinAngle * speed * dt * multiplier
    ent.position.z -= cosAngle * speed * dt * multiplier
  }

  if (ent.control.strafeleft || ent.control.straferight) {
    var multiplier = ent.control.straferight ? 1 : -1
    ent.position.x += cosAngle * speed * dt * multiplier
    ent.position.z += sinAngle * speed * dt * multiplier
  }

  ent.updateRotation()

  // Queue up packets to send - we'll clear this once sent
  if (this.conn.connected)
    ent.addSnapshot(this.conn.getServerTime(), ent.control)

  var weapon = ent.weapon.active === "primary" ? ent.weapon.primary : ent.weapon.secondary
  if (!weapon) return
  var weaponStats = weapons[weapon.id]
  weapon.shotTimer -= dt
  if (ent.control.shoot && (!ent.lastControl.shoot || weaponStats.automatic) && weapon.shotTimer <= 0 && weapon.ammunition > 0) {
    weapon.shotTimer = 1 / weaponStats.firerate
    this.add(bullets.create(this.genLocalId(), ent, "normal"))
    weapon.ammunition--
  }
}
<|endoftext|>


<commit_before>import moment from 'moment';

import locations from '../core/locations';
import Model from '../base/model';
import {capfirst, range, makeAbsoluteURL} from '../utils';

import Place from './place';

export default class Event extends Model {
  getName() {
    return this.data.name || this.getFullName();
  }

  getFullName() {
    return capfirst(this.data.full_name);
  }

  getParent() {
    if (this.data.parent) {
      return new Event(this.data.parent);
    } else {
      return undefined;
    }
  }

  getPlace() {
    if (this.data.place) {
      return new Place(this.data.place);
    } else {
      return undefined;
    }
  }

  getLocation() {
    return locations.get(this.data.location);
  }

  getDisplayDuration() {
    const durations = this.getDisplayDates().map(date => date.getDuration());
    const [first, ...others] = durations;
    if (others.every(duration => duration.asMinutes() == first.asMinutes())) {
      return first;
    } else {
      return undefined;
    }
  }

  getDisplayDates() {
    const allDates = this.getDates();
    const actualDates = allDates.filter(date => date.isActual())
    return actualDates.length ? actualDates : allDates;
  }

  getDates() {
    return this.data.dates.map(spec => new Date(this, spec));
  }

  hasChildren() {
    return this.data.children_count > 0;
  }

  isPremiere() {
    return this.data.is_premiere;
  }

  isFestival() {
    return this.data.kind == 'festival';
  }

  isExhibition() {
    return this.data.kind == 'exhibition';
  }

  isActual() {
    const timezone = this.getLocation().timezone;
    const isDateBased = this.data.end.length == 10;
    const end = moment.tz(this.data.end, timezone);
    const endBound = isDateBased ? end.clone().add(1, 'day') : end;
    return endBound.isAfter(moment());
  }

  getItemType() {
    if (this.isFestival()) {
      return 'Festival';
    } else if (this.isExhibition()) {
      return 'ExhibitionEvent';
    } else {
      return 'TheaterEvent';
    }
  }
}

export class Date {
  constructor(event, spec) {
    this.event = event;
    this.timezone = event.getLocation().timezone;

    this.start = moment.tz(spec.start, this.timezone);
    this.end = moment.tz(spec.end, this.timezone);

    this.isDateBased = spec.start.length == 10;  // 10 characters is ISO date

    this.startBound = this.start;
    this.endBound = this.isDateBased ? this.end.clone().add(1, 'day') : this.end;
  }

  intersectsAny(others) {
    return others.some(other => this.intersects(other));
  }

  intersects(other) {
    return (
      this.endBound.isAfter(other.startBound) &&
      this.startBound.isBefore(other.endBound)
    );
  }

  getDateRange() {
    return {
      start: this.start.clone().startOf('day'),
      end: this.end.clone().startOf('day')
    }
  }

  getDuration() {
    return moment.duration((this.end.unix() - this.start.unix()) * 1000);
  }

  hasKnownEnd() {
    return !this.start.isSame(this.end);
  }

  isActual() {
    return this.endBound.isAfter(moment());
  }

  toJSONLD(app) {
    const url = app.resolver.reverse('event', {id: this.event.data.id});
    const result = {
      '@context': 'http://schema.org',
      '@type': this.event.getItemType(),
      '@id': `${url}#${this.start.unix()}`,
      name: this.event.getName(),
      url: makeAbsoluteURL(url),
    }

    const place = this.event.getPlace();
    if (place) {
      result.location = place.toJSONLD(app);
    }

    const duration = this.getDuration();
    if (duration.asMinutes() > 0) {
      result.duration = duration.toString();
    }

    const price = this.event.data.price;
    if (price && (price.lower != null || price.upper != null)) {
      const offer = {
        '@type': 'AggregateOffer',
        priceCurrency: this.event.getLocation().currency,
      }
      if (price.lower != null) offer.lowPrice = price.lower;
      if (price.upper != null) offer.highPrice = price.upper;
      result.offers = offer;
    }

    if (this.isDateBased) {
      result.startDate = this.start.format('YYYY-MM-DD');
      result.endDate = this.end.format('YYYY-MM-DD');
    } else {
      result.startDate = this.start.format();
      if (this.hasKnownEnd()) result.endDate = this.end.format();
    }

    return result;
  }
}

export function eventsToDates(events) {
  return events
    .map(event => event.getDates())
    .reduce((a, b) => a.concat(b), [])
    .sort((date1, date2) => date1.start.unix() - date2.start.unix());
}
<commit_msg>Shorten Event.getParent() and getPlace()<commit_after>import moment from 'moment';

import locations from '../core/locations';
import Model from '../base/model';
import {capfirst, range, makeAbsoluteURL} from '../utils';

import Place from './place';

export default class Event extends Model {
  getName() {
    return this.data.name || this.getFullName();
  }

  getFullName() {
    return capfirst(this.data.full_name);
  }

  getParent() {
    if (this.data.parent) return new Event(this.data.parent);
  }

  getPlace() {
    if (this.data.place) return new Place(this.data.place);
  }

  getLocation() {
    return locations.get(this.data.location);
  }

  getDisplayDuration() {
    const durations = this.getDisplayDates().map(date => date.getDuration());
    const [first, ...others] = durations;
    if (others.every(duration => duration.asMinutes() == first.asMinutes())) {
      return first;
    } else {
      return undefined;
    }
  }

  getDisplayDates() {
    const allDates = this.getDates();
    const actualDates = allDates.filter(date => date.isActual())
    return actualDates.length ? actualDates : allDates;
  }

  getDates() {
    return this.data.dates.map(spec => new Date(this, spec));
  }

  hasChildren() {
    return this.data.children_count > 0;
  }

  isPremiere() {
    return this.data.is_premiere;
  }

  isFestival() {
    return this.data.kind == 'festival';
  }

  isExhibition() {
    return this.data.kind == 'exhibition';
  }

  isActual() {
    const timezone = this.getLocation().timezone;
    const isDateBased = this.data.end.length == 10;
    const end = moment.tz(this.data.end, timezone);
    const endBound = isDateBased ? end.clone().add(1, 'day') : end;
    return endBound.isAfter(moment());
  }

  getItemType() {
    if (this.isFestival()) {
      return 'Festival';
    } else if (this.isExhibition()) {
      return 'ExhibitionEvent';
    } else {
      return 'TheaterEvent';
    }
  }
}

export class Date {
  constructor(event, spec) {
    this.event = event;
    this.timezone = event.getLocation().timezone;

    this.start = moment.tz(spec.start, this.timezone);
    this.end = moment.tz(spec.end, this.timezone);

    this.isDateBased = spec.start.length == 10;  // 10 characters is ISO date

    this.startBound = this.start;
    this.endBound = this.isDateBased ? this.end.clone().add(1, 'day') : this.end;
  }

  intersectsAny(others) {
    return others.some(other => this.intersects(other));
  }

  intersects(other) {
    return (
      this.endBound.isAfter(other.startBound) &&
      this.startBound.isBefore(other.endBound)
    );
  }

  getDateRange() {
    return {
      start: this.start.clone().startOf('day'),
      end: this.end.clone().startOf('day')
    }
  }

  getDuration() {
    return moment.duration((this.end.unix() - this.start.unix()) * 1000);
  }

  hasKnownEnd() {
    return !this.start.isSame(this.end);
  }

  isActual() {
    return this.endBound.isAfter(moment());
  }

  toJSONLD(app) {
    const url = app.resolver.reverse('event', {id: this.event.data.id});
    const result = {
      '@context': 'http://schema.org',
      '@type': this.event.getItemType(),
      '@id': `${url}#${this.start.unix()}`,
      name: this.event.getName(),
      url: makeAbsoluteURL(url),
    }

    const place = this.event.getPlace();
    if (place) {
      result.location = place.toJSONLD(app);
    }

    const duration = this.getDuration();
    if (duration.asMinutes() > 0) {
      result.duration = duration.toString();
    }

    const price = this.event.data.price;
    if (price && (price.lower != null || price.upper != null)) {
      const offer = {
        '@type': 'AggregateOffer',
        priceCurrency: this.event.getLocation().currency,
      }
      if (price.lower != null) offer.lowPrice = price.lower;
      if (price.upper != null) offer.highPrice = price.upper;
      result.offers = offer;
    }

    if (this.isDateBased) {
      result.startDate = this.start.format('YYYY-MM-DD');
      result.endDate = this.end.format('YYYY-MM-DD');
    } else {
      result.startDate = this.start.format();
      if (this.hasKnownEnd()) result.endDate = this.end.format();
    }

    return result;
  }
}

export function eventsToDates(events) {
  return events
    .map(event => event.getDates())
    .reduce((a, b) => a.concat(b), [])
    .sort((date1, date2) => date1.start.unix() - date2.start.unix());
}
<|endoftext|>