<commit_before>var concat = require('concat-stream')
var http = require('http')
var fs = require('fs')
var url = require('url')

var prStatus = require('./prcheck.js')
var collabStatus = require('./collabcheck.js')
var mergePr = require('./merge.js')

module.exports = function(withEmail) {

  var server = http.createServer(handler)

  function handler(req, res) {
    console.log([new Date(), req.method, req.url])

    // when RR gets a push from email on collab
    if (req.url === '/push') {
      return handleEmail(req, res)
    }

    // when a pr is made to patchwork repo
    if (req.url.match('/orderin')) {
      return getPR(req, res)
    }

    // when git-it verifies user made a pr
    if (req.url.match('/pr')) {
      var queryURL = url.parse(req.url, true)
      var username = queryURL.query.username
      return prStatus(username, function(err, pr) {
        checkPR(res, err, pr)
      })
    }

    // when git-it verifies user added RR as collab
    if (req.url.match('/collab')) {
      var queryURL = url.parse(req.url, true)
      var username = queryURL.query.username
      return collabStatus(username, function(err, collab) {
        checkCollab(res, err, collab)
      })
    }

  // when anything else goes to reporobot.jlord.us
  res.statusCode = 404
  res.setHeader('content-type', 'application/json')
  res.end(JSON.stringify({
    error: 404,
    message: 'not_found'
  }, true, 2))
}

  function handleEmail(req, res) {
    req.pipe(concat(function(buff) {
      var emailObj = JSON.parse(buff)

      if (onHook) withEmail(emailObj, function(err, message) {
        if (err) console.log([new Date(), message, err])
      })
    }))

    res.statusCode = 200
    res.end("Thank you.")
  }

  function getPR(req, res) {
    req.pipe(concat(function(buff) {
      var pullreq = JSON.parse(buff)

      mergePr(pullreq, function(err, message) {
        if (err) console.log([new Date(), message, err])
      })

      res.statusCode = 200
      res.setHeader('content-type', 'application/json')
      res.end()
    }))
  }

  function checkPR(res, err, pr) {
    if (err) {
      console.log(err)
      res.statusCode = 500
      res.end(JSON.stringify({error: err}))
      return
    }
    res.statusCode = 200
    // res.setHeader('content-type', 'application/json')
    res.end(JSON.stringify({
      pr: pr
    }, true, 2))
  }

  function checkCollab(res, err, collab) {
    if (err) {
      console.log(err)
      res.statusCode = 500
      res.end(JSON.stringify({error: err}))
      return
    }
    res.statusCode = 200
    res.setHeader('content-type', 'application/json')
    res.end(JSON.stringify({
      collab: collab
    }, true, 2))
  }

  function mergedPr(res, err) {
    if (err) {
      console.log(err)
      res.statusCode = 500
      res.end(JSON.stringify({error: err}))
      return
    }
    res.statusCode = 200
    res.setHeader('content-type', 'application/json')
    res.end(JSON.stringify({
      merged: true,
    }, true, 2))
  }

  return server
}
<commit_msg>fix email trigger<commit_after>var concat = require('concat-stream')
var http = require('http')
var fs = require('fs')
var url = require('url')

var prStatus = require('./prcheck.js')
var collabStatus = require('./collabcheck.js')
var mergePr = require('./merge.js')

module.exports = function(onHook) {

  var server = http.createServer(handler)

  function handler(req, res) {
    console.log([new Date(), req.method, req.url])

    // when RR gets a push from email on collab
    if (req.url === '/push') {
      return handleEmail(req, res)
    }

    // when a pr is made to patchwork repo
    if (req.url.match('/orderin')) {
      return getPR(req, res)
    }

    // when git-it verifies user made a pr
    if (req.url.match('/pr')) {
      var queryURL = url.parse(req.url, true)
      var username = queryURL.query.username
      return prStatus(username, function(err, pr) {
        checkPR(res, err, pr)
      })
    }

    // when git-it verifies user added RR as collab
    if (req.url.match('/collab')) {
      var queryURL = url.parse(req.url, true)
      var username = queryURL.query.username
      return collabStatus(username, function(err, collab) {
        checkCollab(res, err, collab)
      })
    }

  // when anything else goes to reporobot.jlord.us
  res.statusCode = 404
  res.setHeader('content-type', 'application/json')
  res.end(JSON.stringify({
    error: 404,
    message: 'not_found'
  }, true, 2))
}

  function handleEmail(req, res) {
    req.pipe(concat(function(buff) {
      var emailObj = JSON.parse(buff)

      if (onHook) withEmail(emailObj, function(err, message) {
        if (err) console.log([new Date(), message, err])
      })
    }))

    res.statusCode = 200
    res.end("Thank you.")
  }

  function getPR(req, res) {
    req.pipe(concat(function(buff) {
      var pullreq = JSON.parse(buff)

      mergePr(pullreq, function(err, message) {
        if (err) console.log([new Date(), message, err])
      })

      res.statusCode = 200
      res.setHeader('content-type', 'application/json')
      res.end()
    }))
  }

  function checkPR(res, err, pr) {
    if (err) {
      console.log(err)
      res.statusCode = 500
      res.end(JSON.stringify({error: err}))
      return
    }
    res.statusCode = 200
    // res.setHeader('content-type', 'application/json')
    res.end(JSON.stringify({
      pr: pr
    }, true, 2))
  }

  function checkCollab(res, err, collab) {
    if (err) {
      console.log(err)
      res.statusCode = 500
      res.end(JSON.stringify({error: err}))
      return
    }
    res.statusCode = 200
    res.setHeader('content-type', 'application/json')
    res.end(JSON.stringify({
      collab: collab
    }, true, 2))
  }

  function mergedPr(res, err) {
    if (err) {
      console.log(err)
      res.statusCode = 500
      res.end(JSON.stringify({error: err}))
      return
    }
    res.statusCode = 200
    res.setHeader('content-type', 'application/json')
    res.end(JSON.stringify({
      merged: true,
    }, true, 2))
  }

  return server
}
<|endoftext|>


<commit_before>const { isRegularExpressionLiteral } = require('typescript')
const Long = require('../utils/long')

const INT8_SIZE = 1
const INT16_SIZE = 2
const INT32_SIZE = 4
const INT64_SIZE = 8
const DOUBLE_SIZE = 8

const MOST_SIGNIFICANT_BIT = 0x80 // 128
const OTHER_BITS = 0x7f // 127

module.exports = class Decoder {
  static int32Size() {
    return INT32_SIZE
  }

  static decodeZigZag(value) {
    return (value >>> 1) ^ -(value & 1)
  }

  static decodeZigZag64(longValue) {
    return longValue.shiftRightUnsigned(1).xor(longValue.and(Long.fromInt(1)).negate())
  }

  constructor(buffer) {
    this.buffer = buffer
    this.offset = 0
  }

  readInt8() {
    const value = this.buffer.readInt8(this.offset)
    this.offset += INT8_SIZE
    return value
  }

  canReadInt16() {
    return this.canReadBytes(INT16_SIZE)
  }

  readInt16() {
    const value = this.buffer.readInt16BE(this.offset)
    this.offset += INT16_SIZE
    return value
  }

  canReadInt32() {
    return this.canReadBytes(INT32_SIZE)
  }

  readInt32() {
    const value = this.buffer.readInt32BE(this.offset)
    this.offset += INT32_SIZE
    return value
  }

  canReadInt64() {
    return this.canReadBytes(INT64_SIZE)
  }

  readInt64() {
    const first = this.buffer[this.offset]
    const last = this.buffer[this.offset + 7]

    const low =
      (first << 24) + // Overflow
      this.buffer[this.offset + 1] * 2 ** 16 +
      this.buffer[this.offset + 2] * 2 ** 8 +
      this.buffer[this.offset + 3]
    const high =
      this.buffer[this.offset + 4] * 2 ** 24 +
      this.buffer[this.offset + 5] * 2 ** 16 +
      this.buffer[this.offset + 6] * 2 ** 8 +
      last
    this.offset += INT64_SIZE

    return (BigInt(low) << 32n) + BigInt(high)
  }

  readDouble() {
    const value = this.buffer.readDoubleBE(this.offset)
    this.offset += DOUBLE_SIZE
    return value
  }

  readString() {
    const byteLength = this.readInt16()

    if (byteLength === -1) {
      return null
    }

    const stringBuffer = this.buffer.slice(this.offset, this.offset + byteLength)
    const value = stringBuffer.toString('utf8')
    this.offset += byteLength
    return value
  }

  readVarIntString() {
    const byteLength = this.readVarInt()

    if (byteLength === -1) {
      return null
    }

    const stringBuffer = this.buffer.slice(this.offset, this.offset + byteLength)
    const value = stringBuffer.toString('utf8')
    this.offset += byteLength
    return value
  }

  canReadBytes(length) {
    return Buffer.byteLength(this.buffer) - this.offset >= length
  }

  readBytes(byteLength = this.readInt32()) {
    if (byteLength === -1) {
      return null
    }

    const stringBuffer = this.buffer.slice(this.offset, this.offset + byteLength)
    this.offset += byteLength
    return stringBuffer
  }

  readVarIntBytes() {
    const byteLength = this.readVarInt()

    if (byteLength === -1) {
      return null
    }

    const stringBuffer = this.buffer.slice(this.offset, this.offset + byteLength)
    this.offset += byteLength
    return stringBuffer
  }

  readBoolean() {
    return this.readInt8() === 1
  }

  readAll() {
    const result = this.buffer.slice(this.offset)
    this.offset += Buffer.byteLength(this.buffer)
    return result
  }

  readArray(reader) {
    const length = this.readInt32()

    if (length === -1) {
      return []
    }

    const array = new Array(length)
    for (let i = 0; i < length; i++) {
      array[i] = reader(this)
    }

    return array
  }

  readVarIntArray(reader) {
    const length = this.readVarInt()

    if (length === -1) {
      return []
    }

    const array = new Array(length)
    for (let i = 0; i < length; i++) {
      array[i] = reader(this)
    }

    return array
  }

  async readArrayAsync(reader) {
    const length = this.readInt32()

    if (length === -1) {
      return []
    }

    const array = new Array(length)
    for (let i = 0; i < length; i++) {
      array[i] = await reader(this)
    }

    return array
  }

  readVarInt() {
    let currentByte
    let result = 0
    let i = 0

    do {
      currentByte = this.buffer[this.offset++]
      result += (currentByte & OTHER_BITS) << i
      i += 7
    } while (currentByte >= MOST_SIGNIFICANT_BIT)

    return Decoder.decodeZigZag(result)
  }
  // By default JavaScript's numbers are of type float64, performing bitwise operations converts the numbers to a signed 32-bit integer
  // Unsigned Right Shift Operator >>> ensures the returned value is an unsigned 32-bit integer
  readUVarInt() {
    let currentByte
    let result = 0
    let i = 0
    while (((currentByte = this.buffer[this.offset++]) & MOST_SIGNIFICANT_BIT) != 0) {
      result |= (currentByte & OTHER_BITS) << i
      i += 7
      if (i > 35) {
        throw new Error('Variable length quantity is too long')
      }
    }
    result |= currentByte << i
    return result >>> 0
  }

  readVarLong() {
    let currentByte
    let result = Long.fromInt(0)
    let i = 0

    do {
      currentByte = this.buffer[this.offset++]
      result = result.add(Long.fromInt(currentByte & OTHER_BITS).shiftLeft(i))
      i += 7
    } while (currentByte >= MOST_SIGNIFICANT_BIT)

    return Decoder.decodeZigZag64(result)
  }

  slice(size) {
    return new Decoder(this.buffer.slice(this.offset, this.offset + size))
  }

  forward(size) {
    this.offset += size
  }
}
<commit_msg>fixed eslint errors<commit_after>const Long = require('../utils/long')

const INT8_SIZE = 1
const INT16_SIZE = 2
const INT32_SIZE = 4
const INT64_SIZE = 8
const DOUBLE_SIZE = 8

const MOST_SIGNIFICANT_BIT = 0x80 // 128
const OTHER_BITS = 0x7f // 127

module.exports = class Decoder {
  static int32Size() {
    return INT32_SIZE
  }

  static decodeZigZag(value) {
    return (value >>> 1) ^ -(value & 1)
  }

  static decodeZigZag64(longValue) {
    return longValue.shiftRightUnsigned(1).xor(longValue.and(Long.fromInt(1)).negate())
  }

  constructor(buffer) {
    this.buffer = buffer
    this.offset = 0
  }

  readInt8() {
    const value = this.buffer.readInt8(this.offset)
    this.offset += INT8_SIZE
    return value
  }

  canReadInt16() {
    return this.canReadBytes(INT16_SIZE)
  }

  readInt16() {
    const value = this.buffer.readInt16BE(this.offset)
    this.offset += INT16_SIZE
    return value
  }

  canReadInt32() {
    return this.canReadBytes(INT32_SIZE)
  }

  readInt32() {
    const value = this.buffer.readInt32BE(this.offset)
    this.offset += INT32_SIZE
    return value
  }

  canReadInt64() {
    return this.canReadBytes(INT64_SIZE)
  }

  readInt64() {
    const first = this.buffer[this.offset]
    const last = this.buffer[this.offset + 7]

    const low =
      (first << 24) + // Overflow
      this.buffer[this.offset + 1] * 2 ** 16 +
      this.buffer[this.offset + 2] * 2 ** 8 +
      this.buffer[this.offset + 3]
    const high =
      this.buffer[this.offset + 4] * 2 ** 24 +
      this.buffer[this.offset + 5] * 2 ** 16 +
      this.buffer[this.offset + 6] * 2 ** 8 +
      last
    this.offset += INT64_SIZE

    return (BigInt(low) << 32n) + BigInt(high)
  }

  readDouble() {
    const value = this.buffer.readDoubleBE(this.offset)
    this.offset += DOUBLE_SIZE
    return value
  }

  readString() {
    const byteLength = this.readInt16()

    if (byteLength === -1) {
      return null
    }

    const stringBuffer = this.buffer.slice(this.offset, this.offset + byteLength)
    const value = stringBuffer.toString('utf8')
    this.offset += byteLength
    return value
  }

  readVarIntString() {
    const byteLength = this.readVarInt()

    if (byteLength === -1) {
      return null
    }

    const stringBuffer = this.buffer.slice(this.offset, this.offset + byteLength)
    const value = stringBuffer.toString('utf8')
    this.offset += byteLength
    return value
  }

  canReadBytes(length) {
    return Buffer.byteLength(this.buffer) - this.offset >= length
  }

  readBytes(byteLength = this.readInt32()) {
    if (byteLength === -1) {
      return null
    }

    const stringBuffer = this.buffer.slice(this.offset, this.offset + byteLength)
    this.offset += byteLength
    return stringBuffer
  }

  readVarIntBytes() {
    const byteLength = this.readVarInt()

    if (byteLength === -1) {
      return null
    }

    const stringBuffer = this.buffer.slice(this.offset, this.offset + byteLength)
    this.offset += byteLength
    return stringBuffer
  }

  readBoolean() {
    return this.readInt8() === 1
  }

  readAll() {
    const result = this.buffer.slice(this.offset)
    this.offset += Buffer.byteLength(this.buffer)
    return result
  }

  readArray(reader) {
    const length = this.readInt32()

    if (length === -1) {
      return []
    }

    const array = new Array(length)
    for (let i = 0; i < length; i++) {
      array[i] = reader(this)
    }

    return array
  }

  readVarIntArray(reader) {
    const length = this.readVarInt()

    if (length === -1) {
      return []
    }

    const array = new Array(length)
    for (let i = 0; i < length; i++) {
      array[i] = reader(this)
    }

    return array
  }

  async readArrayAsync(reader) {
    const length = this.readInt32()

    if (length === -1) {
      return []
    }

    const array = new Array(length)
    for (let i = 0; i < length; i++) {
      array[i] = await reader(this)
    }

    return array
  }

  readVarInt() {
    let currentByte
    let result = 0
    let i = 0

    do {
      currentByte = this.buffer[this.offset++]
      result += (currentByte & OTHER_BITS) << i
      i += 7
    } while (currentByte >= MOST_SIGNIFICANT_BIT)

    return Decoder.decodeZigZag(result)
  }

  // By default JavaScript's numbers are of type float64, performing bitwise operations converts the numbers to a signed 32-bit integer
  // Unsigned Right Shift Operator >>> ensures the returned value is an unsigned 32-bit integer
  readUVarInt() {
    let currentByte
    let result = 0
    let i = 0
    while (((currentByte = this.buffer[this.offset++]) & MOST_SIGNIFICANT_BIT) !== 0) {
      result |= (currentByte & OTHER_BITS) << i
      i += 7
      if (i > 35) {
        throw new Error('Variable length quantity is too long')
      }
    }
    result |= currentByte << i
    return result >>> 0
  }

  readVarLong() {
    let currentByte
    let result = Long.fromInt(0)
    let i = 0

    do {
      currentByte = this.buffer[this.offset++]
      result = result.add(Long.fromInt(currentByte & OTHER_BITS).shiftLeft(i))
      i += 7
    } while (currentByte >= MOST_SIGNIFICANT_BIT)

    return Decoder.decodeZigZag64(result)
  }

  slice(size) {
    return new Decoder(this.buffer.slice(this.offset, this.offset + size))
  }

  forward(size) {
    this.offset += size
  }
}
<|endoftext|>


<commit_before>var Botkit = require('botkit')

var token = process.env.SLACK_TOKEN

var races_original = [
	"The Barony of Letnev",
	"The Clan of Saar",
	"The Emirates of Hacan",
	"The Federation of Sol",
	"The Mentak Coalition",
	"The Naalu Collective",
	"The Nekro Virus",
	"The Sardakk N’orr",
	"The Universities of Jol-Nar",
	"The Winnu",
	"The Xxcha Kingdom",
	"The Yssaril Tribes",
	"The Brotherhood of Yin",
	"The Embers of Muaat",
	"The Ghosts of Creuss",
	"The L1z1x Mindnet",
	"The Arborec"
  ]
var races = races_original
var currently_choosing
var current_choices = []
var number_of_choices = 3

var players = {}

var controller = Botkit.slackbot({
  // reconnect to Slack RTM when connection goes bad
  retry: Infinity,
  debug: false
})

// Assume single team mode if we have a SLACK_TOKEN
if (token) {
  console.log('Starting in single-team mode')
  console.log("cause there's this token" + token)
  controller.spawn({
    token: token,
    retry: Infinity
  }).startRTM(function (err, bot, payload) {
    if (err) {
      throw new Error(err)
    }

    console.log('Connected to Slack RTM')
  })
// Otherwise assume multi-team mode - setup beep boop resourcer connection
} else {
  console.log('Starting in Beep Boop multi-team mode')
  require('beepboop-botkit').start(controller, { debug: true })
}

controller.on('bot_channel_join', function (bot, message) {
  bot.reply(message, "I'm here!")
})

controller.hears(['list races'], ['direct_mention','direct_message'], function (bot, message) {
  var reply = "Here are the currently available races:\n"
  races.forEach(function(item) {
    reply += "* " + item + "\n";
  })
  bot.reply(message, reply);
})

controller.hears(['dig'], ['direct_mention'], function (bot, message) {
  var reply = "I heard " + message.match[0] + ".\n";
  reply += "Plus the 1 was " + message.match[1] + ".\n";
  reply += "So that's the text '" + message.text + "'.";
  userData = message.text.match(/<@([A-Z0-9]{9})>/);
  reply += "And the userdata is " + userData + ".";
	reply += "type of userdata is " + typeof(userData) + ".";
	/*userArr = userData.split(",");
	userName = userArr[0]
	userId = userArr[1]
	*/
	reply += "\nThat's userName = " + userName + " and userId = " + userId + ".";
  reply += "message user was " + message.user + ".";
  bot.reply(message, reply);
})

controller.hears(['add'], ['direct_mention'], function (bot, message) {
  var reply = "I heard add. text was " + message.text + ".";
  var userData = message.text.match(/<@([A-Z0-9]{9})>/);
  if (userData) {
		if (!players[userData]) {
			players[userData] = null;
			reply += "\nAdded " + userData + ">.";
		} else {
			reply += "@<" + userData + "> is already playing.";
		}
	} else {
	  reply += "\nBut there was no one to add ???";
	}
  bot.reply(message, reply);
})

controller.hears(['list players'], ['direct_mention'], function (bot, message) {
	var reply = "The players are:\n";
	for (var p in players) {
	  reply += " - " + p + " playing " + players[p] + "."
	}
	bot.reply(message, reply);
})

controller.hears(['hello', 'hi'], ['direct_mention'], function (bot, message) {
  bot.reply(message, 'Hello.')
})

controller.hears(['hello', 'hi'], ['direct_message'], function (bot, message) {
  bot.reply(message, 'Hello.')
  bot.reply(message, 'It\'s nice to talk to you directly.')
})

controller.hears('.*', ['mention'], function (bot, message) {
  bot.reply(message, 'You really do care about me. :heart:')
})

controller.hears('help', ['direct_message', 'direct_mention'], function (bot, message) {
  var help = 'I will respond to the following messages: \n' +
      '`bot hi` for a simple message.\n' +
      '`bot attachment` to see a Slack attachment message.\n' +
      '`@<your bot\'s name>` to demonstrate detecting a mention.\n' +
      '`bot help` to see this again.'
  bot.reply(message, help)
})

controller.hears(['attachment'], ['direct_message', 'direct_mention'], function (bot, message) {
  var text = 'Beep Beep Boop is a ridiculously simple hosting platform for your Slackbots.'
  var attachments = [{
    fallback: text,
    pretext: 'We bring bots to life. :sunglasses: :thumbsup:',
    title: 'Host, deploy and share your bot in seconds.',
    image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
    title_link: 'https://beepboophq.com/',
    text: text,
    color: '#7CD197'
  }]

  bot.reply(message, {
    attachments: attachments
  }, function (err, resp) {
    console.log(err, resp)
  })
})

controller.hears('.*', ['direct_message', 'direct_mention'], function (bot, message) {
  bot.reply(message, 'Sorry <@' + message.user + '>, I don\'t understand. \n')
})
<commit_msg>ok now<commit_after>var Botkit = require('botkit')

var token = process.env.SLACK_TOKEN

var races_original = [
	"The Barony of Letnev",
	"The Clan of Saar",
	"The Emirates of Hacan",
	"The Federation of Sol",
	"The Mentak Coalition",
	"The Naalu Collective",
	"The Nekro Virus",
	"The Sardakk N’orr",
	"The Universities of Jol-Nar",
	"The Winnu",
	"The Xxcha Kingdom",
	"The Yssaril Tribes",
	"The Brotherhood of Yin",
	"The Embers of Muaat",
	"The Ghosts of Creuss",
	"The L1z1x Mindnet",
	"The Arborec"
  ]
var races = races_original
var currently_choosing
var current_choices = []
var number_of_choices = 3

var players = {}

var controller = Botkit.slackbot({
  // reconnect to Slack RTM when connection goes bad
  retry: Infinity,
  debug: false
})

// Assume single team mode if we have a SLACK_TOKEN
if (token) {
  console.log('Starting in single-team mode')
  console.log("cause there's this token" + token)
  controller.spawn({
    token: token,
    retry: Infinity
  }).startRTM(function (err, bot, payload) {
    if (err) {
      throw new Error(err)
    }

    console.log('Connected to Slack RTM')
  })
// Otherwise assume multi-team mode - setup beep boop resourcer connection
} else {
  console.log('Starting in Beep Boop multi-team mode')
  require('beepboop-botkit').start(controller, { debug: true })
}

controller.on('bot_channel_join', function (bot, message) {
  bot.reply(message, "I'm here!")
})

controller.hears(['list races'], ['direct_mention','direct_message'], function (bot, message) {
  var reply = "Here are the currently available races:\n"
  races.forEach(function(item) {
    reply += "* " + item + "\n";
  })
  bot.reply(message, reply);
})

controller.hears(['dig'], ['direct_mention'], function (bot, message) {
  var reply = "I heard " + message.match[0] + ".\n";
  reply += "Plus the 1 was " + message.match[1] + ".\n";
  reply += "So that's the text '" + message.text + "'.";
  userData = message.text.match(/<@([A-Z0-9]{9})>/);
  reply += "And the userdata is " + userData + ".";
	reply += "type of userdata is " + typeof(userData) + ".";
	/*userArr = userData.split(",");
	userName = userArr[0]
	userId = userArr[1]
	reply += "\nThat's userName = " + userName + " and userId = " + userId + ".";
	*/
  reply += "message user was " + message.user + ".";
  bot.reply(message, reply);
})

controller.hears(['add'], ['direct_mention'], function (bot, message) {
  var reply = "I heard add. text was " + message.text + ".";
  var userData = message.text.match(/<@([A-Z0-9]{9})>/);
  if (userData) {
		if (!players[userData]) {
			players[userData] = null;
			reply += "\nAdded " + userData + ">.";
		} else {
			reply += "@<" + userData + "> is already playing.";
		}
	} else {
	  reply += "\nBut there was no one to add ???";
	}
  bot.reply(message, reply);
})

controller.hears(['list players'], ['direct_mention'], function (bot, message) {
	var reply = "The players are:\n";
	for (var p in players) {
	  reply += " - " + p + " playing " + players[p] + "."
	}
	bot.reply(message, reply);
})

controller.hears(['hello', 'hi'], ['direct_mention'], function (bot, message) {
  bot.reply(message, 'Hello.')
})

controller.hears(['hello', 'hi'], ['direct_message'], function (bot, message) {
  bot.reply(message, 'Hello.')
  bot.reply(message, 'It\'s nice to talk to you directly.')
})

controller.hears('.*', ['mention'], function (bot, message) {
  bot.reply(message, 'You really do care about me. :heart:')
})

controller.hears('help', ['direct_message', 'direct_mention'], function (bot, message) {
  var help = 'I will respond to the following messages: \n' +
      '`bot hi` for a simple message.\n' +
      '`bot attachment` to see a Slack attachment message.\n' +
      '`@<your bot\'s name>` to demonstrate detecting a mention.\n' +
      '`bot help` to see this again.'
  bot.reply(message, help)
})

controller.hears(['attachment'], ['direct_message', 'direct_mention'], function (bot, message) {
  var text = 'Beep Beep Boop is a ridiculously simple hosting platform for your Slackbots.'
  var attachments = [{
    fallback: text,
    pretext: 'We bring bots to life. :sunglasses: :thumbsup:',
    title: 'Host, deploy and share your bot in seconds.',
    image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
    title_link: 'https://beepboophq.com/',
    text: text,
    color: '#7CD197'
  }]

  bot.reply(message, {
    attachments: attachments
  }, function (err, resp) {
    console.log(err, resp)
  })
})

controller.hears('.*', ['direct_message', 'direct_mention'], function (bot, message) {
  bot.reply(message, 'Sorry <@' + message.user + '>, I don\'t understand. \n')
})
<|endoftext|>


<commit_before>/**
 * node-tvdb
 *
 * Node.js library for accessing TheTVDB API at <http://www.thetvdb.com/wiki/index.php?title=Programmers_API>
 *
 * Copyright (c) 2014 Edward Wellbrook <edwellbrook@gmail.com>
 * MIT Licensed
 */

var request = require("superagent").get;
var parser  = require("xml2js").parseString;
var promise = require("when").promise;

var remoteProviders = {
    imdbid: /^tt/i,
    zap2it: /^ep/i
};

var parserOptions = {
    trim: true,
    normalize: true,
    ignoreAttrs: true,
    explicitArray: false,
    emptyTag: null
};

var Client = function(accessToken, language) {
    if (!accessToken) {
        throw new Error("Access token must be set.");
    }

    this._token = accessToken;
    this._language = language || "en";
    this._baseURL = "http://www.thetvdb.com/api/";
};

/**
 * Languages
 */

Client.prototype.getLanguages = function(callback) {
    var path = this._baseURL + this._token + "/languages.xml";

    return promise(function(resolve, reject) {
        sendRequest(path, function(error, response) {
            response = (response && response.Languages) ? response.Languages.Language : null;
            callback ? callback(error, response) : error ? reject(error) : resolve(response);
        });
    });
};

Client.prototype.getLanguage = function() {
    return this._language;
};

Client.prototype.setLanguage = function(language) {
    this._language = language;
};

/**
 * Time
 */

Client.prototype.getTime = function(callback) {
    var path = this._baseURL + "Updates.php?type=none";

    return promise(function(resolve, reject) {
        sendRequest(path, function(error, response) {
            response = (response && response.Items) ? response.Items.Time : null;
            callback ? callback(error, response) : error ? reject(error) : resolve(response);
        });
    });
};

/**
 * Series
 */

Client.prototype.getSeries = function(name, callback) {
    var path = this._baseURL + "GetSeries.php?seriesname=" + name + "&language=" + this._language;

    return promise(function(resolve, reject) {
        sendRequest(path, function(error, response) {
            response = (response && response.Data) ? response.Data.Series : null;
            callback ? callback(error, response) : error ? reject(error) : resolve(response);
        });
    });
};

Client.prototype.getSeriesById = function(id, callback) {
    var path = this._baseURL + this._token + "/series/" + id + "/" + this._language + ".xml";

    return promise(function(resolve, reject) {
        sendRequest(path, function(error, response) {
            response = (response && response.Data) ? response.Data.Series : null;
            callback ? callback(error, response) : error ? reject(error) : resolve(response);
        });
    });
};

Client.prototype.getSeriesByRemoteId = function(remoteId, callback) {
    var provider = "";
    var keys     = Object.keys(remoteProviders);
    var len      = keys.length;

    for (var i = 0; i < len; i++) {
        if (remoteProviders[keys[i]].exec(remoteId)) {
            provider = keys[i];
            break;
        }
    }

    var path = this._baseURL + "GetSeriesByRemoteID.php?" + provider + "=" + remoteId + "&language=" + this._language;

    return promise(function(resolve, reject) {
        sendRequest(path, function(error, response) {
            response = (response && response.Data) ? response.Data.Series : null;
            callback ? callback(error, response) : error ? reject(error) : resolve(response);
        });
    });
};

Client.prototype.getSeriesAllById = function(id, callback) {
    var path = this._baseURL + this._token + "/series/" + id + "/all/" + this._language + ".xml";

    return promise(function(resolve, reject) {
        sendRequest(path, function(error, response) {
            if (response && response.Data && response.Data.Series) {
                response.Data.Series.Episodes = response.Data.Episode;
            }

            response = response ? response.Data.Series : null;
            callback ? callback(error, response) : error ? reject(error) : resolve(response);
        });
    });
};

Client.prototype.getActors = function(id, callback) {
    var path = this._baseURL + this._token + "/series/" + id + "/actors.xml";

    return promise(function(resolve, reject) {
        sendRequest(path, function(error, response) {
            response = (response && response.Actors) ? response.Actors.Actor : null;
            callback ? callback(error, response) : error ? reject(error) : resolve(response);
        });
    });
};

Client.prototype.getBanners = function(id, callback) {
    var path = this._baseURL + this._token + "/series/" + id + "/banners.xml";

    return promise(function(resolve, reject) {
        sendRequest(path, function(error, response) {
            response = (response && response.Banners) ? response.Banners.Banner : null;
            callback ? callback(error, response) : error ? reject(error) : resolve(response);
        });
    });
};

/**
 * Episodes
 */

Client.prototype.getEpisodeById = function(id, callback) {
    var path = this._baseURL + this._token + "/episodes/" + id;

    return promise(function(resolve, reject) {
        sendRequest(path, function(error, response) {
            response = (response && response.Data) ? response.Data.Episode : null;
            callback ? callback(error, response) : error ? reject(error) : resolve(response);
        });
    });
};

/**
 * Updates
 */

Client.prototype.getUpdates = function(time, callback) {
    var path = this._baseURL + "Updates.php?type=all&time=" + time;

    return promise(function(resolve, reject) {
        sendRequest(path, function(error, response) {
            response = response ? response.Items : null;
            callback ? callback(error, response) : error ? reject(error) : resolve(response);
        });
    });
};

/**
 * Utilities
 */

function sendRequest(url, done) {

    request(url, function (error, data) {

        if (data &&
            data.statusCode === 200 &&
            data.text != "" &&
            data.type != "text/plain" &&
            !~data.text.indexOf("404 Not Found")) {

            parser(data.text, parserOptions, function(error, results) {
                if (results && results.Error) {
                    error   = new Error(results.Error);
                    results = null;
                }

                done(error, results);
            });

        } else {
            error = error ? error : new Error("Could not complete the request");
            done(error, null);
        }
    });
};

module.exports = Client;
<commit_msg>make http response available through callback<commit_after>/**
 * node-tvdb
 *
 * Node.js library for accessing TheTVDB API at <http://www.thetvdb.com/wiki/index.php?title=Programmers_API>
 *
 * Copyright (c) 2014 Edward Wellbrook <edwellbrook@gmail.com>
 * MIT Licensed
 */

var request = require("superagent").get;
var parser  = require("xml2js").parseString;
var promise = require("when").promise;

var remoteProviders = {
    imdbid: /^tt/i,
    zap2it: /^ep/i
};

var parserOptions = {
    trim: true,
    normalize: true,
    ignoreAttrs: true,
    explicitArray: false,
    emptyTag: null
};

var Client = function(accessToken, language) {
    if (!accessToken) {
        throw new Error("Access token must be set.");
    }

    this._token = accessToken;
    this._language = language || "en";
    this._baseURL = "http://www.thetvdb.com/api/";
};

/**
 * Languages
 */

Client.prototype.getLanguages = function(callback) {
    var path = this._baseURL + this._token + "/languages.xml";

    return promise(function(resolve, reject) {
        sendRequest(path, function(error, response, httpResponse) {
            response = (response && response.Languages) ? response.Languages.Language : null;
            callback ? callback(error, response, httpResponse) : error ? reject(error) : resolve(response);
        });
    });
};

Client.prototype.getLanguage = function() {
    return this._language;
};

Client.prototype.setLanguage = function(language) {
    this._language = language;
};

/**
 * Time
 */

Client.prototype.getTime = function(callback) {
    var path = this._baseURL + "Updates.php?type=none";

    return promise(function(resolve, reject) {
        sendRequest(path, function(error, response, httpResponse) {
            response = (response && response.Items) ? response.Items.Time : null;
            callback ? callback(error, response, httpResponse) : error ? reject(error) : resolve(response);
        });
    });
};

/**
 * Series
 */

Client.prototype.getSeries = function(name, callback) {
    var path = this._baseURL + "GetSeries.php?seriesname=" + name + "&language=" + this._language;

    return promise(function(resolve, reject) {
        sendRequest(path, function(error, response, httpResponse) {
            response = (response && response.Data) ? response.Data.Series : null;
            callback ? callback(error, response, httpResponse) : error ? reject(error) : resolve(response);
        });
    });
};

Client.prototype.getSeriesById = function(id, callback) {
    var path = this._baseURL + this._token + "/series/" + id + "/" + this._language + ".xml";

    return promise(function(resolve, reject) {
        sendRequest(path, function(error, response, httpResponse) {
            response = (response && response.Data) ? response.Data.Series : null;
            callback ? callback(error, response, httpResponse) : error ? reject(error) : resolve(response);
        });
    });
};

Client.prototype.getSeriesByRemoteId = function(remoteId, callback) {
    var provider = "";
    var keys     = Object.keys(remoteProviders);
    var len      = keys.length;

    for (var i = 0; i < len; i++) {
        if (remoteProviders[keys[i]].exec(remoteId)) {
            provider = keys[i];
            break;
        }
    }

    var path = this._baseURL + "GetSeriesByRemoteID.php?" + provider + "=" + remoteId + "&language=" + this._language;

    return promise(function(resolve, reject) {
        sendRequest(path, function(error, response, httpResponse) {
            response = (response && response.Data) ? response.Data.Series : null;
            callback ? callback(error, response, httpResponse) : error ? reject(error) : resolve(response);
        });
    });
};

Client.prototype.getSeriesAllById = function(id, callback) {
    var path = this._baseURL + this._token + "/series/" + id + "/all/" + this._language + ".xml";

    return promise(function(resolve, reject) {
        sendRequest(path, function(error, response, httpResponse) {
            if (response && response.Data && response.Data.Series) {
                response.Data.Series.Episodes = response.Data.Episode;
            }

            response = response ? response.Data.Series : null;
            callback ? callback(error, response, httpResponse) : error ? reject(error) : resolve(response);
        });
    });
};

Client.prototype.getActors = function(id, callback) {
    var path = this._baseURL + this._token + "/series/" + id + "/actors.xml";

    return promise(function(resolve, reject) {
        sendRequest(path, function(error, response, httpResponse) {
            response = (response && response.Actors) ? response.Actors.Actor : null;
            callback ? callback(error, response, httpResponse) : error ? reject(error) : resolve(response);
        });
    });
};

Client.prototype.getBanners = function(id, callback) {
    var path = this._baseURL + this._token + "/series/" + id + "/banners.xml";

    return promise(function(resolve, reject) {
        sendRequest(path, function(error, response, httpResponse) {
            response = (response && response.Banners) ? response.Banners.Banner : null;
            callback ? callback(error, response, httpResponse) : error ? reject(error) : resolve(response);
        });
    });
};

/**
 * Episodes
 */

Client.prototype.getEpisodeById = function(id, callback) {
    var path = this._baseURL + this._token + "/episodes/" + id;

    return promise(function(resolve, reject) {
        sendRequest(path, function(error, response, httpResponse) {
            response = (response && response.Data) ? response.Data.Episode : null;
            callback ? callback(error, response, httpResponse) : error ? reject(error) : resolve(response);
        });
    });
};

/**
 * Updates
 */

Client.prototype.getUpdates = function(time, callback) {
    var path = this._baseURL + "Updates.php?type=all&time=" + time;

    return promise(function(resolve, reject) {
        sendRequest(path, function(error, response, httpResponse) {
            response = response ? response.Items : null;
            callback ? callback(error, response, httpResponse) : error ? reject(error) : resolve(response);
        });
    });
};

/**
 * Utilities
 */

function sendRequest(url, done) {

    request(url, function (error, data) {

        if (data &&
            data.statusCode === 200 &&
            data.text != "" &&
            data.type != "text/plain" &&
            !~data.text.indexOf("404 Not Found")) {

            parser(data.text, parserOptions, function(error, results) {
                if (results && results.Error) {
                    error   = new Error(results.Error);
                    results = null;
                }

                done(error, results, data);
            });

        } else {
            error = error ? error : new Error("Could not complete the request");
            error.statusCode = data.statusCode;

            done(error, null, data);
        }
    });
}

module.exports = Client;
<|endoftext|>


<commit_before>/*!
 * verbalize <https://github.com/jonschlinkert/verbalize>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

var Base = require('log-events');
var util = require('util');
var use = require('use');
var utils = require('./lib/utils');
var plugins = require('./lib/plugins');

function create() {

  var Logger = Base.create();

  /**
   * Create an instance of `Verbalize` with the given `options`.
   *
   * ```js
   * var logger = new Verbalize({verbose: true});
   * ```
   * @param {Object} `options`
   * @api public
   */

  function Verbalize(options) {
    if (!(this instanceof Verbalize)) {
      return new Verbalize(options);
    }
    Logger.call(this);
    this.options = options || {};
    this.define('cache', {});
    use(this);
    this.initDefaults();
    this.initPlugins();
  }

  /**
   * Mixin `Logger` prototype methods
   */

  util.inherits(Verbalize, Logger);

  Verbalize.prototype.initDefaults = function() {
    this.addMode('verbose');
    this.addMode('not', {mode: 'toggle'});
  };

  Verbalize.prototype.initPlugins = function() {
    this.use(plugins.colors(this.options));
    this.use(plugins.styles(this.options));
    this.use(plugins.isEnabled(this.options));
    this.use(plugins.handler(this.options));
  };

  /**
   * Base formatting.
   *
   * @return {String} `msg`
   * @api public
   */

  Verbalize.prototype._format = function(args) {
    args = utils.toArray.apply(null, arguments);

    if (args.length > 0) {
      args[0] = String(args[0]);
    }
    return util.format.apply(util, args);
  };

  /**
   * Write to the console.
   *
   * @return {String} `msg`
   * @api public
   */

  Verbalize.prototype._write = function(msg) {
    process.stdout.write(utils.markup(msg || ''));
    return this;
  };

  /**
   * Write to the console followed by a newline. A blank
   * line is returned if no value is passed.
   *
   * @return {String} `msg`
   * @api public
   */

  Verbalize.prototype._writeln = function(msg) {
    return this._write((msg || '') + '\n');
  };

  /**
   * Write output.
   *
   * @return {String}
   * @api public
   */

  Verbalize.prototype.write = function() {
    return this._write(this._format(arguments));
  };

  /**
   * Write output followed by a newline.
   *
   * @return {String}
   * @api public
   */

  Verbalize.prototype.writeln = function() {
    return this._writeln(this._format(arguments));
  };

  /**
   * Style a basic separator.
   *
   * @return {String}
   * @api public
   */

  Verbalize.prototype.sep = function(str) {
    return this._sep || (this._sep = this.stylize('gray', str || ' · '));
  };

  Verbalize.prototype.style = function(name, options, fn) {
    if (typeof options === 'function') {
      fn = options;
      options = {};
    }
    var opts = utils.extend({type: ['modifier'], fn: fn}, options);
    return this.addLogger(name, opts);
  };

  /**
   * Stylize the given `msg` with the specified `color`.
   *
   * @param {String} `color` The name of the color to use
   * @param {String} `msg` The args to stylize.
   * @return {String}
   */

  Verbalize.prototype.stylize = function(color, args) {
    args = utils.toArray(args);
    var len = args.length;
    var res = [];
    var idx = -1;

    var strip = this.options.stripColor === true;
    while (++idx < len) {
      var arg = args[idx];
      if (strip) {
        res.push(utils.stripColor(arg));
      } else {
        var modifier = null;
        if (typeof color === 'string') {
          modifier = utils.get(this.modifiers, [color]);
        } else {
          modifier = color;
        }
        if (modifier) {
          res.push(modifier.fn.call(this, arg));
        } else {
          res.push(arg);
        }
      }
    }
    return res;
  };

  /**
   * Define non-enumerable property `key` with the given value.
   *
   * @param {String} `key`
   * @param {any} `value`
   * @return {String}
   * @api public
   */

  Verbalize.prototype.define = function(key, value) {
    utils.define(this, key, value);
    return this;
  };

  return Verbalize;
}

/**
 * Expose `Verbalize`
 */

module.exports = create();

module.exports.create = create;
<commit_msg>code comments<commit_after>/*!
 * verbalize <https://github.com/jonschlinkert/verbalize>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

var Base = require('log-events');
var util = require('util');
var use = require('use');
var utils = require('./lib/utils');
var plugins = require('./lib/plugins');

function create() {

  var Logger = Base.create();

  /**
   * Create an instance of `Verbalize` with the given `options`.
   *
   * ```js
   * var logger = new Verbalize({verbose: true});
   * ```
   * @param {Object} `options`
   * @api public
   */

  function Verbalize(options) {
    if (!(this instanceof Verbalize)) {
      return new Verbalize(options);
    }
    Logger.call(this);
    this.options = options || {};
    this.define('cache', {});
    use(this);
    this.initDefaults();
    this.initPlugins();
  }

  /**
   * Mixin `Logger` prototype methods
   */

  util.inherits(Verbalize, Logger);

  Verbalize.prototype.initDefaults = function() {
    this.addMode('verbose');
    this.addMode('not', {mode: 'toggle'});
  };

  Verbalize.prototype.initPlugins = function() {
    this.use(plugins.colors(this.options));
    this.use(plugins.styles(this.options));
    this.use(plugins.isEnabled(this.options));
    this.use(plugins.handler(this.options));
  };

  /**
   * Base formatting.
   *
   * @return {String} `msg`
   * @api public
   */

  Verbalize.prototype._format = function(args) {
    args = utils.toArray.apply(null, arguments);

    if (args.length > 0) {
      args[0] = String(args[0]);
    }
    return util.format.apply(util, args);
  };

  /**
   * Write to the console.
   *
   * @return {String} `msg`
   * @api public
   */

  Verbalize.prototype._write = function(msg) {
    process.stdout.write(utils.markup(msg || ''));
    return this;
  };

  /**
   * Write to the console followed by a newline. A blank
   * line is returned if no value is passed.
   *
   * @return {String} `msg`
   * @api public
   */

  Verbalize.prototype._writeln = function(msg) {
    return this._write((msg || '') + '\n');
  };

  /**
   * Write formatted output.
   *
   * @return {String}
   * @api public
   */

  Verbalize.prototype.write = function() {
    return this._write(this._format(arguments));
  };

  /**
   * Write formatted output followed by a newline.
   *
   * @return {String}
   * @api public
   */

  Verbalize.prototype.writeln = function() {
    return this._writeln(this._format(arguments));
  };

  /**
   * Style a basic separator.
   *
   * @return {String}
   * @api public
   */

  Verbalize.prototype.sep = function(str) {
    return this._sep || (this._sep = this.stylize('gray', str || ' · '));
  };

  /**
   * Stylize the given `msg` with the specified `color`.
   *
   * @param {String} `color` The name of the color to use
   * @param {String} `msg` The args to stylize.
   * @return {String}
   * @api public
   */

  Verbalize.prototype.stylize = function(color, args) {
    args = utils.toArray(args);
    var len = args.length;
    var res = [];
    var idx = -1;

    var strip = this.options.stripColor === true;
    while (++idx < len) {
      var arg = args[idx];
      if (strip) {
        res.push(utils.stripColor(arg));
      } else {
        var modifier = null;
        if (typeof color === 'string') {
          modifier = utils.get(this.modifiers, [color]);
        } else {
          modifier = color;
        }
        if (modifier) {
          res.push(modifier.fn.call(this, arg));
        } else {
          res.push(arg);
        }
      }
    }
    return res;
  };

  /**
   * Add a style logger.
   *
   * ```js
   * logger.style('red', function() {
   *   return this.stylize('red', arguments);
   * });
   * ```
   * @param  {String} `name` Name of style logger method to be added to the logger.
   * @param  {Object} `options` Options to control style logger method.
   * @param  {Function} `fn` Optional function to do the styling.
   * @return {Object} `this` for chaining.
   * @api public
   */

  Verbalize.prototype.style = function(name, options, fn) {
    if (typeof options === 'function') {
      fn = options;
      options = {};
    }
    var opts = utils.extend({type: ['modifier'], fn: fn}, options);
    return this.addLogger(name, opts);
  };

  /**
   * Define non-enumerable property `key` with the given value.
   *
   * @param {String} `key`
   * @param {any} `value`
   * @return {String}
   * @api public
   */

  Verbalize.prototype.define = function(key, value) {
    utils.define(this, key, value);
    return this;
  };

  return Verbalize;
}

/**
 * Expose `Verbalize`
 */

module.exports = create();

/**
 * Static method to create a new constructor.
 * This is useful in tests and places where the original
 * prototype should not be updated.
 *
 * ```js
 * var MyLogger = Verbalize.create();
 * var logger = new MyLogger();
 * ```
 * @name Verbalize.create
 * @api public
 */

module.exports.create = create;
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var BME280 = require('node-bme280');
var barometer = new BME280({address: 0x77});
var latestTemp;
var latestPressure;
var latestHumidity;
var ready = false;

var Datastore = require('nedb')
  , db = new Datastore({ filename: 'data.txt', autoload: true });

barometer.begin(function(err) {
    if (err) {
        console.info('error initializing barometer', err);
        return;
    }
    console.info('barometer running');
	setImmediate(readData);
	setInterval(readData, 60 * 1000);
});

var readData = function () {
	barometer.readPressureAndTemparature(function(err, pressure, temperature, humidity) {
		latestTemp = temperature.toFixed(2);
		latestPressure = (pressure / 100).toFixed(2);
		latestHumidity = humidity.toFixed(2);
		ready = true;
		db.insert({
			time: new Date(),
			ambientTemperature: latestTemp,
			pressure: latestPressure,
			humidity: latestHumidity
		});
	});
};

app.get('/', function (req, res) {
	res.write("<meta http-equiv=\"refresh\" content=\"5\"><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
	if (ready) {
		res.write("Temperature: " + latestTemp + " ℃
");
		res.write("Pressure: " + latestPressure + " hPa
");
		res.write("Humidity: " + latestHumidity + "%\n");
	} else {
		res.write("No data is available currently.");
	}
	res.end("");
});

app.get('/output.csv', function (req, res) {
	db.find({}).sort({ time: 1 }).exec(function (err, docs) {
		for (var i = 0; i < docs.length; i++) {
			var time = docs[i].time;
			var formattedDate = time.getFullYear() + "-" + (time.getMonth() + 1) + "-" + time.getDate();
			var formattedTime = time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds();
			var formattedDateTime = formattedDate + " " + formattedTime; // github doesn't like long lines
			res.write(formattedDateTime + ",");
			res.write(docs[i].ambientTemperature + ",");
			res.write(docs[i].pressure + ",");
			res.write(docs[i].humidity + "\n");
		}
		res.end();
	});
});

app.listen(80, function () {
	console.log('Example app listening on port 80!');
});
<commit_msg>add header<commit_after>var express = require('express');
var app = express();
var BME280 = require('node-bme280');
var barometer = new BME280({address: 0x77});
var latestTemp;
var latestPressure;
var latestHumidity;
var ready = false;

var Datastore = require('nedb')
  , db = new Datastore({ filename: 'data.txt', autoload: true });

barometer.begin(function(err) {
    if (err) {
        console.info('error initializing barometer', err);
        return;
    }
    console.info('barometer running');
	setImmediate(readData);
	setInterval(readData, 60 * 1000);
});

var readData = function () {
	barometer.readPressureAndTemparature(function(err, pressure, temperature, humidity) {
		latestTemp = temperature.toFixed(2);
		latestPressure = (pressure / 100).toFixed(2);
		latestHumidity = humidity.toFixed(2);
		ready = true;
		db.insert({
			time: new Date(),
			ambientTemperature: latestTemp,
			pressure: latestPressure,
			humidity: latestHumidity
		});
	});
};

app.get('/', function (req, res) {
	res.write("<meta http-equiv=\"refresh\" content=\"5\"><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
	if (ready) {
		res.write("Temperature: " + latestTemp + " ℃
");
		res.write("Pressure: " + latestPressure + " hPa
");
		res.write("Humidity: " + latestHumidity + "%\n");
	} else {
		res.write("No data is available currently.");
	}
	res.end("");
});

app.get('/output.csv', function (req, res) {
	db.find({}).sort({ time: 1 }).exec(function (err, docs) {
		res.write("Time,Temperature,Pressure,Humidity\n");
		for (var i = 0; i < docs.length; i++) {
			var time = docs[i].time;
			var formattedDate = time.getFullYear() + "-" + (time.getMonth() + 1) + "-" + time.getDate();
			var formattedTime = time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds();
			var formattedDateTime = formattedDate + " " + formattedTime; // github doesn't like long lines
			res.write(formattedDateTime + ",");
			res.write(docs[i].ambientTemperature + ",");
			res.write(docs[i].pressure + ",");
			res.write(docs[i].humidity + "\n");
		}
		res.end();
	});
});

app.listen(80, function () {
	console.log('Example app listening on port 80!');
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

var argv = require('optimist').argv;
if (argv.h || argv.help) {
  console.log('\nusage:');
  console.log('-h, --help        : show help');
  console.log('-p, --port        : port (default 5080)');
  console.log('-P, --pouch-port  : pouchdb-server port (default 16984)');
  console.log('-l, --log         : pouchdb-server log level (dev|short|tiny|combined|off)');
  console.log('-r, --remote      : remote fullfatdb (default https://registry.npmjs.org)');
  console.log('-R, --remote-skim : remote skimdb (default https://skimdb.npmjs.com/registry)');
  console.log();
  return process.exit(0);
}

var port = argv.p || argv.port || 5080;
var pouchPort = argv.P || argv['pouch-port'] || 16984;

var NUM_PARALLEL_TASKS = 10;

var FAT_REMOTE = argv.r || argv.remote || 'https://registry.npmjs.org';
var SKIM_REMOTE = argv.R || argv['remote-skim'] || 'https://skimdb.npmjs.com/registry';
var FAT_LOCAL = 'http://localhost:' + pouchPort + '/fullfatdb';
var SKIM_LOCAL = 'http://localhost:' + pouchPort + '/skimdb';

console.log('\nWelcome!');
console.log('To start using local-npm, just run: ');
console.log('\n  $ npm set registry http://127.0.0.1:' + port);
console.log('\nTo switch back, you can run: ');
console.log('\n  $ npm set registry ' + FAT_REMOTE);

var request = require('request');
var Promise = require('bluebird');
var fs = require('fs');
var Fullfat = require('npm-fullfat-registry');
var pouchdbServerLite = require('./pouchdb-server-lite');
var app = pouchdbServerLite.app;
var PouchDB = pouchdbServerLite.PouchDB;

var skimRemote = new PouchDB(SKIM_REMOTE);
var skimPouch = new PouchDB('skimdb');
var fatPouch = new PouchDB('fullfatdb');
// I tend to use more than the default 10 listeners
skimPouch.setMaxListeners(NUM_PARALLEL_TASKS * 50);
fatPouch.setMaxListeners(NUM_PARALLEL_TASKS * 50);

// replicate from central skimdb
var upToDate;
var startingTimeout = 1000;
var backoff = 1.1;
var sync;

function replicateSkim() {
  skimRemote.info().then(function (info) {
    sync = skimPouch.replicate.from(skimRemote, {
      live: true,
      batch_size: 1000
    }).on('change', function (change) {
      var percent = Math.min(100,
        (Math.floor(change.last_seq / info.update_seq * 10000) / 100).toFixed(2));
      console.log('Replicating skimdb, last_seq is: ' + change.last_seq + ' (' + percent + '%)');
    }).on('uptodate', function () {
      console.log('local skimdb is up to date');
      fs.writeFile('uptodate.txt', '1');
      upToDate = true;
    }).on('error', function (err) {
      console.error('error during replication with skimdb');
      console.error(err);
      restartReplication();
    });
  }).catch(function (err) {
    console.error('error doing info() on ' + SKIM_REMOTE);
    console.error(err);
    restartReplication();
  });
}
function restartReplication() {
  // just keep going
  startingTimeout *= backoff;
  setTimeout(replicateSkim, Math.round(startingTimeout));
}
replicateSkim();

var fullFat;

// start doing exciting shit
Promise.resolve().then(function () {
  return Promise.promisify(fs.readFile)('uptodate.txt').catch(function (err) {
    return '0'; // default
  });
}).then(function (upToDateFile) {
  upToDate = upToDateFile === '1';
  if (upToDate) {
    console.log('local skimdb is up to date');
  }
}).then(function () {
  // trick Fullfat into never doing automatic syncing; we don't use it for that
  return Promise.promisify(fs.writeFile)('registry.seq', '999999999999');
}).then(function () {
  fullFat = new Fullfat({
    skim: SKIM_LOCAL,
    fat: FAT_LOCAL,
    seq_file: 'registry.seq',
    missing_log: 'missing.log'
  })
  .on('start', function () {
    // we want the changes feed to only be local,
    // but all other operations should be remote
    // if we're not done replicating yet
    process.nextTick(function () {
      fullFat.skim = upToDate ? SKIM_LOCAL : SKIM_REMOTE;
    });
  })
  .on('error', function (err) {
    console.error("fullfat hit an error");
    console.error(err);
  });
}).then(function () {
  // start user-facing proxy server

  // only execute n fullFat.js operations in parallel
  var queues = [];
  for (var i = 0; i < NUM_PARALLEL_TASKS; i++) {
    queues.push(Promise.resolve());
  }

  function processWithFullFat(docId) {
    console.log(docId + ': got request...');
    // recover by fetching with fullFat
    // wait for changes to let us know it was fetched
    var queueIdx = docId.charCodeAt(0) % queues.length;
    queues[queueIdx] = queues[queueIdx].then(function () {
      console.log(docId + ': looking up in pouch');
      return new Promise(function (resolve, reject) {
        var changes = fatPouch.changes({
          since: 'latest',
          live: true
        }).on('change', function onChange(change) {
          console.log(change.id + ': got change');
          if (change.id === docId) {
            console.log('successfully wrote to local fullfatdb: ' + docId);
            changes.cancel();
            resolve();
          }
        }).on('error', function (err) {
          console.error('change hit error');
          reject(err);
        });
        console.log(docId + ': fetching in the background');
        // this seq is only used by fullFat to determine the file name to write tgz's to
        fullFat.getDoc({id: docId, seq: Math.round(Math.random() * 1000000)});
      });
    });
    return queues[queueIdx];
  }

  function updateAfterIncomingChange() {
    // keep a log of what the last seq we checked was
    fs.readFile('skim-seq.txt', function (err, data) {
      var seq = data ? parseInt(data) : 0;
      console.log('reading skimPouch changes since ' + seq);
      skimPouch.changes({since: seq, live: true}).on('change', function (change) {
        fs.writeFile('skim-seq.txt', change.seq.toString());
        fatPouch.allDocs({keys: [change.id]}).then(function (res) {
          if (res[0] && res[0].rev !== change.changes[0].rev) {
            console.log('new change came in for ' + change.id + ', updating...');
            return processWithFullFat(change.id);
          }
        }).catch(function (err) {
          console.error('unhandled skimPouch allDocs err');
          console.error(err);
        });
      }).on('error', function (err) {
        console.error('unhandled skimPouch changes err');
        console.error(err);
      });
    });
  }
  if (upToDate) {
    updateAfterIncomingChange();
  } else {
    skimPouch.on('uptodate', function () {
      fullFat.skim = SKIM_LOCAL; // internal API, probably shouldn't do this
      skimPouch.info().then(function (info) {
        return Promise.promisify(fs.writeFile)('skim-seq.txt',
            info.update_seq.toString()).then(function () {
          updateAfterIncomingChange();
        });
      }).catch(function (err) {
        console.error('unhandled writeFile err');
        console.error(err);
      });
    });
  }

  var server = require('http').createServer(function (req, res) {
    var docId;
    Promise.resolve().then(function () {
      if (req.method.toLowerCase() === 'get') {
        // simple doc or attachment request (get)
        var url = require('url').parse(req.url);
        docId = decodeURIComponent(url.pathname.split('/')[1]);
        if (!docId) {
          return;
        }
        console.log(docId + ': simple doc request');
        // check if it exists first
        return fatPouch.get(docId).catch(function (err) {
          if (err.status === 404) {
            console.log('not found locally: ' + docId);
            process.nextTick(function () {
              processWithFullFat(docId); // exec in background
            });
          }
          throw err;
        });
      } else {
        throw new Error('bad_local_request');
      }
    }).then(function () {
      if (docId) {
        console.log(docId + ': doc exists locally');
      }
      request.get('http://127.0.0.1:' + pouchPort + '/fullfatdb' + req.url).pipe(res);
    }).catch(function (err) {
      if (err.name === 'bad_local_request') {
        console.error('got a bad request: ' + req.url);
        res.status(400).send({error: 'this proxy only accepts GETs'});
      } else {
        console.error(docId + ': no local doc, need to proxy to remote');
        // we got an error, so let's proxy to the remote fat
        // so we can return immediately
        request.get(FAT_REMOTE + req.url).pipe(res);
      }
    });
  });
  server.listen(5080, function (err) {
    if (err) {
      console.error(err);
    } else {
      console.log('Proxy server started at http://127.0.0.1:' + port);
    }
  });
}).catch(function (err) {
  console.error(err);
  throw err;
});

process.on('SIGINT', function () {
  // close gracefully
  sync.cancel();
  Promise.all([fatPouch, skimPouch].map(function (pouch) {
    return pouch.close();
  })).then(function () {
    process.exit(0);
  });
});
<commit_msg>fix readFile<commit_after>#!/usr/bin/env node

'use strict';

var argv = require('optimist').argv;
if (argv.h || argv.help) {
  console.log('\nusage:');
  console.log('-h, --help        : show help');
  console.log('-p, --port        : port (default 5080)');
  console.log('-P, --pouch-port  : pouchdb-server port (default 16984)');
  console.log('-l, --log         : pouchdb-server log level (dev|short|tiny|combined|off)');
  console.log('-r, --remote      : remote fullfatdb (default https://registry.npmjs.org)');
  console.log('-R, --remote-skim : remote skimdb (default https://skimdb.npmjs.com/registry)');
  console.log();
  return process.exit(0);
}

var port = argv.p || argv.port || 5080;
var pouchPort = argv.P || argv['pouch-port'] || 16984;

var NUM_PARALLEL_TASKS = 10;

var FAT_REMOTE = argv.r || argv.remote || 'https://registry.npmjs.org';
var SKIM_REMOTE = argv.R || argv['remote-skim'] || 'https://skimdb.npmjs.com/registry';
var FAT_LOCAL = 'http://localhost:' + pouchPort + '/fullfatdb';
var SKIM_LOCAL = 'http://localhost:' + pouchPort + '/skimdb';

console.log('\nWelcome!');
console.log('To start using local-npm, just run: ');
console.log('\n  $ npm set registry http://127.0.0.1:' + port);
console.log('\nTo switch back, you can run: ');
console.log('\n  $ npm set registry ' + FAT_REMOTE);

var request = require('request');
var Promise = require('bluebird');
var fs = require('fs');
var Fullfat = require('npm-fullfat-registry');
var pouchdbServerLite = require('./pouchdb-server-lite');
var app = pouchdbServerLite.app;
var PouchDB = pouchdbServerLite.PouchDB;

var skimRemote = new PouchDB(SKIM_REMOTE);
var skimPouch = new PouchDB('skimdb');
var fatPouch = new PouchDB('fullfatdb');
// I tend to use more than the default 10 listeners
skimPouch.setMaxListeners(NUM_PARALLEL_TASKS * 100);
fatPouch.setMaxListeners(NUM_PARALLEL_TASKS * 100);

// replicate from central skimdb
var upToDate;
var startingTimeout = 1000;
var backoff = 1.1;
var sync;

function replicateSkim() {
  skimRemote.info().then(function (info) {
    sync = skimPouch.replicate.from(skimRemote, {
      live: true,
      batch_size: 1000
    }).on('change', function (change) {
      var percent = Math.min(100,
        (Math.floor(change.last_seq / info.update_seq * 10000) / 100).toFixed(2));
      console.log('Replicating skimdb, last_seq is: ' + change.last_seq + ' (' + percent + '%)');
    }).on('uptodate', function () {
      console.log('local skimdb is up to date');
      fs.writeFile('uptodate.txt', '1');
      upToDate = true;
    }).on('error', function (err) {
      console.error('error during replication with skimdb');
      console.error(err);
      restartReplication();
    });
  }).catch(function (err) {
    console.error('error doing info() on ' + SKIM_REMOTE);
    console.error(err);
    restartReplication();
  });
}
function restartReplication() {
  // just keep going
  startingTimeout *= backoff;
  setTimeout(replicateSkim, Math.round(startingTimeout));
}
replicateSkim();

var fullFat;

// start doing exciting shit
Promise.resolve().then(function () {
  return Promise.promisify(fs.readFile)('uptodate.txt', {
    encoding: 'utf8'
  }).catch(function (err) {
    return '0'; // default
  });
}).then(function (upToDateFile) {
  upToDate = upToDateFile === '1';
  if (upToDate) {
    console.log('local skimdb is up to date');
  }
}).then(function () {
  // trick Fullfat into never doing automatic syncing; we don't use it for that
  return Promise.promisify(fs.writeFile)('registry.seq', '999999999999');
}).then(function () {
  fullFat = new Fullfat({
    skim: SKIM_LOCAL,
    fat: FAT_LOCAL,
    seq_file: 'registry.seq',
    missing_log: 'missing.log'
  })
  .on('start', function () {
    // we want the changes feed to only be local,
    // but all other operations should be remote
    // if we're not done replicating yet
    process.nextTick(function () {
      fullFat.skim = upToDate ? SKIM_LOCAL : SKIM_REMOTE;
    });
  })
  .on('error', function (err) {
    console.error("fullfat hit an error");
    console.error(err);
  });
}).then(function () {
  // start user-facing proxy server

  // only execute n fullFat.js operations in parallel
  var queues = [];
  for (var i = 0; i < NUM_PARALLEL_TASKS; i++) {
    queues.push(Promise.resolve());
  }

  function processWithFullFat(docId) {
    console.log(docId + ': got request...');
    // recover by fetching with fullFat
    // wait for changes to let us know it was fetched
    var queueIdx = docId.charCodeAt(0) % queues.length;
    queues[queueIdx] = queues[queueIdx].then(function () {
      console.log(docId + ': looking up in pouch');
      return new Promise(function (resolve, reject) {
        var changes = fatPouch.changes({
          since: 'latest',
          live: true
        }).on('change', function onChange(change) {
          console.log(change.id + ': got change');
          if (change.id === docId) {
            console.log('successfully wrote to local fullfatdb: ' + docId);
            changes.cancel();
            resolve();
          }
        }).on('error', function (err) {
          console.error('change hit error');
          reject(err);
        });
        console.log(docId + ': fetching in the background');
        // this seq is only used by fullFat to determine the file name to write tgz's to
        fullFat.getDoc({id: docId, seq: Math.round(Math.random() * 1000000)});
      });
    });
    return queues[queueIdx];
  }

  function updateAfterIncomingChange() {
    // keep a log of what the last seq we checked was
    var queue = Promise.resolve();
    fs.readFile('skim-seq.txt', {encoding: 'utf8'}, function (err, data) {
      var seq = data ? parseInt(data) : 0;
      console.log('reading skimPouch changes since ' + seq);
      skimPouch.changes({since: seq, live: true}).on('change', function (change) {
        queue = queue.then(function () {
          var seqStr = change.seq.toString();
          return Promise.promisify(fs.writeFile)('skim-seq.txt', seqStr);
        }).then(function () {
          return fatPouch.allDocs({keys: [change.id]}).then(function (res) {
            if (res[0] && res[0].rev !== change.changes[0].rev) {
              console.log(change.id + ': new change came in, updating...');
              return processWithFullFat(change.id);
            }
          });
        }).catch(function (err) {
          console.error('unhandled skimPouch allDocs() err');
          console.error(err);
        });
      }).on('error', function (err) {
        console.error('unhandled skimPouch changes err');
        console.error(err);
      });
    });
  }
  if (upToDate) {
    updateAfterIncomingChange();
  } else {
    skimPouch.on('uptodate', function () {
      fullFat.skim = SKIM_LOCAL; // internal API, probably shouldn't do this
      skimPouch.info().then(function (info) {
        return Promise.promisify(fs.writeFile)('skim-seq.txt',
            info.update_seq.toString()).then(function () {
          updateAfterIncomingChange();
        });
      }).catch(function (err) {
        console.error('unhandled writeFile err');
        console.error(err);
      });
    });
  }

  var server = require('http').createServer(function (req, res) {
    var docId;
    Promise.resolve().then(function () {
      if (req.method.toLowerCase() === 'get') {
        // simple doc or attachment request (get)
        var url = require('url').parse(req.url);
        docId = decodeURIComponent(url.pathname.split('/')[1]);
        if (!docId) {
          return;
        }
        console.log(docId + ': simple doc request');
        // check if it exists first
        return fatPouch.get(docId).catch(function (err) {
          if (err.status === 404) {
            console.log('not found locally: ' + docId);
            process.nextTick(function () {
              processWithFullFat(docId); // exec in background
            });
          }
          throw err;
        });
      } else {
        throw new Error('bad_local_request');
      }
    }).then(function () {
      if (docId) {
        console.log(docId + ': doc exists locally');
      }
      request.get('http://127.0.0.1:' + pouchPort + '/fullfatdb' + req.url).pipe(res);
    }).catch(function (err) {
      if (err.name === 'bad_local_request') {
        console.error('got a bad request: ' + req.url);
        res.status(400).send({error: 'this proxy only accepts GETs'});
      } else {
        console.error(docId + ': no local doc, need to proxy to remote');
        // we got an error, so let's proxy to the remote fat
        // so we can return immediately
        request.get(FAT_REMOTE + req.url).pipe(res);
      }
    });
  });
  server.listen(5080, function (err) {
    if (err) {
      console.error(err);
    } else {
      console.log('Proxy server started at http://127.0.0.1:' + port);
    }
  });
}).catch(function (err) {
  console.error(err);
  throw err;
});

process.on('SIGINT', function () {
  // close gracefully
  sync.cancel();
  Promise.all([fatPouch, skimPouch].map(function (pouch) {
    return pouch.close();
  })).then(function () {
    process.exit(0);
  });
});
<|endoftext|>


<commit_before>/*!
 * parse-yuf <https://github.com/akileez/parse-yuf>
 *
 * Copyright (c) 2015 Keith Williams.
 * Licensed under the ISC license.
 */

var fs      = require('fs')
var path    = require('path')
var extract = require('yufrontin')

function parse (input, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  fs.readFile(input, 'utf8', function (err, res) {
    if (err) return cb(err, res)

    var fm = extract(res)

    cb(null, opts.extend ? extend(res, input) : res)
  })
}

function parseSync (input, opts) {
  opts = opts || {}
  var str = fs.readFileSync(input, 'utf8')
  var fm = extract(str)

  return opts.extend ? extend(fm, input) : fm
}

function extend (obj, fp) {
  return {
    abs     : fs.realpathSync(fp),
    rel     : fp,
    file    : path.parse(fp),
    stats   : fs.lstatSync(fp),
    data    : obj.data,
    content : obj.content
  }
}

module.exports = parse
module.exports.sync = parseSync
<commit_msg>source code -- minor edits<commit_after>/*!
 * parse-yuf <https://github.com/akileez/parse-yuf>
 *
 * Copyright (c) 2015 Keith Williams.
 * Licensed under the ISC license.
 */

var fs      = require('fs')
var path    = require('path')
var extract = require('yufrontin')

function parse (input, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  fs.readFile(input, 'utf8', function (err, res) {
    if (err) return cb(err)
    var fm = extract(res)

    cb(null, opts.extend ? extend(res, input) : res)
  })
}

function parseSync (input, opts) {
  opts = opts || {}
  var str = fs.readFileSync(input, 'utf8')
  var fm = extract(str)

  return opts.extend ? extend(fm, input) : fm
}

function extend (obj, fp) {
  return {
    abs     : fs.realpathSync(fp),
    rel     : fp,
    file    : path.parse(fp),
    stats   : fs.lstatSync(fp),
    data    : obj.data,
    content : obj.content
  }
}

module.exports = parse
module.exports.sync = parseSync
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var npm = require('npm');

//We will store all registry links at user level in .npmregistry file
var RPATH = process.env.HOME + '/.npmregistry';
var FILENAME = '.registryInfo';

/**
 * Module exports.
 * @public
 */

module.exports.usage = usage;
module.exports.setup = setup;
module.exports.list = list;
module.exports.add = add;
module.exports.remove = remove;
module.exports.change = change;

/**
 * [usage description]
 * @return {[type]} [description]
 */
function usage () {
	console.log('You can run Switch Registry as ');
	console.log('switch-registry {command} {arguments}');
	console.log('----------------------------------------------');
	console.log('Command       Description                     ');
	console.log('----------------------------------------------');
	console.log('usage       | Display this help');
	console.log('list        | Display list of added registries');
	console.log('add         | Add a new registry');
	console.log('remove      | Remove an existing registry');
	console.log('change      | Change an existing registry');
};

/**
 * [fetchFileData description]
 * @param  {[type]}  str [description]
 * @return {Boolean}     [description]
 */
function fetchFileData(str) {
	var data = '';
    try {
        data = JSON.parse(str);
    } catch (e) {
        return [];
	}
	console.log('finally coming here');
	console.log(data);
    return data;
}

function showFormatedData(data) {
	var displayStr = '';
	for (var key in data) {
		if (data.hasOwnProperty(key)) {
			if(displayStr !== '') {
				displayStr += ' | ';
			}

			if(key === 'active' && data[key] === true) {
				displayStr = '>  ' + displayStr;
			} else {
    			displayStr += data[key];
			}
  		}
	}

	return displayStr;
}

function addToFile(data) {

	fs.writeFile(RPATH+'/'+FILENAME, JSON.stringify(data), 'utf8', function(err) {
		if (err)
			console.log(err);
	});
}

function getCurrentRegistry () {
	//Fetch current registry
	//TODO: Think of a better way to manage this, we can use exec but
	//TODO: that is also not a very good idea
	var rc = require('rc')('npm');
	var url = ((rc.registry).slice(-1) === '/' )? rc.registry : rc.registry + '/';

	return url;
}

function initRegistryFile(data) {
	//Convert file data to Object -- At this point it will be blank
	//TODO: Have to check if data is there
	//TODO: If data is there then normal additon will happen only if it's not there
	console.log('then coming here');

	var url = getCurrentRegistry();

	var currData = fetchFileData(data);

	//Adding default entry
	currData.push({name: 'Default', active: true, url: url});
	//Convert back to JSON string
	addToFile(currData);
}

function setup() {
	//Create npmregistry
	if (!fs.existsSync(RPATH)) {
		//Create file
		fs.mkdirSync(RPATH);
	}
	//Save current registry to registry file if its npmjs default registry
	//TODO : Will check for npmjs thing later, right now considering current one as default

	fs.readFile(RPATH+'/'+FILENAME, 'utf8', function readFileCallback(err, data){
		if (err) {
			fs.open(RPATH+'/'+FILENAME, 'w+', function readFileCallback(err, data){
				console.log('this is another place');
				initRegistryFile('');
			});
			//TODO: Create file here and call add data function
		} else {
			console.log('coming here');
			initRegistryFile(data);
		}
	});
}

/**
 * Function will list down all added registry
 * @param {[type]} args [description]
 */
function list (args) {
	fs.readFile(RPATH+'/'+FILENAME, 'utf8', function readFileCallback(err, data){
		if (err){
			setup();
    		//TODO: Create file here and call add data function
		} else {
			//Convert file data to Object -- At this point it will be blank
			var currData = fetchFileData(data);

			for(var key in currData) {
				console.log(showFormatedData(currData[key]));
			}
		}
	});
};

/**
 * Function will add new custom registry
 * @param {[type]} args [description]
 */
function add (args) {
	console.log('add');
}

/**
 * Function will remove existing custom registry by name
 * @param  {[type]} args [description]
 */
function remove (args) {
	console.log('remove');
}

/**
 * Function will change any existing custom registry by name
 * @param  {[type]} args [description]
 */
function change (args) {
	console.log('change');
}
<commit_msg>Code restructuring<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var npm = require('npm');

//We will store all registry links at user level in .npmregistry file
var RPATH = process.env.HOME + '/.npmregistry';
var FILENAME = '.registryInfo';

/**
 * Module exports.
 * @public
 */

module.exports.usage = usage;
module.exports.setup = setup;
module.exports.list = list;
module.exports.add = add;
module.exports.remove = remove;
module.exports.change = change;

/**
 * [usage description]
 * @return {[type]} [description]
 */
function usage () {
	console.log('You can run Switch Registry as ');
	console.log('switch-registry {command} {arguments}');
	console.log('----------------------------------------------');
	console.log('Command       Description                     ');
	console.log('----------------------------------------------');
	console.log('usage       | Display this help');
	console.log('list        | Display list of added registries');
	console.log('add         | Add a new registry');
	console.log('remove      | Remove an existing registry');
	console.log('change      | Change an existing registry');
};

/**
 * [fetchFileData description]
 * @param  {[type]}  str [description]
 * @return {Boolean}     [description]
 */
function fetchFileData(str) {
	var data = '';
    try {
        data = JSON.parse(str);
    } catch (e) {
        return [];
	}
	console.log('finally coming here');
	console.log(data);
    return data;
}

function showFormatedData(data) {
	var displayStr = '';
	for (var key in data) {
		if (data.hasOwnProperty(key)) {
			if(displayStr !== '') {
				displayStr += ' | ';
			}

			if(key === 'active' && data[key] === true) {
				displayStr = '>  ' + displayStr;
			} else {
    			displayStr += data[key];
			}
  		}
	}

	return displayStr;
}

function addToFile(data) {

	fs.writeFile(RPATH+'/'+FILENAME, JSON.stringify(data), 'utf8', function(err) {
		if (err)
			console.log(err);
	});
}

function getCurrentRegistry () {
	//Fetch current registry
	//TODO: Think of a better way to manage this, we can use exec but
	//TODO: that is also not a very good idea
	var rc = require('rc')('npm');
	var url = ((rc.registry).slice(-1) === '/' )? rc.registry : rc.registry + '/';

	return url;
}

function initRegistryFile(data) {
	//Convert file data to Object -- At this point it will be blank
	//TODO: Have to check if data is there
	//TODO: If data is there then normal additon will happen only if it's not there
	console.log('then coming here');

	var url = getCurrentRegistry();

	var currData = fetchFileData(data);

	//Adding default entry
	currData.push({name: 'Default', active: true, url: url});
	//Convert back to JSON string
	addToFile(currData);
}

function setup() {
	//Create npmregistry
	if (!fs.existsSync(RPATH)) {
		//Create file
		fs.mkdirSync(RPATH);
	}
	//Save current registry to registry file if its npmjs default registry
	//TODO : Will check for npmjs thing later, right now considering current one as default

	fs.readFile(RPATH+'/'+FILENAME, 'utf8', function readFileCallback(err, data){
		if (err) {
			fs.open(RPATH+'/'+FILENAME, 'w+', function readFileCallback(err, data){
				console.log('this is another place');
				initRegistryFile('');
			});
			//TODO: Create file here and call add data function
		} else {
			console.log('coming here');
			initRegistryFile(data);
		}
	});
}

/**
 * Function will list down all added registry
 * @param {[type]} args [description]
 */
function list (args) {
	fs.readFile(RPATH+'/'+FILENAME, 'utf8', function readFileCallback(err, data){
		if (err){
			setup();
    		//TODO: Create file here and call add data function
		} else {
			//Convert file data to Object -- At this point it will be blank
			var currData = fetchFileData(data);

			for(var key in currData) {
				console.log(showFormatedData(currData[key]));
			}
		}
	});
};

/**
 * Function will add new custom registry
 * @param {[type]} args [description]
 */
function add (args) {
	fs.readFile(RPATH+'/'+FILENAME, 'utf8', function readFileCallback(err, data){
		if (err){
			setup();
    		//TODO: Create file here and call add data function
		} else {
			//Convert file data to Object -- At this point it will be blank
			var currData = fetchFileData(data);

			for(var key in currData) {
				console.log(showFormatedData(currData[key]));
			}
		}
	});
}

function executeAdd() {

}

/**
 * Function will remove existing custom registry by name
 * @param  {[type]} args [description]
 */
function remove (args) {
	console.log('remove');
}

/**
 * Function will change any existing custom registry by name
 * @param  {[type]} args [description]
 */
function change (args) {
	console.log('change');
}
<|endoftext|>


<commit_before>module.exports = chromahash

function djb2(str){
    var hash = 5381;
    for (i = 0; i < str.length; i++) {
        char = str.charCodeAt(i);
        hash = ((hash << 5) + hash) + char; /* hash * 33 + c */
    }
    return hash;
}

function to256ish(i) {
  //return (Math.abs(i) % 47) * 5 // almost 256
  return (Math.abs(i) % 251)
}

function toHex(d) {
  return  ("0"+(Number(d).toString(16))).slice(-2)
}

function chromahash(str) {
  const rStr = 'red'
  const gStr = 'green'
  const bStr = 'blue'

  const rHex = toHex(to256ish(djb2(rStr + str)))
  const gHex = toHex(to256ish(djb2(gStr + str)))
  const bHex = toHex(to256ish(djb2(bStr + str)))

  return `${rHex}${gHex}${bHex}`
}
<commit_msg>cleanup some comments<commit_after>module.exports = chromahash

function djb2(str){
    var hash = 5381;
    for (i = 0; i < str.length; i++) {
        char = str.charCodeAt(i);
        hash = ((hash << 5) + hash) + char; /* hash * 33 + c */
    }
    return hash;
}

// simple modulo hash to convert an int to a number from 0 - 255 (or so)
function to256ish(i) {
  // djb2 uses 33 as it's prime... should we then use k = 25 (coprime to 33),
  // m = 10 to get a 256ish number? k = 251 seems to work
  const k = 251
  const m = 1

  return (Math.abs(i) % k) * m
}

// convert a digit (base 10) to hex (base 16) left padded with 0
function toHex(d) {
  return  ("0"+(Number(d).toString(16))).slice(-2)
}

function chromahash(str) {
  // we need to prefix the string to ensure different values for r/g/b but also
  // if we only suffix we seem to get clustering around purple and yellow
  const rStr = 'red'   + str
  const gStr = 'green' + str
  const bStr = 'blue'  + str

  const rHex = toHex(to256ish(djb2(rStr)))
  const gHex = toHex(to256ish(djb2(gStr)))
  const bHex = toHex(to256ish(djb2(bStr)))

  return `${rHex}${gHex}${bHex}`
}
<|endoftext|>


<commit_before><commit_msg>Make Yoobro alive<commit_after>var yoobroFacebook = require("./yoobroFacebook");
var http = require('http');
var fs = require('fs');
var telegramBot = require('node-telegram-bot-api');
var request = require('request');
global._ = require("lodash");
var token = "{telegram-bot-token}";
var bot = new telegramBot(token, {
  polling: true
});
var telegram = require('telegram-bot-api');
var api = new telegram({
        token: token
});
var count = 0;
var processing = false;
var help = "Whazzup!!\n/yoobro - To get one yoobro's story";
var notready = "Wait! I am not ready yet.";
var high = "I am high la! Request later. :3"
var download = function(uri, filename, callback){
  request.head(uri, function(err, res, body){
    request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
  });
};
bot.on('text', function(msg) {
  console.log(msg.text);
  var chatId = msg.chat.id;
  yoobro = /\/yoobro/.test(msg.text);
  if (yoobro) {
    var photo = yoobroFacebook.getRandom();
    if(photo!=false){
      processing = true;
      var path = count+'.png';
      count++;
      download(photo, path, function(){
        api.sendPhoto({
        chat_id: chatId,
        caption: 'Whazzup',
        photo:'./'+path
        }, function(err, data)
        {
          if(err!=null){
            console.log(err);
            bot.sendMessage(chatId, high);
          }
          else
            fs.unlink('./'+path);

        });
        processing = false;
        console.log('Sent');
      });
    }else{
      bot.sendMessage(chatId, notready);
    }
  } else if (msg.text == '/help') {
    bot.sendMessage(chatId, help);
  }  else {
    // do nothing
  }
});
/* To work fine on Heroku Server
var port = process.env.PORT || 443;
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end();
}).listen(port); */
<|endoftext|>