<commit_before>export default class Logger {
    constructor () {
        this.watching = true;

        this.MESSAGES = {
            intro: `
Live mode is enabled.
TestCafe now watches source files and reruns
the tests once the changes are saved.

You can use the following keys in the terminal:
'Ctrl+S' - stops the test run;
'Ctrl+R' - restarts the test run;
'Ctrl+W' - enables/disables watching files;
'Ctrl+C' - quits live mode and closes the browsers.

`,

            sourceChanged:              'The sources have changed. A test run is starting...',
            testRunStarting:            'A test run is starting...',
            testRunStopping:            'The test run is stopping...',
            testRunFinishedWatching:    'Make changes to the source files or press Ctrl+R to restart the test run.',
            testRunFinishedNotWatching: 'Press Ctrl+R to restart the test run.',
            fileWatchingEnabled:        'TestCafe is watching the source files. Save the changes to run tests.',
            fileWatchingDisabled:       'TestCafe is not watching the source files.',
            nothingToStop:              'There are no tests running at the moment.',
            testCafeStopping:           'Stopping TestCafe live mode...',
            watchingFiles:              'Watching the following files:',
        };
    }

    _write (msg) {
        process.stdout.write(msg);
    }

    _status (msg) {
        this._write('\n' + msg + '\n');
    }

    writeIntroMessage (files) {
        this._write(this.MESSAGES.intro);

        if (!Array.isArray(files))
            return;

        this._status(this.MESSAGES.watchingFiles);

        files.forEach(file => {
            this._write('  ' + file + '\n');
        });

        this._write('\n');
    }

    writeRunTestsMessage (sourcesChanged) {
        const statusMessage = sourcesChanged ? this.MESSAGES.sourceChanged : this.MESSAGES.testRunStarting;

        this._status(statusMessage);
    }

    writeTestsFinishedMessage () {
        const statusMessage = this.watching ? this.MESSAGES.testRunFinishedWatching : this.MESSAGES.testRunFinishedNotWatching;

        this._status(statusMessage);
    }

    writeStopRunningMessage () {
        this._status(this.MESSAGES.testRunStopping);
    }

    writeNothingToStopMessage () {
        this._status(this.MESSAGES.nothingToStop);
    }

    writeToggleWatchingMessage (enable) {
        this.watching = enable;

        const statusMessage = enable ? this.MESSAGES.fileWatchingEnabled : this.MESSAGES.fileWatchingDisabled;

        this._status(statusMessage);
    }

    writeExitMessage () {
        this._status(this.MESSAGES.testCafeStopping);
    }

    err (err) {
        /* eslint-disable no-console */
        console.log(err);
        /* eslint-enable no-console */
    }

}
<commit_msg>fix spinner frames (closes #3452) (#3561)<commit_after>import log from '../../cli/log';

export default class Logger {
    constructor () {
        this.watching = true;

        this.MESSAGES = {
            intro: `Live mode is enabled.
TestCafe now watches source files and reruns
the tests once the changes are saved.

You can use the following keys in the terminal:
'Ctrl+S' - stops the test run;
'Ctrl+R' - restarts the test run;
'Ctrl+W' - enables/disables watching files;
'Ctrl+C' - quits live mode and closes the browsers.
`,

            sourceChanged:              'The sources have changed. A test run is starting...',
            testRunStarting:            'A test run is starting...',
            testRunStopping:            'The test run is stopping...',
            testRunFinishedWatching:    'Make changes to the source files or press Ctrl+R to restart the test run.',
            testRunFinishedNotWatching: 'Press Ctrl+R to restart the test run.',
            fileWatchingEnabled:        'TestCafe is watching the source files. Save the changes to run tests.',
            fileWatchingDisabled:       'TestCafe is not watching the source files.',
            nothingToStop:              'There are no tests running at the moment.',
            testCafeStopping:           'Stopping TestCafe live mode...',
            watchingFiles:              'Watching the following files:',
        };
    }

    _write (msg, prefix = '\n') {
        log.write(`${prefix}${msg}`);
    }

    writeIntroMessage (files) {
        this._write(this.MESSAGES.intro);

        if (!Array.isArray(files))
            return;

        this._write(this.MESSAGES.watchingFiles);

        files.forEach(file => {
            this._write(file, '  ');
        });
    }

    writeRunTestsMessage (sourcesChanged) {
        const statusMessage = sourcesChanged ? this.MESSAGES.sourceChanged : this.MESSAGES.testRunStarting;

        this._write(statusMessage);
    }

    writeTestsFinishedMessage () {
        const statusMessage = this.watching ? this.MESSAGES.testRunFinishedWatching : this.MESSAGES.testRunFinishedNotWatching;

        this._write(statusMessage);
    }

    writeStopRunningMessage () {
        this._write(this.MESSAGES.testRunStopping);
    }

    writeNothingToStopMessage () {
        this._write(this.MESSAGES.nothingToStop);
    }

    writeToggleWatchingMessage (enable) {
        this.watching = enable;

        const statusMessage = enable ? this.MESSAGES.fileWatchingEnabled : this.MESSAGES.fileWatchingDisabled;

        this._write(statusMessage);
    }

    writeExitMessage () {
        this._write(this.MESSAGES.testCafeStopping);
    }

    err (err) {
        /* eslint-disable no-console */
        console.log(err);
        /* eslint-enable no-console */
    }

}
<|endoftext|>


<commit_before>module.exports = Server

var bencode = require('bencode')
var debug = require('debug')('bittorrent-tracker')
var dgram = require('dgram')
var EventEmitter = require('events').EventEmitter
var http = require('http')
var inherits = require('inherits')
var portfinder = require('portfinder')
var series = require('run-series')
var string2compact = require('string2compact')

var common = require('./lib/common')
var Swarm = require('./lib/swarm')
var parseHttpRequest = require('./lib/parse_http')
var parseUdpRequest = require('./lib/parse_udp')

// Use random port above 1024
portfinder.basePort = Math.floor(Math.random() * 60000) + 1025

inherits(Server, EventEmitter)

/**
 * A BitTorrent tracker server.
 *
 * A "BitTorrent tracker" is an HTTP service which responds to GET requests from
 * BitTorrent clients. The requests include metrics from clients that help the tracker
 * keep overall statistics about the torrent. The response includes a peer list that
 * helps the client participate in the torrent.
 *
 * @param {Object}  opts            options
 * @param {Number}  opts.interval   interval in ms that clients should announce on
 * @param {Number}  opts.trustProxy Trust 'x-forwarded-for' header from reverse proxy
 * @param {boolean} opts.http       Start an http server? (default: true)
 * @param {boolean} opts.udp        Start a udp server? (default: true)
 */
function Server (opts) {
  var self = this
  if (!(self instanceof Server)) return new Server(opts)
  EventEmitter.call(self)
  opts = opts || {}

  self._intervalMs = opts.interval
    ? opts.interval / 1000
    : 10 * 60 // 10 min (in secs)

  self._trustProxy = !!opts.trustProxy

  self.listening = false
  self.port = null
  self.torrents = {}

  // default to starting an http server unless the user explictly says no
  if (opts.http !== false) {
    self._httpServer = http.createServer()
    self._httpServer.on('request', self._onHttpRequest.bind(self))
    self._httpServer.on('error', self._onError.bind(self))
    self._httpServer.on('listening', onListening)
  }

  // default to starting a udp server unless the user explicitly says no
  if (opts.udp !== false) {
    self._udpServer = dgram.createSocket('udp4')
    self._udpServer.on('message', self._onUdpRequest.bind(self))
    self._udpServer.on('error', self._onError.bind(self))
    self._udpServer.on('listening', onListening)
  }

  var num = !!self._httpServer + !!self._udpServer
  function onListening () {
    num -= 1
    if (num === 0) {
      self.listening = true
      self.emit('listening', self.port)
    }
  }
}

Server.prototype._onError = function (err) {
  var self = this
  self.emit('error', err)
}

Server.prototype.listen = function (port, onlistening) {
  var self = this
  if (typeof port === 'function') {
    onlistening = port
    port = undefined
  }
  if (self.listening) throw new Error('server already listening')
  if (onlistening) self.once('listening', onlistening)

  function onPort (err, port) {
    if (err) return self.emit('error', err)
    self.port = port
    self._httpServer && self._httpServer.listen(port.http || port)
    self._udpServer && self._udpServer.bind(port.udp || port)
  }

  if (port) onPort(null, port)
  else portfinder.getPort(onPort)
}

Server.prototype.close = function (cb) {
  var self = this
  cb = cb || function () {}
  if (self._udpServer) {
    self._udpServer.close()
  }
  if (self._httpServer) {
    self._httpServer.close(cb)
  } else {
    cb(null)
  }
}

Server.prototype.getSwarm = function (binaryInfoHash) {
  var self = this
  if (Buffer.isBuffer(binaryInfoHash)) binaryInfoHash = binaryInfoHash.toString('binary')
  var swarm = self.torrents[binaryInfoHash]
  if (!swarm) {
    swarm = self.torrents[binaryInfoHash] = new Swarm(binaryInfoHash, this)
  }
  return swarm
}

Server.prototype._onHttpRequest = function (req, res) {
  var self = this

  var params
  try {
    params = parseHttpRequest(req, {
      trustProxy: self._trustProxy
    })
  } catch (err) {
    debug('sent error %s', err.message)
    res.end(bencode.encode({
      'failure reason': err.message
    }))

    // even though it's an error for the client, it's just a warning for the server.
    // don't crash the server because a client sent bad data :)
    self.emit('warning', err)

    return
  }

  this._onRequest(params, function (err, response) {
    if (err) {
      self.emit('warning', new Error(err.message))
      response = {
        'failure reason': err.message
      }
    }

    delete response.action  // only needed for UDP encoding
    res.end(bencode.encode(response))
  })
}

Server.prototype._onUdpRequest = function (msg, rinfo) {
  var self = this

  var params
  try {
    params = parseUdpRequest(msg, rinfo)
  } catch (err) {
    self.emit('warning', err)
    // Do not reply for parsing errors
    return
  }

  // Do nothing with invalid request
  if (!params) return

  // Handle
  this._onRequest(params, function (err, response) {
    if (err) {
      self.emit('warning', new Error(err.message))
      response = {
        action: common.ACTIONS.ERRROR,
        'failure reason': err.message
      }
    }

    var socket = dgram.createSocket('udp4')
    response.transactionId = params.transactionId
    response.connectionId = params.connectionId
    var buf = makeUdpPacket(response)
    socket.send(buf, 0, buf.length, rinfo.port, rinfo.address, function () {
      try {
        socket.close()
      } catch (err) {}
    })
  })
}

Server.prototype._onRequest = function (params, cb) {
  var response
  if (params && params.action === common.ACTIONS.CONNECT) {
    cb(null, { action: common.ACTIONS.CONNECT })
  } else if (params && params.action === common.ACTIONS.ANNOUNCE) {
    this._onAnnounce(params, cb)
  } else if (params && params.action === common.ACTIONS.SCRAPE) {
    this._onScrape(params, cb)
  } else {
    cb(new Error('Invalid action'))
  }
}

Server.prototype._onAnnounce = function (params, cb) {
  var self = this
  var swarm = self.getSwarm(params.info_hash)
  swarm.announce(params, function (err, response) {
    if (response) {
      if (!response.action) response.action = common.ACTIONS.ANNOUNCE
      if (!response.intervalMs) response.intervalMs = self._intervalMs
      if (params.compact === 1) {
        response.peers = string2compact(response.peers.map(function (peer) {
          return peer.ip + ':' + peer.port // TODO: ipv6 brackets
        }))
      }
    }
    cb(err, response)
  })
}

Server.prototype._onScrape = function (params, cb) {
  var self = this

  if (typeof params.info_hash === 'string') {
    params.info_hash = [ params.info_hash ]
  } else if (params.info_hash == null) {
    // if info_hash param is omitted, stats for all torrents are returned
    // TODO: make this configurable!
    params.info_hash = Object.keys(self.torrents)
  }

  if (!Array.isArray(params.info_hash)) {
    var err = new Error('invalid info_hash')
    self.emit('warning', err)
    return cb(err)
  }

  var response = {
    action: common.ACTIONS.SCRAPE,
    files: {},
    flags: {
      min_request_interval: self._intervalMs
    }
  }

  series(params.info_hash.map(function (infoHash) {
    var swarm = self.getSwarm(infoHash)
    return function (cb) {
      swarm.scrape(infoHash, params, function (err, scrapeInfo) {
        cb(err, scrapeInfo && {
          infoHash: infoHash,
          complete: scrapeInfo.complete || 0,
          incomplete: scrapeInfo.incomplete || 0
        })
      })
    }
  }), function (err, results) {
    if (err) return cb(err)

    results.forEach(function (result) {
      response.files[result.infoHash] = {
        complete: result.complete,
        incomplete: result.incomplete,
        downloaded: result.complete // TODO: this only provides a lower-bound
      }
    })

    cb(null, response)
  })
}

function makeUdpPacket (params) {
  switch (params.action) {
    case common.ACTIONS.CONNECT:
      return Buffer.concat([
        common.toUInt32(common.ACTIONS.CONNECT),
        common.toUInt32(params.transactionId),
        params.connectionId
      ])
    case common.ACTIONS.ANNOUNCE:
      return Buffer.concat([
        common.toUInt32(common.ACTIONS.ANNOUNCE),
        common.toUInt32(params.transactionId),
        common.toUInt32(params.intervalMs),
        common.toUInt32(params.incomplete),
        common.toUInt32(params.complete),
        params.peers
      ])
    case common.ACTIONS.SCRAPE:
      var firstInfoHash = Object.keys(params.files)[0]
      var scrapeInfo = firstInfoHash ? {
        complete: params.files[firstInfoHash].complete,
        incomplete: params.files[firstInfoHash].incomplete,
        completed: params.files[firstInfoHash].complete // TODO: this only provides a lower-bound
      } : {}
      return Buffer.concat([
        common.toUInt32(common.ACTIONS.SCRAPE),
        common.toUInt32(params.transactionId),
        common.toUInt32(scrapeInfo.complete),
        common.toUInt32(scrapeInfo.completed),
        common.toUInt32(scrapeInfo.incomplete)
      ])
    case common.ACTIONS.ERROR:
      return Buffer.concat([
        common.toUInt32(common.ACTIONS.ERROR),
        common.toUInt32(params.transactionId || 0),
        new Buffer(params.message, 'utf8')
      ])
  default:
    throw new Error('Action not implemented: ' + params.action)
  }
}
<commit_msg>server _onHttpRequest(): ensure non-empty params<commit_after>module.exports = Server

var bencode = require('bencode')
var debug = require('debug')('bittorrent-tracker')
var dgram = require('dgram')
var EventEmitter = require('events').EventEmitter
var http = require('http')
var inherits = require('inherits')
var portfinder = require('portfinder')
var series = require('run-series')
var string2compact = require('string2compact')

var common = require('./lib/common')
var Swarm = require('./lib/swarm')
var parseHttpRequest = require('./lib/parse_http')
var parseUdpRequest = require('./lib/parse_udp')

// Use random port above 1024
portfinder.basePort = Math.floor(Math.random() * 60000) + 1025

inherits(Server, EventEmitter)

/**
 * A BitTorrent tracker server.
 *
 * A "BitTorrent tracker" is an HTTP service which responds to GET requests from
 * BitTorrent clients. The requests include metrics from clients that help the tracker
 * keep overall statistics about the torrent. The response includes a peer list that
 * helps the client participate in the torrent.
 *
 * @param {Object}  opts            options
 * @param {Number}  opts.interval   interval in ms that clients should announce on
 * @param {Number}  opts.trustProxy Trust 'x-forwarded-for' header from reverse proxy
 * @param {boolean} opts.http       Start an http server? (default: true)
 * @param {boolean} opts.udp        Start a udp server? (default: true)
 */
function Server (opts) {
  var self = this
  if (!(self instanceof Server)) return new Server(opts)
  EventEmitter.call(self)
  opts = opts || {}

  self._intervalMs = opts.interval
    ? opts.interval / 1000
    : 10 * 60 // 10 min (in secs)

  self._trustProxy = !!opts.trustProxy

  self.listening = false
  self.port = null
  self.torrents = {}

  // default to starting an http server unless the user explictly says no
  if (opts.http !== false) {
    self._httpServer = http.createServer()
    self._httpServer.on('request', self._onHttpRequest.bind(self))
    self._httpServer.on('error', self._onError.bind(self))
    self._httpServer.on('listening', onListening)
  }

  // default to starting a udp server unless the user explicitly says no
  if (opts.udp !== false) {
    self._udpServer = dgram.createSocket('udp4')
    self._udpServer.on('message', self._onUdpRequest.bind(self))
    self._udpServer.on('error', self._onError.bind(self))
    self._udpServer.on('listening', onListening)
  }

  var num = !!self._httpServer + !!self._udpServer
  function onListening () {
    num -= 1
    if (num === 0) {
      self.listening = true
      self.emit('listening', self.port)
    }
  }
}

Server.prototype._onError = function (err) {
  var self = this
  self.emit('error', err)
}

Server.prototype.listen = function (port, onlistening) {
  var self = this
  if (typeof port === 'function') {
    onlistening = port
    port = undefined
  }
  if (self.listening) throw new Error('server already listening')
  if (onlistening) self.once('listening', onlistening)

  function onPort (err, port) {
    if (err) return self.emit('error', err)
    self.port = port
    self._httpServer && self._httpServer.listen(port.http || port)
    self._udpServer && self._udpServer.bind(port.udp || port)
  }

  if (port) onPort(null, port)
  else portfinder.getPort(onPort)
}

Server.prototype.close = function (cb) {
  var self = this
  cb = cb || function () {}
  if (self._udpServer) {
    self._udpServer.close()
  }
  if (self._httpServer) {
    self._httpServer.close(cb)
  } else {
    cb(null)
  }
}

Server.prototype.getSwarm = function (binaryInfoHash) {
  var self = this
  if (Buffer.isBuffer(binaryInfoHash)) binaryInfoHash = binaryInfoHash.toString('binary')
  var swarm = self.torrents[binaryInfoHash]
  if (!swarm) {
    swarm = self.torrents[binaryInfoHash] = new Swarm(binaryInfoHash, this)
  }
  return swarm
}

Server.prototype._onHttpRequest = function (req, res) {
  var self = this
  var error
  var params
  try {
    params = parseHttpRequest(req, {
      trustProxy: self._trustProxy
    })
  } catch (err) {
    error = err
  }

  if (!error && !params) error = new Error('Empty HTTP parameters')
  if (error) {
    debug('sent error %s', error.message)
    res.end(bencode.encode({
      'failure reason': error.message
    }))

    // even though it's an error for the client, it's just a warning for the server.
    // don't crash the server because a client sent bad data :)
    self.emit('warning', error)

    return
  }

  this._onRequest(params, function (err, response) {
    if (err) {
      self.emit('warning', new Error(err.message))
      response = {
        'failure reason': err.message
      }
    }

    delete response.action  // only needed for UDP encoding
    res.end(bencode.encode(response))
  })
}

Server.prototype._onUdpRequest = function (msg, rinfo) {
  var self = this

  var params
  try {
    params = parseUdpRequest(msg, rinfo)
  } catch (err) {
    self.emit('warning', err)
    // Do not reply for parsing errors
    return
  }

  // Do nothing with invalid request
  if (!params) return

  // Handle
  this._onRequest(params, function (err, response) {
    if (err) {
      self.emit('warning', new Error(err.message))
      response = {
        action: common.ACTIONS.ERRROR,
        'failure reason': err.message
      }
    }

    var socket = dgram.createSocket('udp4')
    response.transactionId = params.transactionId
    response.connectionId = params.connectionId
    var buf = makeUdpPacket(response)
    socket.send(buf, 0, buf.length, rinfo.port, rinfo.address, function () {
      try {
        socket.close()
      } catch (err) {}
    })
  })
}

Server.prototype._onRequest = function (params, cb) {
  var response
  if (params && params.action === common.ACTIONS.CONNECT) {
    cb(null, { action: common.ACTIONS.CONNECT })
  } else if (params && params.action === common.ACTIONS.ANNOUNCE) {
    this._onAnnounce(params, cb)
  } else if (params && params.action === common.ACTIONS.SCRAPE) {
    this._onScrape(params, cb)
  } else {
    cb(new Error('Invalid action'))
  }
}

Server.prototype._onAnnounce = function (params, cb) {
  var self = this
  var swarm = self.getSwarm(params.info_hash)
  swarm.announce(params, function (err, response) {
    if (response) {
      if (!response.action) response.action = common.ACTIONS.ANNOUNCE
      if (!response.intervalMs) response.intervalMs = self._intervalMs
      if (params.compact === 1) {
        response.peers = string2compact(response.peers.map(function (peer) {
          return peer.ip + ':' + peer.port // TODO: ipv6 brackets
        }))
      }
    }
    cb(err, response)
  })
}

Server.prototype._onScrape = function (params, cb) {
  var self = this

  if (typeof params.info_hash === 'string') {
    params.info_hash = [ params.info_hash ]
  } else if (params.info_hash == null) {
    // if info_hash param is omitted, stats for all torrents are returned
    // TODO: make this configurable!
    params.info_hash = Object.keys(self.torrents)
  }

  if (!Array.isArray(params.info_hash)) {
    var err = new Error('invalid info_hash')
    self.emit('warning', err)
    return cb(err)
  }

  var response = {
    action: common.ACTIONS.SCRAPE,
    files: {},
    flags: {
      min_request_interval: self._intervalMs
    }
  }

  series(params.info_hash.map(function (infoHash) {
    var swarm = self.getSwarm(infoHash)
    return function (cb) {
      swarm.scrape(infoHash, params, function (err, scrapeInfo) {
        cb(err, scrapeInfo && {
          infoHash: infoHash,
          complete: scrapeInfo.complete || 0,
          incomplete: scrapeInfo.incomplete || 0
        })
      })
    }
  }), function (err, results) {
    if (err) return cb(err)

    results.forEach(function (result) {
      response.files[result.infoHash] = {
        complete: result.complete,
        incomplete: result.incomplete,
        downloaded: result.complete // TODO: this only provides a lower-bound
      }
    })

    cb(null, response)
  })
}

function makeUdpPacket (params) {
  switch (params.action) {
    case common.ACTIONS.CONNECT:
      return Buffer.concat([
        common.toUInt32(common.ACTIONS.CONNECT),
        common.toUInt32(params.transactionId),
        params.connectionId
      ])
    case common.ACTIONS.ANNOUNCE:
      return Buffer.concat([
        common.toUInt32(common.ACTIONS.ANNOUNCE),
        common.toUInt32(params.transactionId),
        common.toUInt32(params.intervalMs),
        common.toUInt32(params.incomplete),
        common.toUInt32(params.complete),
        params.peers
      ])
    case common.ACTIONS.SCRAPE:
      var firstInfoHash = Object.keys(params.files)[0]
      var scrapeInfo = firstInfoHash ? {
        complete: params.files[firstInfoHash].complete,
        incomplete: params.files[firstInfoHash].incomplete,
        completed: params.files[firstInfoHash].complete // TODO: this only provides a lower-bound
      } : {}
      return Buffer.concat([
        common.toUInt32(common.ACTIONS.SCRAPE),
        common.toUInt32(params.transactionId),
        common.toUInt32(scrapeInfo.complete),
        common.toUInt32(scrapeInfo.completed),
        common.toUInt32(scrapeInfo.incomplete)
      ])
    case common.ACTIONS.ERROR:
      return Buffer.concat([
        common.toUInt32(common.ACTIONS.ERROR),
        common.toUInt32(params.transactionId || 0),
        new Buffer(params.message, 'utf8')
      ])
  default:
    throw new Error('Action not implemented: ' + params.action)
  }
}
<|endoftext|>


<commit_before>"use strict";

const PORT        = process.env.PORT || 8080;
const ENV         = process.env.ENV || "development";
const express     = require("express");
const bodyParser  = require("body-parser");
const sass        = require("node-sass-middleware");
const app         = express();

const knexConfig  = require("./knexfile");
const knex        = require("knex")(knexConfig[ENV]);
const morgan      = require('morgan');
const knexLogger  = require('knex-logger');

// Seperated Routes for each Resource
const usersRoutes = require("./routes/users");

const accountSid = process.env.TWILIO_KEY;
const authToken =  process.env.TWILIO_SECRET;
const client = require('twilio')(accountSid, authToken);

app.use(morgan('dev'));

// Log knex SQL queries to STDOUT as well
app.use(knexLogger(knex));

app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/styles", sass({
  src: __dirname + "/styles",
  dest: __dirname + "/public/styles",
  debug: true,
  outputStyle: 'expanded'
}));
app.use(express.static("public"));

// Mount all resource routes

app.post('/sms', function(req, res) {
  const MessagingResponse = require('twilio').twiml.MessagingResponse;
  var twiml = new MessagingResponse();
  knex('order').select('status').where('phone','=',req.body.From).asCallback((err,row) => {
    if(err)console.error(err);
    console.log(row[0]);
    var status = row[0].status;
    if(status==='ordered'){
      if(req.body.Body.toLowerCase() === 'confirm'){
        twiml.message('Thanks, your order is now being processed');
        res.writeHead(200, {'Content-Type': 'text/xml'});
        console.log(req.body.From);
        knex('order')
          .where('phone', '=', req.body.From)
          .update({
            status: 'confirmed',
          }).asCallback((err)=>{
            if(err)console.error(err);
            knex.select('receipt').from('order')
              .where('phone', '=', req.body.From)
              .asCallback((err,row)=>{
                if(err)console.error(err);
                client.messages.create({
                  to: process.env.VERIFIED_NUMBER,
                  from: process.env.TWILIO_NUMBER,
                  body: `${req.body.From} Has ordered these items:\n
                  ${row[0].receipt}`
                }).then((message)=>{
                  console.log(message.sid);
                  res.end(twiml.toString());
                  });
                })
            });
      }else if(req.body.Body.toLowerCase()==='decline'){
        twiml.message('Your order has been cancelled');
        res.writeHead(200, {'Content-Type': 'text/xml'});
        knex('order')
          .where('phone', '=', req.body.From)
          .del().asCallback((err)=>{
            if(err)console.error(err);
            res.end(twiml.toString());
          });
        }
      }else if(status==='confirmed'){
        if(req.body.Body.toLowerCase() === 'receipt'){
          knex('order').select('receipt').where('phone','=',req.body.From).asCallback((err,row) =>{
            if(err)console.error(err);
            var receipt = row[0].receipt;
            twiml.message(`Here is your current order: \n
              ${receipt}
              `);
            res.writeHead(200, {'Content-Type': 'text/xml'});
            console.log(req.body.From);
            knex('order')
              .where('phone', '=', req.body.From)
              .update({
                status: 'confirmed',
              }).asCallback((err)=>{
                if(err)console.error(err);
                  res.end(twiml.toString());
                })
              });
            }
        }else if(req.body.Body.toLowerCase()==='decline' && status!=='processed'){
            twiml.message('Your order has been cancelled');
            res.writeHead(200, {'Content-Type': 'text/xml'});
            knex('order')
              .where('phone', '=', req.body.From)
              .del().asCallback((err)=>{
                if(err)console.error(err);
                res.end(twiml.toString());
              });
        }else if(req.body.toLowerCase()==='process'){
           twiml.message('Your food is now being made. It will be ready in 5 minutes');
           res.writeHead(200, {'Content-Type': 'text/xml'});
           console.log(req.body.From);
           knex('order')
             .where('phone', '=', req.body.From)
             .update({
               status: 'processed',
             }).asCallback((err)=>{
               if(err)console.error(err);
               res.end(twiml.toString());
             });
           }else if(req.body.toLowerCase()==='finish' && status==='processed'){
           }
         });
      });
app.post("/order", (req, res) => {
    client.messages.create({
      to: process.env.VERIFIED_NUMBER,
      from: process.env.TWILIO_NUMBER,
      body: `Your order has been placed ${req.body.name}: \n${req.body.receipt.replace(/<\/tr>/g,'\n').replace(/<[^>]*>/g,'')}\n
      text "confirm" to start the order or text "cancel" to undo`,
    }).then((message) => console.log(message.sid));
        knex('order').insert({
        name: req.body.name || 'kyle',
        phone: process.env.VERIFIED_NUMBER,
        receipt: req.body.receipt.replace(/<\/tr>/g,'\n').replace(/<[^>]*>/g,''),
        status: 'ordered'
      }).asCallback((err,row)=>{
        if(err)console.error(err)
         res.end('Done');
      });
    });
app.use("/api/users", usersRoutes(knex));

// Home page
app.get("/", (req, res) => {
  res.redirect('/menu');
});

app.get("/menu", (req, res) => {
 knex.select('name','price','type').from('dishes').asCallback((err,rows)=>{
    if (err) return console.error(err);
      let templateVars = {
        dishes:rows,
        dish:{},
        addons:{}
      }
      knex.select('*').from('dishes').where('name','Billionaire Burger').asCallback((err,row)=>{
         if (err) return console.error(err);
           templateVars.dish = row;
          knex.select('name','price','pic').from('dishes').where('type','sides').asCallback((err,sides)=>{
            templateVars.addons = sides;
            console.log(templateVars);
            res.render('index',templateVars)
          });
    });
  });

app.get("/menu/:name",(req, res) => {
  console.log(req.params.name);
  knex.select('*').from('dishes').where('name',req.params.name).asCallback((err,row)=>{
     if (err) return console.error(err);
       res.json({
         dish:row[0]
       });
     })
   });
});

app.post("/cart",(req, res) => {
  if(!req.body.name)return console.error('param does not exist');
  console.log(req.body.name);

  knex('menu_cart').insert({
    cart_id: knex.select('id').from('cart').where('owner','Kyle'),
    menu_id: knex.select('id').from('dishes').where('name',req.body.name),
    quantity: req.body.quantity
  }).asCallback((err)=>{
    if (err) return console.error(err);
    knex.countDistinct("menu_id").from('menu_cart').where('cart_id',knex.select('id').from('cart').where('owner','Kyle')).asCallback((err,row)=>{
      if (err) return console.error(err);
          res.json({
            items: row[0]
          });
        });
      });
    });

app.get("/cart", (req, res) => {
  knex('dishes')
  .leftJoin('menu_cart','dishes.id','menu_cart.menu_id')
  .leftJoin('cart','menu_cart.cart_id','cart.id')
  .select('name','price', 'menu_cart.quantity as quantity').distinct()
  .whereNotNull('quantity')
  .asCallback((err,rows)=>{
    console.log(rows)
    let templateVars = {
      cart : rows
    }
     res.json(templateVars);
  })
});
app.listen(PORT, () => {
  console.log("Example app listening on port " + PORT);
});
<commit_msg>remofixed confirm command<commit_after>"use strict";

const PORT        = process.env.PORT || 8080;
const ENV         = process.env.ENV || "development";
const express     = require("express");
const bodyParser  = require("body-parser");
const sass        = require("node-sass-middleware");
const app         = express();

const knexConfig  = require("./knexfile");
const knex        = require("knex")(knexConfig[ENV]);
const morgan      = require('morgan');
const knexLogger  = require('knex-logger');

// Seperated Routes for each Resource
const usersRoutes = require("./routes/users");

const accountSid = process.env.TWILIO_KEY;
const authToken =  process.env.TWILIO_SECRET;
const client = require('twilio')(accountSid, authToken);

app.use(morgan('dev'));

// Log knex SQL queries to STDOUT as well
app.use(knexLogger(knex));

app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/styles", sass({
  src: __dirname + "/styles",
  dest: __dirname + "/public/styles",
  debug: true,
  outputStyle: 'expanded'
}));
app.use(express.static("public"));

// Mount all resource routes

app.post('/sms', function(req, res) {
  const MessagingResponse = require('twilio').twiml.MessagingResponse;
  var twiml = new MessagingResponse();
  knex('order').select('status').where('phone','=',req.body.From).asCallback((err,row) => {
    if(err)console.error(err);
    console.log(row[0]);
    var status = row[0].status;
    if(status==='ordered'){
      if(req.body.Body.toLowerCase() === 'confirm'){
        twiml.message('Thanks, your order is now being processed');
        res.writeHead(200, {'Content-Type': 'text/xml'});
        console.log(req.body.From);
        knex('order')
          .where('phone', '=', req.body.From)
          .update({
            status: 'confirmed',
          }).asCallback((err)=>{
            if(err)console.error(err);
            knex.select('receipt').from('order')
              .where('phone', '=', req.body.From)
              .asCallback((err,row)=>{
                if(err)console.error(err);
                client.messages.create({
                  to: process.env.VERIFIED_NUMBER,
                  from: process.env.TWILIO_NUMBER,
                  body: `${req.body.From} Has ordered these items:\n
                  ${row[0].receipt}`
                }).then((message)=>{
                  console.log(message.sid);
                  res.end(twiml.toString());
                  });
                })
            });
      }else if(req.body.Body.toLowerCase()==='decline'){
        twiml.message('Your order has been cancelled');
        res.writeHead(200, {'Content-Type': 'text/xml'});
        knex('order')
          .where('phone', '=', req.body.From)
          .del().asCallback((err)=>{
            if(err)console.error(err);
            res.end(twiml.toString());
          });
        }
      }else if(status==='confirmed'){
        if(req.body.Body.toLowerCase() === 'receipt'){
          knex('order').select('receipt').where('phone','=',req.body.From).asCallback((err,row) =>{
            if(err)console.error(err);
            var receipt = row[0].receipt;
            twiml.message(`Here is your current order: \n
              ${receipt}
              `);
            res.writeHead(200, {'Content-Type': 'text/xml'});
            console.log(req.body.From);
            knex('order')
              .where('phone', '=', req.body.From)
              .update({
                status: 'confirmed',
              }).asCallback((err)=>{
                if(err)console.error(err);
                  res.end(twiml.toString());
                })
              });
            }
        }else if(req.body.Body.toLowerCase()==='decline' && status!=='processed'){
            twiml.message('Your order has been cancelled');
            res.writeHead(200, {'Content-Type': 'text/xml'});
            knex('order')
              .where('phone', '=', req.body.From)
              .del().asCallback((err)=>{
                if(err)console.error(err);
                res.end(twiml.toString());
              });
        }else if(req.body.toLowerCase()==='process'){
           twiml.message('Your food is now being made. It will be ready in 5 minutes');
           res.writeHead(200, {'Content-Type': 'text/xml'});
           console.log(req.body.From);
           knex('order')
             .where('phone', '=', req.body.From)
             .update({
               status: 'processed',
             }).asCallback((err)=>{
               if(err)console.error(err);
               res.end(twiml.toString());
             });
           }else if(req.body.toLowerCase()==='finish' && status==='processed'){
             twiml.message('Thanks for ordering at Zuckerburgers!');
             res.writeHead(200, {'Content-Type': 'text/xml'});
             console.log(req.body.From);
             knex('order')
               .where('phone', '=', req.body.From)
               .update({
                 status: 'finished',
               }).asCallback((err)=>{
                 if(err)console.error(err);
                 res.end(twiml.toString());
               });
           }
         });
      });
app.post("/order", (req, res) => {
    client.messages.create({
      to: process.env.VERIFIED_NUMBER,
      from: process.env.TWILIO_NUMBER,
      body: `Your order has been placed ${req.body.name}: \n${req.body.receipt.replace(/<\/tr>/g,'\n').replace(/<[^>]*>/g,'')}\n
      text "confirm" to start the order or text "cancel" to undo`,
    }).then((message) => console.log(message.sid));
        knex('order').insert({
        name: req.body.name || 'kyle',
        phone: process.env.VERIFIED_NUMBER,
        receipt: req.body.receipt.replace(/<\/tr>/g,'\n').replace(/<[^>]*>/g,''),
        status: 'ordered'
      }).asCallback((err,row)=>{
        if(err)console.error(err)
         res.end('Done');
      });
    });
app.use("/api/users", usersRoutes(knex));

// Home page
app.get("/", (req, res) => {
  res.redirect('/menu');
});

app.get("/menu", (req, res) => {
 knex.select('name','price','type').from('dishes').asCallback((err,rows)=>{
    if (err) return console.error(err);
      let templateVars = {
        dishes:rows,
        dish:{},
        addons:{}
      }
      knex.select('*').from('dishes').where('name','Billionaire Burger').asCallback((err,row)=>{
         if (err) return console.error(err);
           templateVars.dish = row;
          knex.select('name','price','pic').from('dishes').where('type','sides').asCallback((err,sides)=>{
            templateVars.addons = sides;
            console.log(templateVars);
            res.render('index',templateVars)
          });
    });
  });

app.get("/menu/:name",(req, res) => {
  console.log(req.params.name);
  knex.select('*').from('dishes').where('name',req.params.name).asCallback((err,row)=>{
     if (err) return console.error(err);
       res.json({
         dish:row[0]
       });
     })
   });
});

app.post("/cart",(req, res) => {
  if(!req.body.name)return console.error('param does not exist');
  console.log(req.body.name);

  knex('menu_cart').insert({
    cart_id: knex.select('id').from('cart').where('owner','Kyle'),
    menu_id: knex.select('id').from('dishes').where('name',req.body.name),
    quantity: req.body.quantity
  }).asCallback((err)=>{
    if (err) return console.error(err);
    knex.countDistinct("menu_id").from('menu_cart').where('cart_id',knex.select('id').from('cart').where('owner','Kyle')).asCallback((err,row)=>{
      if (err) return console.error(err);
          res.json({
            items: row[0]
          });
        });
      });
    });

app.get("/cart", (req, res) => {
  knex('dishes')
  .leftJoin('menu_cart','dishes.id','menu_cart.menu_id')
  .leftJoin('cart','menu_cart.cart_id','cart.id')
  .select('name','price', 'menu_cart.quantity as quantity').distinct()
  .whereNotNull('quantity')
  .asCallback((err,rows)=>{
    console.log(rows)
    let templateVars = {
      cart : rows
    }
     res.json(templateVars);
  })
});
app.listen(PORT, () => {
  console.log("Example app listening on port " + PORT);
});
<|endoftext|>


<commit_before>import Discord from 'discord.js';

import Events from './events';

/**
 * Importation de la configuration.
 */
import config from './config.json';

const bot = new Discord.Client();
const events = new Events(bot);

const env = process.env.NODE_ENV;

console.info('[INFO]', 'Lancement du bot en cours...');

/**
 *
 */
Promise.all([events.load(), bot.login(config.token)])
  .then((debug) => {
    console.info('[INFO]', 'Le bot est maintenant connecté.');
    if (env !== 'production') console.log('[LOG]', debug);
  })
  .catch((err) => {
    console.error('[ERREUR]', err.message);
    if (env !== 'production') console.log('[LOG]', err);
  });

<commit_msg>Retravaillé le code de lancement du bot<commit_after>import Discord from 'discord.js';
import colors from 'colors/safe';
import Events from './events/';
import Log from './libs/log';
import config from './config.json';

const bot = new Discord.Client();
const events = new Events(bot);
const log = new Log(process.env.NODE_ENV);

log.info('Lancement du bot en cours...');

Promise.all([events.load(), bot.login(config.token)])
  .then((debug) => {
    log.info('Le bot est maintenant connecté.');
    log.verbose(debug);
  })
  .catch((err) => {
    log.error(err.message);
    log.verbose(err);
  });

<|endoftext|>


<commit_before>var express = require('express');
var app = express();

var tracking = require('./TrackApi.js');

//USPS: tracking.trackUSPS(username, trackingNumber, callback);

//UPS: tracking.trackUPS(usernane, password, accessKey, trackingNumber, callback);

//Fedex: tracking.trackFedex(username, password, accountNumber, meterNumber, trackingNumber, callback);

app.get('/usps/track', function (req, res)
{

	res.send("Please enter a tracking numebr");
});

app.listen(3000, function () {
 console.log('listening on port');
});
<commit_msg>change for port<commit_after>ar express = require('express');
var app = express();

var tracking = require('./TrackApi.js');

//USPS: tracking.trackUSPS(username, trackingNumber, callback);

//UPS: tracking.trackUPS(usernane, password, accessKey, trackingNumber, callback);

//Fedex: tracking.trackFedex(username, password, accountNumber, meterNumber, trackingNumber, callback);

app.set('port', (process.env.PORT || 5000));
app.get('/', function (req, res)
{

				res.send("Tracking Api");

});
app.get('/ups/track/:tracking_number', function (req, res)
{
				tracking.trackUPS
				(
				"eshipglobal",
				"e$h1pStudXm",
				"FCCDA6BAB35B7FB2",
				req.params.tracking_number, function (err, data)
				{
					if (err) {
						console.error(err);
						res.send(err);
					}

					if (data) {
						console.log(req.params.tracking_number);
						 res.send(data);
					}

				});

});
app.get('/ups/track', function (req, res)
{

	res.send("Please enter a tracking numebr");
});
app.get('/fedex/track/:tracking_number', function (req, res)
{
				tracking.trackFedex
				(
				"9SX2fuvq5EuwSujI",
				"1limvzjV3X1OpS584XjnAknPP",
				"212081140",
				"5291363",
				req.params.tracking_number, function (err, data)
				{
					if (err) {
						console.error(err);
						res.send(err);
					}

					if (data) {
						console.log(req.params.tracking_number);
						 res.send(data);
					}

				});

});
app.get('/fedex/track', function (req, res)
{

	res.send("Please enter a tracking numebr");
});

app.get('/usps/track/:tracking_number', function (req, res)
{
				tracking.trackUSPS
				(
				"241ESHIP3455",
				req.params.tracking_number, function (err, data)
				{
					if (err) {
						console.error(err);
						res.send(err);
					}

					if (data) {
						console.log(req.params.tracking_number);
						 res.send(data);
					}

				});

});
app.get('/usps/track', function (req, res)
{

	res.send("Please enter a tracking numebr");
});
app.listen(app.get('port'), function () {
 console.log('listening on port');
});
<|endoftext|>


<commit_before>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages 😎:
\`help\` - to see this message.
\`hi\` - to demonstrate a conversation that tracks state.
\`thanks\` - to demonstrate a simple response.
\`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
\`attachment\` - to see a Slack attachment message.
`

//*********************************************
// Setup different handlers for messages
//*********************************************

// response to the user typing "help"
function getReactionGif(msg){
	// msg.say("Fetching Reaction Gifs...");
	var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
        if (xhr.readyState == 4 && xhr.status == 200){
            // console.log(xhr.responseText);
			var jsonResponse = JSON.parse(xhr.responseText);
			// console.log(jsonResponse);
			// msg.say(jsonResponse.data.image_url);

			msg.say({
		      text: '',
		      attachments: [{
		   	 text: '',
		   	 title: '',
			 //  	 image_url: jsonResponse.data.image_url,
		   	 image_url: jsonResponse.data.fixed_height_downsampled_url,
		   	 title_link: '',
		   	 color: ''
		      }]
		    })

			// msg.say(jsonResponse.data.url);

        }
    }
    xhr.open("GET", "http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=reaction", true);
    xhr.send();

}
// slapp.event('file_shared', (msg) => {
//
// 	msg.say(":thumbsup:");
// 	getReactionGif(msg);
//
// })

// add a smile reaction by the bot for any message reacted to
slapp.event('file_shared', (msg) => {
	msg.say(":thumbsup:");
	let token = msg.meta.bot_token
	let id = msg.body.event.item.ts
	let channel = msg.body.event.item.channel
	slapp.client.reactions.add({token, 'smile', id, channel}, (err) => {
		if (err) console.log('Error adding reaction', err)
	})
})

// slapp.event('file_share', (msg) => {
slapp.message('file_share', ['mention', 'direct_message'], (msg) => {
	msg.say(":thumbsup: :cool:");
  // let token = msg.meta.bot_token
  // let id = msg.body.event.item.ts
  // let channel = msg.body.event.item.channel
  // slapp.client.reactions.add({token, 'smile', id, channel}, (err) => {
  //   if (err) console.log('Error adding reaction', err)
  // })
})

slapp.message('help', ['mention', 'direct_message'], (msg) => {

	msg.say(HELP_TEXT);
})

// Catch all mentions of the bot
slapp.message('', ['mention'], (msg) => {
  // respond only 40% of the time

	// console.log("detected me");
	// msg.say("What?");
	getReactionGif(msg);
})

// slapp.message('Robert', ['mention', 'direct_message'], (msg) => {
//   msg.say('What a dick!')
// })

// slapp.message('jens', ['mention', 'direct_message'], (msg) => {
//   msg.say('What a dick!')
// })

slapp.message(/^(Ralf|Jens|Robert|Frank|Isa|Jan|Daniel)/i, ['mention', 'direct_message'], (msg) => {
	// var text = (msg.body.event && msg.body.event.text) || '';
	msg.say([
      '🚀',
      '💩',
      ':+1: That\'s my man',
      'Best colleague :sun_with_face: :full_moon_with_face:'
    ])
})

// "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
slapp
  .message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
    msg
      .say(`${text}, how are you?`)
      // sends next event from user to this route, passing along state
      .route('how-are-you', { greeting: text })
  })
  .route('how-are-you', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("Whoops, I'm still waiting to hear how you're doing.")
        .say('How are you?')
        .route('how-are-you', state)
    }

    // add their response to state
    state.status = text

    msg
      .say(`Ok then. What's your favorite color?`)
      .route('color', state)
  })
  .route('color', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("I'm eagerly awaiting to hear your favorite color.")
        .route('color', state)
    }

    // add their response to state
    state.color = text

    msg
      .say('Thanks for sharing.')
      .say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``)
    // At this point, since we don't route anywhere, the "conversation" is over
  })

// Can use a regex as well
slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
  // You can provide a list of responses, and a random one will be chosen
  // You can also include slack emoji in your responses
  msg.say([
    "You're welcome :smile:",
    'You bet',
    ':+1: Of course',
    'Anytime :sun_with_face: :full_moon_with_face:'
  ])
})

// demonstrate returning an attachment...
slapp.message('attachment', ['mention', 'direct_message'], (msg) => {
  msg.say({
    text: 'Check out this amazing attachment! :confetti_ball: ',
    attachments: [{
      text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
      title: 'Slapp Library - Open Source',
      image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
      title_link: 'https://beepboophq.com/',
      color: '#7CD197'
    }]
  })
})

// Catch-all for any other responses not handled above
slapp.message('.*', ['direct_message','direct_mention'], (msg) => {
  // respond only 40% of the time

	if (Math.random() < 0.4) {
		msg.say([':wave:', ':pray:', ':raised_hands:', ':kissing_heart:',':monkey:'])
	}else{
		// getReactionGif(msg);
	}
})

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }
  console.log(`Listening on port ${port}`)
})
<commit_msg>update<commit_after>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages 😎:
\`help\` - to see this message.
\`hi\` - to demonstrate a conversation that tracks state.
\`thanks\` - to demonstrate a simple response.
\`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
\`attachment\` - to see a Slack attachment message.
`

//*********************************************
// Setup different handlers for messages
//*********************************************

// response to the user typing "help"
function getReactionGif(msg){
	// msg.say("Fetching Reaction Gifs...");
	var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
        if (xhr.readyState == 4 && xhr.status == 200){
            // console.log(xhr.responseText);
			var jsonResponse = JSON.parse(xhr.responseText);
			// console.log(jsonResponse);
			// msg.say(jsonResponse.data.image_url);

			msg.say({
		      text: '',
		      attachments: [{
		   	 text: '',
		   	 title: '',
			 //  	 image_url: jsonResponse.data.image_url,
		   	 image_url: jsonResponse.data.fixed_height_downsampled_url,
		   	 title_link: '',
		   	 color: ''
		      }]
		    })

			// msg.say(jsonResponse.data.url);

        }
    }
    xhr.open("GET", "http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=reaction", true);
    xhr.send();

}
// slapp.event('file_shared', (msg) => {
//
// 	msg.say(":thumbsup:");
// 	getReactionGif(msg);
//
// })

// add a smile reaction by the bot for any message reacted to
slapp.event('file_shared', (msg) => {
	msg.say(":thumbsup:");
	// let token = msg.meta.bot_token
	// let id = msg.body.event.item.ts
	// let channel = msg.body.event.item.channel
	// slapp.client.reactions.add({token, 'smile', id, channel}, (err) => {
	// 	if (err) console.log('Error adding reaction', err)
	// })
})

// slapp.event('file_share', (msg) => {
slapp.message('file_share', ['mention', 'direct_message'], (msg) => {
	msg.say(":thumbsup: :cool:");
  // let token = msg.meta.bot_token
  // let id = msg.body.event.item.ts
  // let channel = msg.body.event.item.channel
  // slapp.client.reactions.add({token, 'smile', id, channel}, (err) => {
  //   if (err) console.log('Error adding reaction', err)
  // })
})

slapp.message('help', ['mention', 'direct_message'], (msg) => {

	msg.say(HELP_TEXT);
})

// Catch all mentions of the bot
slapp.message('', ['mention'], (msg) => {
  // respond only 40% of the time

	// console.log("detected me");
	// msg.say("What?");
	getReactionGif(msg);
})

// slapp.message('Robert', ['mention', 'direct_message'], (msg) => {
//   msg.say('What a dick!')
// })

// slapp.message('jens', ['mention', 'direct_message'], (msg) => {
//   msg.say('What a dick!')
// })

slapp.message(/^(Ralf|Jens|Robert|Frank|Isa|Jan|Daniel)/i, ['mention', 'direct_message'], (msg) => {
	// var text = (msg.body.event && msg.body.event.text) || '';
	msg.say([
      '🚀',
      '💩',
      ':+1: That\'s my man',
      'Best colleague :sun_with_face: :full_moon_with_face:'
    ])
})

// "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
slapp
  .message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
    msg
      .say(`${text}, how are you?`)
      // sends next event from user to this route, passing along state
      .route('how-are-you', { greeting: text })
  })
  .route('how-are-you', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("Whoops, I'm still waiting to hear how you're doing.")
        .say('How are you?')
        .route('how-are-you', state)
    }

    // add their response to state
    state.status = text

    msg
      .say(`Ok then. What's your favorite color?`)
      .route('color', state)
  })
  .route('color', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("I'm eagerly awaiting to hear your favorite color.")
        .route('color', state)
    }

    // add their response to state
    state.color = text

    msg
      .say('Thanks for sharing.')
      .say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``)
    // At this point, since we don't route anywhere, the "conversation" is over
  })

// Can use a regex as well
slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
  // You can provide a list of responses, and a random one will be chosen
  // You can also include slack emoji in your responses
  msg.say([
    "You're welcome :smile:",
    'You bet',
    ':+1: Of course',
    'Anytime :sun_with_face: :full_moon_with_face:'
  ])
})

// demonstrate returning an attachment...
slapp.message('attachment', ['mention', 'direct_message'], (msg) => {
  msg.say({
    text: 'Check out this amazing attachment! :confetti_ball: ',
    attachments: [{
      text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
      title: 'Slapp Library - Open Source',
      image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
      title_link: 'https://beepboophq.com/',
      color: '#7CD197'
    }]
  })
})

// Catch-all for any other responses not handled above
slapp.message('.*', ['direct_message','direct_mention'], (msg) => {
  // respond only 40% of the time

	if (Math.random() < 0.4) {
		msg.say([':wave:', ':pray:', ':raised_hands:', ':kissing_heart:',':monkey:'])
	}else{
		// getReactionGif(msg);
	}
})

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }
  console.log(`Listening on port ${port}`)
})
<|endoftext|>


<commit_before>// server.js
// aoneill - 04/15/15

// Modules
var config = require('./config.js'),
    express = require('express'),
    bodyParser = require('body-parser'),
    hb = require('express-handlebars'),
    sass = require('node-sass-middleware'),
    path = require('path'),
    url = require('url');

// Paths
var _config = path.join(__dirname, config.src);
var _subdomains = path.join(__dirname, config.subdomains);
var _static = path.join(__dirname, config.static);
var _sass = path.join(__dirname, config.sass);

// Init
var server = express();
server.engine('handlebars', hb({
  extname: '.hbs'
}));

// Setup middleware and properties
server.set('view engine', 'handlebars');
server.set('views', path.join(__dirname, config.views));
server.use(sass({
  src: _sass,
  dest: path.join(_static, config.css),
  prefix: config.css,
}));
server.use(express.static(_static));
server.use(bodyParser.urlencoded({extended: false}));

// Start up
server.listen(config.port);

// Sub-configurations
console.log("Loading subdomains...");
require(path.join(_config, 'subdomains.js')).load(_subdomains, express, server);

console.log("Loading routes...");
require(path.join(_config, 'routes.js')).load(server);

console.log('Starting on http://0.0.0.0:' + config.port);
<commit_msg>Fixed Handlebars extension issue<commit_after>// server.js
// aoneill - 04/15/15

// Modules
var config = require('./config.js'),
    express = require('express'),
    bodyParser = require('body-parser'),
    hb = require('express-handlebars'),
    sass = require('node-sass-middleware'),
    path = require('path'),
    url = require('url');

// Paths
var _config = path.join(__dirname, config.src);
var _subdomains = path.join(__dirname, config.subdomains);
var _static = path.join(__dirname, config.static);
var _sass = path.join(__dirname, config.sass);

// Init
var server = express();
server.engine('.hbs', hb({
  extname: '.hbs'
}));

// Setup middleware and properties
server.set('view engine', '.hbs');
server.set('views', path.join(__dirname, config.views));
server.use(sass({
  src: _sass,
  dest: path.join(_static, config.css),
  prefix: config.css,
}));
server.use(express.static(_static));
server.use(bodyParser.urlencoded({extended: false}));

// Start up
server.listen(config.port);

// Sub-configurations
console.log("Loading subdomains...");
require(path.join(_config, 'subdomains.js')).load(_subdomains, express, server);

console.log("Loading routes...");
require(path.join(_config, 'routes.js')).load(server);

console.log('Starting on http://0.0.0.0:' + config.port);
<|endoftext|>


<commit_before>var http = require('http');
var port = 5000;
http.createServer(function (req, res) {
	res.writeHead(200, {'Content-Type': 'text/plain'});
	res.end('Hello World\n');
}).listen(port);

console.log('Server running on port ' + port);<commit_msg>changed port<commit_after>var http = require('http');
var port = process.env.PORT || 5000;
http.createServer(function (req, res) {
	res.writeHead(200, {'Content-Type': 'text/plain'});
	res.end('Hello World\n');
}).listen(port);

console.log('Server running on port ' + port);<|endoftext|>


<commit_before>'use strict';

const host = '0.0.0.0',
    port = 80;

const _ = require('lodash'),
    bunyan = require('bunyan'),
    bodyParser = require('body-parser'),
    pckg = require(__dirname + '/package.json'),
    logger = bunyan.createLogger({ name: pckg.name }),
    express = require('express'),
    app = express();

app.enable('trust proxy');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Intercepts all HTTP verb requests
app.all('*', function (req, res, next) {
    // Returned response headers
    const responseHeaders = {};

    // Parses the wanted response code
    const mirrorCode = req.get('X-Mirror-Code') || 200;

    const delay = req.get('X-Mirror-Delay') || 0;

    // Finds out if the request should be returned as the response
    const mirrorRequest = (req.get('X-Mirror-Request')
        && req.get('X-Mirror-Request').toLowerCase() == 'true')
        || false;

    // Finds out if the response should be returned
    const mirrorBody = (req.get('X-Mirror-Body')
        && req.get('X-Mirror-Body').toLowerCase() == 'true')
        || false;

    // Parses X-Mirror-* headers, skips app specific headers
    const reqHeaders = _.without(
        _.filter(
            Object.keys(req.headers), (name) => _.startsWith(name, 'x-mirror-')
        ), 'x-mirror-code', 'x-mirror-request', 'x-mirror-body', 'x-mirror-delay'
    );

    // Injects X-Mirror-* headers to response headers
    reqHeaders.forEach(function (name) {
        const resHeader = _.startCase(_.trimStart(name, 'x-mirror-')).replace(' ', '-');
        responseHeaders[resHeader] = req.headers[name];
    });

    // Builds the request object
    const request = {
        request: {
            ip: req.ip,
            ips: req.ips,
            method: req.method,
            url: req.originalUrl,
            headers: req.headers,
            body: req.body
        }
    };

    logger.info(request);

    // Prepares the response
    res.status(mirrorCode).set(responseHeaders);

    // Appends the full request or only the request body if wanted
    if (mirrorRequest) {
        res.json(request);
    } else if (mirrorBody) {
        res.send(req.body);
    }

    // Flushes!
    return setTimeout(() => res.end(), delay);
});

// Basic error handler
app.use(function (err, req, res, next) {
    logger.fatal(err);
    res.status(500).json(err);
});

app.listen(port, host, 511, () => logger.info('Listening on http://%s:%s', host, port));
<commit_msg>Fix space to hyphen replacement when header name has multiple spaces. Closes #14<commit_after>'use strict';

const host = '0.0.0.0',
    port = 80;

const _ = require('lodash'),
    bunyan = require('bunyan'),
    bodyParser = require('body-parser'),
    pckg = require(__dirname + '/package.json'),
    logger = bunyan.createLogger({ name: pckg.name }),
    express = require('express'),
    app = express();

app.enable('trust proxy');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Intercepts all HTTP verb requests
app.all('*', function (req, res, next) {
    // Returned response headers
    const responseHeaders = {};

    // Parses the wanted response code
    const mirrorCode = req.get('X-Mirror-Code') || 200;

    const delay = req.get('X-Mirror-Delay') || 0;

    // Finds out if the request should be returned as the response
    const mirrorRequest = (req.get('X-Mirror-Request')
        && req.get('X-Mirror-Request').toLowerCase() == 'true')
        || false;

    // Finds out if the response should be returned
    const mirrorBody = (req.get('X-Mirror-Body')
        && req.get('X-Mirror-Body').toLowerCase() == 'true')
        || false;

    // Parses X-Mirror-* headers, skips app specific headers
    const reqHeaders = _.without(
        _.filter(
            Object.keys(req.headers), (name) => _.startsWith(name, 'x-mirror-')
        ), 'x-mirror-code', 'x-mirror-request', 'x-mirror-body', 'x-mirror-delay'
    );

    // Injects X-Mirror-* headers to response headers
    reqHeaders.forEach(function (name) {
        const resHeader = _.startCase(_.trimStart(name, 'x-mirror-')).replaceAll(' ', '-');
        responseHeaders[resHeader] = req.headers[name];
    });

    // Builds the request object
    const request = {
        request: {
            ip: req.ip,
            ips: req.ips,
            method: req.method,
            url: req.originalUrl,
            headers: req.headers,
            body: req.body
        }
    };

    logger.info(request);

    // Prepares the response
    res.status(mirrorCode).set(responseHeaders);

    // Appends the full request or only the request body if wanted
    if (mirrorRequest) {
        res.json(request);
    } else if (mirrorBody) {
        res.send(req.body);
    }

    // Flushes!
    return setTimeout(() => res.end(), delay);
});

// Basic error handler
app.use(function (err, req, res, next) {
    logger.fatal(err);
    res.status(500).json(err);
});

app.listen(port, host, 511, () => logger.info('Listening on http://%s:%s', host, port));
<|endoftext|>


<commit_before>import React, { useState } from 'react';

import { withDesign } from 'storybook-addon-designs';
import { action } from '@storybook/addon-actions';
import { withKnobs, boolean, optionsKnob as options } from '@storybook/addon-knobs';
import { ThemeProvider } from 'styled-components';
import toUpper from 'lodash/toUpper';
import random from 'lodash/random';
import SearchIcon from '@material-ui/icons/Search';
import MoreHorizRoundedIcon from '@material-ui/icons/MoreHorizRounded';
import { Flex, Box, Text } from 'rebass/styled-components';

import baseTheme from '../app/themes/baseTheme';
import Table from '../app/components/elements/Table';
import Avatar from '../app/components/elements/Avatar';
import TextInput from '../app/components/elements/TextInput';
import Pagination from '../app/components/elements/Pagination';
import Select from '../app/components/elements/Select';
import Button from '../app/components/elements/Button';
import Icon from '../app/components/elements/Icon';

/* eslint-disable max-len */

// Wrap each story component with the base theme
const withTheme = Story => (
  <ThemeProvider theme={baseTheme}>
    <Story />
  </ThemeProvider>
);

export default {
  title: 'Tables',
  decorators: [withDesign, withKnobs, withTheme],
};

const createPatient = (name, email) => {
  const colors = [
    'blues',
    'cyans',
    'greens',
    'indigos',
    'oranges',
    'pinks',
    'purples',
  ];

  return { name, email, color: colors[random(colors.length - 1)] };
};

const createData = (patient, status, permission, role) => ({ patient, status, permission, role });

const renderPatient = ({ patient }) => {
  let initials = patient.name.match(/\b\w/g) || [];
  initials = toUpper((initials.shift() || '') + (initials.pop() || ''));

  return (
    <Flex alignItems="center">
      <Avatar color={`${patient.color}.9`} bg={`${patient.color}.0`} mr={3} initials={initials} />
      <Box>
        <Text fontWeight="medium">{patient.name}</Text>
        <Text>{patient.email}</Text>
      </Box>
    </Flex>
  );
};

const renderStatus = ({ status }) => {
  let color = 'text.primary';
  let bg = 'transparent';

  if (status) {
    color = status === 'success' ? 'greens.9' : 'indigos.9';
    bg = status === 'success' ? 'greens.0' : 'indigos.0';
  }

  return <Text as="span" px={2} py={1} fontWeight="medium" sx={{ borderRadius: 4 }} color={color} bg={bg}>{status}</Text>;
};

const renderEdit = ({ patient }) => (
  <Button p={0} fontSize="inherit" variant="text" onClick={action(`"Edit" called for ${patient.name}`)}>Edit</Button>
);

const renderMore = ({ patient }) => (
  <Icon variant="button" icon={MoreHorizRoundedIcon} label="More actions" onClick={action(`"More actions" called for ${patient.name}`)} />
);

const columns = [
  { title: 'Patient', field: 'patient', align: 'left', sortable: true, sortBy: 'patient.name', render: renderPatient, searchable: true, searchBy: ['patient.name', 'patient.email'] },
  { title: 'Status', field: 'status', align: 'left', sortable: true, render: renderStatus, searchable: true },
  { title: 'Permission', field: 'permission', align: 'left' },
  { title: 'Role', field: 'role', align: 'left' },
  { title: 'Edit', field: 'edit', render: renderEdit, align: 'left' },
  { title: '', field: 'more', render: renderMore, align: 'left' },
];

const data = [
  createData(createPatient('Claire Clownfish', 'claire@testemail.com'), '', 'Prescriber', 'Clinic Admin'),
  createData(createPatient('James Jellyfish', 'james@testemail.com'), 'success', '', 'Clinic Member'),
  createData(createPatient('Bill Barracuda', 'bill@testemail.com'), '', 'Prescriber', 'Clinic Admin'),
  createData(createPatient('Sam Jellyfish', 'sam@testemail.com'), '', 'Prescriber', 'Clinic Member'),
  createData(createPatient('Oprah Orca', 'oprah@testemail.com'), 'pending', '', 'Clinic Admin'),
  createData(createPatient('Wendy Barracuda', 'wendy@testemail.com'), 'pending', '', 'Clinic Admin'),
  createData(createPatient('George Grouper', 'george@testemail.com'), '', 'Prescriber', 'Clinic Admin'),
  createData(createPatient('Peter Pike', 'peter@testemail.com'), 'success', '', 'Clinic Member'),
  createData(createPatient('Patsy Pickeral', 'patsy@testemail.com'), '', 'Prescriber', 'Clinic Admin'),
  createData(createPatient('Tom Turtle', 'tom@testemail.com'), '', 'Prescriber', 'Clinic Member'),
  createData(createPatient('Perry Porpoise', 'perry@testemail.com'), 'pending', '', 'Clinic Admin'),
  createData(createPatient('Marco Manowar', 'marco@testemail.com'), 'success', '', 'Clinic Admin'),
];

const stickyHeader = () => boolean('Sticky Header', false);
const rowHover = () => boolean('Enable Row Hover', true);

const variants = {
  Default: 'default',
  Condensed: 'condensed',
};

const variant = () => options('Variant', variants, 'default', { display: 'inline-radio' });

const backgrounds = {
  None: 'transparent',
  'Light Grey': 'lightestGrey',
};

const background = () => options('Background Color', backgrounds, 'transparent', { display: 'inline-radio' });

export const Simple = () => {
  const [searchText, setSearchText] = useState();
  const [page, setPage] = React.useState(1);
  const [rowsPerPage, setRowsPerPage] = React.useState(3);

  const getPageCount = rowCount => Math.ceil(rowCount / rowsPerPage);
  const [count, setCount] = React.useState(getPageCount(data.length));

  function handleSearchChange(event) {
    setSearchText(event.target.value);
  }

  const handleRowsPerPageChange = event => {
    setPage(1);
    setRowsPerPage(+event.target.value);
  };

  const handlePageChange = (event, newValue) => {
    setPage(newValue);
  };

  const handleFilterChange = filteredData => {
    setCount(getPageCount(filteredData.length));
  };

  const rowsPerPageOptions = [
    { value: 3, label: '3' },
    { value: 5, label: '5' },
    { value: 10, label: '10' },
    { value: 15, label: '15' },
  ];

  return (
    <React.Fragment>
      <Flex my={3} justifyContent="flex-end" flexGrow>
        <Select
          themeProps={{
            mr: 3,
            width: 'auto',
          }}
          label="Rows per Page"
          name="row-count-select"
          options={rowsPerPageOptions}
          value={rowsPerPage}
          onChange={handleRowsPerPageChange}
          variant="condensed"
        />
        <TextInput
          themeProps={{
            width: 'auto',
            minWidth: '250px',
          }}
          placeholder="enter search text"
          icon={SearchIcon}
          label="Search clinicians"
          name="search"
          onChange={handleSearchChange}
          variant="condensed"
        />
      </Flex>
      <Table
        label="Sample clinician list"
        id="my-table"
        stickyHeader={stickyHeader()}
        rowHover={rowHover()}
        variant={variant()}
        data={data}
        columns={columns}
        bg={background()}
        searchText={searchText}
        onFilter={handleFilterChange}
        page={page}
        rowsPerPage={rowsPerPage}
        orderBy="patient.name"
        order="asc"
      />
      <Pagination
        id="my-paginator`"
        page={page}
        count={count}
        onChange={handlePageChange}
        disabled={count < 2}
        variant="default"
        my={3}
      />
    </React.Fragment>
  );
};

Simple.story = {
  name: 'Simple',
  parameters: {
    design: {
      type: 'figma',
      url: 'https://www.figma.com/file/iuXkrpuLTXExSnuPJE3Jtn/Tidepool-Design-System---Sprint-1?node-id=4%3A993',
    },
  },
};
<commit_msg>[WEB-755] Merge branch 'web-559-component-library' into web-755-split-button<commit_after>import React, { useState } from 'react';

import { withDesign } from 'storybook-addon-designs';
import { action } from '@storybook/addon-actions';
import { withKnobs, boolean, optionsKnob as options } from '@storybook/addon-knobs';
import { ThemeProvider } from 'styled-components';
import toUpper from 'lodash/toUpper';
import random from 'lodash/random';
import SearchIcon from '@material-ui/icons/Search';
import MoreHorizRoundedIcon from '@material-ui/icons/MoreHorizRounded';
import { Flex, Box, Text } from 'rebass/styled-components';

import baseTheme from '../app/themes/baseTheme';
import Table from '../app/components/elements/Table';
import Avatar from '../app/components/elements/Avatar';
import TextInput from '../app/components/elements/TextInput';
import Pagination from '../app/components/elements/Pagination';
import Select from '../app/components/elements/Select';
import Button from '../app/components/elements/Button';
import Icon from '../app/components/elements/Icon';

/* eslint-disable max-len */

// Wrap each story component with the base theme
const withTheme = Story => (
  <ThemeProvider theme={baseTheme}>
    <Story />
  </ThemeProvider>
);

export default {
  title: 'Tables',
  decorators: [withDesign, withKnobs, withTheme],
};

const createPatient = (name, email) => {
  const colors = [
    'blues',
    'cyans',
    'greens',
    'indigos',
    'oranges',
    'pinks',
    'purples',
  ];

  return { name, email, color: colors[random(colors.length - 1)] };
};

const createData = (patient, status, permission, role) => ({ patient, status, permission, role });

const renderPatient = ({ patient }) => {
  let initials = patient.name.match(/\b\w/g) || [];
  initials = toUpper((initials.shift() || '') + (initials.pop() || ''));

  return (
    <Flex alignItems="center">
      <Avatar color={`${patient.color}.9`} bg={`${patient.color}.0`} mr={3} initials={initials} />
      <Box>
        <Text fontWeight="medium">{patient.name}</Text>
        <Text>{patient.email}</Text>
      </Box>
    </Flex>
  );
};

const renderStatus = ({ status }) => {
  let color = 'text.primary';
  let bg = 'transparent';

  if (status) {
    color = status === 'success' ? 'greens.9' : 'indigos.9';
    bg = status === 'success' ? 'greens.0' : 'indigos.0';
  }

  return <Text as="span" px={2} py={1} fontWeight="medium" sx={{ borderRadius: 4 }} color={color} bg={bg}>{status}</Text>;
};

const renderEdit = ({ patient }) => (
  <Button p={0} fontSize="inherit" variant="text" onClick={action(`"Edit" called for ${patient.name}`)}>Edit</Button>
);

const renderMore = ({ patient }) => (
  <Icon variant="button" icon={MoreHorizRoundedIcon} label="More actions" onClick={action(`"More actions" called for ${patient.name}`)} />
);

const columns = [
  { title: 'Patient', field: 'patient', align: 'left', sortable: true, sortBy: 'patient.name', render: renderPatient, searchable: true, searchBy: ['patient.name', 'patient.email'] },
  { title: 'Status', field: 'status', align: 'left', sortable: true, render: renderStatus, searchable: true },
  { title: 'Permission', field: 'permission', align: 'left' },
  { title: 'Role', field: 'role', align: 'left' },
  { title: 'Edit', field: 'edit', render: renderEdit, align: 'left' },
  { title: '', field: 'more', render: renderMore, align: 'left' },
];

const data = [
  createData(createPatient('Claire Clownfish', 'claire@testemail.com'), '', 'Prescriber', 'Clinic Admin'),
  createData(createPatient('James Jellyfish', 'james@testemail.com'), 'success', '', 'Clinic Member'),
  createData(createPatient('Bill Barracuda', 'bill@testemail.com'), '', 'Prescriber', 'Clinic Admin'),
  createData(createPatient('Sam Jellyfish', 'sam@testemail.com'), '', 'Prescriber', 'Clinic Member'),
  createData(createPatient('Oprah Orca', 'oprah@testemail.com'), 'pending', '', 'Clinic Admin'),
  createData(createPatient('Wendy Barracuda', 'wendy@testemail.com'), 'pending', '', 'Clinic Admin'),
  createData(createPatient('George Grouper', 'george@testemail.com'), '', 'Prescriber', 'Clinic Admin'),
  createData(createPatient('Peter Pike', 'peter@testemail.com'), 'success', '', 'Clinic Member'),
  createData(createPatient('Patsy Pickeral', 'patsy@testemail.com'), '', 'Prescriber', 'Clinic Admin'),
  createData(createPatient('Tom Turtle', 'tom@testemail.com'), '', 'Prescriber', 'Clinic Member'),
  createData(createPatient('Perry Porpoise', 'perry@testemail.com'), 'pending', '', 'Clinic Admin'),
  createData(createPatient('Marco Manowar', 'marco@testemail.com'), 'success', '', 'Clinic Admin'),
];

const stickyHeader = () => boolean('Sticky Header', false);
const rowHover = () => boolean('Enable Row Hover', true);

const variants = {
  Default: 'default',
  Condensed: 'condensed',
};

const variant = () => options('Variant', variants, 'default', { display: 'inline-radio' });

const backgrounds = {
  None: 'transparent',
  'Light Grey': 'lightestGrey',
};

const background = () => options('Background Color', backgrounds, 'transparent', { display: 'inline-radio' });

export const Simple = () => {
  const [searchText, setSearchText] = useState();
  const [page, setPage] = React.useState(1);
  const [rowsPerPage, setRowsPerPage] = React.useState(3);

  const getPageCount = rowCount => Math.ceil(rowCount / rowsPerPage);
  const [count, setCount] = React.useState(getPageCount(data.length));

  function handleSearchChange(event) {
    setSearchText(event.target.value);
    setPage(1);
  }

  const handleRowsPerPageChange = event => {
    setPage(1);
    setRowsPerPage(+event.target.value);
  };

  const handlePageChange = (event, newValue) => {
    setPage(newValue);
  };

  const handleFilterChange = filteredData => {
    setCount(getPageCount(filteredData.length));
  };

  const rowsPerPageOptions = [
    { value: 3, label: '3' },
    { value: 5, label: '5' },
    { value: 10, label: '10' },
    { value: 15, label: '15' },
  ];

  return (
    <React.Fragment>
      <Flex my={3} justifyContent="flex-end" flexGrow>
        <Select
          themeProps={{
            mr: 3,
            width: 'auto',
          }}
          label="Rows per Page"
          name="row-count-select"
          options={rowsPerPageOptions}
          value={rowsPerPage}
          onChange={handleRowsPerPageChange}
          variant="condensed"
        />
        <TextInput
          themeProps={{
            width: 'auto',
            minWidth: '250px',
          }}
          placeholder="enter search text"
          icon={SearchIcon}
          label="Search clinicians"
          name="search"
          onChange={handleSearchChange}
          variant="condensed"
        />
      </Flex>
      <Table
        label="Sample clinician list"
        id="my-table"
        stickyHeader={stickyHeader()}
        rowHover={rowHover()}
        variant={variant()}
        data={data}
        columns={columns}
        bg={background()}
        searchText={searchText}
        onFilter={handleFilterChange}
        page={page}
        rowsPerPage={rowsPerPage}
        orderBy="patient.name"
        order="asc"
      />
      <Pagination
        id="my-paginator`"
        page={page}
        count={count}
        onChange={handlePageChange}
        disabled={count < 2}
        variant="default"
        my={3}
      />
    </React.Fragment>
  );
};

Simple.story = {
  name: 'Simple',
  parameters: {
    design: {
      type: 'figma',
      url: 'https://www.figma.com/file/iuXkrpuLTXExSnuPJE3Jtn/Tidepool-Design-System---Sprint-1?node-id=4%3A993',
    },
  },
};
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.set('port', (process.env.PORT || 5000));
app.use(bodyParser.json());

app.get('/', function(req, res) {
	res.send('DC Metro App is up and ready to go!');
});

app.post('/echo_request/parse', function(req, res) {
	var respJSON = null;
	if (req.body.request.type === 'LaunchRequest') {
		respJSON = buildResponse('DC Metro Echo', 'Metro App', 'Welcome to the DC Metro App! How can I help you?', false);
	}
	res.json(respJSON);
});

buildResponse = function(title, subtitle, content, shouldEndSession) {
	return {
		version: '1.0',
		response: {
			outputSpeech: {
				type: 'PlainText',
				text: content
			},
			card: {
				type: 'Simple',
				title: title,
				subtitle: subtitle,
				content: content
			},
			shouldEndSession: shouldEndSession
		}
	};
};

var server = app.listen(app.get('port'), function() {
	console.log('App listening on port', app.get('port'));
});
<commit_msg>Use spaces instead of tabs<commit_after>var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.set('port', (process.env.PORT || 5000));
app.use(bodyParser.json());

app.get('/', function(req, res) {
  res.send('DC Metro App is up and ready to go!');
});

app.post('/echo_request/parse', function(req, res) {
  var respJSON = null;
  if (req.body.request.type === 'LaunchRequest') {
    respJSON = buildResponse('DC Metro Echo', 'Metro App', 'Welcome to the DC Metro App! How can I help you?', false);
  }
  res.json(respJSON);
});

buildResponse = function(title, subtitle, content, shouldEndSession) {
  return {
    version: '1.0',
    response: {
      outputSpeech: {
        type: 'PlainText',
        text: content
      },
      card: {
        type: 'Simple',
        title: title,
        subtitle: subtitle,
        content: content
      },
      shouldEndSession: shouldEndSession
    }
  };
};

var server = app.listen(app.get('port'), function() {
  console.log('App listening on port', app.get('port'));
});
<|endoftext|>


<commit_before>/* eslint-disable */
import * as skinview3d from '../libs/skinview3d';
import { withKnobs, radios, number  } from '@storybook/addon-knobs';

export default {
	title: 'Skinview3d',
	decorators: [withKnobs]
};

let currentAnimation;

const createViewer = () => {
	const element = document.createElement('div');
  element.style.width = '400px';
	element.style.height = '500px';

	let viewer = new skinview3d.SkinViewer({
		domElement: element,
		width: 600,
		height: 600,
		skinUrl: 'texture/1_8_texturemap_redux.png',
	});

	let control = skinview3d.createOrbitControls(viewer);
	control.enableRotate = true;
	control.enableZoom = false;
	control.enablePan = false;

	return { viewer, element };
}

let { viewer, element } = createViewer();

export const NoAnimation = () => {
	if (currentAnimation) {
		currentAnimation.remove();
	}

	return element;
};

export const WithAnimation = () => {

	if (currentAnimation) {
		currentAnimation.remove();
	}

	const animationMap = {
		'Walk': skinview3d.WalkingAnimation,
		'Run': skinview3d.RunningAnimation,
		'Rotate': skinview3d.RotatingAnimation,
	};

	const animationKey = radios('Animations', Object.keys(animationMap), 'Run');
	currentAnimation = viewer.animations.add(animationMap[animationKey]);

	const label = 'Speed';

	const defaultValue = 1;
	const options = {
		 range: true,
		 min: 0.1,
		 max: 3,
		 step: 0.01,
	};
	const value = number(label, defaultValue, options);

	currentAnimation.speed = value;

	return element;
};

export const TestTextures = () => {

	const skinOptions = {
		'1.8 Skin': '1_8_texturemap_redux',
		'Classic Skin': 'Hacksore',
		'HD Skin': 'ironman_hd',
	};
	const skinUrl = radios('Skin Textures', skinOptions, '1_8_texturemap_redux');

	const capeOptions = {
		'None': 'none',
		'Classic Cape': 'cape',
		'HD Cape': 'hd_cape',
	};

	const capeUrl = radios('Cape Textures', capeOptions, 'none');
	viewer.skinUrl = `texture/${skinUrl}.png`;

	// Will fix with #48
	viewer.capeUrl = capeUrl !== 'none' ? `texture/${capeUrl}.png` : null;

	return element;
};
<commit_msg>Update stories<commit_after>/* eslint-disable */
import * as skinview3d from "../libs/skinview3d";
import { withKnobs, radios, number } from "@storybook/addon-knobs";

export default {
	title: "Skinview3d",
	decorators: [withKnobs],
};

let currentAnimation;

const createViewer = () => {
	const element = document.createElement("div");
	const viewer = new skinview3d.SkinViewer(element, {
		width: 300,
		height: 400,
		skin: "texture/1_8_texturemap_redux.png",
	});

	console.log(viewer);

	// Control objects with your mouse!
	const control = skinview3d.createOrbitControls(viewer);
	control.enableRotate = true;
	control.enableZoom = false;
	control.enablePan = false;

	// Add an animation
	currentAnimation = viewer.animations.add(skinview3d.WalkingAnimation);

	return { viewer, element };
};

let { viewer, element } = createViewer();

export const Basic = () => {
	// reset
	let { viewer, element } = createViewer();
	if (currentAnimation) {
		currentAnimation.remove();
	}

	return element;
};

export const Animation = () => {
	if (currentAnimation) {
		currentAnimation.remove();
	}

	const animationMap = {
		Walk: skinview3d.WalkingAnimation,
		Run: skinview3d.RunningAnimation,
		Rotate: skinview3d.RotatingAnimation,
	};

	const animationKey = radios("Animations", Object.keys(animationMap), "Run");
	currentAnimation = viewer.animations.add(animationMap[animationKey]);

	const label = "Speed";

	const defaultValue = 0.5;
	const options = {
		range: true,
		min: 0.1,
		max: 2,
		step: 0.01,
	};
	const value = number(label, defaultValue, options);

	currentAnimation.speed = value;

	return element;
};

export const Textures = () => {
	const skinOptions = {
		"1.8 Skin": "1_8_texturemap_redux",
		"Classic Skin": "Hacksore",
		"HD Skin": "ironman_hd",
	};
	const skinUrl = radios("Skin Textures", skinOptions, "1_8_texturemap_redux");

	const capeOptions = {
		None: "none",
		"Classic Cape": "cape",
		"HD Cape": "hd_cape",
	};

	const capeUrl = radios("Cape Textures", capeOptions, "none");
	viewer.loadSkin(`texture/${skinUrl}.png`);

	if (capeUrl === "none") {
		viewer.loadCape(null);
	}

	viewer.loadCape(`texture/${capeUrl}.png`);

	return element;
};
<|endoftext|>


<commit_before>var db = require('../models');
var LocalStrategy = require('passport-local').Strategy;
var TwitterStrategy = require('passport-twitter').Strategy;

module.exports = {
  serializeUser: function(user, done) {
    done(null, user.id);
  },
  deserializeUser: function(id, done) {
    db.user.findById(id).then(function(user) {
      done(null, user.get());
    }).catch(done);
  },
  localStrategy: new LocalStrategy({
      usernameField: 'email'
    },
    function(email, password, done) {
      db.user.find({where: {email: email}}).then(function(user) {
        if (user) {
          user.checkPassword(password, function(err, result) {
            if (err) return done(err);
            if (result) {
              done(null, user.get());
            } else {
              done(null, false, {message: 'Invalid password'});
            }
          });
        } else {
          done(null, false, {message: 'Unknown user'});
        }
      });
  }),
  twitterStrategy: new TwitterStrategy({
    consumerKey: process.env.TWITTER_CONSUMER_KEY,
    consumerSecret: process.env.TWITTER_CONSUMER_SECRET,
    callbackURL: process.env.BASE_URL + '/auth/twitter/callback'
  },
  function(token, tokenSecret, profile, done) {
    //do things
    db.provider.find({
      where: {
        pid: profile.id,
        type: profile.provider
      },
      include: [db.user]
    }).then(function(provider) {
      if(provider && provider.user) {
        provider.token = token;
        provider.save().then(function() {
          done(null, provider.user.get());
        });
      } else {
        var username = profile.username;
        db.user.findOrCreate({
          where: {username: username},
          defaults: {email: null}
        }).spread(function(user, created) {
          if(created) {
            user.createProvider({
              pid: profile.id,
              token: token,
              type: profile.provider
            }).then(function() {
              done(null, user.get());
            });
          } else {
            done(null, false, {message: 'You already signed up with this email address. Please login'});
          }
        });
      }
    });
  })
};

<commit_msg>changed local strategy to use username as the usernameField<commit_after>var db = require('../models');
var LocalStrategy = require('passport-local').Strategy;
var TwitterStrategy = require('passport-twitter').Strategy;

module.exports = {
  serializeUser: function(user, done) {
    done(null, user.id);
  },
  deserializeUser: function(id, done) {
    db.user.findById(id).then(function(user) {
      done(null, user.get());
    }).catch(done);
  },
  localStrategy: new LocalStrategy({
      usernameField: 'username'
    },
    function(username, password, done) {
      db.user.find({where: {username: username}}).then(function(user) {
        if(user) {
          user.checkPassword(password, function(err, result) {
            if(err) {
              return done(err);
            }
            if(result) {
              done(null, user.get());
            } else {
              done(null, false, {message: 'Invalid password'});
            }
          });
        } else {
          done(null, false, {message: 'Unknown user'});
        }
      });
  }),
  twitterStrategy: new TwitterStrategy({
    consumerKey: process.env.TWITTER_CONSUMER_KEY,
    consumerSecret: process.env.TWITTER_CONSUMER_SECRET,
    callbackURL: process.env.BASE_URL + '/auth/twitter/callback'
  },
  function(token, tokenSecret, profile, done) {
    db.provider.find({
      where: {
        pid: profile.id,
        type: profile.provider
      },
      include: [db.user]
    }).then(function(provider) {
      if(provider && provider.user) {
        provider.token = token;
        provider.save().then(function() {
          done(null, provider.user.get());
        });
      } else {
        var username = profile.username;
        db.user.findOrCreate({
          where: {username: username},
          defaults: {email: null}
        }).spread(function(user, created) {
          if(created) {
            user.createProvider({
              pid: profile.id,
              token: token,
              type: profile.provider
            }).then(function() {
              done(null, user.get());
            });
          } else {
            done(null, false, {message: 'This username already exists. Please login'});
          }
        });
      }
    });
  })
};

<|endoftext|>


<commit_before>var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var app = require("express");
var server = require("http").Server(app);
var io = require("socket.io")(server);

var handleClient = function (socket) {
    socket.sendUTF("hello");
    console.log("connect");
};

io.on("connection", handleClient);

console.log("listen: "+ipaddress+" "+port);
server.listen(port, ipaddress);

//Openshift variables
/*
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;

var ws = require("nodejs-websocket")

// Scream server example: "hi" -> "HI!!!"
var server = ws.createServer(function (conn) {
    console.log("New connection")
    conn.on("text", function (str) {
        console.log("Received "+str)
        conn.sendText(str.toUpperCase()+"!!!")
    })
    conn.on("close", function (code, reason) {
        console.log("Connection closed")
    })
}).listen(8080)
*/

/*
//NodeJS require modules
var WebSocketServer = require('ws').Server
    wss = new WebSocketServer({host:ipaddress, port:port});

wss.on('connection', function(ws) {
    console.log((new Date()) + ' Connection from origin: ' + ws._socket.remoteAddress);
});

console.log((new Date()) + " Server is listening on: " + ipaddress + ':' port);
*/

/*
var net = require('net');
var sockets = [];
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var guestId = 0;

var server = net.createServer(function(socket) {
	// Increment
	guestId++;

	socket.nickname = "Guest" + guestId;
	var clientName = socket.nickname;

	sockets.push(socket);

	// Log it to the server output
	console.log(clientName + ' joined this chat.');

	// Welcome user to the socket
	socket.write("Welcome to telnet chat!\n");

	// Broadcast to all
	broadcast(clientName, clientName + ' joined this chat.\n');

	// When client sends data
	socket.on('data', function(data) {

		var message = clientName + '> ' + data.toString();

		broadcast(clientName, message);

		// Log it to the server output
		process.stdout.write(message);
	});

	// When client leaves
	socket.on('end', function() {

		var message = clientName + ' left this chat\n';

		// Log it to the server output
		process.stdout.write(message);

		// Remove client from socket array
		removeSocket(socket);

		// Notify all clients
		broadcast(clientName, message);
	});

	// When socket gets errors
	socket.on('error', function(error) {

		console.log('Socket got problems: ', error.message);

	});
});

// Broadcast to others, excluding the sender
function broadcast(from, message) {

	// If there are no sockets, then don't broadcast any messages
	if (sockets.length === 0) {
		process.stdout.write('Everyone left the chat');
		return;
	}

	// If there are clients remaining then broadcast message
	sockets.forEach(function(socket, index, array){
		// Dont send any messages to the sender
		if(socket.nickname === from) return;

		socket.write(message);

	});

};

// Remove disconnected client from sockets array
function removeSocket(socket) {

	sockets.splice(sockets.indexOf(socket), 1);

};

// Listening for any problems with the server
server.on('error', function(error) {

	console.log("So we got problems!", error.message);

});

// Listen for a port to telnet to
// then in the terminal just run 'telnet localhost [port]'
server.listen(port, ipaddress, function() {

	console.log("Server listening at http://localhost:" + port);

});

*/<commit_msg>using the example from OpenShift<commit_after>var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

var WebSocketServer = require('ws').Server
var http = require('http');

var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
	response.writeHead(200, {'Content-Type': 'text/plain'});
	  response.write("Welcome to Node.js on OpenShift!\n\n");
	  response.end("Thanks for visiting us! \n");
});

server.listen( port, ipaddress, function() {
    console.log((new Date()) + ' Server is listening on port 8080');
});

wss = new WebSocketServer({
    server: server,
    autoAcceptConnections: false
});
wss.on('connection', function(ws) {
  console.log("New connection");
  ws.on('message', function(message) {
    ws.send("Received: " + message);
  });
  ws.send('Welcome!');
});

console.log("Listening to " + ipaddress + ":" + port + "...");

/*
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var app = require("express");
var server = require("http").Server(app);
var io = require("socket.io")(server);

var handleClient = function (socket) {
    socket.sendUTF("hello");
    console.log("connect");
};

io.on("connection", handleClient);

console.log("listen: "+ipaddress+" "+port);
server.listen(port, ipaddress);

*/

//Openshift variables
/*
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;

var ws = require("nodejs-websocket")

// Scream server example: "hi" -> "HI!!!"
var server = ws.createServer(function (conn) {
    console.log("New connection")
    conn.on("text", function (str) {
        console.log("Received "+str)
        conn.sendText(str.toUpperCase()+"!!!")
    })
    conn.on("close", function (code, reason) {
        console.log("Connection closed")
    })
}).listen(8080)
*/

/*
//NodeJS require modules
var WebSocketServer = require('ws').Server
    wss = new WebSocketServer({host:ipaddress, port:port});

wss.on('connection', function(ws) {
    console.log((new Date()) + ' Connection from origin: ' + ws._socket.remoteAddress);
});

console.log((new Date()) + " Server is listening on: " + ipaddress + ':' port);
*/

/*
var net = require('net');
var sockets = [];
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var guestId = 0;

var server = net.createServer(function(socket) {
	// Increment
	guestId++;

	socket.nickname = "Guest" + guestId;
	var clientName = socket.nickname;

	sockets.push(socket);

	// Log it to the server output
	console.log(clientName + ' joined this chat.');

	// Welcome user to the socket
	socket.write("Welcome to telnet chat!\n");

	// Broadcast to all
	broadcast(clientName, clientName + ' joined this chat.\n');

	// When client sends data
	socket.on('data', function(data) {

		var message = clientName + '> ' + data.toString();

		broadcast(clientName, message);

		// Log it to the server output
		process.stdout.write(message);
	});

	// When client leaves
	socket.on('end', function() {

		var message = clientName + ' left this chat\n';

		// Log it to the server output
		process.stdout.write(message);

		// Remove client from socket array
		removeSocket(socket);

		// Notify all clients
		broadcast(clientName, message);
	});

	// When socket gets errors
	socket.on('error', function(error) {

		console.log('Socket got problems: ', error.message);

	});
});

// Broadcast to others, excluding the sender
function broadcast(from, message) {

	// If there are no sockets, then don't broadcast any messages
	if (sockets.length === 0) {
		process.stdout.write('Everyone left the chat');
		return;
	}

	// If there are clients remaining then broadcast message
	sockets.forEach(function(socket, index, array){
		// Dont send any messages to the sender
		if(socket.nickname === from) return;

		socket.write(message);

	});

};

// Remove disconnected client from sockets array
function removeSocket(socket) {

	sockets.splice(sockets.indexOf(socket), 1);

};

// Listening for any problems with the server
server.on('error', function(error) {

	console.log("So we got problems!", error.message);

});

// Listen for a port to telnet to
// then in the terminal just run 'telnet localhost [port]'
server.listen(port, ipaddress, function() {

	console.log("Server listening at http://localhost:" + port);

});

*/<|endoftext|>