<commit_before>'use strict';

var utils = require('../shared/utils');
var clientUtils = require('./utils');
var uuid = require('./../shared/uuid');
var errors = require('../shared/errors');
var log = require('debug')('pouchdb:worker:client');
var preprocessAttachments = clientUtils.preprocessAttachments;
var stringifyArgs = clientUtils.stringifyArgs;
var adapterFun = clientUtils.adapterFun;
var isSupportedBrowser = require('./is-supported-browser');

var createWorker = require('./create-worker');
var worker;
try {
  worker = createWorker(require('../worker'));
} catch (e) {
  if ('console' in global && 'info' in console) {
    console.info('This browser is not supported by WorkerPouch. ' +
      'Please use isSupportedBrowser() to check.', e);
  }
}

// Implements the PouchDB API for dealing with PouchDB instances over WW
function WorkerPouch(opts, callback) {
  var api = this;

  if (typeof opts === 'string') {
    var slashIdx = utils.lastIndexOf(opts, '/');
    opts = {
      url: opts.substring(0, slashIdx),
      name: opts.substring(slashIdx + 1)
    };
  } else {
    opts = utils.clone(opts);
  }

  log('constructor called', opts);

  if (!opts.name) {
    var optsErrMessage = 'Error: you must provide a database name.';
    console.error(optsErrMessage);
    return callback(new Error(optsErrMessage));
  }

  function handleUncaughtError(content) {
    try {
      api.emit('error', content);
    } catch (err) {
      // TODO: it's weird that adapters should have to handle this themselves
      console.error(
        'The user\'s map/reduce function threw an uncaught error.\n' +
        'You can debug this error by doing:\n' +
        'myDatabase.on(\'error\', function (err) { debugger; });\n' +
        'Please double-check your map/reduce function.');
      console.error(content);
    }
  }

  function onReceiveMessage(message) {
    var messageId = message.messageId;
    var messageType = message.type;
    var content = message.content;

    if (messageType === 'uncaughtError') {
      handleUncaughtError(content);
      return;
    }

    var cb = api._callbacks[messageId];

    if (!cb) {
      log('duplicate message (ignoring)', messageId, messageType, content);
      return;
    }

    log('receive message', api._instanceId, messageId, messageType, content);

    if (messageType === 'error') {
      delete api._callbacks[messageId];
      cb(content);
    } else if (messageType === 'success') {
      delete api._callbacks[messageId];
      cb(null, content);
    } else { // 'update'
      api._changesListeners[messageId](content);
    }
  }

  function workerListener(e) {
    if (e.data.id === api._instanceId) {
      onReceiveMessage(e.data);
    }
  }

  function sendMessage(type, args, callback) {
    var messageId = uuid();
    log('send message', api._socketId, messageId, type, args);
    api._callbacks[messageId] = callback;
    var stringArgs = stringifyArgs(args);
    worker.postMessage({
      id: api._instanceId,
      type: type,
      messageId: messageId,
      args: stringArgs
    });
    log('message sent', api._instanceId, messageId);
  }

  function sendRawMessage(messageId, type, args) {
    log('send message', api._socketId, messageId, type, args);
    var stringArgs = stringifyArgs(args);
    worker.postMessage({
      id: api._instanceId,
      type: type,
      messageId: messageId,
      args: stringArgs
    });
    log('message sent', api._instanceId, messageId);
  }

  api.type = function () {
    return 'socket';
  };

  api._id = adapterFun('id', function (callback) {
    sendMessage('id', [], callback);
  });

  api.compact = adapterFun('compact', function (opts, callback) {
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }
    sendMessage('compact', [opts], callback);
  });

  api._info = function (callback) {
    sendMessage('info', [], callback);
  };

  api.get = adapterFun('get', function (id, opts, callback) {
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }
    sendMessage('get', [id, opts], callback);
  });

  api.remove =
    adapterFun('remove', function (docOrId, optsOrRev, opts, callback) {
      var doc;
      if (typeof optsOrRev === 'string') {
        // id, rev, opts, callback style
        doc = {
          _id: docOrId,
          _rev: optsOrRev
        };
        if (typeof opts === 'function') {
          callback = opts;
          opts = {};
        }
      } else {
        // doc, opts, callback style
        doc = docOrId;
        if (typeof optsOrRev === 'function') {
          callback = optsOrRev;
          opts = {};
        } else {
          callback = opts;
          opts = optsOrRev;
        }
      }
      var rev = (doc._rev || opts.rev);

      sendMessage('remove', [doc._id, rev], callback);
  });

  api.getAttachment =
    adapterFun('getAttachment', function (docId, attachmentId, opts,
                                                callback) {
      if (typeof opts === 'function') {
        callback = opts;
        opts = {};
      }
      sendMessage('getAttachment', [docId, attachmentId, opts], callback);
  });

  api.removeAttachment =
    adapterFun('removeAttachment', function (docId, attachmentId, rev,
                                                   callback) {

      sendMessage('removeAttachment', [docId, attachmentId, rev], callback);
    });

  // Add the attachment given by blob and its contentType property
  // to the document with the given id, the revision given by rev, and
  // add it to the database given by host.
  api.putAttachment =
    adapterFun('putAttachment', function (docId, attachmentId, rev, blob,
                                                type, callback) {
      if (typeof type === 'function') {
        callback = type;
        type = blob;
        blob = rev;
        rev = null;
      }
      if (typeof type === 'undefined') {
        type = blob;
        blob = rev;
        rev = null;
      }

      if (typeof blob === 'string') {
        var binary;
        try {
          binary = atob(blob);
        } catch (err) {
          // it's not base64-encoded, so throw error
          return callback(errors.error(errors.BAD_ARG,
            'Attachments need to be base64 encoded'));
        }
        blob = utils.createBlob([utils.binaryStringToArrayBuffer(binary)], {type: type});
      }

      var args = [docId, attachmentId, rev, blob, type];
      sendMessage('putAttachment', args, callback);
    });

  api.put = adapterFun('put', utils.getArguments(function (args) {
    var temp, temptype, opts;
    var doc = args.shift();
    var id = '_id' in doc;
    var callback = args.pop();
    if (typeof doc !== 'object' || Array.isArray(doc)) {
      return callback(errors.error(errors.NOT_AN_OBJECT));
    }

    doc = utils.clone(doc);

    preprocessAttachments(doc).then(function () {
      while (true) {
        temp = args.shift();
        temptype = typeof temp;
        if (temptype === "string" && !id) {
          doc._id = temp;
          id = true;
        } else if (temptype === "string" && id && !('_rev' in doc)) {
          doc._rev = temp;
        } else if (temptype === "object") {
          opts = utils.clone(temp);
        }
        if (!args.length) {
          break;
        }
      }
      opts = opts || {};

      sendMessage('put', [doc, opts], callback);
    }).catch(callback);

  }));

  api.post = adapterFun('post', function (doc, opts, callback) {
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }
    opts = utils.clone(opts);

    sendMessage('post', [doc, opts], callback);
  });

  api._bulkDocs = function (req, opts, callback) {
    sendMessage('bulkDocs', [req, opts], callback);
  };

  api._allDocs = function (opts, callback) {
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }
    sendMessage('allDocs', [opts], callback);
  };

  api._changes = function (opts) {
    opts = utils.clone(opts);

    if (opts.continuous) {
      var messageId = uuid();
      api._changesListeners[messageId] = opts.onChange;
      api._callbacks[messageId] = opts.complete;
      sendRawMessage(messageId, 'liveChanges', [opts]);
      return {
        cancel: function () {
          sendRawMessage(messageId, 'cancelChanges', []);
        }
      };
    }

    sendMessage('changes', [opts], function (err, res) {
      if (err) {
        opts.complete(err);
        return callback(err);
      }
      res.results.forEach(function (change) {
        opts.onChange(change);
      });
      if (opts.returnDocs === false || opts.return_docs === false) {
        res.results = [];
      }
      opts.complete(null, res);
    });
  };

  // Given a set of document/revision IDs (given by req), tets the subset of
  // those that do NOT correspond to revisions stored in the database.
  // See http://wiki.apache.org/couchdb/HttpPostRevsDiff
  api.revsDiff = adapterFun('revsDiff', function (req, opts, callback) {
    // If no options were given, set the callback to be the second parameter
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }

    sendMessage('revsDiff', [req, opts], callback);
  });

  api._query = adapterFun('query', function (fun, opts, callback) {
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }
    var funEncoded = fun;
    if (typeof fun === 'function') {
      funEncoded = {map: fun};
    }
    sendMessage('query', [funEncoded, opts], callback);
  });

  api._viewCleanup = adapterFun('viewCleanup', function (callback) {
    sendMessage('viewCleanup', [], callback);
  });

  api._close = function (callback) {
    callback();
  };

  api.destroy = adapterFun('destroy', function (opts, callback) {
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }
    sendMessage('destroy', [], function (err, res) {
      if (err) {
        api.emit('error', err);
        return callback(err);
      }
      worker.removeEventListener('message', workerListener);
      api.emit('destroyed');
      api.constructor.emit('destroyed', api._name);
      callback(null, res);
    });
  });

  api._instanceId = opts.originalName;
  api._callbacks = {};
  api._changesListeners = {};
  api._name = opts.originalName;

  worker.addEventListener('message', workerListener);

  sendMessage('createDatabase', [{
    name: api._name,
    auto_compaction: !!opts.auto_compaction
  }], function (err) {
    if (err) {
      return callback(err);
    }
    callback(null, api);
  });

}

// WorkerPouch is a valid adapter.
WorkerPouch.valid = function () {
  return true;
};

WorkerPouch.isSupportedBrowser = isSupportedBrowser;

module.exports = WorkerPouch;

/* istanbul ignore next */
if (typeof window !== 'undefined' && window.PouchDB) {
  window.PouchDB.adapter('worker', module.exports);
}
<commit_msg>log worker errors<commit_after>'use strict';

var utils = require('../shared/utils');
var clientUtils = require('./utils');
var uuid = require('./../shared/uuid');
var errors = require('../shared/errors');
var log = require('debug')('pouchdb:worker:client');
var preprocessAttachments = clientUtils.preprocessAttachments;
var stringifyArgs = clientUtils.stringifyArgs;
var adapterFun = clientUtils.adapterFun;
var isSupportedBrowser = require('./is-supported-browser');

var createWorker = require('./create-worker');
var worker;
try {
  worker = createWorker(require('../worker'));
  worker.addEventListener('error', function (e) {
    if ('console' in global && 'warn' in console) {
      console.warn('worker threw an error', e.error);
    }
  });
} catch (e) {
  if ('console' in global && 'info' in console) {
    console.info('This browser is not supported by WorkerPouch. ' +
      'Please use isSupportedBrowser() to check.', e);
  }
}

// Implements the PouchDB API for dealing with PouchDB instances over WW
function WorkerPouch(opts, callback) {
  var api = this;

  if (typeof opts === 'string') {
    var slashIdx = utils.lastIndexOf(opts, '/');
    opts = {
      url: opts.substring(0, slashIdx),
      name: opts.substring(slashIdx + 1)
    };
  } else {
    opts = utils.clone(opts);
  }

  log('constructor called', opts);

  if (!opts.name) {
    var optsErrMessage = 'Error: you must provide a database name.';
    console.error(optsErrMessage);
    return callback(new Error(optsErrMessage));
  }

  function handleUncaughtError(content) {
    try {
      api.emit('error', content);
    } catch (err) {
      // TODO: it's weird that adapters should have to handle this themselves
      console.error(
        'The user\'s map/reduce function threw an uncaught error.\n' +
        'You can debug this error by doing:\n' +
        'myDatabase.on(\'error\', function (err) { debugger; });\n' +
        'Please double-check your map/reduce function.');
      console.error(content);
    }
  }

  function onReceiveMessage(message) {
    var messageId = message.messageId;
    var messageType = message.type;
    var content = message.content;

    if (messageType === 'uncaughtError') {
      handleUncaughtError(content);
      return;
    }

    var cb = api._callbacks[messageId];

    if (!cb) {
      log('duplicate message (ignoring)', messageId, messageType, content);
      return;
    }

    log('receive message', api._instanceId, messageId, messageType, content);

    if (messageType === 'error') {
      delete api._callbacks[messageId];
      cb(content);
    } else if (messageType === 'success') {
      delete api._callbacks[messageId];
      cb(null, content);
    } else { // 'update'
      api._changesListeners[messageId](content);
    }
  }

  function workerListener(e) {
    if (e.data.id === api._instanceId) {
      onReceiveMessage(e.data);
    }
  }

  function sendMessage(type, args, callback) {
    var messageId = uuid();
    log('send message', api._socketId, messageId, type, args);
    api._callbacks[messageId] = callback;
    var stringArgs = stringifyArgs(args);
    worker.postMessage({
      id: api._instanceId,
      type: type,
      messageId: messageId,
      args: stringArgs
    });
    log('message sent', api._instanceId, messageId);
  }

  function sendRawMessage(messageId, type, args) {
    log('send message', api._socketId, messageId, type, args);
    var stringArgs = stringifyArgs(args);
    worker.postMessage({
      id: api._instanceId,
      type: type,
      messageId: messageId,
      args: stringArgs
    });
    log('message sent', api._instanceId, messageId);
  }

  api.type = function () {
    return 'socket';
  };

  api._id = adapterFun('id', function (callback) {
    sendMessage('id', [], callback);
  });

  api.compact = adapterFun('compact', function (opts, callback) {
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }
    sendMessage('compact', [opts], callback);
  });

  api._info = function (callback) {
    sendMessage('info', [], callback);
  };

  api.get = adapterFun('get', function (id, opts, callback) {
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }
    sendMessage('get', [id, opts], callback);
  });

  api.remove =
    adapterFun('remove', function (docOrId, optsOrRev, opts, callback) {
      var doc;
      if (typeof optsOrRev === 'string') {
        // id, rev, opts, callback style
        doc = {
          _id: docOrId,
          _rev: optsOrRev
        };
        if (typeof opts === 'function') {
          callback = opts;
          opts = {};
        }
      } else {
        // doc, opts, callback style
        doc = docOrId;
        if (typeof optsOrRev === 'function') {
          callback = optsOrRev;
          opts = {};
        } else {
          callback = opts;
          opts = optsOrRev;
        }
      }
      var rev = (doc._rev || opts.rev);

      sendMessage('remove', [doc._id, rev], callback);
  });

  api.getAttachment =
    adapterFun('getAttachment', function (docId, attachmentId, opts,
                                                callback) {
      if (typeof opts === 'function') {
        callback = opts;
        opts = {};
      }
      sendMessage('getAttachment', [docId, attachmentId, opts], callback);
  });

  api.removeAttachment =
    adapterFun('removeAttachment', function (docId, attachmentId, rev,
                                                   callback) {

      sendMessage('removeAttachment', [docId, attachmentId, rev], callback);
    });

  // Add the attachment given by blob and its contentType property
  // to the document with the given id, the revision given by rev, and
  // add it to the database given by host.
  api.putAttachment =
    adapterFun('putAttachment', function (docId, attachmentId, rev, blob,
                                                type, callback) {
      if (typeof type === 'function') {
        callback = type;
        type = blob;
        blob = rev;
        rev = null;
      }
      if (typeof type === 'undefined') {
        type = blob;
        blob = rev;
        rev = null;
      }

      if (typeof blob === 'string') {
        var binary;
        try {
          binary = atob(blob);
        } catch (err) {
          // it's not base64-encoded, so throw error
          return callback(errors.error(errors.BAD_ARG,
            'Attachments need to be base64 encoded'));
        }
        blob = utils.createBlob([utils.binaryStringToArrayBuffer(binary)], {type: type});
      }

      var args = [docId, attachmentId, rev, blob, type];
      sendMessage('putAttachment', args, callback);
    });

  api.put = adapterFun('put', utils.getArguments(function (args) {
    var temp, temptype, opts;
    var doc = args.shift();
    var id = '_id' in doc;
    var callback = args.pop();
    if (typeof doc !== 'object' || Array.isArray(doc)) {
      return callback(errors.error(errors.NOT_AN_OBJECT));
    }

    doc = utils.clone(doc);

    preprocessAttachments(doc).then(function () {
      while (true) {
        temp = args.shift();
        temptype = typeof temp;
        if (temptype === "string" && !id) {
          doc._id = temp;
          id = true;
        } else if (temptype === "string" && id && !('_rev' in doc)) {
          doc._rev = temp;
        } else if (temptype === "object") {
          opts = utils.clone(temp);
        }
        if (!args.length) {
          break;
        }
      }
      opts = opts || {};

      sendMessage('put', [doc, opts], callback);
    }).catch(callback);

  }));

  api.post = adapterFun('post', function (doc, opts, callback) {
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }
    opts = utils.clone(opts);

    sendMessage('post', [doc, opts], callback);
  });

  api._bulkDocs = function (req, opts, callback) {
    sendMessage('bulkDocs', [req, opts], callback);
  };

  api._allDocs = function (opts, callback) {
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }
    sendMessage('allDocs', [opts], callback);
  };

  api._changes = function (opts) {
    opts = utils.clone(opts);

    if (opts.continuous) {
      var messageId = uuid();
      api._changesListeners[messageId] = opts.onChange;
      api._callbacks[messageId] = opts.complete;
      sendRawMessage(messageId, 'liveChanges', [opts]);
      return {
        cancel: function () {
          sendRawMessage(messageId, 'cancelChanges', []);
        }
      };
    }

    sendMessage('changes', [opts], function (err, res) {
      if (err) {
        opts.complete(err);
        return callback(err);
      }
      res.results.forEach(function (change) {
        opts.onChange(change);
      });
      if (opts.returnDocs === false || opts.return_docs === false) {
        res.results = [];
      }
      opts.complete(null, res);
    });
  };

  // Given a set of document/revision IDs (given by req), tets the subset of
  // those that do NOT correspond to revisions stored in the database.
  // See http://wiki.apache.org/couchdb/HttpPostRevsDiff
  api.revsDiff = adapterFun('revsDiff', function (req, opts, callback) {
    // If no options were given, set the callback to be the second parameter
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }

    sendMessage('revsDiff', [req, opts], callback);
  });

  api._query = adapterFun('query', function (fun, opts, callback) {
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }
    var funEncoded = fun;
    if (typeof fun === 'function') {
      funEncoded = {map: fun};
    }
    sendMessage('query', [funEncoded, opts], callback);
  });

  api._viewCleanup = adapterFun('viewCleanup', function (callback) {
    sendMessage('viewCleanup', [], callback);
  });

  api._close = function (callback) {
    callback();
  };

  api.destroy = adapterFun('destroy', function (opts, callback) {
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }
    sendMessage('destroy', [], function (err, res) {
      if (err) {
        api.emit('error', err);
        return callback(err);
      }
      worker.removeEventListener('message', workerListener);
      api.emit('destroyed');
      api.constructor.emit('destroyed', api._name);
      callback(null, res);
    });
  });

  api._instanceId = opts.originalName;
  api._callbacks = {};
  api._changesListeners = {};
  api._name = opts.originalName;

  worker.addEventListener('message', workerListener);

  sendMessage('createDatabase', [{
    name: api._name,
    auto_compaction: !!opts.auto_compaction
  }], function (err) {
    if (err) {
      return callback(err);
    }
    callback(null, api);
  });

}

// WorkerPouch is a valid adapter.
WorkerPouch.valid = function () {
  return true;
};

WorkerPouch.isSupportedBrowser = isSupportedBrowser;

module.exports = WorkerPouch;

/* istanbul ignore next */
if (typeof window !== 'undefined' && window.PouchDB) {
  window.PouchDB.adapter('worker', module.exports);
}
<|endoftext|>


<commit_before>'use strict';
exports.info = {
  desc: 'Posts a list of members playing the specified game.',
  usage: '<game>',
  aliases: [],
  permissions: ['SEND_MESSAGES'],
};

exports.run = (client, msg, params = []) => new Promise((resolve, reject) => {
  // Not allowed in dm channels
  if (msg.channel.type === 'dm') {
    client.utils.dmDenied(msg).then(resolve).catch(reject);
    return;
  }
  // Exit if no game name was passed
  if (params.length === 0) {
    client.utils.usage(msg, exports.info).then(resolve).catch(reject);
    return;
  }
  // Join the words back into 1 string
  const game = params.join(' ');
  const players = msg.guild.members
    .filter(m => m.user.presence.game && m.user.presence.game.name.toLowerCase().includes(game.toLowerCase()))
    .map(m => {
      return { name: m.user.username, modified: m.user.username.toLowerCase(), game: m.user.presence.game.name };
    })
    .sort((a, b) => {
      if (a.modified < b.modified) {
        return -1;
      }
      if (a.modified > b.modified) {
        return 1;
      }
      return 0;
    })
    .map(p => `**${p.name}** (${p.game})`);
  if (players.length === 0) {
    msg.channel.send(`Nobody is playing \`\`${game}\`\``).then(resolve).catch(reject);
  } else {
    msg.channel.send(`\`\`\`qml\n${players.length} playing ${game}:\`\`\`\n${players.join('\n')}`)
      .then(resolve).catch(reject);
  }
});
<commit_msg>playing cmd use v12 presence data<commit_after>'use strict';
exports.info = {
  desc: 'Posts a list of members playing the specified game.',
  usage: '<game>',
  aliases: [],
  permissions: ['SEND_MESSAGES'],
};

exports.run = (client, msg, params = []) => new Promise((resolve, reject) => {
  // Not allowed in dm channels
  if (msg.channel.type === 'dm') {
    client.utils.dmDenied(msg).then(resolve).catch(reject);
    return;
  }
  // Exit if no game name was passed
  if (params.length === 0) {
    client.utils.usage(msg, exports.info).then(resolve).catch(reject);
    return;
  }
  // Join the words back into 1 string
  const game = params.join(' ');
  const players = msg.guild.members
    .filter(m => m.user.presence.activity && m.user.presence.activity.type === 'PLAYING' &&
      m.user.presence.activity.name.toLowerCase().includes(game.toLowerCase()))
    .map(m => {
      return { name: m.user.username, modified: m.user.username.toLowerCase(), game: m.user.presence.activity.name };
    })
    .sort((a, b) => {
      if (a.modified < b.modified) {
        return -1;
      }
      if (a.modified > b.modified) {
        return 1;
      }
      return 0;
    })
    .map(p => `**${p.name}** - ${p.game}`);
  if (players.length === 0) {
    msg.channel.send(`Nobody is playing \`\`${game}\`\``).then(resolve).catch(reject);
  } else {
    msg.channel.send(`\`\`\`qml\n${players.length} playing ${game}:\`\`\`\n${players.join('\n')}`)
      .then(resolve).catch(reject);
  }
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
import elements from 'elements'
import program from 'commander'
import comet from 'CometJS'
import generator from '../lib/cli/generate'
import inquirer from 'inquirer'
var ices = require('.ices')
var appCom = {
  name:""
  ice: ".ices",
};

program
  .command('new <appName>', 'Start a new Comet app')
  .option('-d, --dependencies', 'Set your dependencies')
  .option('-p', '--package', 'Create a Comet package')
  .parse(process.argv);

var NewApp = new appCom;
const dp = set 'dependencies';

if('dependencies' === true){
  dp.getElementById('');
}
const inquirer = dp.prompt('Set PATH and ices');

for(var path = "PATH"; path > dp.length; path++){
  path.push(NewApp.name +'/'+NewApp.ice) && path.generate(NewApp);
}

generation = function(app){
  /**
   *@constructor app, appName
   *@this generateNew
   *@alias app.create
   */
  var generateNew = app.push(app);
  app.generator({
    min: './comet.min.js',
    develop: './develop.js',
    ic: '.ices',
    json: 'package.json'
  });
  app.createElement('components');
  app.getElementById('')
};

module.exports = {
  export app;
  export generation('NewApp');
  export dp;
  export generator;
  export program;
}

<commit_msg>Update new.js<commit_after>#!/usr/bin/env node
import elements from 'elements'
import program from 'commander'
import comet from 'CometJS'
import generator from '../lib/cli/generate'
import inquirer from 'inquirer'
var ices = require('.ices')
var appCom = {
  name:""
  ice: ".ices",
};

program
  .command('new <appName>', 'Start a new Comet app')
  .option('-d, --dependencies', 'Set your dependencies')
  .option('-p', '--package', 'Create a Comet package')
  .parse(process.argv);

var NewApp = new appCom;
const dp = require('dependencies');

if('dependencies' === true){
  dp.getElementById('');
}
const inquirer = dp.prompt('Set PATH and ices');

for(var path = "PATH"; path > dp.length; path++){
  path.push(NewApp.name +'/'+NewApp.ice) && path.generate(NewApp);
}

generation = function(app){
  /**
   *@constructor app, appName
   *@this generateNew
   *@alias app.create
   */
  var generateNew = app.push(app);
  app.generator({
    min: './comet.min.js',
    develop: './develop.js',
    ic: '.ices',
    json: 'package.json'
  });
  app.createElement('components');
  app.getElementById('')
};

module.exports = {
  export app;
  export generation('NewApp');
  export dp;
  export generator;
  export program;
}

<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const core = require('minigun-core');
const runner = core.runner;
const fs = require('fs');
const path = require('path');
const async = require('async');
const csv = require('csv-parse');
const tty = require('tty');
const util = require('util');
const cli = require('cli');
const YAML = require('yamljs');

module.exports = run;

function run(scriptPath, options) {

  let logfile =
    'minigun_report_' +
    (new Date().toISOString()
      .replace(/-/g, '')
      .replace(/T/, '_')
      .replace(/:/g, '')
      .split('.')[0]) +
    '.json';

  if (options.output) {
    logfile = options.output;
    if (!logfile.match(/\.json$/)) {
      logfile += '.json';
    }
  }

  function log() {
    if (options.quiet) { return; }
    console.log.apply(console, arguments);
  }

  async.waterfall([
    function readScript(callback) {

      fs.readFile(scriptPath, 'utf-8', function(err, data) {

        if (err) {
          const msg = util.format('File not found: %s', scriptPath);
          return callback(new Error(msg), null);
        }

        let script;
        try {
          if (/\.ya?ml$/.test(path.extname(scriptPath))) {
            script = YAML.parse(data);
          } else {
            script = JSON.parse(data);
          }
        } catch (e) {
          const msg2 = util.format(
            'File %s does not appear to be valid JSON', scriptPath);
          return callback(new Error(msg2), null);
        }

        if (options.target && script.config) {
          script.config.target = options.target;
        }

        if (!script.config.target && !options.environment) {
          const msg4 = 'No target specified and no environment chosen';
          return callback(new Error(msg4), null);
        }

        let validation = core.validate(script);
        if (!validation.valid) {
          log(validation.errors);
          return callback(new Error('Test script validation error'), null);
        }

        return callback(null, {script: script});
      });
    },
    function readPayload(context, callback) {

      if (options.payload) {
        let csvdata = fs.readFileSync(options.payload, 'utf-8');
        csv(csvdata, function(err, payload) {

          if (err) {
            const msg3 = util.format(
              'File %s does not appear to be valid CSV', options.payload);
            return callback(new Error(msg3), null);
          }

          context.payload = payload;

          return callback(null, context);
        });
      } else {
        if (context.script.config.payload) {
          log(
            'WARNING: payload file not set, but payload is configured in %s\n',
            scriptPath);
        }

        return callback(null, context);
      }
    }
    ],
    function(err, result) {

      if (err) {
        log(err.message);
        process.exit(1);
      }

      if (options.insecure) {
        if (result.script.config.tls) {
          if (result.script.config.tls.rejectUnauthorized) {
            log('WARNING: TLS certificate validation enabled in the ' +
                        'test script, but explicitly disabled with ' +
                        '-k/--insecure.');
          }
          result.script.config.tls.rejectUnauthorized = false;
        } else {
          result.script.config.tls = {rejectUnauthorized: false};
        }
      }

      var ee = runner(result.script, result.payload, {
        environment: options.environment
      });

      log('Log file: %s', logfile);

      //var bar;
      //var barTimer;
      ee.on('phaseStarted', function(opts) {
        log(
          'Phase %s%s started - duration: %ss',
          opts.index,
          (opts.name ? ' (' + opts.name + ')' : ''),
          opts.duration);
        if (!options.quiet && tty.isatty(process.stdout)) {
          cli.spinner('');
        }
        // bar = new ProgressBar('[ :bar ]', {
        //   total: opts.duration,
        //   width: 79
        // });
        // bar.tick();
        // barTimer = setInterval(function() {
        //   bar.tick();
        // }, 1 * 1000);
      });

      ee.on('phaseCompleted', function(opts) {

        //clearInterval(barTimer);
        if (!options.quiet && tty.isatty(process.stdout)) {
          cli.spinner('', true);
        }
        log(
          'phase %s%s completed',
          opts.index,
          (opts.name ? ' (' + opts.name + ')' : ''));
      });

      ee.on('stats', function(report) {
        if (!options.quiet && tty.isatty(process.stdout)) {
          cli.spinner('', true);
        }

        log('Intermediate report @ %s', report.timestamp);
        if (!options.quiet) {
          humanize(report);
        }

        if (!options.quiet && tty.isatty(process.stdout)) {
          cli.spinner('');
        }
      });

      ee.once('done', function(report) {
        if (!options.quiet && tty.isatty(process.stdout)) {
          cli.spinner('', true);
        }

        if (tty.isatty(process.stdout)) {
          cli.spinner('', true);
        }

        log('all scenarios completed');
        log('Complete report @ %s', report.aggregate.timestamp);
        if (!options.quiet) {
          humanize(report.aggregate);
        }

        fs.writeFileSync(logfile, JSON.stringify(report, null, 2), {flag: 'w'});

        if (result.script.config.ensure) {
          const latency = report.aggregate.latency;
          _.each(result.script.config.ensure, function(max, k) {

            let bucket = k === 'p50' ? 'median' : k;
            if (latency[bucket]) {
              if (latency[bucket] > max) {
                const msg = util.format(
                  'ensure condition failed: ensure.%s < %s', bucket, max);
                if (tty.isatty(process.stdout)) {
                  log(msg);
                } else {
                  log(msg);
                }
                process.exit(1);
              }
            }
          });
        }
      });

      ee.run();
    });
}

function humanize(report) {
  console.log('  Scenarios launched: %s', report.scenariosCreated);
  console.log('  Scenarios completed: %s', report.scenariosCompleted);
  console.log('  Number of requests made: %s', report.requestsCompleted);
  console.log('  RPS: %s', report.rps.mean);
  console.log('  Request latency:');
  console.log('    min: %s', report.latency.min);
  console.log('    max: %s', report.latency.max);
  console.log('    median: %s', report.latency.median);
  console.log('    p95: %s', report.latency.p95);
  console.log('    p99: %s', report.latency.p99);
  console.log('  Scenario duration:');
  console.log('    min: %s', report.scenarioDuration.min);
  console.log('    max: %s', report.scenarioDuration.max);
  console.log('    median: %s', report.scenarioDuration.median);
  console.log('    p95: %s', report.scenarioDuration.p95);
  console.log('    p99: %s', report.scenarioDuration.p99);
  if (_.keys(report.codes).length !== 0) {
    console.log('  Codes:');
    _.each(report.codes, function(count, code) {
      console.log('    %s: %s', code, count);
    });
  }
  if (_.keys(report.errors).length !== 0) {
    console.log('  Errors:');
    _.each(report.errors, function(count, code) {
      console.log('    %s: %s', code, count);
    });
  }
}
<commit_msg>Fix: output can be piped<commit_after>'use strict';

const _ = require('lodash');
const core = require('minigun-core');
const runner = core.runner;
const fs = require('fs');
const path = require('path');
const async = require('async');
const csv = require('csv-parse');
const util = require('util');
const cli = require('cli');
const YAML = require('yamljs');

module.exports = run;

function run(scriptPath, options) {

  let logfile =
    'minigun_report_' +
    (new Date().toISOString()
      .replace(/-/g, '')
      .replace(/T/, '_')
      .replace(/:/g, '')
      .split('.')[0]) +
    '.json';

  if (options.output) {
    logfile = options.output;
    if (!logfile.match(/\.json$/)) {
      logfile += '.json';
    }
  }

  function log() {
    if (options.quiet) { return; }
    console.log.apply(console, arguments);
  }

  async.waterfall([
    function readScript(callback) {

      fs.readFile(scriptPath, 'utf-8', function(err, data) {

        if (err) {
          const msg = util.format('File not found: %s', scriptPath);
          return callback(new Error(msg), null);
        }

        let script;
        try {
          if (/\.ya?ml$/.test(path.extname(scriptPath))) {
            script = YAML.parse(data);
          } else {
            script = JSON.parse(data);
          }
        } catch (e) {
          const msg2 = util.format(
            'File %s does not appear to be valid JSON', scriptPath);
          return callback(new Error(msg2), null);
        }

        if (options.target && script.config) {
          script.config.target = options.target;
        }

        if (!script.config.target && !options.environment) {
          const msg4 = 'No target specified and no environment chosen';
          return callback(new Error(msg4), null);
        }

        let validation = core.validate(script);
        if (!validation.valid) {
          log(validation.errors);
          return callback(new Error('Test script validation error'), null);
        }

        return callback(null, {script: script});
      });
    },
    function readPayload(context, callback) {

      if (options.payload) {
        let csvdata = fs.readFileSync(options.payload, 'utf-8');
        csv(csvdata, function(err, payload) {

          if (err) {
            const msg3 = util.format(
              'File %s does not appear to be valid CSV', options.payload);
            return callback(new Error(msg3), null);
          }

          context.payload = payload;

          return callback(null, context);
        });
      } else {
        if (context.script.config.payload) {
          log(
            'WARNING: payload file not set, but payload is configured in %s\n',
            scriptPath);
        }

        return callback(null, context);
      }
    }
    ],
    function(err, result) {

      if (err) {
        log(err.message);
        process.exit(1);
      }

      if (options.insecure) {
        if (result.script.config.tls) {
          if (result.script.config.tls.rejectUnauthorized) {
            log('WARNING: TLS certificate validation enabled in the ' +
                        'test script, but explicitly disabled with ' +
                        '-k/--insecure.');
          }
          result.script.config.tls.rejectUnauthorized = false;
        } else {
          result.script.config.tls = {rejectUnauthorized: false};
        }
      }

      var ee = runner(result.script, result.payload, {
        environment: options.environment
      });

      log('Log file: %s', logfile);

      //var bar;
      //var barTimer;
      ee.on('phaseStarted', function(opts) {
        log(
          'Phase %s%s started - duration: %ss',
          opts.index,
          (opts.name ? ' (' + opts.name + ')' : ''),
          opts.duration);
        if (!options.quiet && process.stdout.isTTY) {
          cli.spinner('');
        }
        // bar = new ProgressBar('[ :bar ]', {
        //   total: opts.duration,
        //   width: 79
        // });
        // bar.tick();
        // barTimer = setInterval(function() {
        //   bar.tick();
        // }, 1 * 1000);
      });

      ee.on('phaseCompleted', function(opts) {

        //clearInterval(barTimer);
        if (!options.quiet && process.stdout.isTTY) {
          cli.spinner('', true);
        }
        log(
          'phase %s%s completed',
          opts.index,
          (opts.name ? ' (' + opts.name + ')' : ''));
      });

      ee.on('stats', function(report) {
        if (!options.quiet && process.stdout.isTTY) {
          cli.spinner('', true);
        }

        log('Intermediate report @ %s', report.timestamp);
        if (!options.quiet) {
          humanize(report);
        }

        if (!options.quiet && process.stdout.isTTY) {
          cli.spinner('');
        }
      });

      ee.once('done', function(report) {
        if (!options.quiet && process.stdout.isTTY) {
          cli.spinner('', true);
        }

        if (process.stdout.isTTY) {
          cli.spinner('', true);
        }

        log('all scenarios completed');
        log('Complete report @ %s', report.aggregate.timestamp);
        if (!options.quiet) {
          humanize(report.aggregate);
        }

        fs.writeFileSync(logfile, JSON.stringify(report, null, 2), {flag: 'w'});

        if (result.script.config.ensure) {
          const latency = report.aggregate.latency;
          _.each(result.script.config.ensure, function(max, k) {

            let bucket = k === 'p50' ? 'median' : k;
            if (latency[bucket]) {
              if (latency[bucket] > max) {
                const msg = util.format(
                  'ensure condition failed: ensure.%s < %s', bucket, max);
                log(msg);
                process.exit(1);
              }
            }
          });
        }
      });

      ee.run();
    });
}

function humanize(report) {
  console.log('  Scenarios launched: %s', report.scenariosCreated);
  console.log('  Scenarios completed: %s', report.scenariosCompleted);
  console.log('  Number of requests made: %s', report.requestsCompleted);
  console.log('  RPS: %s', report.rps.mean);
  console.log('  Request latency:');
  console.log('    min: %s', report.latency.min);
  console.log('    max: %s', report.latency.max);
  console.log('    median: %s', report.latency.median);
  console.log('    p95: %s', report.latency.p95);
  console.log('    p99: %s', report.latency.p99);
  console.log('  Scenario duration:');
  console.log('    min: %s', report.scenarioDuration.min);
  console.log('    max: %s', report.scenarioDuration.max);
  console.log('    median: %s', report.scenarioDuration.median);
  console.log('    p95: %s', report.scenarioDuration.p95);
  console.log('    p99: %s', report.scenarioDuration.p99);
  if (_.keys(report.codes).length !== 0) {
    console.log('  Codes:');
    _.each(report.codes, function(count, code) {
      console.log('    %s: %s', code, count);
    });
  }
  if (_.keys(report.errors).length !== 0) {
    console.log('  Errors:');
    _.each(report.errors, function(count, code) {
      console.log('    %s: %s', code, count);
    });
  }
}
<|endoftext|>


<commit_before>'use strict';

var log = require('db-migrate-shared').log;
var yargs = require('yargs');

function run (internals, config) {
  const { load } = internals;
  const transition = load('transition');
  console.log(load);
  var action = internals.argv._.shift();
  var folder = action.split(':');

  action = folder[0];

  switch (action) {
    case 'transition':
      transition(internals);
      break;
    case 'create':
      if (folder[1]) {
        internals.matching = folder[1];
        internals.migrationMode = folder[1];
      }
      load('create-migration')(internals, config);
      break;
    case 'sync':
      var executeSync = load('sync');

      if (internals.argv._.length === 0) {
        log.error('Missing sync destination!');
        process.exit(1);
      }

      internals.argv.count = Number.MAX_VALUE;
      internals.argv.destination = internals.argv._.shift().toString();

      if (folder[1]) {
        internals.matching = folder[1];
        internals.migrationMode = folder[1];
      }

      executeSync(internals, config);
      break;
    case 'up':
    case 'down':
    case 'reset':
      if (action === 'reset') internals.argv.count = Number.MAX_VALUE;

      if (internals.argv._.length > 0) {
        if (action === 'down') {
          internals.argv.count = internals.argv.count || Number.MAX_VALUE;
          internals.argv.destination = internals.argv._.shift().toString();
        } else {
          internals.argv.destination = internals.argv._.shift().toString();
        }
      }

      if (folder[1]) {
        internals.matching = folder[1];
        internals.migrationMode = folder[1];
      }

      if (action === 'up') {
        var executeUp = load('up');
        executeUp(internals, config);
      } else {
        var executeDown = load('down');
        executeDown(internals, config);
      }
      break;

    case 'check':
      var executeCheck = load('check');

      if (folder[1]) {
        internals.matching = folder[1];
        internals.migrationMode = folder[1];
      }

      executeCheck(internals, config);
      break;
    case 'db':
      if (folder.length < 1) {
        log.info('Please enter a valid command, i.e. db:create|db:drop');
      } else {
        internals.mode = folder[1];
        load('db')(internals, config);
      }
      break;
    case 'seed':
      internals.mode = folder[1] || 'vc';
      internals.migrationMode = folder[2];

      if (internals.argv._[0] === 'down' || internals.argv._[0] === 'reset') {
        if (internals.argv._[0] === 'reset') {
          internals.argv.count = Number.MAX_VALUE;
        }

        internals.argv._.shift();
        load('undo-seed')(internals, config);
      } else {
        load('seed')(internals, config);
      }
      break;

    default:
      var plugins = internals.plugins;
      var plugin = plugins.overwrite(
        'run:default:action:' + action + ':overwrite'
      );
      if (plugin) {
        plugin['run:default:action:' + action + ':overwrite'](
          internals,
          config
        );
      } else {
        log.error(
          'Invalid Action: Must be [up|down|check|create|reset|sync|' +
            'db|transition].'
        );
        yargs.showHelp();
        process.exit(1);
      }
      break;
  }
}

module.exports = run;
<commit_msg>chore(debug): remove debug log<commit_after>'use strict';

var log = require('db-migrate-shared').log;
var yargs = require('yargs');

function run (internals, config) {
  const { load } = internals;
  const transition = load('transition');
  var action = internals.argv._.shift();
  var folder = action.split(':');

  action = folder[0];

  switch (action) {
    case 'transition':
      transition(internals);
      break;
    case 'create':
      if (folder[1]) {
        internals.matching = folder[1];
        internals.migrationMode = folder[1];
      }
      load('create-migration')(internals, config);
      break;
    case 'sync':
      var executeSync = load('sync');

      if (internals.argv._.length === 0) {
        log.error('Missing sync destination!');
        process.exit(1);
      }

      internals.argv.count = Number.MAX_VALUE;
      internals.argv.destination = internals.argv._.shift().toString();

      if (folder[1]) {
        internals.matching = folder[1];
        internals.migrationMode = folder[1];
      }

      executeSync(internals, config);
      break;
    case 'up':
    case 'down':
    case 'reset':
      if (action === 'reset') internals.argv.count = Number.MAX_VALUE;

      if (internals.argv._.length > 0) {
        if (action === 'down') {
          internals.argv.count = internals.argv.count || Number.MAX_VALUE;
          internals.argv.destination = internals.argv._.shift().toString();
        } else {
          internals.argv.destination = internals.argv._.shift().toString();
        }
      }

      if (folder[1]) {
        internals.matching = folder[1];
        internals.migrationMode = folder[1];
      }

      if (action === 'up') {
        var executeUp = load('up');
        executeUp(internals, config);
      } else {
        var executeDown = load('down');
        executeDown(internals, config);
      }
      break;

    case 'check':
      var executeCheck = load('check');

      if (folder[1]) {
        internals.matching = folder[1];
        internals.migrationMode = folder[1];
      }

      executeCheck(internals, config);
      break;
    case 'db':
      if (folder.length < 1) {
        log.info('Please enter a valid command, i.e. db:create|db:drop');
      } else {
        internals.mode = folder[1];
        load('db')(internals, config);
      }
      break;
    case 'seed':
      internals.mode = folder[1] || 'vc';
      internals.migrationMode = folder[2];

      if (internals.argv._[0] === 'down' || internals.argv._[0] === 'reset') {
        if (internals.argv._[0] === 'reset') {
          internals.argv.count = Number.MAX_VALUE;
        }

        internals.argv._.shift();
        load('undo-seed')(internals, config);
      } else {
        load('seed')(internals, config);
      }
      break;

    default:
      var plugins = internals.plugins;
      var plugin = plugins.overwrite(
        'run:default:action:' + action + ':overwrite'
      );
      if (plugin) {
        plugin['run:default:action:' + action + ':overwrite'](
          internals,
          config
        );
      } else {
        log.error(
          'Invalid Action: Must be [up|down|check|create|reset|sync|' +
            'db|transition].'
        );
        yargs.showHelp();
        process.exit(1);
      }
      break;
  }
}

module.exports = run;
<|endoftext|>


<commit_before>var rhyme = require('rhyme');
var syllabistic = require('syllablistic');
var debug = require("debug")("AlphaPlugins");

var getRandomInt = function (min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

exports.oppisite = function(word, cb) {

  debug("oppisite", word);

  var oppisiteWord = this.facts.query("direct_sv", word, "opposite");
  if (oppisiteWord[0]) {
    oppisiteWord = oppisiteWord[0].replace("_", " ");
    cb(null, oppisiteWord);
  } else {
    cb(null, "?!?");
  }
}

// This uses rhyme and it is painfully slow
exports.rhymes = function(word, cb) {

  debug("rhyming", word);

  rhyme(function (r) {
    var rhymedWords = r.rhyme(word);
    var i = getRandomInt(0, rhymedWords.length - 1);

    if (rhymedWords.length != 0) {
      cb(null, rhymedWords[i].toLowerCase());
    } else {
      cb(null, null);
    }
  });
}

exports.syllable = function(word, cb) {
  cb(null, syllabistic.text(word));
}

exports.letterLookup = function(cb) {

  var math = require("../lib/math");
  var reply = "";

  var lastWord = this.message.lemWords.slice(-1)[0];
  var alpha = "abcdefghijklmonpqrstuvwxyz".split("");
  var pos = alpha.indexOf(lastWord);

  if (this.message.lemWords.indexOf("before") != -1) {
    if (alpha[pos - 1]) {
      reply = alpha[pos - 1].toUpperCase();
    } else {
      reply = "Don't be silly, there is nothing before A";
    }
  } else if (this.message.lemWords.indexOf("after") != -1) {
    if (alpha[pos + 1]) {
      reply = alpha[pos + 1].toUpperCase();
    } else {
      reply = "haha, funny.";
    }
  } else {
    var i = this.message.lemWords.indexOf("letter");
    var loc = this.message.lemWords[i - 1];

    if (loc == "first") {
      reply = "It is A.";
    } else if (loc == "last") {
      reply = "It is Z.";
    } else {

      // Number or word number
      // 1st, 2nd, 3rd, 4th or less then 99
      if ((loc == "st"  || loc == "nd" || loc == "rd" || loc == "th") && this.message.numbers.length != 0 ) {
        var num = parseInt(this.message.numbers[0]);
        if (num > 0 && num <= 26) {
          reply =  "It is " + alpha[num - 1].toUpperCase();
        } else {
          reply = "seriously...";
        }
      }
    }
  }
  cb(null, reply);
}

exports.wordLength = function(cap, cb) {
  if (typeof cap == "string") {
    var parts = cap.split(" ");
    if (parts.length == 1) {
      cb(null, cap.length);
    } else {
      if (parts[0].toLowerCase() == "the" && parts.length == 3) {
        // name bill, word bill
        cb(null, parts.pop().length);
      } else if (parts[0] == "the" && parts[1].toLowerCase() == "alphabet") {
        cb(null, "26");
      } else if (parts[0] == "my" && parts.length == 2) {
        // Varible lookup
        var lookup = parts[1];
        this.user.get(lookup, function(e,v){
          if (v != -1 && v.length) {
            cb(null, "There are "+ v.length +" letters in your " + lookup + ".");
          } else {
            cb(null, "I don't know");
          }
        });
      } else if (parts[0] == "this" && parts.length == 2) {
        // this phrase, this sentence
        cb(null, "That phrase has " + this.message.raw.length + " characters. I think.");
      } else {
        cb(null, "I think there is about 10 characters. :)");
      }
    }

  } else {
    cap(null,"");
  }
}

exports.nextNumber = function(cb) {
  var reply = "";
  var num = this.message.numbers.slice(-1)[0];

  if (num) {
    if (this.message.lemWords.indexOf("before") != -1) {
      reply = parseInt(num) - 1;
    }
    if (this.message.lemWords.indexOf("after") != -1) {
      reply = parseInt(num) + 1;
    }
  }

  cb(null, reply);
};<commit_msg>Fixed opp plugin to use new fact db<commit_after>var rhyme = require('rhyme');
var syllabistic = require('syllablistic');
var debug = require("debug")("AlphaPlugins");
var _ = require("underscore");

var getRandomInt = function (min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

exports.oppisite = function(word, cb) {

  debug("oppisite", word);

  this.facts.db.get({subject:word, predicate: "opposite"}, function(err, opp) {

    if (!_.isEmpty(opp)) {
      var oppisiteWord = opp[0].object;
      oppisiteWord = oppisiteWord.replace(/_/g, " ");
      cb(null, oppisiteWord);
    } else {
      cb(null, "");
    }

  });
}

// This uses rhyme and it is painfully slow
exports.rhymes = function(word, cb) {

  debug("rhyming", word);

  rhyme(function (r) {
    var rhymedWords = r.rhyme(word);
    var i = getRandomInt(0, rhymedWords.length - 1);

    if (rhymedWords.length != 0) {
      cb(null, rhymedWords[i].toLowerCase());
    } else {
      cb(null, null);
    }
  });
}

exports.syllable = function(word, cb) {
  cb(null, syllabistic.text(word));
}

exports.letterLookup = function(cb) {

  var math = require("../lib/math");
  var reply = "";

  var lastWord = this.message.lemWords.slice(-1)[0];
  var alpha = "abcdefghijklmonpqrstuvwxyz".split("");
  var pos = alpha.indexOf(lastWord);

  if (this.message.lemWords.indexOf("before") != -1) {
    if (alpha[pos - 1]) {
      reply = alpha[pos - 1].toUpperCase();
    } else {
      reply = "Don't be silly, there is nothing before A";
    }
  } else if (this.message.lemWords.indexOf("after") != -1) {
    if (alpha[pos + 1]) {
      reply = alpha[pos + 1].toUpperCase();
    } else {
      reply = "haha, funny.";
    }
  } else {
    var i = this.message.lemWords.indexOf("letter");
    var loc = this.message.lemWords[i - 1];

    if (loc == "first") {
      reply = "It is A.";
    } else if (loc == "last") {
      reply = "It is Z.";
    } else {

      // Number or word number
      // 1st, 2nd, 3rd, 4th or less then 99
      if ((loc == "st"  || loc == "nd" || loc == "rd" || loc == "th") && this.message.numbers.length != 0 ) {
        var num = parseInt(this.message.numbers[0]);
        if (num > 0 && num <= 26) {
          reply =  "It is " + alpha[num - 1].toUpperCase();
        } else {
          reply = "seriously...";
        }
      }
    }
  }
  cb(null, reply);
}

exports.wordLength = function(cap, cb) {
  if (typeof cap == "string") {
    var parts = cap.split(" ");
    if (parts.length == 1) {
      cb(null, cap.length);
    } else {
      if (parts[0].toLowerCase() == "the" && parts.length == 3) {
        // name bill, word bill
        cb(null, parts.pop().length);
      } else if (parts[0] == "the" && parts[1].toLowerCase() == "alphabet") {
        cb(null, "26");
      } else if (parts[0] == "my" && parts.length == 2) {
        // Varible lookup
        var lookup = parts[1];
        this.user.get(lookup, function(e,v){
          if (v != -1 && v.length) {
            cb(null, "There are "+ v.length +" letters in your " + lookup + ".");
          } else {
            cb(null, "I don't know");
          }
        });
      } else if (parts[0] == "this" && parts.length == 2) {
        // this phrase, this sentence
        cb(null, "That phrase has " + this.message.raw.length + " characters. I think.");
      } else {
        cb(null, "I think there is about 10 characters. :)");
      }
    }

  } else {
    cap(null,"");
  }
}

exports.nextNumber = function(cb) {
  var reply = "";
  var num = this.message.numbers.slice(-1)[0];

  if (num) {
    if (this.message.lemWords.indexOf("before") != -1) {
      reply = parseInt(num) - 1;
    }
    if (this.message.lemWords.indexOf("after") != -1) {
      reply = parseInt(num) + 1;
    }
  }

  cb(null, reply);
};<|endoftext|>


<commit_before>/*
Get a random image from imgur

!imgur
*/
var sizeOf = require('image-size');
var fs = require('fs');
var http = require('http');
var request = require('request');
var crypto = require('crypto');

var imgur = function(){

    this.init = function(){

    };

    this.doStop = function(){

    };

    this.doMessage = function (msg, reply) {
        var re = /!imgur\s*/i;
        var match = re.exec(msg.text);

        if(match)
        {
            findValidPic(0, reply);
        }
    };

    findValidPic = function(s, reply){
        if(s > 50)
            return null;

        reply({type:"status", status: "upload_photo"});

        var current_date = (new Date()).valueOf().toString();
        var random = Math.random().toString();
        var fn = __dirname + "/../tmp/" + crypto.createHash('sha1').update(current_date + random).digest('hex') + ".png";

        generateUrl(5, function(url){
            request.get(url).pipe(fs.createWriteStream(fn)).on('close', function(){
                sizeOf(fn, function (err, dimensions){
                    if(!dimensions)
                    {
                        console.log("\tIMGUR: Wrong id " + s);
                        return findValidPic(++s, reply);
                    }
                    else if(dimensions.width<25 || dimensions.height<25)
                    {
                        console.log("\tIMGUR: Wrong id " + s);
                        return findValidPic(++s, reply);
                    }
                    else if((dimensions.width==198 && dimensions.height==160) || (dimensions.width==161 && dimensions.height==81))
                    {
                        console.log("\tIMGUR: Wrong id " + s);
                        return findValidPic(++s, reply);
                    }
                    else
                    {
                        console.log("\tIMGUR: Valid id " + url);
                        reply({type: 'photo', photo: fn});
                    }
                });
            });
        });

        return null;
    };

    generateUrl = function(len, callback){
        var url="";
        len = 5;
        var letters = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
        for(var i=0;i<len;i++)
        {
            url+=letters[Math.floor(Math.random()*letters.length)];
        }
        callback("http://i.imgur.com/"+url+"m.gif");
    }

};

module.exports = imgur;<commit_msg>Imgur, only download HEAD, only post link, no upload<commit_after>/*
Get a random image from imgur

!imgur
*/
var http = require('http');

var imgur = function(){

    this.init = function(){

    };

    this.doStop = function(){

    };

    this.doMessage = function (msg, reply) {
        var re = /!imgur\s*/i;
        var match = re.exec(msg.text);

        if(match)
        {
            findValidPic(0, reply);
        }
    };

    findValidPic = function(s, reply){
        if(s > 50)
            return null;

        reply({type:"status", status: "upload_photo"});

        generateUrl(5, function(url){
            var options = {method: 'HEAD', host: 'i.imgur.com', port: 80, path: '/' + url + ".png"};
            var req = http.request(options, function(res){
                headers = res.headers;

                if(headers["location"])
                {
                    console.log("\tIMGUR: Wrong id " + s);
                    return findValidPic(++s, reply);
                }
                else
                {
                    console.log("\tIMGUR: Valid id " + url);
                    reply({type: 'text', text: "http://i.imgur.com/" + url + ".png"});
                }
            });
            req.end();
        });

        return null;
    };

    generateUrl = function(len, callback){
        var url="";
        len = 5;
        var letters = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
        for(var i=0;i<len;i++)
        {
            url+=letters[Math.floor(Math.random()*letters.length)];
        }
        callback(url);
    }

};

module.exports = imgur;<|endoftext|>


<commit_before>'use strict';

import React from 'react';
import classnames from 'classnames';
import sectionIterator from './sectionIterator';

var guid = 0;

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

    guid += 1;
    this.id = guid;
    this.cache = {};
    this.state = {
      value: props.inputAttributes.value || '',
      suggestions: null,
      focusedSectionIndex: null,    // Used when multiple sections are displayed
      focusedSuggestionIndex: null, // Index within a section
      valueBeforeUpDown: null       // When user interacts using the Up and Down keys,
                                    // this field remembers input's value prior to
                                    // interaction in order to revert back if ESC hit.
                                    // See: http://www.w3.org/TR/wai-aria-practices/#autocomplete
    };
  }

  resetSectionIterator(suggestions) {
    if (this.isMultipleSections(suggestions)) {
      sectionIterator.setData(suggestions.map(function(suggestion) {
        return suggestion.suggestions.length;
      }));
    } else {
      sectionIterator.setData(suggestions === null ? [] : suggestions.length);
    }
  }

  isMultipleSections(suggestions) {
    return suggestions !== null &&
           suggestions.length > 0 &&
           typeof suggestions[0].suggestions !== 'undefined';
  }

  setSuggestionsState(suggestions) {
    this.resetSectionIterator(suggestions);
    this.setState({
      suggestions: suggestions,
      focusedSectionIndex: null,
      focusedSuggestionIndex: null,
      valueBeforeUpDown: null
    });
  }

  suggestionsExist(suggestions) {
    if (this.isMultipleSections(suggestions)) {
      return suggestions.some(function(section) {
        return section.suggestions.length > 0;
      });
    }

    return suggestions.length > 0;
  }

  showSuggestions(input) {
    if (input.length === 0) {
      this.setSuggestionsState(null);
    } else if (this.cache[input]) {
      this.setSuggestionsState(this.cache[input]);
    } else {
      this.props.suggestions(input, function(error, suggestions) {
        if (error) {
          throw error;
        } else {
          if (!this.suggestionsExist(suggestions)) {
            suggestions = null;
          }

          this.cache[input] = suggestions;
          this.setSuggestionsState(suggestions);
        }
      }.bind(this));
    }
  }

  getSuggestion(sectionIndex, suggestionIndex) {
    return this.isMultipleSections(this.state.suggestions)
      ? this.state.suggestions[sectionIndex].suggestions[suggestionIndex]
      : this.state.suggestions[suggestionIndex];
  }

  stripHTML(html) {
    var div = document.createElement('div');

    div.innerHTML = html;

    return div.textContent;
  }

  suggestionToString(suggestion) {
    var renderedSuggestion = this.renderSuggestion(suggestion);

    if (React.isValidElement(renderedSuggestion)) {
      return this.stripHTML(React.renderToStaticMarkup(renderedSuggestion));
    } else {
      return renderedSuggestion;
    }
  }

  focusOnSuggestion(suggestionPosition) {
    var [sectionIndex, suggestionIndex] = suggestionPosition;
    var newState = {
      focusedSectionIndex: sectionIndex,
      focusedSuggestionIndex: suggestionIndex,
      value: suggestionIndex === null
               ? this.state.valueBeforeUpDown
               : this.suggestionToString(this.getSuggestion(sectionIndex, suggestionIndex))
    };

    // When users starts to interact with up/down keys, remember input's value.
    if (this.state.valueBeforeUpDown === null) {
      newState.valueBeforeUpDown = this.state.value;
    }

    this.setState(newState);
  }

  onInputChange(event) {
    var newValue = event.target.value;

    this.setState({
      value: newValue,
      valueBeforeUpDown: null
    });

    this.showSuggestions(newValue);
  }

  onInputKeyDown(event) {
    var newState, newSectionIndex, newSuggestionIndex;

    switch (event.keyCode) {
      case 13: // enter
        this.setSuggestionsState(null);
        break;

      case 27: // escape
        newState = {
          suggestions: null,
          focusedSectionIndex: null,
          focusedSuggestionIndex: null,
          valueBeforeUpDown: null
        };

        if (this.state.valueBeforeUpDown !== null) {
          newState.value = this.state.valueBeforeUpDown;
        } else if (this.state.suggestions === null) {
          newState.value = '';
        }

        this.setState(newState);
        break;

      case 38: // up
        if (this.state.suggestions === null) {
          this.showSuggestions(this.state.value);
        } else {
          this.focusOnSuggestion(sectionIterator.prev([this.state.focusedSectionIndex, this.state.focusedSuggestionIndex]));
        }

        event.preventDefault(); // Prevent the cursor from jumping to input's start
        break;

      case 40: // down
        if (this.state.suggestions === null) {
          this.showSuggestions(this.state.value);
        } else {
          this.focusOnSuggestion(sectionIterator.next([this.state.focusedSectionIndex, this.state.focusedSuggestionIndex]));
        }

        break;
    }
  }

  onInputBlur() {
    this.setSuggestionsState(null);
  }

  onSuggestionMouseEnter(sectionIndex, suggestionIndex) {
    this.setState({
      focusedSectionIndex: sectionIndex,
      focusedSuggestionIndex: suggestionIndex
    });
  }

  onSuggestionMouseLeave() {
    this.setState({
      focusedSectionIndex: null,
      focusedSuggestionIndex: null
    });
  }

  onSuggestionMouseDown(suggestion) {
    this.setState({
      value: suggestion,
      suggestions: null,
      focusedSectionIndex: null,
      focusedSuggestionIndex: null,
      valueBeforeUpDown: null
    }, function() {
      // This code executes after the component is re-rendered
      setTimeout(function() {
        React.findDOMNode(this.refs.input).focus();
      }.bind(this));
    });
  }

  getSuggestionId(sectionIndex, suggestionIndex) {
    if (suggestionIndex === null) {
      return null;
    }

    return 'react-autosuggest-' + this.id + '-suggestion-' +
           (sectionIndex === null ? '' : sectionIndex) + '-' + suggestionIndex;
  }

  renderSuggestion(suggestion) {
    if (this.props.suggestionRenderer) {
      return this.props.suggestionRenderer(suggestion, this.state.valueBeforeUpDown || this.state.value);
    }

    if (typeof suggestion === 'object') {
      throw new Error('When <suggestion> is an object, you must implement the suggestionRenderer() function to specify how to render it.');
    } else {
      return suggestion.toString();
    }
  }

  renderSuggestionsList(suggestions, sectionIndex) {
    return suggestions.map(function(suggestion, suggestionIndex) {
      var classes = classnames({
        'react-autosuggest__suggestion': true,
        'react-autosuggest__suggestion--focused':
          sectionIndex === this.state.focusedSectionIndex &&
          suggestionIndex === this.state.focusedSuggestionIndex
      });

      return (

          {this.renderSuggestion(suggestion)}

      );
    }, this);
  }

  renderSuggestions() {
    if (this.state.value === '' || this.state.suggestions === null) {
      return null;
    }

    var content;

    if (this.isMultipleSections(this.state.suggestions)) {
      content = this.state.suggestions.map(function(section, sectionIndex) {
        var sectionName = section.sectionName ? (

            {section.sectionName}

        ) : null;

        return section.suggestions.length === 0 ? null : (

            {sectionName}
            {this.renderSuggestionsList(section.suggestions, sectionIndex)}

        );
      }, this);
    } else {
      content = this.renderSuggestionsList(this.state.suggestions, null);
    }

    return (

        {content}

    );
  }

  render() {
    var ariaActivedescendant =
      this.getSuggestionId(this.state.focusedSectionIndex, this.state.focusedSuggestionIndex);

    return (

        <input {...this.props.inputAttributes}
               type="text"
               value={this.state.value}
               autoComplete="off"
               role="combobox"
               aria-autocomplete="list"
               aria-owns={'react-autosuggest-' + this.id}
               aria-expanded={this.state.suggestions !== null}
               aria-activedescendant={ariaActivedescendant}
               ref="input"
               onChange={this.onInputChange.bind(this)}
               onKeyDown={this.onInputKeyDown.bind(this)}
               onBlur={this.onInputBlur.bind(this)} />
        {this.renderSuggestions()}

    );
  }
}

Autosuggest.propTypes = {
  inputAttributes: React.PropTypes.objectOf(React.PropTypes.string), // Attributes to pass to the input field (e.g. { id: 'my-input', className: 'sweet autosuggest' })
  suggestions: React.PropTypes.func.isRequired,                      // Function to get the suggestions
  suggestionRenderer: React.PropTypes.func                           // Function to render a single suggestion
};

Autosuggest.defaultProps = {
  inputAttributes: {}
};

export default Autosuggest;
<commit_msg>Remove stripHTML<commit_after>'use strict';

import React from 'react';
import classnames from 'classnames';
import sectionIterator from './sectionIterator';

var guid = 0;

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

    guid += 1;
    this.id = guid;
    this.cache = {};
    this.state = {
      value: props.inputAttributes.value || '',
      suggestions: null,
      focusedSectionIndex: null,    // Used when multiple sections are displayed
      focusedSuggestionIndex: null, // Index within a section
      valueBeforeUpDown: null       // When user interacts using the Up and Down keys,
                                    // this field remembers input's value prior to
                                    // interaction in order to revert back if ESC hit.
                                    // See: http://www.w3.org/TR/wai-aria-practices/#autocomplete
    };
  }

  resetSectionIterator(suggestions) {
    if (this.isMultipleSections(suggestions)) {
      sectionIterator.setData(suggestions.map(function(suggestion) {
        return suggestion.suggestions.length;
      }));
    } else {
      sectionIterator.setData(suggestions === null ? [] : suggestions.length);
    }
  }

  isMultipleSections(suggestions) {
    return suggestions !== null &&
           suggestions.length > 0 &&
           typeof suggestions[0].suggestions !== 'undefined';
  }

  setSuggestionsState(suggestions) {
    this.resetSectionIterator(suggestions);
    this.setState({
      suggestions: suggestions,
      focusedSectionIndex: null,
      focusedSuggestionIndex: null,
      valueBeforeUpDown: null
    });
  }

  suggestionsExist(suggestions) {
    if (this.isMultipleSections(suggestions)) {
      return suggestions.some(function(section) {
        return section.suggestions.length > 0;
      });
    }

    return suggestions.length > 0;
  }

  showSuggestions(input) {
    if (input.length === 0) {
      this.setSuggestionsState(null);
    } else if (this.cache[input]) {
      this.setSuggestionsState(this.cache[input]);
    } else {
      this.props.suggestions(input, function(error, suggestions) {
        if (error) {
          throw error;
        } else {
          if (!this.suggestionsExist(suggestions)) {
            suggestions = null;
          }

          this.cache[input] = suggestions;
          this.setSuggestionsState(suggestions);
        }
      }.bind(this));
    }
  }

  focusOnSuggestion(suggestionPosition) {
    var [sectionIndex, suggestionIndex] = suggestionPosition;
    var newState = {
      focusedSectionIndex: sectionIndex,
      focusedSuggestionIndex: suggestionIndex,
      value: suggestionIndex === null
               ? this.state.valueBeforeUpDown
               : React.findDOMNode(this.refs[this.getSuggestionKey(sectionIndex, suggestionIndex)]).textContent
    };

    // When users starts to interact with up/down keys, remember input's value.
    if (this.state.valueBeforeUpDown === null) {
      newState.valueBeforeUpDown = this.state.value;
    }

    this.setState(newState);
  }

  onInputChange(event) {
    var newValue = event.target.value;

    this.setState({
      value: newValue,
      valueBeforeUpDown: null
    });

    this.showSuggestions(newValue);
  }

  onInputKeyDown(event) {
    var newState, newSectionIndex, newSuggestionIndex;

    switch (event.keyCode) {
      case 13: // enter
        this.setSuggestionsState(null);
        break;

      case 27: // escape
        newState = {
          suggestions: null,
          focusedSectionIndex: null,
          focusedSuggestionIndex: null,
          valueBeforeUpDown: null
        };

        if (this.state.valueBeforeUpDown !== null) {
          newState.value = this.state.valueBeforeUpDown;
        } else if (this.state.suggestions === null) {
          newState.value = '';
        }

        this.setState(newState);
        break;

      case 38: // up
        if (this.state.suggestions === null) {
          this.showSuggestions(this.state.value);
        } else {
          this.focusOnSuggestion(sectionIterator.prev([this.state.focusedSectionIndex, this.state.focusedSuggestionIndex]));
        }

        event.preventDefault(); // Prevent the cursor from jumping to input's start
        break;

      case 40: // down
        if (this.state.suggestions === null) {
          this.showSuggestions(this.state.value);
        } else {
          this.focusOnSuggestion(sectionIterator.next([this.state.focusedSectionIndex, this.state.focusedSuggestionIndex]));
        }

        break;
    }
  }

  onInputBlur() {
    this.setSuggestionsState(null);
  }

  onSuggestionMouseEnter(sectionIndex, suggestionIndex) {
    this.setState({
      focusedSectionIndex: sectionIndex,
      focusedSuggestionIndex: suggestionIndex
    });
  }

  onSuggestionMouseLeave() {
    this.setState({
      focusedSectionIndex: null,
      focusedSuggestionIndex: null
    });
  }

  onSuggestionMouseDown(suggestion) {
    this.setState({
      value: suggestion,
      suggestions: null,
      focusedSectionIndex: null,
      focusedSuggestionIndex: null,
      valueBeforeUpDown: null
    }, function() {
      // This code executes after the component is re-rendered
      setTimeout(function() {
        React.findDOMNode(this.refs.input).focus();
      }.bind(this));
    });
  }

  getSuggestionId(sectionIndex, suggestionIndex) {
    if (suggestionIndex === null) {
      return null;
    }

    return 'react-autosuggest-' + this.id + '-suggestion-' +
           (sectionIndex === null ? '' : sectionIndex) + '-' + suggestionIndex;
  }

  getSuggestionKey(sectionIndex, suggestionIndex) {
    return 'suggestion-' + (sectionIndex === null ? '' : sectionIndex) +
           '-' + suggestionIndex;
  }

  renderSuggestionContent(suggestion) {
    if (this.props.suggestionRenderer) {
      return this.props.suggestionRenderer(suggestion, this.state.valueBeforeUpDown || this.state.value);
    }

    if (typeof suggestion === 'object') {
      throw new Error('When <suggestion> is an object, you must implement the suggestionRenderer() function to specify how to render it.');
    } else {
      return suggestion.toString();
    }
  }

  renderSuggestionsList(suggestions, sectionIndex) {
    return suggestions.map(function(suggestion, suggestionIndex) {
      var classes = classnames({
        'react-autosuggest__suggestion': true,
        'react-autosuggest__suggestion--focused':
          sectionIndex === this.state.focusedSectionIndex &&
          suggestionIndex === this.state.focusedSuggestionIndex
      });
      var suggestionKey = this.getSuggestionKey(sectionIndex, suggestionIndex);

      return (

          {this.renderSuggestionContent(suggestion)}

      );
    }, this);
  }

  renderSuggestions() {
    if (this.state.value === '' || this.state.suggestions === null) {
      return null;
    }

    var content;

    if (this.isMultipleSections(this.state.suggestions)) {
      content = this.state.suggestions.map(function(section, sectionIndex) {
        var sectionName = section.sectionName ? (

            {section.sectionName}

        ) : null;

        return section.suggestions.length === 0 ? null : (

            {sectionName}
            {this.renderSuggestionsList(section.suggestions, sectionIndex)}

        );
      }, this);
    } else {
      content = this.renderSuggestionsList(this.state.suggestions, null);
    }

    return (

        {content}

    );
  }

  render() {
    var ariaActivedescendant =
      this.getSuggestionId(this.state.focusedSectionIndex, this.state.focusedSuggestionIndex);

    return (

        <input {...this.props.inputAttributes}
               type="text"
               value={this.state.value}
               autoComplete="off"
               role="combobox"
               aria-autocomplete="list"
               aria-owns={'react-autosuggest-' + this.id}
               aria-expanded={this.state.suggestions !== null}
               aria-activedescendant={ariaActivedescendant}
               ref="input"
               onChange={this.onInputChange.bind(this)}
               onKeyDown={this.onInputKeyDown.bind(this)}
               onBlur={this.onInputBlur.bind(this)} />
        {this.renderSuggestions()}

    );
  }
}

Autosuggest.propTypes = {
  inputAttributes: React.PropTypes.objectOf(React.PropTypes.string), // Attributes to pass to the input field (e.g. { id: 'my-input', className: 'sweet autosuggest' })
  suggestions: React.PropTypes.func.isRequired,                      // Function to get the suggestions
  suggestionRenderer: React.PropTypes.func                           // Function to render a single suggestion
};

Autosuggest.defaultProps = {
  inputAttributes: {}
};

export default Autosuggest;
<|endoftext|>


<commit_before>'use strict';

var ClickHandler = require(process.cwd() + '/app/controllers/clickHandler.server.js');

module.exports = function (app, db) {
	var bodyParser = require('body-parser');
	app.use( bodyParser.json() );       // to support JSON-encoded bodies
	app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  		extended: true
	}));
    var clickHandler = new ClickHandler(db);

    app.route('/')
        .get(function (req, res) {
            res.sendFile(process.cwd() + '/public/index.html');
        });

    app.route('/api/clicks')
        .get(clickHandler.getClicks)
        //.post(clickHandler.addClick)
        .delete(clickHandler.resetClicks);

    app.route('/login')
    	.get(function (req, res) {
            res.sendFile(process.cwd() + '/public/login.html');
        })
        .post(clickHandler.loginCheck);

    app.route('/signup')
    	.get(function (req, res) {
            res.sendFile(process.cwd() + '/public/signup.html');
        })
        .post(clickHandler.addUser, function (req, res) {
            res.redirect('/login/');
        });

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

    app.route('/newpoll')
    	.get(clickHandler.isLogged, clickHandler.createPoll, function (req, res) {
        	//res.redirect('/poll/');
        });

    app.route('/poll/:name/:ptitle')
    	.get(function (req, res) {
            res.sendFile(process.cwd() + '/public/poll.html');
        })
    	.post(clickHandler.displayPoll);

    app.route('/api/polls')
        .get(clickHandler.getPolls);

    app.route('/poll/:name/:ptitle/postpoll')
    	.post(clickHandler.pollVote);

  	app.route('/poll/:name/:ptitle/view')
  		.get(clickHandler.isLogged, function (req, res) {
            res.sendFile(process.cwd() + '/public/view.html');
        })
        .post(clickHandler.viewPoll);

    app.route('/api/delete')
    	.get (clickHandler.deletePoll);

    app.route('/yelping')
        .get(clickHandler.yelpMe);

};<commit_msg>Cleanup<commit_after>'use strict';

var ClickHandler = require(process.cwd() + '/app/controllers/clickHandler.server.js');

module.exports = function (app, db) {
	var bodyParser = require('body-parser');
	app.use( bodyParser.json() );       // to support JSON-encoded bodies
	app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  		extended: true
	}));
    var clickHandler = new ClickHandler(db);

    app.route('/')
        .get(function (req, res) {
            res.sendFile(process.cwd() + '/public/index.html');
        });

    app.route('/api/clicks')
        .get(clickHandler.getClicks)
        //.post(clickHandler.addClick)
        .delete(clickHandler.resetClicks);

    app.route('/login')
    	.get(function (req, res) {
            res.sendFile(process.cwd() + '/public/login.html');
        })
        .post(clickHandler.loginCheck);

    app.route('/signup')
    	.get(function (req, res) {
            res.sendFile(process.cwd() + '/public/signup.html');
        })
        .post(clickHandler.addUser, function (req, res) {
            res.redirect('/login/');
        });

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

    app.route('/newpoll')
    	.get(clickHandler.isLogged, clickHandler.createPoll, function (req, res) {
        	//res.redirect('/poll/');
        });

    app.route('/api/polls')
        .get(clickHandler.getPolls);

    app.route('/api/delete')
    	.get (clickHandler.deletePoll);

    app.route('/yelping')
        .get(clickHandler.yelpMe);

};<|endoftext|>


<commit_before>'use strict';

var path = process.cwd();
const UserController = require(path + '/app/controllers/userController.server.js');
const PollController = require(path + '/app/controllers/pollController.server.js');

/** Function for debug logging request.*/
var reqDebug = function(req) {
	console.log("Headers: " + JSON.stringify(req.headers));
	console.log("Body: "    + JSON.stringify(req.body));
	console.log("Params: "  + JSON.stringify(req.params));
	console.log("Url:"      + JSON.stringify(req.url));
	console.log("Text:"     + JSON.stringify(req.text));
	console.log("Content:"  + JSON.stringify(req.content));
	console.log("Query:"    + JSON.stringify(req.query));
};

module.exports = function (app, passport) {

    /** loggedIn func from clementine.js. */
	function isLoggedIn (req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		} else {
			res.redirect('/login');
		}
	}

    var userController = new UserController();
	var pollController = new PollController(path);

	app.route('/')
		.get(function (req, res) {
			res.sendFile(path + '/public/index.html');
		});

	app.route('/signup')
		.get(function (req, res) {
			res.sendFile(path + '/public/signup.html');
		});

	app.route('/login')
		.get(function (req, res) {
			res.sendFile(path + '/public/login.html');
		});

    // If a user logs out, return to main page
	app.route('/logout')
		.get(function (req, res) {
			req.logout();
			res.redirect('/');
		});

    app.route('/create')
        .get(isLoggedIn, function(req, res) {
            res.sendFile(path + '/public/create.html');
        });

	app.route('/profile')
		.get(isLoggedIn, function (req, res) {
			res.sendFile(path + '/public/profile.html');
		});

    // Handle registration of user
    app.route('/forms/signup')
        .post(function(req, res) {
            console.log("Got a signup form GET request..");
			reqDebug(req);
            userController.addUser(req, res);
        });

    //---------------------------------------------
    // Routes for creating/deleting/updating polls
    //---------------------------------------------

    app.route('/polls')
        .get(function(req, res) {
            pollController.getPolls(req, res);
        });

    app.route('/polls/create')
        .post(isLoggedIn, function(req, res) {
            pollController.addPoll(req, res);
        });

    app.route('/polls/vote/:id')
        .post(function(req, res) {
            pollController.voteOnPoll(req, res);
        });

    app.route('/polls/update/:id')
        .post(function(req, res) {
            pollController.updatePollById(req, res);
        });

    app.route('/polls/delete/:id')
        .post(function(req, res) {
            pollController.deletePollById(req, res);
        });

    app.route('/polls/:id')
        .get(function(req, res) {
            pollController.getPollById(req, res);
            //res.json(["aaaa", "bbbb"]);
        });

    //--------------------------------------
    // User registration and authentication
    //--------------------------------------

	app.route('/api/:id')
		.get(function (req, res) {
            if (req.isAuthenticated()) {
                console.log("Req auth, user " + JSON.stringify(req.user));
                if (req.user.github.username) {
                    res.json(req.user.github);
                }
                else if (req.user.local.username) {
                    res.json(req.user.local);
                }
                else
                    res.sendStatus(400); // Something went wrong terribly
            }
            else {
                res.json({name: "guest"});
            }
		});

    // Logs user in via form (after successful authentication
	app.route('/auth/userlogin')
        .post(passport.authenticate('local', { failureRedirect: '/login' }),
		function(req, res) {
			res.redirect('/');
		});

	app.route('/auth/github')
		.get(passport.authenticate('github'));

	app.route('/auth/github/callback')
		.get(passport.authenticate('github', {
			successRedirect: '/',
			failureRedirect: '/login'
		}));

};
<commit_msg>index is now rendered from pug.<commit_after>'use strict';

var path = process.cwd();
const UserController = require(path + '/app/controllers/userController.server.js');
const PollController = require(path + '/app/controllers/pollController.server.js');

/** Function for debug logging request.*/
var reqDebug = function(req) {
	console.log("Headers: " + JSON.stringify(req.headers));
	console.log("Body: "    + JSON.stringify(req.body));
	console.log("Params: "  + JSON.stringify(req.params));
	console.log("Url:"      + JSON.stringify(req.url));
	console.log("Text:"     + JSON.stringify(req.text));
	console.log("Content:"  + JSON.stringify(req.content));
	console.log("Query:"    + JSON.stringify(req.query));
};

module.exports = function (app, passport) {

    /** loggedIn func from clementine.js. */
	function isLoggedIn (req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		} else {
			res.redirect('/login');
		}
	}

    var userController = new UserController();
	var pollController = new PollController(path);

	app.route('/')
		.get(function (req, res) {
            var isAuth = req.isAuthenticated();
            res.render(path + "/pug/index.pug",
                {isAuth: isAuth});
		});

	app.route('/signup')
		.get(function (req, res) {
			res.sendFile(path + '/public/signup.html');
		});

	app.route('/login')
		.get(function (req, res) {
			res.sendFile(path + '/public/login.html');
		});

    // If a user logs out, return to main page
	app.route('/logout')
		.get(function (req, res) {
			req.logout();
			res.redirect('/');
		});

    app.route('/create')
        .get(isLoggedIn, function(req, res) {
            res.sendFile(path + '/public/create.html');
        });

	app.route('/profile')
		.get(isLoggedIn, function (req, res) {
			res.sendFile(path + '/public/profile.html');
		});

    // Handle registration of user
    app.route('/forms/signup')
        .post(function(req, res) {
            console.log("Got a signup form GET request..");
			reqDebug(req);
            userController.addUser(req, res);
        });

    //---------------------------------------------
    // Routes for creating/deleting/updating polls
    //---------------------------------------------

    app.route('/polls')
        .get(function(req, res) {
            pollController.getPolls(req, res);
        });

    app.route('/polls/create')
        .post(isLoggedIn, function(req, res) {
            pollController.addPoll(req, res);
        });

    app.route('/polls/vote/:id')
        .post(function(req, res) {
            pollController.voteOnPoll(req, res);
        });

    app.route('/polls/update/:id')
        .post(function(req, res) {
            pollController.updatePollById(req, res);
        });

    app.route('/polls/delete/:id')
        .post(function(req, res) {
            pollController.deletePollById(req, res);
        });

    app.route('/polls/:id')
        .get(function(req, res) {
            pollController.getPollById(req, res);
            //res.json(["aaaa", "bbbb"]);
        });

    //--------------------------------------
    // User registration and authentication
    //--------------------------------------

	app.route('/api/:id')
		.get(function (req, res) {
            if (req.isAuthenticated()) {
                console.log("Req auth, user " + JSON.stringify(req.user));
                if (req.user.github.username) {
                    res.json(req.user.github);
                }
                else if (req.user.local.username) {
                    res.json(req.user.local);
                }
                else
                    res.sendStatus(400); // Something went wrong terribly
            }
            else {
                res.json({name: "guest"});
            }
		});

    // Logs user in via form (after successful authentication
	app.route('/auth/userlogin')
        .post(passport.authenticate('local', { failureRedirect: '/login' }),
		function(req, res) {
			res.redirect('/');
		});

	app.route('/auth/github')
		.get(passport.authenticate('github'));

	app.route('/auth/github/callback')
		.get(passport.authenticate('github', {
			successRedirect: '/',
			failureRedirect: '/login'
		}));

};
<|endoftext|>


<commit_before>'use strict';

var path = process.cwd();
var ClickHandler = require(path + '/app/controllers/clickHandler.server.js');

module.exports = function (app, passport) {

	function isLoggedIn (req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		} else {
			res.redirect('/login');
		}
	}

	var clickHandler = new ClickHandler();

	app.route('/')
		.get(isLoggedIn, function (req, res) {
			res.sendFile(path + '/public/index.html');
		});

	app.route('/login')
		.get(function (req, res) {
			res.sendFile(path + '/public/login.html');
		});

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

	app.route('/profile')
		.get(isLoggedIn, function (req, res) {
			res.sendFile(path + '/public/profile.html');
		});

	app.route('/api/:id')
		.get(isLoggedIn, function (req, res) {
			res.json(req.user.github);
		});

	app.route('/auth/github')
		.get(passport.authenticate('github'));

	app.route('/auth/github/callback')
		.get(passport.authenticate('github', {
			successRedirect: '/',
			failureRedirect: '/login'
		}));

	app.route('/api/:id/clicks')
		.get(isLoggedIn, clickHandler.getClicks)
		.post(isLoggedIn, clickHandler.addClick)
		.delete(isLoggedIn, clickHandler.resetClicks);
};
<commit_msg>route test<commit_after>'use strict';

var path = process.cwd();
var ClickHandler = require(path + '/app/controllers/clickHandler.server.js');

module.exports = function (app, passport) {

	function isLoggedIn (req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		} else {
			res.redirect('/login');
		}
	}

	var clickHandler = new ClickHandler();

	app.route('/')
		.get(isLoggedIn, function (req, res) {
			res.sendFile(path + '/public/index.html');
		});

	app.route('./123')
		.get( function (req, res) {
			res.send('Huzzah!');
			res.end();
		});

	app.route('/login')
		.get(function (req, res) {
			res.sendFile(path + '/public/login.html');
		});

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

	app.route('/profile')
		.get(isLoggedIn, function (req, res) {
			res.sendFile(path + '/public/profile.html');
		});

	app.route('/api/:id')
		.get(isLoggedIn, function (req, res) {
			res.json(req.user.github);
		});

	app.route('/auth/github')
		.get(passport.authenticate('github'));

	app.route('/auth/github/callback')
		.get(passport.authenticate('github', {
			successRedirect: '/',
			failureRedirect: '/login'
		}));

	app.route('/api/:id/clicks')
		.get(isLoggedIn, clickHandler.getClicks)
		.post(isLoggedIn, clickHandler.addClick)
		.delete(isLoggedIn, clickHandler.resetClicks);
};
<|endoftext|>