<commit_before>'use strict';

var Boom = require('boom');
var ModuleDAO = require('../dao/ModuleDAO');

function DialplansController(database) {
};

// [GET] /dialplan/module/exists/{id}
DialplansController.prototype.exists = function (request, reply) {

    try {
        var mid = request.params.mid * 1,
            sid = request.params.sid * 1;
        ModuleDAO.find(mid, sid, function (err, rows) {
            if (err || rows.length == 0) {
                reply("error");
                console.log("module don't exists");
            }
            else {
                reply("exists");
            }
        });

    } catch (e) {
        reply(Boom.notFound(e.message));
    }

};

// [POST] /dialplan/module/updateFile/{id}
DialplansController.prototype.updateFile = function (request, reply) {

    try {
        var mid = request.params.mid * 1,
            sid = request.params.sid * 1;

        var file = request.payload.file;

        ModuleDAO.find(mid, sid, function (err, rows) {
            if (err || rows.length == 0) {
                reply("error");
                console.log("module don't exists");
            }
            else {

                // update file
                ModuleDAO.updateFile(mid, file, function (err, result) {
                    if (err) {
                        console.log(err);
                        return;
                    }
                    reply("updated");
                    console.log("updated");
                });

            }
        });

    } catch (e) {
        reply(Boom.notFound(e.message));
    }

};

module.exports = DialplansController;
<commit_msg>Path updated<commit_after>'use strict';

var Boom = require('boom');
var ModuleDAO = require('../dao/ModuleDAO');

function DialplansController(database) {
};

// [GET] /dialplan/module/exists/{id}
DialplansController.prototype.exists = function (request, reply) {

    try {
        var mid = request.params.mid * 1,
            sid = request.params.sid * 1;
        ModuleDAO.find(mid, sid, function (err, rows) {
            if (err || rows.length == 0) {
                reply("error");
                console.log("module don't exists");
            }
            else {
                reply("exists");
            }
        });

    } catch (e) {
        reply(Boom.notFound(e.message));
    }

};

// [POST] /dialplan/module/updateFile/{id}
DialplansController.prototype.updateFile = function (request, reply) {

    try {
        var mid = request.params.mid * 1,
            sid = request.params.sid * 1;

        var file = "custom/"+request.payload.file;

        ModuleDAO.find(mid, sid, function (err, rows) {
            if (err || rows.length == 0) {
                reply("error");
                console.log("module don't exists");
            }
            else {

                // update file
                ModuleDAO.updateFile(mid, file, function (err, result) {
                    if (err) {
                        console.log(err);
                        return;
                    }
                    reply("updated");
                    console.log("updated");
                });

            }
        });

    } catch (e) {
        reply(Boom.notFound(e.message));
    }

};

module.exports = DialplansController;
<|endoftext|>


<commit_before>/* http://learningwebgl.com/blog/?p=507
 */
function noisetexture(context, width, height) {

	this.texture = null;
	this.image	 = null;

	this.gl			 = context;

	this.width   = width;
	this.height  = height;

	this.initialize = function() {
		this.texture = this.gl.createTexture();
		this.gl.bindTexture(this.gl.TEXTURE_2D, this.texture);

		var pixels = new WebGLFloatArray(this.width * this.height * 4);
		var count = this.width * this.height * 4;
		//*
		for (var i = 0; i < count; i += 4) {
			pixels[i] = Math.random() * 3.0;
		}
		//*/
		this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.width, this.height, 0, this.gl.RGBA, this.gl.FLOAT, pixels);

		this.gl.enable(this.gl.TEXTURE_2D);
		this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, this.gl.LINEAR);
		this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this.gl.LINEAR);
		this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_S_WRAP, this.gl.CLAMP);
		this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_T_WRAP, this.gl.CLAMP);
		this.gl.bindTexture(this.gl.TEXTURE_2D, null);
	}

	this.bind = function() {
		this.gl.enable(this.gl.TEXTURE_2D);
		this.gl.bindTexture(this.gl.TEXTURE_2D, this.texture);
	}

	this.initialize();

	return this.texture;
}<commit_msg>No need for noisetexture anymore, what with ftexture around.<commit_after><|endoftext|>


<commit_before>var events = require('events');
var util = require('util');
var crypto = require('crypto');

var mrf24j40 = require('node-mrf24j40');
var MRF24J40 = mrf24j40.MRF24J40;
var ControlRegister = mrf24j40.ControlRegister;
var FIFO = mrf24j40.FIFO;

var osnp = require('node-osnp');
var OSNPAddressTable = osnp.OSNPAddressTable;
var OSNPCommandQueue = osnp.OSNPCommandQueue;
var FrameType = osnp.FrameType;
var AddressingMode = osnp.AddressingMode;
var MACCommand = osnp.MACCommand;
var SecurityLevel = osnp.SecurityLevel;
var RXMode = osnp.RXMode;

var radio;
var txQueue;
var txFrame;

var addressTable;
var deviceQueues;

var deviceDiscoveryPeriods;

module.exports = new events.EventEmitter();
exports = module.exports;

function QueuedFrame(frame, timeout, callback) {
  this.frame = frame;
  this.osnpTransmissionTimeout = timeout;
  this.callback = callback;
}

exports.allowMultipleCommandsInPacket = false;

exports.start = function(pairedDevices) {
  deviceQueues = {};
  txQueue = [];
  txFrame = null;

  var initAddresses = [];

  for(var i = 0, len = pairedDevices.length; i < len; i++) {
    queue = new OSNPCommandQueue();
    queue.device = pairedDevices[i];
    deviceQueues[queue.device.protocolInfo.shortAddress.toString('hex')] = queue;
    deviceQueues[queue.device.protocolInfo.eui.toString('hex')] = queue;
    initAddresses.push(queue.device.protocolInfo.shortAddress.readUInt16LE(0));
  }

  addressTable = new OSNPAddressTable(initAddresses);

  if (process.platform == 'linux') {
    radio = new MRF24J40('linux');
  }

  osnp.setPANID(new Buffer([0xfe, 0xca]));
  osnp.setShortAddress(new Buffer([0x00, 0x00]));
  //TODO: make this configurable or read from somewhere
  osnp.setEUI(new Buffer([0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17]));

  if (radio) {
    radio.on('frame', handleReceived);
    radio.on('securedFrame', handleSecuredFrame);
    radio.on('transmitted', handleTransmitted);
    radio.initialize();
    radio.setPANCoordinator();
    radio.setPANID(osnp.getPANID());
    radio.setEUI(osnp.getEUI());
    radio.setShortAddress(osnp.getShortAddress());
    radio.setChannel(2);
  }
}

exports.discoverDevices = function() {
  deviceDiscoveryPeriods = 0;
  transmitDiscoveryRequest();
}

exports.pair = function(device, pairingData, cb) {
  device.protocolInfo.shortAddress = new Buffer(2);
  device.protocolInfo.shortAddress.writeUInt16LE(addressTable.allocate(), 0);
  device.protocolInfo.txKey = pairingData;
  device.protocolInfo._txKey = crypto.randomBytes(16);
  device.protocolInfo.rxKey = crypto.randomBytes(16);
  device.protocolInfo.securityLevel = SecurityLevel.AES_CCM_64;
  var frame = osnp.createPairingCommand(device.protocolInfo.eui, device.protocolInfo.shortAddress, device.protocolInfo._txKey, device.protocolInfo.rxKey);
  deviceQueues[device.protocolInfo.shortAddress.toString('hex')] = deviceQueues[device.protocolInfo.eui.toString('hex')];
  addToQueue(frame, device, 1000, cb);
}

exports.unpair = function(device, cb) {
  var frame = osnp.createUnpairingCommand(device.protocolInfo.shortAddress);
  addToQueue(frame, device, 1000, cb);
}

exports.send = function(device, data, timeout, cb) {
  var frame = osnp.createCommandPacket(data, device.protocolInfo.eui, device.protocolInfo.shortAddress, device.paired);
  addToQueue(frame, device, timeout, cb);
}

function tryUnsetFramePending() {
  var empty = true;

  for(var queueName in deviceQueues) {
    var queue = deviceQueues[queueName];

    if (isPollDriven(queue.device) && !queue.isEmpty()) {
      empty = false;
      break;
    }
  }

  if (empty) {
    radio.setDataRequestFramePending(false);
  }
}

function getQueue(address) {
  var queue = deviceQueues[address.toString('hex')];

  if (!queue) {
    queue = new OSNPCommandQueue();
    deviceQueues[address.toString('hex')] = queue;
  }

  return queue;
}

function tryDequeue(queue) {
  var cmd;

  if (!isPollDriven(queue.device)) {
    cmd = queue.dequeue();
  } else if (queue.active) {
    cmd = queue.dequeue();

    if (!cmd || queue.isEmpty()) {
      queue.active = false;
    } else {
      //add the frame pending bit
      cmd.frame.frameControlLow = cmd.frame.frameControlLow | 0x10;
    }
  }

  if (cmd) {
    txQueue.push({ securityInfo: queue.device.protocolInfo, frame: cmd.frame });
    tryTransmit();
  }

  tryUnsetFramePending();
}

function addToQueue(frame, device, timeout, cb) {
  if (isPollDriven(device)) {
    radio.setDataRequestFramePending(true);
  }

  var queue = getQueue(frame.destinationAddress);
  queue.device = device;
  queue.queue(new QueuedFrame(frame, timeout, cb));
  tryDequeue(queue);
}

function transmitDiscoveryRequest() {
  var frame = osnp.createDiscoveryRequest();
  txQueue.push({ frame: frame });
  tryTransmit();

  if (deviceDiscoveryPeriods < 240) {
    deviceDiscoveryPeriods++;
    setTimeout(transmitDiscoveryRequest, 250);
  } else {
    exports.emit('deviceDiscoveryFinished');
  }
}

function tryTransmit() {
  if (!txFrame && (txQueue.length > 0)) {
    var frame = txQueue.shift();
    txFrame = frame;

    var frameLength = frame.frame.getEncodedLength();
    var headerLength = frameLength - frame.frame.payload.length;

    if (frame.frame.hasSecurityEnabled()) {
      headerLength -= 5;
      radio.setCipher(false, false, frame.securityInfo.securityLevel, frame.securityInfo.securityLevel);
      radio.setTXNSecurityKey(frame.securityInfo.txKey);
      frame.frame.frameCounter = frame.securityInfo.txFrameCounter++;
      //TODO: the device needs to be updated in the db
    }

    var buf = new Buffer(frameLength + 2);
    buf[0] = headerLength;
    buf[1] = frameLength;
    frame.frame.encode(buf.slice(2));
    radio.transmit(buf);
  }
}

function handleMACFrame(frame) {
  switch (frame.payload[0]) {
  case MACCommand.ASSOCIATION_RESPONSE:
    //TODO: handle error
    var queue = getQueue(frame.sourceAddress);

    if (queue.device) {
      var cmd = queue.deviceResponded();

      if (cmd) {
        queue.device.protocolInfo.capabilities = frame.payload[1];
        queue.device.protocolInfo.securityLevel = frame.payload[2];
        queue.device.protocolInfo.txKey = queue.device.protocolInfo._txKey;
        delete queue.device.protocolInfo['_txKey'];
        //TODO: update db
        cmd.callback(queue.device);
      }

      tryDequeue(queue);
    }
    break;
  case MACCommand.DATA_REQUEST:
    var queue = getQueue(frame.sourceAddress);

    if (queue.device) {
      queue.active = true;
      tryDequeue(queue);
    }
    break;
  case MACCommand.DISCOVER:
    var protocolInfo = new OSNPProtocolInfo(frame.sourceAddress);
    exports.emit('deviceDiscovered', protocolInfo);
    break;
  }
}

function handleDataFrame(frame) {
  var queue = getQueue(frame.sourceAddress);

  if (!queue.device) {
    return;
  }

  if (frame.payload[0] == 0xE2) {
    exports.emit('notificationReceived', queue.device, frame.payload);
    return;
  }

  var cmd = queue.deviceResponded();

  if (cmd) {
    cmd.callback(frame.payload);
  }

  tryDequeue(queue);
}

function handleSecuredFrame(rawFrame) {
  var frame = osnp.parseFrame(rawFrame);
  var queue = getQueue(frame.sourceAddress);

  if (!queue.device) {
    radio.setCipher(false, true, 0x00, 0x00);
    return;
  }

  radio.setRXSecurityKey(queue.device.protocolInfo.rxKey);
  radio.setCipher(true, false, queue.device.protocolInfo.securityLevel, queue.device.protocolInfo.securityLevel);
}

function handleReceived(rawFrame, lqi, rssi) {
  //TODO: check security and counter
  var frame = osnp.parseFrame(rawFrame);

  switch(frame.getFrameType()) {
  case FrameType.MAC_CMD:
    handleMACFrame(frame);
    break;
  case FrameType.DATA:
    handleDataFrame(frame);
    break;
  }
}

function handleTransmitted(txErr, ccaErr) {
  if(ccaErr) {
    txQueue.push(txFrame);
  } else if (txErr) {
    var queue = getQueue(txFrame.frame.destinationAddress);
    var sentCmd = queue.deviceResponded();
    //TODO: handle error by invoking callback with a proper error code
  } else if (txFrame.frame.payload[0] == MACCommand.DISASSOCIATED) {
    var queue = getQueue(txFrame.frame.destinationAddress);
    delete deviceQueues[queue.device.protocolInfo.shortAddress];
    delete deviceQueues[queue.device.protocolInfo.eui];
    addressTable.free(queue.device.protocolInfo.shortAddress);
    var cmd = queue.deviceResponded();
    cmd.callback(queue.device);
  }

  txFrame = null;
  tryTransmit();
}

function isPollDriven(device) {
  return (device.protocolInfo.capabilities !== null && ((device.protocolInfo.capabilities & 0x01) == RXMode.POLL_DRIVEN));
}

function OSNPProtocolInfo(eui) {
  this.eui = new Buffer(eui.length);
  eui.copy(this.eui);
  this.shortAddress = null;
  this.capabilities = null;
  this.securityLevel = null;
  this.rxKey = null;
  this.txKey = null;
  this.rxFrameCounter = 0;
  this.txFrameCounter = 0;
  this.id = this.eui.toString('hex');
}
<commit_msg>changed handling of security interrupts<commit_after>var events = require('events');
var util = require('util');
var crypto = require('crypto');

var mrf24j40 = require('node-mrf24j40');
var MRF24J40 = mrf24j40.MRF24J40;
var ControlRegister = mrf24j40.ControlRegister;
var FIFO = mrf24j40.FIFO;

var osnp = require('node-osnp');
var OSNPAddressTable = osnp.OSNPAddressTable;
var OSNPCommandQueue = osnp.OSNPCommandQueue;
var FrameType = osnp.FrameType;
var AddressingMode = osnp.AddressingMode;
var MACCommand = osnp.MACCommand;
var SecurityLevel = osnp.SecurityLevel;
var RXMode = osnp.RXMode;

var radio;
var txQueue;
var txFrame;

var addressTable;
var deviceQueues;

var deviceDiscoveryPeriods;

module.exports = new events.EventEmitter();
exports = module.exports;

function QueuedFrame(frame, timeout, callback) {
  this.frame = frame;
  this.osnpTransmissionTimeout = timeout;
  this.callback = callback;
}

exports.allowMultipleCommandsInPacket = false;

exports.start = function(pairedDevices) {
  deviceQueues = {};
  txQueue = [];
  txFrame = null;

  var initAddresses = [];

  for(var i = 0, len = pairedDevices.length; i < len; i++) {
    queue = new OSNPCommandQueue();
    queue.device = pairedDevices[i];
    deviceQueues[queue.device.protocolInfo.shortAddress.toString('hex')] = queue;
    deviceQueues[queue.device.protocolInfo.eui.toString('hex')] = queue;
    initAddresses.push(queue.device.protocolInfo.shortAddress.readUInt16LE(0));
  }

  addressTable = new OSNPAddressTable(initAddresses);

  if (process.platform == 'linux') {
    radio = new MRF24J40('linux');
  }

  osnp.setPANID(new Buffer([0xfe, 0xca]));
  osnp.setShortAddress(new Buffer([0x00, 0x00]));
  //TODO: make this configurable or read from somewhere
  osnp.setEUI(new Buffer([0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17]));

  if (radio) {
    radio.on('frame', handleReceived);
    radio.on('keyRequest', handleKeyRequest);
    radio.on('transmitted', handleTransmitted);
    radio.initialize();
    radio.setPANCoordinator();
    radio.setPANID(osnp.getPANID());
    radio.setEUI(osnp.getEUI());
    radio.setShortAddress(osnp.getShortAddress());
    radio.setChannel(2);
  }
}

exports.discoverDevices = function() {
  deviceDiscoveryPeriods = 0;
  transmitDiscoveryRequest();
}

exports.pair = function(device, pairingData, cb) {
  device.protocolInfo.shortAddress = new Buffer(2);
  device.protocolInfo.shortAddress.writeUInt16LE(addressTable.allocate(), 0);
  device.protocolInfo.txKey = pairingData;
  device.protocolInfo._txKey = crypto.randomBytes(16);
  device.protocolInfo.rxKey = crypto.randomBytes(16);
  device.protocolInfo.securityLevel = SecurityLevel.AES_CCM_64;
  var frame = osnp.createPairingCommand(device.protocolInfo.eui, device.protocolInfo.shortAddress, device.protocolInfo._txKey, device.protocolInfo.rxKey);
  deviceQueues[device.protocolInfo.shortAddress.toString('hex')] = deviceQueues[device.protocolInfo.eui.toString('hex')];
  addToQueue(frame, device, 1000, cb);
}

exports.unpair = function(device, cb) {
  var frame = osnp.createUnpairingCommand(device.protocolInfo.shortAddress);
  addToQueue(frame, device, 1000, cb);
}

exports.send = function(device, data, timeout, cb) {
  var frame = osnp.createCommandPacket(data, device.protocolInfo.eui, device.protocolInfo.shortAddress, device.paired);
  addToQueue(frame, device, timeout, cb);
}

function tryUnsetFramePending() {
  var empty = true;

  for(var queueName in deviceQueues) {
    var queue = deviceQueues[queueName];

    if (isPollDriven(queue.device) && !queue.isEmpty()) {
      empty = false;
      break;
    }
  }

  if (empty) {
    radio.setDataRequestFramePending(false);
  }
}

function getQueue(address) {
  var queue = deviceQueues[address.toString('hex')];

  if (!queue) {
    queue = new OSNPCommandQueue();
    deviceQueues[address.toString('hex')] = queue;
  }

  return queue;
}

function tryDequeue(queue) {
  var cmd;

  if (!isPollDriven(queue.device)) {
    cmd = queue.dequeue();
  } else if (queue.active) {
    cmd = queue.dequeue();

    if (!cmd || queue.isEmpty()) {
      queue.active = false;
    } else {
      //add the frame pending bit
      cmd.frame.frameControlLow = cmd.frame.frameControlLow | 0x10;
    }
  }

  if (cmd) {
    txQueue.push({ securityInfo: queue.device.protocolInfo, frame: cmd.frame });
    tryTransmit();
  }

  tryUnsetFramePending();
}

function addToQueue(frame, device, timeout, cb) {
  if (isPollDriven(device)) {
    radio.setDataRequestFramePending(true);
  }

  var queue = getQueue(frame.destinationAddress);
  queue.device = device;
  queue.queue(new QueuedFrame(frame, timeout, cb));
  tryDequeue(queue);
}

function transmitDiscoveryRequest() {
  var frame = osnp.createDiscoveryRequest();
  txQueue.push({ frame: frame });
  tryTransmit();

  if (deviceDiscoveryPeriods < 240) {
    deviceDiscoveryPeriods++;
    setTimeout(transmitDiscoveryRequest, 250);
  } else {
    exports.emit('deviceDiscoveryFinished');
  }
}

function tryTransmit() {
  if (!txFrame && (txQueue.length > 0)) {
    var frame = txQueue.shift();
    txFrame = frame;

    var frameLength = frame.frame.getEncodedLength();
    var headerLength = frameLength - frame.frame.payload.length;

    if (frame.frame.hasSecurityEnabled()) {
      headerLength -= 5;
      radio.setCipher(false, false, frame.securityInfo.securityLevel, frame.securityInfo.securityLevel);
      radio.setTXNSecurityKey(frame.securityInfo.txKey);
      frame.frame.frameCounter = frame.securityInfo.txFrameCounter++;
      //TODO: the device needs to be updated in the db
    }

    var buf = new Buffer(frameLength + 2);
    buf[0] = headerLength;
    buf[1] = frameLength;
    frame.frame.encode(buf.slice(2));
    radio.transmit(buf);
  }
}

function handleMACFrame(frame) {
  switch (frame.payload[0]) {
  case MACCommand.ASSOCIATION_RESPONSE:
    //TODO: handle error
    var queue = getQueue(frame.sourceAddress);

    if (queue.device) {
      var cmd = queue.deviceResponded();

      if (cmd) {
        queue.device.protocolInfo.capabilities = frame.payload[1];
        queue.device.protocolInfo.securityLevel = frame.payload[2];
        queue.device.protocolInfo.txKey = queue.device.protocolInfo._txKey;
        delete queue.device.protocolInfo['_txKey'];
        //TODO: update db
        cmd.callback(queue.device);
      }

      tryDequeue(queue);
    }
    break;
  case MACCommand.DATA_REQUEST:
    var queue = getQueue(frame.sourceAddress);

    if (queue.device) {
      queue.active = true;
      tryDequeue(queue);
    }
    break;
  case MACCommand.DISCOVER:
    var protocolInfo = new OSNPProtocolInfo(frame.sourceAddress);
    exports.emit('deviceDiscovered', protocolInfo);
    break;
  }
}

function handleDataFrame(frame) {
  var queue = getQueue(frame.sourceAddress);

  if (!queue.device) {
    return;
  }

  if (frame.payload[0] == 0xE2) {
    exports.emit('notificationReceived', queue.device, frame.payload);
    return;
  }

  var cmd = queue.deviceResponded();

  if (cmd) {
    cmd.callback(frame.payload);
  }

  tryDequeue(queue);
}

function handleKeyRequest(eui) {
  var queue = getQueue(eui);

  if (!queue.device) {
    radio.setCipher(false, true, 0x00, 0x00);
    return;
  }

  radio.setRXSecurityKey(queue.device.protocolInfo.rxKey);
  radio.setCipher(true, false, queue.device.protocolInfo.securityLevel, queue.device.protocolInfo.securityLevel);
}

function handleReceived(rawFrame, lqi, rssi) {
  //TODO: check security and counter
  var frame = osnp.parseFrame(rawFrame);

  switch(frame.getFrameType()) {
  case FrameType.MAC_CMD:
    handleMACFrame(frame);
    break;
  case FrameType.DATA:
    handleDataFrame(frame);
    break;
  }
}

function handleTransmitted(txErr, ccaErr) {
  if(ccaErr) {
    txQueue.push(txFrame);
  } else if (txErr) {
    var queue = getQueue(txFrame.frame.destinationAddress);
    var sentCmd = queue.deviceResponded();
    //TODO: handle error by invoking callback with a proper error code
  } else if (txFrame.frame.payload[0] == MACCommand.DISASSOCIATED) {
    var queue = getQueue(txFrame.frame.destinationAddress);
    delete deviceQueues[queue.device.protocolInfo.shortAddress];
    delete deviceQueues[queue.device.protocolInfo.eui];
    addressTable.free(queue.device.protocolInfo.shortAddress);
    var cmd = queue.deviceResponded();
    cmd.callback(queue.device);
  }

  txFrame = null;
  tryTransmit();
}

function isPollDriven(device) {
  return (device.protocolInfo.capabilities !== null && ((device.protocolInfo.capabilities & 0x01) == RXMode.POLL_DRIVEN));
}

function OSNPProtocolInfo(eui) {
  this.eui = new Buffer(eui.length);
  eui.copy(this.eui);
  this.shortAddress = null;
  this.capabilities = null;
  this.securityLevel = null;
  this.rxKey = null;
  this.txKey = null;
  this.rxFrameCounter = 0;
  this.txFrameCounter = 0;
  this.id = this.eui.toString('hex');
}
<|endoftext|>


<commit_before>var phrases = ["Were you born in a barn?", "Get some work done", "Useless scrub", "Stop jacking off", "I'll bust your chops", "Are you born in a water park?", "Stop fapping around", "Are you born in a barn?", "Later, shizlord", "Oy!"];
var dialogs = ["WERE U BORN IN A BARN???", "GET SUM WERK DUN", "Useless scrub...", "Stop jacking off", "I'LL BUST YOUR CHOPS", "R U BORN IN A WATER PARK??", "Stop fapping around", "R U BORN IN A BARN???", "LATER, SHIZLORD", "OI!!"];

function androo(){
    var index = Math.round(Math.random()*(phrases.length-1));

    var ttsOptions = {
        gender: "male",
        rate: 0.7
    }

    chrome.tts.speak(phrases[index],ttsOptions);
    alert(dialogs[index]);

    setTimeout(androo,Math.random()*60*1000);
}

setTimeout(androo,20000);
<commit_msg>1 minute is a bit too long<commit_after>var phrases = ["Were you born in a barn?", "Get some work done", "Useless scrub", "Stop jacking off", "I'll bust your chops", "Are you born in a water park?", "Stop fapping around", "Are you born in a barn?", "Later, shizlord", "Oy!"];
var dialogs = ["WERE U BORN IN A BARN???", "GET SUM WERK DUN", "Useless scrub...", "Stop jacking off", "I'LL BUST YOUR CHOPS", "R U BORN IN A WATER PARK??", "Stop fapping around", "R U BORN IN A BARN???", "LATER, SHIZLORD", "OI!!"];

function androo(){
    var index = Math.round(Math.random()*(phrases.length-1));

    var ttsOptions = {
        gender: "male",
        rate: 0.7
    }

    chrome.tts.speak(phrases[index],ttsOptions);
    alert(dialogs[index]);

    setTimeout(androo,Math.random()*30*1000);
}

setTimeout(androo,20000);
<|endoftext|>


<commit_before>/*jshint curly: false */
import Ember from "ember";

/**
 * Helper proving a way to test the presence of an item in an array.
 *
 * Depending on the given parameters, the test is made on
 * - the presence of a literal:
 *    ``{{array-contains array 'foo'}}``
 * - the presence of the object itself:
 *    ``{{array-contains array object}}``
 * - the presence of an object containing a specific property with a specific value:
 *    ``{{array-contains array 'value' property='title'}}``
 *
 * Note that null or undefined are considered acceptable and equivalent values for 'value' parameter (resolve both to null)
 *
 * This helper could be used standalone or, more often, combined with the ``if`` helper:
 *
 * ```html
 * {{if (array-contains array 'value' property='title') 'something' 'something else'}}
 * ```
 *
 * This addon installs observers on the provided array to listen any external change made on it. It includes any addition/removal
 * of an item and, if a property is specified, any change of the property of any array element.
 *
 * **extends** [Ember.Helper](https://github.com/emberjs/ember.js/blob/f96aecd212fe96b9560c8832b7bbb4988d6670d0/packages/ember-htmlbars/lib/helper.js#L48)
 *
 * @public
 * @class ArrayContainsHelper
 */
export default Ember.Helper.extend({

  /**
   * Test if an array contains an object, eventually based on one of this object property / value
   *
   * Returns true if:
   * - the array in ``params[0]`` contains the object value in ``params[1]``
   * - the array in ``params[0]`` contains an object holding a property named ``hash.property`` with
   * value equals to ``params[1]``
   *
   * Returns false otherwise and if the array in ``params[0]`` is null or undefined
   *
   * **extends** [Ember.Helper.compute](https://github.com/emberjs/ember.js/blob/f96aecd212fe96b9560c8832b7bbb4988d6670d0/packages/ember-htmlbars/lib/helper.js#L82)
   *
   * @method compute
   * @param {Array} params array and value to test. Array can be null, undefined or valid Array.
   * value could be a literal or an object
   * @param {Object} hash named arguments accepted by this helper (``property``)
   * @throws {Ember.Error} [(Ember.Error)](https://github.com/emberjs/ember.js/blob/27862a18b8773e57c52dbc7141b1f92a505f16ff/packages/ember-metal/lib/error.js#L22) if params is null or not an array or if the given array (from ``params[0]``) is
   * not null and not an array.
   */
  compute(params, hash) {
    Ember.assert('params should be a not null valid array', Ember.isArray(params));

    let array = params[0];
    let value = params[1];

    // if array undefined or null, we test against an empty array. This is particularily usefull
    // if the test occurs before a promise is resolved, for example
    if (Ember.isNone(array)) { array = Ember.A([]); }

    Ember.assert('First parameter should be a valid array', Ember.isArray(array));

    let property = hash ? hash.property : null;
    let contains = false;
    this.setupRecompute(array, property);

    // Wrap into an Ember.Array to use advanced method
    // Note: This operation does not modify the original array
    let emberArray = Ember.A(array);

    if (property) {
      // Property provided, test the property
      contains = emberArray.isAny(property, value);
    } else {
      // No property provided, test the full object
      contains = emberArray.contains(value);
    }

    return contains;
  },

  recompute: function () {
    if (this._stream) { this._stream.notify(); }
  },

  destroy() {
    if (this.teardown) { this.teardown(); }
    this._super(...arguments);
  },

  /**
   * Install and clean observers to be able to recompute result if array changes :
   * content added or removed or observed property modified.
   *
   * @method setupRecompute
   * @param {Array} array The given array
   * @param {String} property Name of the property to test
   * @private
   */
  setupRecompute(array, property) {
    this.set('_array', array);

    // Remove existing observers, if any
    if (this.teardown) { this.teardown(); }
    if (this.teardownProperty) { this.teardownProperty(); }

    // Install observer on the array itself : run when adding / removing items to the array
    let arrayPath = '_array.[]';
    this.addObserver(arrayPath, this, this.recompute);
    // define method to remove observer
    this.teardown = () => {
      this.removeObserver(arrayPath, this, this.recompute);
    };

    if (property) {
      // Install observer on the given property, if any
      let propertyPath = `_array.@each.${property}`;
      this.addObserver(propertyPath, this, this.recompute);
      // define method to remove observer
      this.teardownProperty = () => {
        this.removeObserver(propertyPath, this, this.recompute);
      };
    }
  }
});
<commit_msg>refactor(array-contains): use unitary imports instead of globals<commit_after>// Note: exported packages are defined in ember.js/vendor/ember/shims.js
import { isNone } from 'ember-utils';
import { A as emberArray, isEmberArray as isArray } from 'ember-array/utils';
import { assert } from 'ember-metal/utils';
import Helper from 'ember-helper';
import set from 'ember-metal/set';
import { addObserver, removeObserver } from 'ember-metal/observer';

/**
 * Helper proving a way to test the presence of an item in an array.
 *
 * Depending on the given parameters, the test is made on
 * - the presence of a literal:
 *    ``{{array-contains array 'foo'}}``
 * - the presence of the object itself:
 *    ``{{array-contains array object}}``
 * - the presence of an object containing a specific property with a specific value:
 *    ``{{array-contains array 'value' property='title'}}``
 *
 * Note that null or undefined are considered acceptable and equivalent values for 'value' parameter (resolve both to null)
 *
 * This helper could be used standalone or, more often, combined with the ``if`` helper:
 *
 * ```html
 * {{if (array-contains array 'value' property='title') 'something' 'something else'}}
 * ```
 *
 * This addon installs observers on the provided array to listen any external change made on it. It includes any addition/removal
 * of an item and, if a property is specified, any change of the property of any array element.
 *
 * **extends** [Ember.Helper](https://github.com/emberjs/ember.js/blob/f96aecd212fe96b9560c8832b7bbb4988d6670d0/packages/ember-htmlbars/lib/helper.js#L48)
 *
 * @public
 * @class ArrayContainsHelper
 */
export default Helper.extend({

  /**
   * Test if an array contains an object, eventually based on one of this object property / value
   *
   * Returns true if:
   * - the array in ``params[0]`` contains the object value in ``params[1]``
   * - the array in ``params[0]`` contains an object holding a property named ``hash.property`` with
   * value equals to ``params[1]``
   *
   * Returns false otherwise and if the array in ``params[0]`` is null or undefined
   *
   * **extends** [Ember.Helper.compute](https://github.com/emberjs/ember.js/blob/f96aecd212fe96b9560c8832b7bbb4988d6670d0/packages/ember-htmlbars/lib/helper.js#L82)
   *
   * @method compute
   * @param {Array} params array and value to test. Array can be null, undefined or valid Array.
   * value could be a literal or an object
   * @param {Object} hash named arguments accepted by this helper (``property``)
   * @throws {Ember.Error} [(Ember.Error)](https://github.com/emberjs/ember.js/blob/27862a18b8773e57c52dbc7141b1f92a505f16ff/packages/ember-metal/lib/error.js#L22) if params is null or not an array or if the given array (from ``params[0]``) is
   * not null and not an array.
   */
  compute(params, hash) {
    assert('params should be a not null valid array', isArray(params));

    let array = params[0];
    let value = params[1];

    // if array undefined or null, we test against an empty array. This is particularily usefull
    // if the test occurs before a promise is resolved, for example
    if (isNone(array)) { array = emberArray([]); }

    assert('First parameter should be a valid array', isArray(array));

    let property = hash ? hash.property : null;
    let contains = false;
    this.setupRecompute(array, property);

    // Wrap into an Ember.Array to use advanced method
    // Note: This operation does not modify the original array
    let wrappedArray = emberArray(array);

    if (property) {
      // Property provided, test the property
      contains = wrappedArray.isAny(property, value);
    } else {
      // No property provided, test the full object
      contains = wrappedArray.contains(value);
    }

    return contains;
  },

  recompute: function () {
    if (this._stream) { this._stream.notify(); }
  },

  destroy() {
    if (this.teardown) { this.teardown(); }
    this._super(...arguments);
  },

  /**
   * Install and clean observers to be able to recompute result if array changes :
   * content added or removed or observed property modified.
   *
   * @method setupRecompute
   * @param {Array} array The given array
   * @param {String} property Name of the property to test
   * @private
   */
  setupRecompute(array, property) {
    set(this, '_array', array);

    // Remove existing observers, if any
    if (this.teardown) { this.teardown(); }
    if (this.teardownProperty) { this.teardownProperty(); }

    // Install observer on the array itself : run when adding / removing items to the array
    let arrayPath = '_array.[]';
    addObserver(this, arrayPath, this, this.recompute);
    // define method to remove observer
    this.teardown = () => {
      removeObserver(this, arrayPath, this, this.recompute);
    };

    if (property) {
      // Install observer on the given property, if any
      let propertyPath = `_array.@each.${property}`;
      addObserver(this, propertyPath, this, this.recompute);
      // define method to remove observer
      this.teardownProperty = () => {
        removeObserver(this, propertyPath, this, this.recompute);
      };
    }
  }
});
<|endoftext|>


<commit_before>const spacetime = require('spacetime')
const parseTime = require('../times/parse')

const dayNames = {
  mon: 'monday',
  tue: 'tuesday',
  tues: 'wednesday',
  wed: 'wednesday',
  thu: 'thursday',
  fri: 'friday',
  sat: 'saturday',
  sun: 'sunday',
  monday: 'monday',
  tuesday: 'tuesday',
  wednesday: 'wednesday',
  thursday: 'thursday',
  friday: 'friday',
  saturday: 'saturday',
  sunday: 'sunday',
}
// 'any tuesday' vs 'every tuesday'
const parseLogic = function (m) {
  if (m.match('(every|each)').found) {
    return 'AND'
  }
  if (m.match('(any|a)').found) {
    return 'OR'
  }
  return null
}

// parse repeating dates, like 'every week'
const parseIntervals = function (doc, context) {
  // 'every week'
  let m = doc.match('[<logic>(every|any|each)] [<skip>other?] [<unit>#Duration] (starting|beginning|commencing)?')
  if (m.found) {
    let repeat = { interval: {} }
    let unit = m.groups('unit').text('reduced')
    repeat.interval[unit] = 1
    repeat.choose = parseLogic(m)
    // 'every other week'
    if (m.groups('skip').found) {
      repeat.interval[unit] = 2
    }
    doc = doc.remove(m)
    return { repeat: repeat }
  }

  // 'every two weeks'
  m = doc.match('[<logic>(every|any|each)] [<num>#Value] [<unit>#Duration] (starting|beginning|commencing)?')
  if (m.found) {
    let repeat = { interval: {} }
    let units = m.groups('unit')
    units.nouns().toSingular()
    let unit = units.text('reduced')
    repeat.interval[unit] = m.groups('num').numbers().get(0)
    repeat.choose = parseLogic(m)
    doc = doc.remove(m)
    return { repeat: repeat }
  }

  // 'every friday'
  m = doc.match('[<logic>(every|any|each|a)] [<skip>other?] [<day>#WeekDay+] (starting|beginning|commencing)?')
  if (m.found) {
    let repeat = { interval: { day: 1 }, filter: { weekDays: {} } }
    let str = m.groups('day').text('reduced')
    str = dayNames[str] //normalize it
    if (str) {
      repeat.filter.weekDays[str] = true
      repeat.choose = parseLogic(m)
      doc = doc.remove(m)
      return { repeat: repeat }
    }
  }

  // 'every weekday'
  m = doc.match(
    '[<logic>(every|any|each|a)] [<day>(weekday|week day|weekend|weekend day)] (starting|beginning|commencing)?'
  )
  if (m.found) {
    let repeat = { interval: { day: 1 }, filter: { weekDays: {} } }
    let day = m.groups('day')
    if (day.has('(weekday|week day)')) {
      repeat.filter.weekDays = {
        monday: true,
        tuesday: true,
        wednesday: true,
        thursday: true,
        friday: true,
      }
    } else if (day.has('(weekend|weekend day)')) {
      repeat.filter.weekDays = {
        saturday: true,
        sunday: true,
      }
    }
    repeat.choose = parseLogic(m)
    doc = doc.remove(m)
    return { repeat: repeat }
  }

  // mondays
  m = doc.match(
    '[<day>(mondays|tuesdays|wednesdays|thursdays|fridays|saturdays|sundays)] (at|near|after)? [<time>#Time+?]'
  )
  if (m.found) {
    let repeat = { interval: { day: 1 }, filter: { weekDays: {} } }
    let str = m.groups('day').text('reduced')
    str = str.replace(/s$/, '')
    str = dayNames[str] //normalize it
    if (str) {
      repeat.filter.weekDays[str] = true
      repeat.choose = 'OR'
      doc = doc.remove(m)
      let time = m.groups('time')
      if (time.found) {
        repeat.time = parseTime(time, context)
      }
      return { repeat: repeat }
    }
  }
  return null
}
module.exports = parseIntervals
<commit_msg>linter fix<commit_after>const parseTime = require('../times/parse')

const dayNames = {
  mon: 'monday',
  tue: 'tuesday',
  tues: 'wednesday',
  wed: 'wednesday',
  thu: 'thursday',
  fri: 'friday',
  sat: 'saturday',
  sun: 'sunday',
  monday: 'monday',
  tuesday: 'tuesday',
  wednesday: 'wednesday',
  thursday: 'thursday',
  friday: 'friday',
  saturday: 'saturday',
  sunday: 'sunday',
}
// 'any tuesday' vs 'every tuesday'
const parseLogic = function (m) {
  if (m.match('(every|each)').found) {
    return 'AND'
  }
  if (m.match('(any|a)').found) {
    return 'OR'
  }
  return null
}

// parse repeating dates, like 'every week'
const parseIntervals = function (doc, context) {
  // 'every week'
  let m = doc.match('[<logic>(every|any|each)] [<skip>other?] [<unit>#Duration] (starting|beginning|commencing)?')
  if (m.found) {
    let repeat = { interval: {} }
    let unit = m.groups('unit').text('reduced')
    repeat.interval[unit] = 1
    repeat.choose = parseLogic(m)
    // 'every other week'
    if (m.groups('skip').found) {
      repeat.interval[unit] = 2
    }
    doc = doc.remove(m)
    return { repeat: repeat }
  }

  // 'every two weeks'
  m = doc.match('[<logic>(every|any|each)] [<num>#Value] [<unit>#Duration] (starting|beginning|commencing)?')
  if (m.found) {
    let repeat = { interval: {} }
    let units = m.groups('unit')
    units.nouns().toSingular()
    let unit = units.text('reduced')
    repeat.interval[unit] = m.groups('num').numbers().get(0)
    repeat.choose = parseLogic(m)
    doc = doc.remove(m)
    return { repeat: repeat }
  }

  // 'every friday'
  m = doc.match('[<logic>(every|any|each|a)] [<skip>other?] [<day>#WeekDay+] (starting|beginning|commencing)?')
  if (m.found) {
    let repeat = { interval: { day: 1 }, filter: { weekDays: {} } }
    let str = m.groups('day').text('reduced')
    str = dayNames[str] //normalize it
    if (str) {
      repeat.filter.weekDays[str] = true
      repeat.choose = parseLogic(m)
      doc = doc.remove(m)
      return { repeat: repeat }
    }
  }

  // 'every weekday'
  m = doc.match(
    '[<logic>(every|any|each|a)] [<day>(weekday|week day|weekend|weekend day)] (starting|beginning|commencing)?'
  )
  if (m.found) {
    let repeat = { interval: { day: 1 }, filter: { weekDays: {} } }
    let day = m.groups('day')
    if (day.has('(weekday|week day)')) {
      repeat.filter.weekDays = {
        monday: true,
        tuesday: true,
        wednesday: true,
        thursday: true,
        friday: true,
      }
    } else if (day.has('(weekend|weekend day)')) {
      repeat.filter.weekDays = {
        saturday: true,
        sunday: true,
      }
    }
    repeat.choose = parseLogic(m)
    doc = doc.remove(m)
    return { repeat: repeat }
  }

  // mondays
  m = doc.match(
    '[<day>(mondays|tuesdays|wednesdays|thursdays|fridays|saturdays|sundays)] (at|near|after)? [<time>#Time+?]'
  )
  if (m.found) {
    let repeat = { interval: { day: 1 }, filter: { weekDays: {} } }
    let str = m.groups('day').text('reduced')
    str = str.replace(/s$/, '')
    str = dayNames[str] //normalize it
    if (str) {
      repeat.filter.weekDays[str] = true
      repeat.choose = 'OR'
      doc = doc.remove(m)
      let time = m.groups('time')
      if (time.found) {
        repeat.time = parseTime(time, context)
      }
      return { repeat: repeat }
    }
  }
  return null
}
module.exports = parseIntervals
<|endoftext|>


<commit_before>'use strict';

var fs                    = require('fs-extra');

var fileUtils             = rootRequire('utils/file-utils');
var authenticationUtils   = rootRequire('utils/authentication-utils');
var model                 = rootRequire('models/model');
var cloudstorage          = rootRequire('libs/cloudstorage/cloudstorage');

module.exports.controller = function(app) {
  /*
   |--------------------------------------------------------------------------
   | GET /companies/search/
   |--------------------------------------------------------------------------
   */
  app.get('/companies/search/:searchString', authenticationUtils.ensureAuthenticated, authenticationUtils.ensureAdmin, function(req, res) {
    var searchString = req.params.searchString;
    model.Company.find({ where: {displayName: searchString} }).then(function(companies) {
      res.send(companies);
    });
  });

  /*
   |--------------------------------------------------------------------------
   | GET /companies/
   | return List of all the companies
   |--------------------------------------------------------------------------
   */
  app.get('/companies/', authenticationUtils.ensureAuthenticated, authenticationUtils.ensureAdmin, function(req, res) {
    var searchString = req.params.searchString;
    model.Company.findAll().then(function(companies) {
      res.send(companies);
    });
  });

  /*
   |--------------------------------------------------------------------------
   | GET /companies/id/labels
   | return all the companies of the given company
   |--------------------------------------------------------------------------
   */
  app.get('/companies/:id/labels', authenticationUtils.ensureAuthenticated, authenticationUtils.ensureAdmin, function(req, res) {
    var companyId = req.params.id;
    model.Company.find({ where: {id: companyId} }).then(function(company) {
      if(company){
          company.getLabels().success(function(associatedLabels) {
              res.send(associatedLabels);
          })
      }else{
        res.send(company);
      }
    });
  });

  /*
   |--------------------------------------------------------------------------
   | GET /companies/id
   | return The company with id passed as part of the path. Empty object if it doesn't exists.
   | this function has been set to limited to admin only. We may consider at some point to release
   | a lighter way for having an all user access (for promo proposal)
   |--------------------------------------------------------------------------
   */
  app.get('/companies/:id', authenticationUtils.ensureAuthenticated, authenticationUtils.ensureAdmin, function(req, res) {
    var companyId = req.params.id;
    model.Company.find({ where: {id: companyId} }).then(function(company) {
      // rewrite with inclusion
      if(company){
          company.getUsers({attributes: ['displayName']}).success(function(associatedUsers) {
              company.dataValues.owners = (associatedUsers);
              res.send(company);
          })
      }else{
        res.send(company);
      }
    });
  });
  /*
   |--------------------------------------------------------------------------
   | PUT /companies/id
   | return the update company
   | update the companies with id
   |--------------------------------------------------------------------------
   */
  app.put('/companies/:id', authenticationUtils.ensureAuthenticated, authenticationUtils.ensureAdmin, function(req, res) {
    var companyId = req.params.id;

    model.Company.find({where: {id: companyId} }).then(function(company) {
      if (company) { // if the record exists in the db
        company.updateAttributes(req.body).then(function(company) {
          res.send();
        });
      }
    })
  });

  /*
   |--------------------------------------------------------------------------
   | POST /companies/:idCompany/owners/   POST {the id of owner to add}
   | return List of all the companies
   |--------------------------------------------------------------------------
   */
  app.post('/companies/:companyId/owners', authenticationUtils.ensureAuthenticated, authenticationUtils.ensureAdmin, function(req, res) {
    var newOwnerId = req.body.newOwner;
    var companyId = req.params.companyId

    console.log(newOwnerId+" == "+companyId)
    model.Company.find({where: {id: companyId}}).then(function(company) {
      company.getUsers({ where: {id: newOwnerId}}).success(function(users) {
        if(users.length == 0){
            model.User.find({where: {id: newOwnerId}}).then(function(user) {
              company.addUsers(user).success(function() {
                res.send();
              })
            })
        }else{

          console.log("This user waas already associated to this company!")
          // TODO, there were an error, need to fix
        }
      })
    });
  });

  /*
   |--------------------------------------------------------------------------
   | POST /companies/:idCompany/profilePicture/:width/:height   POST {the id of owner to add}
   | return List of all the companies
   |--------------------------------------------------------------------------
   */

  app.post('/companies/:idCompany/profilePicture/:width/:height/',
    authenticationUtils.ensureAuthenticated,
    fileUtils.uploadFunction(fileUtils.localImagePath, fileUtils.remoteImagePath),
    fileUtils.resizeFunction(fileUtils.localImagePath, fileUtils.remoteImagePath),
    function (req, res, next) {
      var idCompany = req.params.idCompany;
      model.Company.find({ where: {id: idCompany} }).then(function(company) {
        var oldLogo = company.logo;
        var oldFullSizeLogo = company.fullSizeLogo;
        company.logo = fileUtils.remoteImagePath(req, req.uploadedFile[0].resizedFilename);
        company.fullSizeLogo = fileUtils.remoteImagePath(req, req.uploadedFile[0].filename);

        company.save().then(function (company) {
          // we remove old avatars from the CDN
          cloudstorage.remove(oldLogo);
          cloudstorage.remove(oldFullSizeLogo);
          // We remove temporarily stored files
          fs.unlink(fileUtils.localImagePath(req, req.uploadedFile[0].filename));
          fs.unlink(fileUtils.localImagePath(req, req.uploadedFile[0].resizedFilename));

          res.writeHead(200, {"content-type":"text/html"});   //http response header
          res.end(JSON.stringify(req.uploadedFile));
        });
      });
  });

}<commit_msg>Add remove company owner API<commit_after>'use strict';

var fs                    = require('fs-extra');

var fileUtils             = rootRequire('utils/file-utils');
var authenticationUtils   = rootRequire('utils/authentication-utils');
var model                 = rootRequire('models/model');
var cloudstorage          = rootRequire('libs/cloudstorage/cloudstorage');

module.exports.controller = function(app) {
  /*
   |--------------------------------------------------------------------------
   | GET /companies/search/
   |--------------------------------------------------------------------------
   */
  app.get('/companies/search/:searchString', authenticationUtils.ensureAuthenticated, authenticationUtils.ensureAdmin, function(req, res) {
    var searchString = req.params.searchString;
    model.Company.find({ where: {displayName: searchString} }).then(function(companies) {
      res.send(companies);
    });
  });

  /*
   |--------------------------------------------------------------------------
   | GET /companies/
   | return List of all the companies
   |--------------------------------------------------------------------------
   */
  app.get('/companies/', authenticationUtils.ensureAuthenticated, authenticationUtils.ensureAdmin, function(req, res) {
    var searchString = req.params.searchString;
    model.Company.findAll().then(function(companies) {
      res.send(companies);
    });
  });

  /*
   |--------------------------------------------------------------------------
   | GET /companies/id/labels
   | return all the companies of the given company
   |--------------------------------------------------------------------------
   */
  app.get('/companies/:id/labels', authenticationUtils.ensureAuthenticated, authenticationUtils.ensureAdmin, function(req, res) {
    var companyId = req.params.id;
    model.Company.find({ where: {id: companyId} }).then(function(company) {
      if(company){
          company.getLabels().success(function(associatedLabels) {
              res.send(associatedLabels);
          })
      }else{
        res.send(company);
      }
    });
  });

  /*
   |--------------------------------------------------------------------------
   | GET /companies/id
   | return The company with id passed as part of the path. Empty object if it doesn't exists.
   | this function has been set to limited to admin only. We may consider at some point to release
   | a lighter way for having an all user access (for promo proposal)
   |--------------------------------------------------------------------------
   */
  app.get('/companies/:id', authenticationUtils.ensureAuthenticated, authenticationUtils.ensureAdmin, function(req, res) {
    var companyId = req.params.id;
    model.Company.find({ where: {id: companyId} }).then(function(company) {
      // rewrite with inclusion
      if(company){
          company.getUsers({attributes: ['displayName']}).success(function(associatedUsers) {
              company.dataValues.owners = (associatedUsers);
              res.send(company);
          })
      }else{
        res.send(company);
      }
    });
  });
  /*
   |--------------------------------------------------------------------------
   | PUT /companies/id
   | return the update company
   | update the companies with id
   |--------------------------------------------------------------------------
   */
  app.put('/companies/:id', authenticationUtils.ensureAuthenticated, authenticationUtils.ensureAdmin, function(req, res) {
    var companyId = req.params.id;

    model.Company.find({where: {id: companyId} }).then(function(company) {
      if (company) { // if the record exists in the db
        company.updateAttributes(req.body).then(function(company) {
          res.send();
        });
      }
    })
  });

  /*
   |--------------------------------------------------------------------------
   | DELETE /companies/:idCompany/owners/:idUser
   | delete the owner idUser in the company idCompany
   |--------------------------------------------------------------------------
   */
  app.delete('/companies/:companyId/owners/:userId', authenticationUtils.ensureAuthenticated, authenticationUtils.ensureAdmin, function(req, res) {
    var ownerId = req.params.userId;
    var companyId = req.params.companyId

    model.Company.find({where: {id: companyId}}).then(function(company) {
      console.log("REMOVE  USER FROM COMPANY")
      company.getUsers({where: {id: ownerId}}).then(function(users) {
        if (users && users.length == 1) {
          company.removeUser(users[0]).success(function() {
            res.send();
          });
        }
      });
    });
  });

  /*
   |--------------------------------------------------------------------------
   | POST /companies/:idCompany/owners/   POST {the id of owner to add}
   | return List of all the companies
   |--------------------------------------------------------------------------
   */
  app.post('/companies/:companyId/owners', authenticationUtils.ensureAuthenticated, authenticationUtils.ensureAdmin, function(req, res) {
    var newOwnerId = req.body.newOwner;
    var companyId = req.params.companyId

    console.log(newOwnerId+" == "+companyId)
    model.Company.find({where: {id: companyId}}).then(function(company) {
      company.getUsers({ where: {id: newOwnerId}}).success(function(users) {
        if(users.length == 0){
            model.User.find({where: {id: newOwnerId}}).then(function(user) {
              company.addUsers(user).success(function() {
                res.send();
              })
            })
        }else{

          console.log("This user waas already associated to this company!")
          // TODO, there were an error, need to fix
        }
      })
    });
  });

  /*
   |--------------------------------------------------------------------------
   | POST /companies/:idCompany/profilePicture/:width/:height   POST {the id of owner to add}
   | return List of all the companies
   |--------------------------------------------------------------------------
   */

  app.post('/companies/:idCompany/profilePicture/:width/:height/',
    authenticationUtils.ensureAuthenticated,
    fileUtils.uploadFunction(fileUtils.localImagePath, fileUtils.remoteImagePath),
    fileUtils.resizeFunction(fileUtils.localImagePath, fileUtils.remoteImagePath),
    function (req, res, next) {
      var idCompany = req.params.idCompany;
      model.Company.find({ where: {id: idCompany} }).then(function(company) {
        var oldLogo = company.logo;
        var oldFullSizeLogo = company.fullSizeLogo;
        company.logo = fileUtils.remoteImagePath(req, req.uploadedFile[0].resizedFilename);
        company.fullSizeLogo = fileUtils.remoteImagePath(req, req.uploadedFile[0].filename);

        company.save().then(function (company) {
          // we remove old avatars from the CDN
          cloudstorage.remove(oldLogo);
          cloudstorage.remove(oldFullSizeLogo);
          // We remove temporarily stored files
          fs.unlink(fileUtils.localImagePath(req, req.uploadedFile[0].filename));
          fs.unlink(fileUtils.localImagePath(req, req.uploadedFile[0].resizedFilename));

          res.writeHead(200, {"content-type":"text/html"});   //http response header
          res.end(JSON.stringify(req.uploadedFile));
        });
      });
  });

}<|endoftext|>


<commit_before>var User = require('../models/User');

var Article = require('../models/Article')

exports.index = function(req,res,next){
	if (  !!req.user ){
		User.findById(req.user._id, function(err, user) {
	  		var pocketConnected = false;
	  		var accessToken = '';
	    	user.tokens.forEach( function(item){
	    		if ( item.kind == 'pocket' ){
	    			pocketConnected = true;
	    			accessToken = item.accessToken
	    		}
	    	})

	    	Article.find({}).where({'email':req.user.email,'status':"0"}).exec( function(err,articles){
	    		var timeRequired = 0;
	    		if ( !articles.length ){
	    			articles = []
	    		} else {

	    			articles.forEach( function(item){
	    				item.final_title = item.resolved_title || item.given_title ||  item.resolved_url || 'Article';
	    				item.estimatedTime = Math.floor(item.word_count/ 200)
	    				timeRequired += item.estimatedTime
	    			})
	    		}

	    		res.render('dashboard',{
		  			pocketConnected: pocketConnected,
		  			accessToken : accessToken,
		  			title : 'Dashboard',
		  			articleCount : articles.length,
		  			timeRequired : timeRequired,
		  			articles : articles
			    })
	    	})
	    });
	} else {
		res.redirect('/');
	}
}<commit_msg>removing 0 min items by using cieling instead of floor)<commit_after>var User = require('../models/User');

var Article = require('../models/Article');

exports.index = function(req,res,next){
	if (  !!req.user ){
		User.findById(req.user._id, function(err, user) {
	  		var pocketConnected = false;
	  		var accessToken = '';
	    	user.tokens.forEach( function(item){
	    		if ( item.kind == 'pocket' ){
	    			pocketConnected = true;
	    			accessToken = item.accessToken;
	    		}
	    	});

	    	Article.find({}).where({'email':req.user.email,'status':"0"}).exec( function(err,articles){
	    		var timeRequired = 0;
	    		if ( !articles.length ){
	    			articles = [];
	    		} else {

	    			articles.forEach( function(item){
	    				item.final_title = item.resolved_title || item.given_title ||  item.resolved_url || 'Article';
	    				item.estimatedTime = Math.ceil(item.word_count/ 200);
	    				timeRequired += item.estimatedTime;
	    			});
	    		}

	    		res.render('dashboard',{
		  			pocketConnected: pocketConnected,
		  			accessToken : accessToken,
		  			title : 'Dashboard',
		  			articleCount : articles.length,
		  			timeRequired : timeRequired,
		  			articles : articles
			    });
	    	});
	    });
	} else {
		res.redirect('/');
	}
};<|endoftext|>


<commit_before>

var canvasWidth = 800;
var canvasHeight = 800;
var x = 100;
var y = 100;
var xspeed = 2.5;
var yspeed = 2;

var radius = 350;
var angle = 0;
var clock = true;
var DEBUG = false;
var shared = {};
var rollingBack = false;

var STATE_IDLE = 0;
var STATE_HITTING = 1;
var STATE_GAMEOVER = 3;
var STATE_ROLLINGBACK = 2;

var state = STATE_IDLE;

function setup() {
  createCanvas(canvasWidth, canvasHeight);
  shared.circleColors = [
      color(230, 143, 143),
      color(125, 240, 125),
      color(0, 0, 240),
      color(250, 0, 250),
      color(250, 0, 0),
      color(255, 222, 8)];

  shared.colorSize = shared.circleColors.length;
  shared.hitted = false;
  shared.lineColorIndex = randomExclude(0, shared.colorSize -1, 1);

  shared.buttonRestart = new Button({
      label: "You failed\nClick to Restart!"
  });
  shared.buttonRestart.centerSize(canvasWidth/2, canvasHeight/2, 200, 100);
};
var crossed = false;
var lastHit = false;
var randomInt = function(low, high) {
    var result =  floor(random(low, high + 1));
    if(result === high+1) {
        result = low;
    }
    return result;
};

var randomExclude = function(low, high, exclude) {
    var result = randomInt(low, high-1);
    if(result >= exclude) {
        result = exclude + 1;
    }
    return result;
};

function drawBackground() {
  //fill(100，100，100);
  fill(100, 100, 100);
  rect(0, 0, canvasWidth, canvasHeight);
}

function drawBall() {
  x = x + xspeed;
  y = y + yspeed;

  if ((x > width) || (x < 0)) {
    xspeed = xspeed * -1;
  }
  if ((y > height) || (y < 0)) {
    yspeed = yspeed * -1;
  }
  stroke(0);
  strokeWeight(2);
  fill(255, 0, 0);
  ellipse(x, y, 48, 48);
}

function rectLeftTop() {
  noStroke();
  fill(0, 255, 1);
  rect(0, 0, 50, 30);
}

function drawLine() {
  //line
  stroke(0, 173, 0);
  strokeWeight(4);
  line(0, 0, 100, 310);
}

function drawArc() {
  strokeWeight(2);
  arc(100, 100, 200, 200, 0, 80);
}

function rad(angle) {
   return angle / 180 * Math.PI;
}

function mousePressed() {
    if (state === STATE_GAMEOVER) {
      state = STATE_IDLE;
      angle = 0;
      //shared.lineColorIndex = randomExclude(0, 0 shared.lineColorIndex);
      return;
    } else if (state !== STATE_HITTING) {
      console.log("gameOver because !crossed!");
      state = STATE_GAMEOVER;
      return;
    } else {//HITTING
      clock = !clock;
      state = STATE_ROLLINGBACK;
      shared.lineColorIndex = randomExclude(0, shared.colorSize -1, shared.lineColorIndex);
    }
};

function draw() {
  //background(51);
  if(state  == STATE_GAMEOVER) {
    shared.buttonRestart.draw();
    return;
  }
  drawBackground();
  noFill();
  var centerX = canvasWidth / 2;
  var centerY = canvasHeight / 2;
  var circleColors = shared.circleColors;

  var range = 360 / shared.circleColors.length;
  if(DEBUG) {
    console.log("length: " + shared.circleColors.length);
    console.log("range: " + range);
  }
  var angleBegin = 0;
  strokeWeight(2);

  for(var i = 0; i < circleColors.length; i++) {
      stroke(circleColors[i]);
      arc(centerX, centerY, radius * 2, radius * 2, rad(angleBegin), rad(angleBegin + range));
      angleBegin = angleBegin + range;
  }
  var gameOver = (state === STATE_GAMEOVER);
  if(!gameOver) {
    angle += (clock ?  1 : -1) * 5;
    if(angle > 360) {
        angle -= 360;
    }
    if(angle < 0) {
        angle += 360;
    }
  }
  var colorIndex = floor((angle/range)) % circleColors.length;
  if(DEBUG) {
      println("range : " + range + " angle: " + angle + "colorIndex: " + colorIndex);
  }
  var currentColor = circleColors[colorIndex];
  stroke(circleColors[shared.lineColorIndex]);
  line(centerX, centerY, centerX + radius * cos(rad(angle)), centerY + radius * sin(rad(angle)));
  var hit = (colorIndex == shared.lineColorIndex);
  console.log("colorIndex : " + colorIndex + "  lineColorIndex : " + shared.lineColorIndex);
  if (hit) {
     console.log("hit");
  }
  console.log("old state : " + state);
  if (state === STATE_ROLLINGBACK) {
     if(!hit) {
       state = STATE_IDLE;
     }
  }else if(state === STATE_IDLE) {
     if(hit) {
       state = STATE_HITTING;
     }
  }else if(state === STATE_HITTING) {
     if(!hit) {
      state = STATE_GAMEOVER;
     }
  }else if(state === STATE_ROLLINGBACK) {
    if(!hit){
      state = STATE_IDLE;
    }
  }
  console.log("new state : " + state);

};

<commit_msg>sppeda<commit_after>

var canvasWidth = 800;
var canvasHeight = 800;
var x = 100;
var y = 100;
var xspeed = 2.5;
var yspeed = 2;

var radius = 350;
var angle = 0;
var clock = true;
var DEBUG = false;
var shared = {};
var rollingBack = false;

var STATE_IDLE = 0;
var STATE_HITTING = 1;
var STATE_GAMEOVER = 3;
var STATE_ROLLINGBACK = 2;

var state = STATE_IDLE;

function setup() {
  createCanvas(canvasWidth, canvasHeight);
  shared.circleColors = [
      color(230, 143, 143),
      color(125, 240, 125),
      color(0, 0, 240),
      color(250, 0, 250),
      color(250, 0, 0),
      color(255, 222, 8)];

  shared.colorSize = shared.circleColors.length;
  shared.hitted = false;
  shared.lineColorIndex = randomExclude(0, shared.colorSize -1, 1);

  shared.buttonRestart = new Button({
      label: "You failed\nClick to Restart!"
  });
  shared.buttonRestart.centerSize(canvasWidth/2, canvasHeight/2, 200, 100);
};
var crossed = false;
var lastHit = false;
var randomInt = function(low, high) {
    var result =  floor(random(low, high + 1));
    if(result === high+1) {
        result = low;
    }
    return result;
};

var randomExclude = function(low, high, exclude) {
    var result = randomInt(low, high-1);
    if(result >= exclude) {
        result = exclude + 1;
    }
    return result;
};

function drawBackground() {
  //fill(100，100，100);
  fill(100, 100, 100);
  rect(0, 0, canvasWidth, canvasHeight);
}

function drawBall() {
  x = x + xspeed;
  y = y + yspeed;

  if ((x > width) || (x < 0)) {
    xspeed = xspeed * -1;
  }
  if ((y > height) || (y < 0)) {
    yspeed = yspeed * -1;
  }
  stroke(0);
  strokeWeight(2);
  fill(255, 0, 0);
  ellipse(x, y, 48, 48);
}

function rectLeftTop() {
  noStroke();
  fill(0, 255, 1);
  rect(0, 0, 50, 30);
}

function drawLine() {
  //line
  stroke(0, 173, 0);
  strokeWeight(4);
  line(0, 0, 100, 310);
}

function drawArc() {
  strokeWeight(2);
  arc(100, 100, 200, 200, 0, 80);
}

function rad(angle) {
   return angle / 180 * Math.PI;
}

function mousePressed() {
    if (state === STATE_GAMEOVER) {
      state = STATE_IDLE;
      angle = 0;
      //shared.lineColorIndex = randomExclude(0, 0 shared.lineColorIndex);
      return;
    } else if (state !== STATE_HITTING) {
      console.log("gameOver because !crossed!");
      state = STATE_GAMEOVER;
      return;
    } else {//HITTING
      clock = !clock;
      state = STATE_ROLLINGBACK;
      shared.lineColorIndex = randomExclude(0, shared.colorSize -1, shared.lineColorIndex);
    }
};

function draw() {
  //background(51);
  if(state  == STATE_GAMEOVER) {
    shared.buttonRestart.draw();
    return;
  }
  drawBackground();
  noFill();
  var centerX = canvasWidth / 2;
  var centerY = canvasHeight / 2;
  var circleColors = shared.circleColors;

  var range = 360 / shared.circleColors.length;
  if(DEBUG) {
    console.log("length: " + shared.circleColors.length);
    console.log("range: " + range);
  }
  var angleBegin = 0;
  strokeWeight(2);

  for(var i = 0; i < circleColors.length; i++) {
      stroke(circleColors[i]);
      arc(centerX, centerY, radius * 2, radius * 2, rad(angleBegin), rad(angleBegin + range));
      angleBegin = angleBegin + range;
  }
  var gameOver = (state === STATE_GAMEOVER);
  if(!gameOver) {
    angle += (clock ?  1 : -1) * 8;
    if(angle > 360) {
        angle -= 360;
    }
    if(angle < 0) {
        angle += 360;
    }
  }
  var colorIndex = floor((angle/range)) % circleColors.length;
  if(DEBUG) {
      println("range : " + range + " angle: " + angle + "colorIndex: " + colorIndex);
  }
  var currentColor = circleColors[colorIndex];
  stroke(circleColors[shared.lineColorIndex]);
  line(centerX, centerY, centerX + radius * cos(rad(angle)), centerY + radius * sin(rad(angle)));
  var hit = (colorIndex == shared.lineColorIndex);
  console.log("colorIndex : " + colorIndex + "  lineColorIndex : " + shared.lineColorIndex);
  if (hit) {
     console.log("hit");
  }
  console.log("old state : " + state);
  if (state === STATE_ROLLINGBACK) {
     if(!hit) {
       state = STATE_IDLE;
     }
  }else if(state === STATE_IDLE) {
     if(hit) {
       state = STATE_HITTING;
     }
  }else if(state === STATE_HITTING) {
     if(!hit) {
      state = STATE_GAMEOVER;
     }
  }else if(state === STATE_ROLLINGBACK) {
    if(!hit){
      state = STATE_IDLE;
    }
  }
  console.log("new state : " + state);

};

<|endoftext|>


<commit_before>function Phonebook(){
	var record = [];
}

Phonebook.prototype.readFile = function(element,replace) {
	var input = element;
	if (!input.files.length) {
		displayAlert('Please select a file!');
		return;
	}
	if(replace){
		this.record = [];
	}

	var file = input.files[0];
	input.value = "";
	var reader = new FileReader();
	reader.onloadend = function(e) {
		if (e.target.readyState == FileReader.DONE) {
			var json = e.target.result;
			try{
				var pb = JSON.parse(json);
			}catch(e){
				displayAlert("File is not valid");
				return;
			}
			var l = pb.length;
			var k = 0;
			for (var i = 0; i < l; i++) {
				if (isDuplicate(pb[i])){
					k++
					continue;
				}
				if (!pb[i].hasOwnProperty('name') || !checkName(pb[i].name)){
					k++;
					continue;
				}
				if (!pb[i].hasOwnProperty('surname') || !checkName(pb[i].surname) ){
					k++;
					continue;
				}
				if (!pb[i].hasOwnProperty('number') || !checkNumber(pb[i].number)){
					k++;
					continue;
				}
				this.record.push(pb[i]);
			}
			if (k > 0){
				displayAlert("Error: Phonebook loaded, but "+k+" record/s have been ignored because they are not valid");
			}
			else {
				displayAlert("Phonebook loaded successfully!");
			}
			//search();
		}
	}
	reader.readAsBinaryString(file);
}

Phonebook.prototype.search = function(text) {
	function search(){
	var search = document.getElementById('search').value.trim() + "£";
	search = search.replace(/surname:/i,"£2");
	search = search.replace(/name:/i,"£1");
	search = search.replace(/number:/i,"£3");
	var l = phonebook.length;
	var result = [];
	for (var i = 0; i < l; i++){
		var case1=/£1/.test(search);
		var case2=/£2/.test(search);
		var case3=/£3/.test(search);
		if (case1 || case2 || case3){
			var match1 = false;
			var match2 = false;
			var match3 = false;
			if(case1){
				var r = search.match(/£1(.*?) *£/)[1].trim();
				var regexp = new RegExp(r,"i");
				if(regexp.test(phonebook[i].name)){
					match1 = true;
				}
			}
			if(case2) {
				var r = search.match(/£2(.*?) *£/)[1].trim();
				var regexp = new RegExp(r,"i");
				if(regexp.test(phonebook[i].surname)){
					match2 = true;
				}
			}
			if(case3) {
				var r = search.match(/£3(.*?) *£/)[1].trim();
				var regexp = new RegExp(r,"i");
				if(regexp.test(phonebook[i].number)){
					match3 = true;
				}
			}
			if((case1 == match1)&&(case2 == match2)&&(case3 == match3)){
				var temp = {
					"name" : phonebook[i].name,
					"surname" : phonebook[i].surname,
					"number" : phonebook[i].number,
					"id" : i
				}
				result.push(temp);
			}
		} else {
			var regexp = search.slice(0,-1).split(" ");
			var text = phonebook[i].name + " " + phonebook[i].surname + " " + phonebook[i].number;
			var match = true;
			for (var j = 0; j < regexp.length; j++) {
				regexp[j] = new RegExp(regexp[j], "i");
				if(!regexp[j].test(text)){
					match = false;
					break;
				}
			}
			if(match){
				var temp = {
					"name" : phonebook[i].name,
					"surname" : phonebook[i].surname,
					"number" : phonebook[i].number,
					"id" : i
				}
				result.push(temp);
			}
		}
	}
	//toHtml(result);
	return result;
}
};<commit_msg>add "all" prototype<commit_after>function Phonebook(){
	this.records = [];
}

Phonebook.prototype.readFile = function(element,callback) {
	var input = element;
	if (!input.files.length) {
		this.displayAlert('Please select a file!');
		return;
	}
	var that = this;
	var file = input.files[0];
	input.value = "";
	var reader = new FileReader();
	reader.onloadend = function(e) {
		if (e.target.readyState == FileReader.DONE) {
			var json = e.target.result;
			try{
				var pb = JSON.parse(json);
			}catch(e){
				that.displayAlert("File is not valid");
				return;
			}
			var l = pb.length;
			var k = 0;
			for (var i = 0; i < l; i++) {
				if (that.isDuplicate(pb[i])){
					k++
					continue;
				}
				if (!pb[i].hasOwnProperty('name') || !that.checkName(pb[i].name)){
					k++;
					continue;
				}
				if (!pb[i].hasOwnProperty('surname') || !that.checkName(pb[i].surname) ){
					k++;
					continue;
				}
				if (!pb[i].hasOwnProperty('number') || !that.checkNumber(pb[i].number)){
					k++;
					continue;
				}
				pb[i].name = pb[i].name.trim();
				pb[i].surname = pb[i].surname.trim();
				pb[i].number = pb[i].number.trim();
				that.records.push(pb[i]);
			}
			if (k > 0){
				that.displayAlert("Error: Phonebook loaded, but "+k+" record/s have been ignored because they are not valid");
			}
			else {
				that.displayAlert("Phonebook loaded successfully!");
			}
			callback();
		}
	}
	reader.readAsBinaryString(file);
}

Phonebook.prototype.search = function(text) {
	var search = text.trim() + "£";
	search = search.replace(/surname:/i,"£2");
	search = search.replace(/name:/i,"£1");
	search = search.replace(/number:/i,"£3");
	var l = this.records.length;
	var result = [];
	for (var i = 0; i < l; i++){
		var case1=/£1/.test(search);
		var case2=/£2/.test(search);
		var case3=/£3/.test(search);
		if (case1 || case2 || case3){
			var match1 = false;
			var match2 = false;
			var match3 = false;
			if(case1){
				var r = search.match(/£1(.*?) *£/)[1].trim();
				var regexp = new RegExp(r,"i");
				if(regexp.test(this.records[i].name)){
					match1 = true;
				}
			}
			if(case2) {
				var r = search.match(/£2(.*?) *£/)[1].trim();
				var regexp = new RegExp(r,"i");
				if(regexp.test(this.records[i].surname)){
					match2 = true;
				}
			}
			if(case3) {
				var r = search.match(/£3(.*?) *£/)[1].trim();
				var regexp = new RegExp(r,"i");
				if(regexp.test(this.records[i].number)){
					match3 = true;
				}
			}
			if((case1 == match1)&&(case2 == match2)&&(case3 == match3)){
				var temp = {
					"name" : this.records[i].name,
					"surname" : this.records[i].surname,
					"number" : this.records[i].number,
					"id" : i
				}
				result.push(temp);
			}
		} else {
			var regexp = search.slice(0,-1).split(" ");
			var text = this.records[i].name + " " + this.records[i].surname + " " + this.records[i].number;
			var match = true;
			for (var j = 0; j < regexp.length; j++) {
				regexp[j] = new RegExp(regexp[j], "i");
				if(!regexp[j].test(text)){
					match = false;
					break;
				}
			}
			if(match){
				var temp = {
					"name" : this.records[i].name,
					"surname" : this.records[i].surname,
					"number" : this.records[i].number,
					"id" : i
				}
				result.push(temp);
			}
		}
	}
	return result;
}

Phonebook.prototype.displayAlert = function(text){
	try {
		var alert = document.getElementById('alert');
		alert.style.display = "block";
		alert.innerHTML = text;
		window.setTimeout(function(){alert.style.display = "none"}, 3000);
	} catch(e){
		console.log(e+" Element 'alert' doesn't exist");
	}
}

Phonebook.prototype.isDuplicate = function(e){
	bool = false;
	for (var i = 0; i < this.records.length; i++) {
		if(this.records[i].name == e.name && this.records[i].surname == e.surname && this.records[i].number == e.number){
			bool = true;
			break;
		}
	}
	return bool;
}

Phonebook.prototype.checkName = function(name) {
	var regexp = /^[\w ]+$/;
	return regexp.test(name);
}

Phonebook.prototype.checkNumber = function(n) {
	var regexp = /^\+\d{1,3} \d+ \d{6,}$/;
	return regexp.test(n);
}

Phonebook.prototype.clear = function() {
	this.records=[];
	return;
}

Phonebook.prototype.toString = function() {
	if(this.records.length) {
		return JSON.stringify(this.records);
	} else {
		return false;
	}
}

Phonebook.prototype.newRecord = function(name,surname,number) {
	if(this.checkName(name) && this.checkName(surname) && this.checkNumber(number)){
		var e = {
			"name" : name,
			"surname" : surname,
			"number" : number
		};
		if(this.isDuplicate(e)){
			this.displayAlert("This record already exists");
		} else {
			this.records.push(e);
			this.displayAlert("New record added");
			return true;
		}
	} else {
		return false;
	}
}

Phonebook.prototype.editRecord = function(i,name,surname,number) {
	if(this.checkName(name) && this.checkName(surname) && this.checkNumber(number)){
		var e = {
			"name" : name,
			"surname" : surname,
			"number" : number
		};
		if(this.isDuplicate(e)){
			return 1;
		} else {
			this.records[i].name = name;
			this.records[i].surname = surname;
			this.records[i].number = number;
			return 2;
		}
	} else {
		return false;
	}
}

Phonebook.prototype.removeRecord = function(i) {
	this.records.splice(i,1);
};<|endoftext|>


<commit_before>window.define = function(factory) {
    try{ delete window.define; } catch(e){ window.define = void 0; } // IE
    window.when = factory();
};
window.define.amd = {};<commit_msg>small change<commit_after>;(function(global){
    var mapping = {}, cached = {};
    global.define = function(id, func){
        mapping[id] = func;
    };
    global.require = function(id){
        if(cached[id])
            return cached[id];
        else
            return cached[id] = mapping[id]({});
    };
})(this);<|endoftext|>


<commit_before>'use strict';

// Call this function when the page loads (the "ready" event)
$(document).ready(function() {
    var emotions = JSON.parse($("#emotionJSON").val());
    addGraph(emotions);

})

//fake data for now
//var emotions = [
 // {"emotion":"happy", "count":5},
 // {"emotion":"tired", "count":2},
 // {"emotion":"sad", "count":4},
//];

//this is just playing around with d3 api

function addGraph(emotions) {
  var data = emotions.slice();
  for(var i = 0; i < data.length; i++) {
    if (data[i]['_id']=='default') {
      data.splice(i, 1);
      break;
    }
  }
  var w = 400;
  var h = 400;
  var x = d3.scale.linear()
    .domain([0, d3.max(data, function(d) {return d.count; })])
    .range([0, w-150]);

  console.log(data);
  console.log("adding svg");
  var canvas = d3.select(".container").append("svg")
                .attr("width", w)
                .attr("height", h)
              .append("g")
                //.attr("transform", "translate(20,0)");

  var bars = canvas.selectAll(".bar")
     .data(data)
     .enter().append("g")
     .attr("class", "bar")
     //.attr("transform", function(d, i ) {return "translate("+0+","+(i*50) + ")"});

  bars.append("rect")
   .on("click", function(d){click(d)})
   .attr("y", function(d,i) {return i * 50;})
   .attr("width", 0)
   .attr("height", 45)
   .attr("fill", "white")
   .transition()
    .duration(300)
    //.ease("quad")
    .attr("width", function(d) {return x(d.count); });

  bars.append("text")
       .attr("x", function(d) {return x(d.count); })
       .attr("dx", 10)
       .attr("y", function(d,i) {return i * 50 + 25;})
       .attr("text-anchor", "start")
       .attr("fill", "#196966")
       .text(function (d) {return d._id+" ("+d.count+")"; });

  function click(d) {
    console.log(d._id);
    window.location.href="/search?queryString="+d._id+"&queryField=emotion";
  }
}<commit_msg>fixed graphs<commit_after>'use strict';

// Call this function when the page loads (the "ready" event)
$(document).ready(function() {
    var emotions = JSON.parse($("#emotionJSON").val());
    addGraph(emotions);

})

function addGraph(emotions) {
  var data = emotions.slice();
  for(var i = 0; i < data.length; i++) {
    if (data[i]['_id']=='default') {
      data.splice(i, 1);
      break;
    }
  }
  var w = 300;
  var h = 400;
  var x = d3.scale.linear()
    .domain([0, d3.max(data, function(d) {return d.count; })])
    .range([0, w-90]);

  var canvas = d3.select(".container").append("svg")
                .attr("width", w)
                .attr("height", h)
              .append("g")
                //.attr("transform", "translate(20,0)");

  var bars = canvas.selectAll(".bar")
     .data(data)
     .enter().append("g")
     .attr("class", "bar")
     //.attr("transform", function(d, i ) {return "translate("+0+","+(i*50) + ")"});

  bars.append("rect")
   .on("click", function(d){click(d)})
   .attr("y", function(d,i) {return i * 50;})
   .attr("width", 0)
   .attr("height", 45)
   .attr("fill", "white")
   .transition()
    .duration(300)
    //.ease("quad")
    .attr("width", function(d) {return x(d.count); });

  bars.append("text")
       .attr("x", function(d) {return x(d.count); })
       .attr("dx", 10)
       .attr("y", function(d,i) {return i * 50 + 25;})
       .attr("text-anchor", "start")
       .attr("fill", "#196966")
       .text(function (d) {return d._id+" ("+d.count+")"; });

  function click(d) {
    window.location.href="/search?queryString="+d._id+"&queryField=emotion";
  }
}<|endoftext|>


<commit_before>//var data = require('explore.json');

//get dishes json data
    var dishes;
    var bookmarks;
    //for current dish
    var curr;
    var i = 0; //tracker number
    var face = false;
    var ups = false;
    var downs = false;
    var complete = false;

$(document).ready(function() {

    //get JSON data with first
    console.log("BEFORE EXPLORE!");

    //get json array data
    $.get('/addExplore', function(data) {
        dishes = data;
        console.log("getJSON activated!");
        console.log(dishes);
         //loading slideshow
        curr = dishes.dishes[i];
        console.log(curr);
        var name = curr.dishName;
        console.log("name variable testing..." + name);
        var im = "../" + curr.imgURL;
        console.log("Image is..." + im);
        $('#dish_img').attr('src', im);
        console.log(dishes.dishes.length);
    });

    //move to next dish image
    $('#next').click(function() {
      //change current dish number
      i = i+1;
      console.log(i);
      curr = dishes.dishes[i];

      console.log(curr);
      var im = curr.imgURL;
      $('#dish_img').attr('src', im);
      console.log(dishes.length);
    });

    $('#prev').click(function() {
      i = i-1;
      console.log(i);
      curr = dishes.dishes[i];

      console.log(curr);
      var im = curr.imgURL;
      $('#dish_img').attr('src', im);
      console.log(dishes.length);
    });

    $('#dish_img').click(function() {
            localStorage.setItem('rate', i);
            console.log("ajax testing...");

        });

    //push new dish into your bookmarks
    $('#book_button').click(function() {
      console.log(bookmarks);
      alert(curr.dishName + " bookmarked!");
      var newBMK = {
        'dishName' : curr.dishName,
        'restaurantName' : curr.restaurantName,
        'imgURL' : curr.imgURL,
        'address' : 'SD, CA'
      }
      console.log("BMK push testing...")
      console.log(newBMK);

      $.get(
        "/addBookmark",
        {
          'dishName' : curr.dishName,
          'restaurantName' : curr.restaurantName,
          'imgURL' : curr.imgURL,
          'address' : curr.address
        }
      );
    })

  });
<commit_msg>add google analytics<commit_after>//var data = require('explore.json');

//get dishes json data
    var dishes;
    var bookmarks;
    //for current dish
    var curr;
    var i = 0; //tracker number
    var face = false;
    var ups = false;
    var downs = false;
    var complete = false;

$(document).ready(function() {

    //get JSON data with first
    console.log("BEFORE EXPLORE!");

    //get json array data
    $.get('/addExplore', function(data) {
        dishes = data;
        console.log("getJSON activated!");
        console.log(dishes);
         //loading slideshow
        curr = dishes.dishes[i];
        console.log(curr);
        var name = curr.dishName;
        console.log("name variable testing..." + name);
        var im = "../" + curr.imgURL;
        console.log("Image is..." + im);
        $('#dish_img').attr('src', im);
        console.log(dishes.dishes.length);
    });

    //move to next dish image
    $('#next').click(function() {
      //change current dish number
      i = i+1;
      console.log(i);
      curr = dishes.dishes[i];

      console.log(curr);
      var im = curr.imgURL;
      $('#dish_img').attr('src', im);
      console.log(dishes.length);
    });

    $('#prev').click(function() {
      i = i-1;
      console.log(i);
      curr = dishes.dishes[i];

      console.log(curr);
      var im = curr.imgURL;
      $('#dish_img').attr('src', im);
      console.log(dishes.length);
    });

    $('#dish_img').click(function() {
            localStorage.setItem('rate', i);
            console.log("ajax testing...");

        });

    //push new dish into your bookmarks
    $('#book_button').click(function() {
      console.log(bookmarks);
      alert(curr.dishName + " bookmarked!");
      ga("send", "event", "bookmark", "click");
      var newBMK = {
        'dishName' : curr.dishName,
        'restaurantName' : curr.restaurantName,
        'imgURL' : curr.imgURL,
        'address' : 'SD, CA'
      }
      console.log("BMK push testing...")
      console.log(newBMK);

      $.get(
        "/addBookmark",
        {
          'dishName' : curr.dishName,
          'restaurantName' : curr.restaurantName,
          'imgURL' : curr.imgURL,
          'address' : curr.address
        }
      );
    })

  });
<|endoftext|>


<commit_before>function fileSelector(base, options, callback) {
	if (typeof options == 'function') {
		callback = options;
		options = {};
	}
	getDirContents(base, function(files){
		options = $.extend(true, {
			types: [/.*/], // MIMEtypes to accept
			multiple: false, // let multiple files be selected
			preview: true, // show a little info about the file
			nosel: false, // allow dialog to be closed without a file having been selected
			buttonLabel: _('filesel-button-open'), // text to be shown on OK button
			name: '', // text to be initially placed in text input
			_: _,
			imageForFile: imageForFile,
			dialog: {
				title: _('filesel-title-open'),
				close: function(e){
					if (e.currentTarget) { // clicked X in corner
						callback(null);
					}
				},
				modal: true,
				minHeight: 600,
				minWidth: 600,
				height: $(window).height()/1.1,
				width: $(window).width()/1.5
			}
		}, options, {dialog: {buttons: []}});
		options.dialog.buttons[0] = {text: _('filesel-button-cancel'), click: function() {
			$(this).dialog('close').dialog('destroy').remove();
			callback(null);
		}};
		options.dialog.buttons[1] = {
			text: options.buttonLabel,
			icons: {primary: 'ui-icon-check'},
			disabled: !options.nosel,
			class: 'ok',
			click: function() {
				var selected = $('#filesel .files .file.sel'), name = $('#filesel-name').val();
				if (selected.length) {
					if (options.multiple) { // we need an array, even if just one was selected
						selected = selected.map(function(){return new LBFile($(this).data('info'))}).get();
					} else {
						selected = new LBFile(selected.data('info'));
					}
					console.log(selected)
				} else {
					selected = null;
				}
				$(this).dialog('close').dialog('destroy').remove();
				callback({name:name,selected:selected});
			}
		};
		function filesFilter(){ // filter by type
			return options.types.filter(function(reg){
				return reg.test(this.type);
			}, this).length;
		}
		options.files = (s.dirFirst?
			files({type:'directory'}).filter(filesFilter).order(s.sortby).get().concat(
				files({type:{'!is':'directory'}}).filter(filesFilter).order(s.sortby).get())
			:files(filesFilter).order(s.sortby).get()).
			map(function(i){return new LBFile(i)});

		var dialog = $(jade.render('filesel',options));
		$('.sidebar',dialog).append($('#sidebar-places li').clone().add(
			$('#sidebar-bookmarks li').clone().each(function(){$('span[title]',this).remove()})
		));
		dialog = $(dialog).dialog(options.dialog);
		$('button.newfolder',dialog).button();
		$('.pathbar',dialog).buttonset().height(41);
		pathbar(base, $('.pathbar',dialog), 41);
		$('#filesel .content').height($('#filesel').height()-$('#filesel .top').height()-10);
		$('#filesel').data('base',base);
		$('#filesel').data('types',options.types);
		$('#filesel').data('callback',callback);
	});
}

fileSelector.updatePreview = function() {
	if ($('#filesel').hasClass('preview') && $('#filesel .sel').length) {
		var info = new LBFile($('#filesel .sel.last').data('info'));
		console.log(info);
		$('#filesel .preview').html(jade.render('filesel.preview',{
			info: info,
			_: _,
			imageForFile: imageForFile,
			count: $('#filesel .sel').length
		}));
	} else {
		$('#filesel .preview').html('
'+_('filesel-none-selected')+'
');
	}
	$('#filesel').parents('.ui-dialog').find('.ui-dialog-buttonset button.ok').button(
		'option', 'disabled', $('#filesel').hasClass('forcesel') && $('#filesel .sel').length<1);
};

$(d).on('click','#filesel .files .file', function(e){
	if ($(this).hasClass('sel')) {
		if ($('#filesel').hasClass('multiple') && e.ctrlKey && $('#filesel .sel').length>1) {
			$(this).removeClass('sel');
			if ($(this).hasClass('last')) {
				if ($(this).nextAll('.sel').length) {$(this).nextMatching('.sel').addClass('last')}
				else if ($(this).prevAll('.sel').length) {$(this).prevMatching('.sel').addClass('last')}
				else {$('#filesel .sel').add(this).removeClass('last')}
			}
		}
		else if ($('#filesel').hasClass('nosel') && $('#filesel .sel').length==1) {
			$(this).removeClass('sel last');
		} else {
			$('#filesel .sel').removeClass('sel');
			$(this).addClass('sel last');
		}
	} else {
		$('#filesel .last').removeClass('last');
		if (!e.ctrlKey || !$('#filesel').hasClass('multiple')) {$('#filesel .sel').removeClass('sel')}
		$(this).addClass('sel last');
	}
	fileSelector.updatePreview();
});
$(d).on('dblclick','#filesel .files .file', function(){
	if ($(this).data('info').type=='directory') { // "cd" to the dir
		var info = [
			$(this).data('path'),
			{
				types: $('#filesel').data('types'),
				multiple: $('#filesel').hasClass('multiple'),
				preview: $('#filesel').hasClass('preview'),
				nosel: $('#filesel').hasClass('nosel'),
				buttonLabel: $('#filesel').parents('.ui-dialog').
					find('.ui-dialog-buttonset button.ok').button('option','label'),
				name: $('#filesel-name').val()
			},
			$('#filesel').data('callback'),
		];
		$('#filesel').dialog('close').dialog('destroy').remove();
		fileSelector.apply(null,info);
	} else {
		$('#filesel').parents('.ui-dialog').find('.ui-dialog-buttonset button.ok').click();
	}
});

//clearInterval(refresh)<commit_msg>filesel: Pass callback 2 arguments: selected LBFile(s), and name. Used to put them together in an object.<commit_after>function fileSelector(base, options, callback) {
	if (typeof options == 'function') {
		callback = options;
		options = {};
	}
	getDirContents(base, function(files){
		options = $.extend(true, {
			types: [/.*/], // MIMEtypes to accept
			multiple: false, // let multiple files be selected
			preview: true, // show a little info about the file
			nosel: false, // allow dialog to be closed without a file having been selected
			buttonLabel: _('filesel-button-open'), // text to be shown on OK button
			name: '', // text to be initially placed in text input
			_: _,
			imageForFile: imageForFile,
			dialog: {
				title: _('filesel-title-open'),
				close: function(e){
					if (e.currentTarget) { // clicked X in corner
						callback(null);
					}
				},
				modal: true,
				minHeight: 600,
				minWidth: 600,
				height: $(window).height()/1.1,
				width: $(window).width()/1.5
			}
		}, options, {dialog: {buttons: []}});
		options.dialog.buttons[0] = {text: _('filesel-button-cancel'), click: function() {
			$(this).dialog('close').dialog('destroy').remove();
			callback(null);
		}};
		options.dialog.buttons[1] = {
			text: options.buttonLabel,
			icons: {primary: 'ui-icon-check'},
			disabled: !options.nosel,
			class: 'ok',
			click: function() {
				var selected = $('#filesel .files .file.sel'), name = $('#filesel-name').val();
				if (selected.length) {
					if (options.multiple) { // we need an array, even if just one was selected
						selected = selected.map(function(){return new LBFile($(this).data('info'))}).get();
					} else {
						selected = new LBFile(selected.data('info'));
					}
					console.log(selected)
				} else {
					selected = null;
				}
				$(this).dialog('close').dialog('destroy').remove();
				callback(selected,LBFile.path.join(base,name));
			}
		};
		function filesFilter(){ // filter by type
			if (options.types[0]==/.*/) {return true}
			return options.types.filter(function(reg){
				return reg.test(this.type);
			}, this).length;
		}
		options.files = (s.dirFirst?
			files({type:'directory'}).filter(filesFilter).order(s.sortby).get().concat(
				files({type:{'!is':'directory'}}).filter(filesFilter).order(s.sortby).get())
			:files(filesFilter).order(s.sortby).get()).
			map(function(i){return new LBFile(i)});

		var dialog = $(jade.render('filesel',options));
		$('.sidebar',dialog).append($('#sidebar-places li').clone().add(
			$('#sidebar-bookmarks li').clone().each(function(){$('span[title]',this).remove()})
		));
		dialog = $(dialog).dialog(options.dialog);
		$('button.newfolder',dialog).button();
		$('.pathbar',dialog).buttonset().height(41);
		pathbar(base, $('.pathbar',dialog), 41);
		$('#filesel .content').height($('#filesel').height()-$('#filesel .top').height()-10);
		$('#filesel').data('base',base);
		$('#filesel').data('types',options.types);
		$('#filesel').data('callback',callback);
	});
}

fileSelector.updatePreview = function() {
	if ($('#filesel').hasClass('preview') && $('#filesel .sel').length) {
		var info = new LBFile($('#filesel .sel.last').data('info'));
		console.log(info);
		$('#filesel .preview').html(jade.render('filesel.preview',{
			info: info,
			_: _,
			imageForFile: imageForFile,
			count: $('#filesel .sel').length
		}));
	} else {
		$('#filesel .preview').html('
'+_('filesel-none-selected')+'
');
	}
	$('#filesel').parents('.ui-dialog').find('.ui-dialog-buttonset button.ok').button(
		'option', 'disabled', $('#filesel').hasClass('forcesel') && $('#filesel .sel').length<1);
};

$(d).on('click','#filesel .files .file', function(e){
	if ($(this).hasClass('sel')) {
		if ($('#filesel').hasClass('multiple') && e.ctrlKey && $('#filesel .sel').length>1) {
			$(this).removeClass('sel');
			if ($(this).hasClass('last')) {
				if ($(this).nextAll('.sel').length) {$(this).nextMatching('.sel').addClass('last')}
				else if ($(this).prevAll('.sel').length) {$(this).prevMatching('.sel').addClass('last')}
				else {$('#filesel .sel').add(this).removeClass('last')}
			}
		}
		else if ($('#filesel').hasClass('nosel') && $('#filesel .sel').length==1) {
			$(this).removeClass('sel last');
		} else {
			$('#filesel .sel').removeClass('sel');
			$(this).addClass('sel last');
		}
	} else {
		$('#filesel .last').removeClass('last');
		if (!e.ctrlKey || !$('#filesel').hasClass('multiple')) {$('#filesel .sel').removeClass('sel')}
		$(this).addClass('sel last');
	}
	fileSelector.updatePreview();
});
$(d).on('dblclick','#filesel .files .file', function(){
	if ($(this).data('info').type=='directory') { // "cd" to the dir
		var info = [
			$(this).data('path'),
			{
				types: $('#filesel').data('types'),
				multiple: $('#filesel').hasClass('multiple'),
				preview: $('#filesel').hasClass('preview'),
				nosel: $('#filesel').hasClass('nosel'),
				buttonLabel: $('#filesel').parents('.ui-dialog').
					find('.ui-dialog-buttonset button.ok').button('option','label'),
				name: $('#filesel-name').val()
			},
			$('#filesel').data('callback'),
		];
		$('#filesel').dialog('close').dialog('destroy').remove();
		fileSelector.apply(null,info);
	} else {
		$('#filesel').parents('.ui-dialog').find('.ui-dialog-buttonset button.ok').click();
	}
});

//clearInterval(refresh)<|endoftext|>