<commit_before>'use strict'

const pkg = require('./package.json')
const os = require('os')
const https = require('https')
const uuid = require('uuid')

const system = (process.platform === 'linux') ? require('./src/system.js') : require('./src/mockSystem.js')
const setConfig = require('./src/config.js')
const Context = require('./src/context.js')
const Callback = require('./src/callback.js')
const log = console.log

const VERSION = pkg.version
const MODULE_LOAD_TIME = Date.now()
const PROCESS_ID = uuid.v4()
const httpsAgent = new https.Agent({
  maxCachedSessions: 1,
  keepAlive: true
});

httpsAgent.originalCreateConnection = httpsAgent.createConnection
httpsAgent.createConnection = function(port, host, options) {
  /* noDelay is documented as defaulting to true, but docs lie.
     this sacrifices throughput for latency and should be faster
     for how we submit data. */
  var socket = httpsAgent.originalCreateConnection(port, host, options);
  socket.setNoDelay(true);
  return socket
}

// Default on module load; changed to false on first handler invocation.
var COLDSTART = true

function _make_generateLog(metrics, func, start_time, config, context) {
  var pre_stat_promise = system.readstat('self')

  return function generateLog(err, callback) {
    Promise.all([
        pre_stat_promise,
        system.readstat('self'),
        system.readstatus('self'),
        system.readbootid()
      ]).then((
        pre_proc_self_stat,
        proc_self_stat,
        proc_self_status,
        boot_id
      ) => {
        var runtime_env = {
          agent: {
            runtime: 'nodejs',
            version: VERSION,
            load_time: MODULE_LOAD_TIME
          },
          host: {
            container_id: boot_id
          },
          os: {
            hostname: os.hostname(),
            uptime: os.uptime(),
            totalmem: os.totalmem(),
            freemem: os.freemem(),
            usedmem: os.totalmem() - os.freemem(),
            cpus: os.cpus(),
            arch: os.arch(),
            linux: {
              pid: {
                self: {
                  stat_start: pre_proc_self_stat,
                  stat: proc_self_stat,
                  status: proc_self_status
                }
              }
            }
          },
          nodejs: {
            title: process.title,
            version: process.version,
            modulesloadList: process.modulesloadList,
            versions: process.versions,
            arch: process.arch,
            platform: process.platform,
            argv: process.argv,
            execArgv: process.execArgv,
            pid: process.pid,
            features: process.features,
            execPath: process.execPath,
            debugPort: process.debugPort,
            _maxListeners: process._maxListeners,
            config: process.config,
            maxTickDepth: process.maxTickDepth,
            // /* Circular ref */ mainModule: process.mainModule,
            release: process.release,
            uptime: process.uptime(),
            getuid: process.getuid(),
            getgid: process.getgid(),
            geteuid: process.geteuid(),
            getegid: process.getegid(),
            memoryUsage: process.memoryUsage(),
          }
        }

        var retainErr = {}
        if (err) {
          retainErr = ((err) => {
            return {
              name: err.name,
              message: err.message,
              stack: err.stack,
              lineNumber: err.lineNumber,
              columnNumber: err.columnNumber,
              fileName: err.fileName
            }
          })((typeof(err) === 'string') ? new Error(err) : err)
        }

        var time_sec_nanosec = process.hrtime(start_time)

        /*
         depreciated fields:
         - time_sec_nanosec (use duration; 11/23/2016)
         - time_sec (use duration; 11/23/2016)
        */
        var response_body = {
          environment: runtime_env,
          aws: {
            functionName: context.functionName,
            functionVersion: context.functionVersion,
            invokedFunctionArn: context.invokedFunctionArn,
            memoryLimitInMB: context.memoryLimitInMB,
            awsRequestId: context.awsRequestId,
            logGroupName: context.logGroupName,
            logStreamName: context.logStreamName
          },
          coldstart: COLDSTART,
          errors: retainErr,
          custom_metrics: metrics,
          time_sec_nanosec: time_sec_nanosec,
          time_sec: time_sec_nanosec[0],
          time_nanosec: time_sec_nanosec[1],
          duration: Math.ceil(time_sec_nanosec[0] * 1000000000.0 + time_sec_nanosec[1]),
          processId: PROCESS_ID,
          client_id: config.clientId,
          installMethod: config.installMethod
        }

        if (COLDSTART === true) {
          COLDSTART = false
        }

        if (context.getRemainingTimeInMillis) {
          response_body.aws.getRemainingTimeInMillis = context.getRemainingTimeInMillis()
        }

        if (config.debug) {
          log('IOPIPE-DEBUG: ', JSON.stringify(response_body))
        }

        var req = https.request({
          hostname: config.url,
          path: config.path,
          port: 443,
          method: 'POST',
          headers: {'content-type' : 'application/json'},
          agent: httpsAgent,
          timeout: config.networkTimeout
        }, (res) => {
          var apiResponse = ''

          res.on('data', function (chunk) {
            apiResponse += chunk
          })

          res.on('end', function () {
            if (config.debug) {
              log(`API STATUS: ${res.statusCode}`)
              log(`API RESPONSE: ${apiResponse}`)
            }
            callback()
          })
        }).on('error', (err) => {
          // Log errors, don't block on failed requests
          if (config.debug) {
            log('Write to IOpipe failed')
            log(err)
          }
          callback()
        })

        req.write(JSON.stringify(response_body))
        req.end()
      }
    ).catch((err) => {
      if (err && config.debug) {
        log('Error collecting IOpipe data:')
        log(err)
      }
      callback()
    })
  }
}

module.exports = function(options) {
  var fn = function(func) {
    fn.metricsQueue = []
    const config = setConfig(options)

    if (!config.clientId) {
      // No-op if user doesn't set an IOpipe token.
      return func
    }

    return function() {
      fn.metricsQueue = []
      let args = [].slice.call(arguments)

      var start_time = process.hrtime()
      var generateLog = _make_generateLog(fn.metricsQueue, func, start_time, config, args[1])

      var end_time = 599900  /* Maximum execution: 100ms short of 5 minutes */
      if (config.timeoutWindow > 0 && args[1] && args[1].getRemainingTimeInMillis) {
        end_time = Math.max(0, args[1].getRemainingTimeInMillis() - config.timeoutWindow)
      }

      var timeout = setTimeout(() => {
        generateLog(new Error("Timeout Exceeded."), function noop() {})
      }, end_time)

      var callback = (err, cb) => {
        clearTimeout(timeout)
        generateLog(err, cb)
      }

      /* Mangle arguments, wrapping callbacks. */
      args[1] = Context(callback, args[1])
      args[2] = Callback(callback, args[2])

      try {
        return func.apply(this, args)
      }
      catch (err) {
        clearTimeout(timeout)
        generateLog(err, function noop() {})
        return undefined
      }
    }
  }

  // Alias decorate to the wrapper function
  fn.decorate = fn

  fn.log = function(name, value) {
    var numberValue, stringValue
    if (typeof value === 'number') {
      numberValue = value
    } else {
      if(typeof value === 'object') {
        JSON.stringify(value)
      } else {
        stringValue = String(value)
      }
    }
    fn.metricsQueue.push({
      name: name,
      n: numberValue,
      s: stringValue
    })
  }

  return fn
}
<commit_msg>Fix value assignment<commit_after>'use strict'

const pkg = require('./package.json')
const os = require('os')
const https = require('https')
const uuid = require('uuid')

const system = (process.platform === 'linux') ? require('./src/system.js') : require('./src/mockSystem.js')
const setConfig = require('./src/config.js')
const Context = require('./src/context.js')
const Callback = require('./src/callback.js')
const log = console.log

const VERSION = pkg.version
const MODULE_LOAD_TIME = Date.now()
const PROCESS_ID = uuid.v4()
const httpsAgent = new https.Agent({
  maxCachedSessions: 1,
  keepAlive: true
});

httpsAgent.originalCreateConnection = httpsAgent.createConnection
httpsAgent.createConnection = function(port, host, options) {
  /* noDelay is documented as defaulting to true, but docs lie.
     this sacrifices throughput for latency and should be faster
     for how we submit data. */
  var socket = httpsAgent.originalCreateConnection(port, host, options);
  socket.setNoDelay(true);
  return socket
}

// Default on module load; changed to false on first handler invocation.
var COLDSTART = true

function _make_generateLog(metrics, func, start_time, config, context) {
  var pre_stat_promise = system.readstat('self')

  return function generateLog(err, callback) {
    Promise.all([
        pre_stat_promise,
        system.readstat('self'),
        system.readstatus('self'),
        system.readbootid()
      ]).then((results) => {
        const [pre_proc_self_stat,
          proc_self_stat,
          proc_self_status,
          boot_id] = results
        var runtime_env = {
          agent: {
            runtime: 'nodejs',
            version: VERSION,
            load_time: MODULE_LOAD_TIME
          },
          host: {
            container_id: boot_id
          },
          os: {
            hostname: os.hostname(),
            uptime: os.uptime(),
            totalmem: os.totalmem(),
            freemem: os.freemem(),
            usedmem: os.totalmem() - os.freemem(),
            cpus: os.cpus(),
            arch: os.arch(),
            linux: {
              pid: {
                self: {
                  stat_start: pre_proc_self_stat,
                  stat: proc_self_stat,
                  status: proc_self_status
                }
              }
            }
          },
          nodejs: {
            title: process.title,
            version: process.version,
            modulesloadList: process.modulesloadList,
            versions: process.versions,
            arch: process.arch,
            platform: process.platform,
            argv: process.argv,
            execArgv: process.execArgv,
            pid: process.pid,
            features: process.features,
            execPath: process.execPath,
            debugPort: process.debugPort,
            _maxListeners: process._maxListeners,
            config: process.config,
            maxTickDepth: process.maxTickDepth,
            // /* Circular ref */ mainModule: process.mainModule,
            release: process.release,
            uptime: process.uptime(),
            getuid: process.getuid(),
            getgid: process.getgid(),
            geteuid: process.geteuid(),
            getegid: process.getegid(),
            memoryUsage: process.memoryUsage(),
          }
        }

        var retainErr = {}
        if (err) {
          retainErr = ((err) => {
            return {
              name: err.name,
              message: err.message,
              stack: err.stack,
              lineNumber: err.lineNumber,
              columnNumber: err.columnNumber,
              fileName: err.fileName
            }
          })((typeof(err) === 'string') ? new Error(err) : err)
        }

        var time_sec_nanosec = process.hrtime(start_time)

        /*
         depreciated fields:
         - time_sec_nanosec (use duration; 11/23/2016)
         - time_sec (use duration; 11/23/2016)
        */
        var response_body = {
          environment: runtime_env,
          aws: {
            functionName: context.functionName,
            functionVersion: context.functionVersion,
            invokedFunctionArn: context.invokedFunctionArn,
            memoryLimitInMB: context.memoryLimitInMB,
            awsRequestId: context.awsRequestId,
            logGroupName: context.logGroupName,
            logStreamName: context.logStreamName
          },
          coldstart: COLDSTART,
          errors: retainErr,
          custom_metrics: metrics,
          time_sec_nanosec: time_sec_nanosec,
          time_sec: time_sec_nanosec[0],
          time_nanosec: time_sec_nanosec[1],
          duration: Math.ceil(time_sec_nanosec[0] * 1000000000.0 + time_sec_nanosec[1]),
          processId: PROCESS_ID,
          client_id: config.clientId,
          installMethod: config.installMethod
        }

        if (COLDSTART === true) {
          COLDSTART = false
        }

        if (context.getRemainingTimeInMillis) {
          response_body.aws.getRemainingTimeInMillis = context.getRemainingTimeInMillis()
        }

        if (config.debug) {
          log('IOPIPE-DEBUG: ', JSON.stringify(response_body))
        }

        var req = https.request({
          hostname: config.url,
          path: config.path,
          port: 443,
          method: 'POST',
          headers: {'content-type' : 'application/json'},
          agent: httpsAgent,
          timeout: config.networkTimeout
        }, (res) => {
          var apiResponse = ''

          res.on('data', function (chunk) {
            apiResponse += chunk
          })

          res.on('end', function () {
            if (config.debug) {
              log(`API STATUS: ${res.statusCode}`)
              log(`API RESPONSE: ${apiResponse}`)
            }
            callback()
          })
        }).on('error', (err) => {
          // Log errors, don't block on failed requests
          if (config.debug) {
            log('Write to IOpipe failed')
            log(err)
          }
          callback()
        })

        req.write(JSON.stringify(response_body))
        req.end()
      }
    ).catch((err) => {
      if (err && config.debug) {
        log('Error collecting IOpipe data:')
        log(err)
      }
      callback()
    })
  }
}

module.exports = function(options) {
  var fn = function(func) {
    fn.metricsQueue = []
    const config = setConfig(options)

    if (!config.clientId) {
      // No-op if user doesn't set an IOpipe token.
      return func
    }

    return function() {
      fn.metricsQueue = []
      let args = [].slice.call(arguments)

      var start_time = process.hrtime()
      var generateLog = _make_generateLog(fn.metricsQueue, func, start_time, config, args[1])

      var end_time = 599900  /* Maximum execution: 100ms short of 5 minutes */
      if (config.timeoutWindow > 0 && args[1] && args[1].getRemainingTimeInMillis) {
        end_time = Math.max(0, args[1].getRemainingTimeInMillis() - config.timeoutWindow)
      }

      var timeout = setTimeout(() => {
        generateLog(new Error("Timeout Exceeded."), function noop() {})
      }, end_time)

      var callback = (err, cb) => {
        clearTimeout(timeout)
        generateLog(err, cb)
      }

      /* Mangle arguments, wrapping callbacks. */
      args[1] = Context(callback, args[1])
      args[2] = Callback(callback, args[2])

      try {
        return func.apply(this, args)
      }
      catch (err) {
        clearTimeout(timeout)
        generateLog(err, function noop() {})
        return undefined
      }
    }
  }

  // Alias decorate to the wrapper function
  fn.decorate = fn

  fn.log = function(name, value) {
    var numberValue, stringValue
    if (typeof value === 'number') {
      numberValue = value
    } else {
      if(typeof value === 'object') {
        JSON.stringify(value)
      } else {
        stringValue = String(value)
      }
    }
    fn.metricsQueue.push({
      name: name,
      n: numberValue,
      s: stringValue
    })
  }

  return fn
}
<|endoftext|>


<commit_before>var express = require('express'),
    multipart = require('connect-multiparty'),
    path = require('path');

var app = express();

app.use(express.static('public'));
app.use(multipart({
    uploadDir: path.join(__dirname, 'uploads')
}));

app.post('/project-files', function(req, res) {
    'use strict';
    console.log(req.files.appDataZip);
    res.send('ok').end();
});

var port = 3300;

var server = app.listen(port, function() {
    'use strict';
    console.log('App listening at port', server.address().port);
});
<commit_msg>Configured S3 uploading<commit_after>var express = require('express'),
    multipart = require('connect-multiparty'),
    s3 = require('s3'),
    fs = require('fs'),
    path = require('path');

var env;

try {
    env = fs.readFileSync('./.env', 'utf8');
    env = JSON.parse(env);
} catch(e) {
    console.log(e.message);
}

var s3Client = s3.createClient({
    multipartUploadThreshold: 20971520,
    multipartUploadSize: 15728640,
    s3Options: {
        accessKeyId: env.awsAccessKeyId,
        secretAccessKey: env.awsSecretAccessKey
    }
});

var app = express();

app.use(express.static('public'));
app.use(multipart({
    uploadDir: path.join(__dirname, 'uploads')
}));

app.post('/project-files', function(req, res) {
    'use strict';
    if(req.files.appDataZip) {
        var filePath = req.files.appDataZip.path;
        console.log(filePath);

        var awsUploader = s3Client.uploadFile({
            localFile: filePath,
            s3Params: {
                Bucket: env.awsBucket,
                Key: path.basename(filePath),
                ACL: 'public-read'
            }
        });

        awsUploader.on('error', function(err) {
            console.error('unable to upload:', err.stack);
        });

        awsUploader.on('progress', function() {
            // console.log('progress', awsUploader.progressMd5Amount,
            // awsUploader.progressAmount, awsUploader.progressTotal);
            console.log(((awsUploader.progressAmount / awsUploader.progressTotal) * 100).toFixed(4) + '%');
        });

        awsUploader.on('end', function() {
            fs.unlink(filePath, function(err) {
                if(err) {
                    console.error(err.message);
                }
            });
            console.log('done uploading');
        });

    }
    res.send('ok').end();
});

var port = 3300;

var server = app.listen(port, function() {
    'use strict';
    console.log('App listening at port', server.address().port);
});
<|endoftext|>


<commit_before>'use strict'

var assert = require('assert')
var ms = require('ms')
var Promise = require('promise')
var github = require('github').json

function delay(time, value) {
  return new Promise(function (resolve) {
    setTimeout(function () {
      resolve(value)
    }, ms(time.toString()))
  })
}
function poll(condition, options) {
  options = options || {}
  return condition().then(function (done) {
    if (done) {
      return done
    } else if (options.timeout && options.start && Date.now() - options.start > ms(options.timeout.toString())) {
      var err = new Error('operation timed out')
      err.code = 'TIMEOUT'
      throw err
    } else {
      return delay(typeof options.delay === 'function' ? options.delay(options.attempt || 1) : options.delay || 0).then(function () {
        return poll(condition, {
          attempt: (options.attempt || 1) + 1
          delay: options.delay,
          timeout: options.timeout,
          start: options.start || Date.now()
        })
      })
    }
  })
}

exports.exists = exists
function exists(user, repo, options, callback) {
  options = JSON.stringify(JSON.parse(options || {}))
  options.host = 'github.com'
  return github('head', '/:user/:repo', {user: user, repo: repo}, options)
    .then(function () {
      return true
    }, function () {
      return false
    }).nodeify(callback)
}

exports.fork = fork
function fork(from, to, repo, options, callback) {
  options = options || {}
  return github('post', '/repos/:owner/:repo/forks', {owner: from, repo: repo, organization: to}, options)
    .then(function (res) {
      return poll(function () {
        return exists(to, repo, options)
      }, {timeout: options.timeout || '5 minutes', delay: function (attempt) { return (attempt * 5) + 'seconds' })
      .then(function () { return res })
    }).nodeify(callback)
}

exports.branch = branch
function branch(user, repo, from, to, options, callback) {
  github('get', '/repos/:owner/:repo/git/refs/:ref', {owner: user, repo: repo, ref: 'heads/' + from})
    .then(function (res) {
      return github('post', '/repos/:owner/:repo/git/refs', {owner: user, repo: repo, ref: 'refs/heads/' + to, sha: res.object.sha})
    })
}

exports.commit = commit //does 5 API requests
function commit(user, repo, commit, options, callback) {
  var branch = commit.branch || 'master'
  var message = commit.message
  var updates = commit.updates
  var shaLatestCommit, shaBaseTree, shaNewTree, shaNewCommit

  Promise.from(null).then(function () {

    //check for correct input
    assert(user && typeof user === 'string', '`user` must be a string')
    assert(repo && typeof repo === 'string', '`repo` must be a string')
    assert(branch && typeof branch === 'string', '`branch` must be a string')
    assert(message && typeof message === 'strin'g, '`message` must be a string')
    updates.forEach(function (file) { // {path: path, content: content}
      file.path = file.path.replace(/\\/g, '/').replace(/^\//, '')
      file.mode = file.mode || '100644'
      file.type = file.type || 'blob'
      file.content = file.content
    })

    return github('get', '/repos/:owner/:repo/git/refs/:ref', {owner: user, repo: repo, ref: 'heads/' + branch}, options)
  }).then(function (res) {
    shaLatestCommit = res.object.sha
    return github('get', '/repos/:owner/:repo/git/commits/:sha', {owner: user, repo: repo, sha: shaLatestCommit}, options)
  }).then(function (res) {
    shaBaseTree = res.tree.sha
    return github('post', '/repos/:owner/:repo/git/trees', {owner: user, repo: repo, tree: updates, base_tree: shaBaseTree}, options)
  }).then(function (res) {
    shaNewTree = res.sha
    return github('post', '/repos/:owner/:repo/git/commits', {owner: user, repo: repo, message: message, tree: shaNewTree, parents: [shaLatestCommit]}, options)
  }).then(function (res) {
    shaNewCommit = res.sha
    return github('patch', '/repos/:owner/:repo/git/refs/:ref', {owner: user, repo: repo, ref: 'heads/' + branch, sha: shaNewCommit, force: options.force || false})
  }).nodeify(callback)
}

exports.pull = pull
function pull(from, to, msg, options, callback) {
  var query = {
    owner: to.owner,
    repo: to.repo || from.repo,
    base: to.branch || 'master',
    head: from.user + ':' + (from.branch || 'master')
  }
  if (typeof msg.issue === 'number') {
    query.issue = msg.issue.toString()
  } else {
    query.title = msg.title
    query.body = msg.body || ''
  }
  return github('post', '/repos/:owner/:repo/pulls', query, options)
}<commit_msg>Fix syntax errors (ooops)<commit_after>'use strict'

var assert = require('assert')
var ms = require('ms')
var Promise = require('promise')
var github = require('github-basic').json

function delay(time, value) {
  return new Promise(function (resolve) {
    setTimeout(function () {
      resolve(value)
    }, ms(time.toString()))
  })
}
function poll(condition, options) {
  options = options || {}
  return condition().then(function (done) {
    if (done) {
      return done
    } else if (options.timeout && options.start && Date.now() - options.start > ms(options.timeout.toString())) {
      var err = new Error('operation timed out')
      err.code = 'TIMEOUT'
      throw err
    } else {
      return delay(typeof options.delay === 'function' ? options.delay(options.attempt || 1) : options.delay || 0).then(function () {
        return poll(condition, {
          attempt: (options.attempt || 1) + 1,
          delay: options.delay,
          timeout: options.timeout,
          start: options.start || Date.now()
        })
      })
    }
  })
}

exports.exists = exists
function exists(user, repo, options, callback) {
  options = JSON.stringify(JSON.parse(options || {}))
  options.host = 'github.com'
  return github('head', '/:user/:repo', {user: user, repo: repo}, options)
    .then(function () {
      return true
    }, function () {
      return false
    }).nodeify(callback)
}

exports.fork = fork
function fork(from, to, repo, options, callback) {
  options = options || {}
  return github('post', '/repos/:owner/:repo/forks', {owner: from, repo: repo, organization: to}, options)
    .then(function (res) {
      return poll(function () {
        return exists(to, repo, options)
      }, {timeout: options.timeout || '5 minutes', delay: function (attempt) { return (attempt * 5) + 'seconds' }})
      .then(function () { return res })
    }).nodeify(callback)
}

exports.branch = branch
function branch(user, repo, from, to, options, callback) {
  github('get', '/repos/:owner/:repo/git/refs/:ref', {owner: user, repo: repo, ref: 'heads/' + from})
    .then(function (res) {
      return github('post', '/repos/:owner/:repo/git/refs', {owner: user, repo: repo, ref: 'refs/heads/' + to, sha: res.object.sha})
    })
}

exports.commit = commit //does 5 API requests
function commit(user, repo, commit, options, callback) {
  var branch = commit.branch || 'master'
  var message = commit.message
  var updates = commit.updates
  var shaLatestCommit, shaBaseTree, shaNewTree, shaNewCommit

  Promise.from(null).then(function () {

    //check for correct input
    assert(user && typeof user === 'string', '`user` must be a string')
    assert(repo && typeof repo === 'string', '`repo` must be a string')
    assert(branch && typeof branch === 'string', '`branch` must be a string')
    assert(message && typeof message === 'string', '`message` must be a string')
    updates.forEach(function (file) { // {path: path, content: content}
      file.path = file.path.replace(/\\/g, '/').replace(/^\//, '')
      file.mode = file.mode || '100644'
      file.type = file.type || 'blob'
      file.content = file.content
    })

    return github('get', '/repos/:owner/:repo/git/refs/:ref', {owner: user, repo: repo, ref: 'heads/' + branch}, options)
  }).then(function (res) {
    shaLatestCommit = res.object.sha
    return github('get', '/repos/:owner/:repo/git/commits/:sha', {owner: user, repo: repo, sha: shaLatestCommit}, options)
  }).then(function (res) {
    shaBaseTree = res.tree.sha
    return github('post', '/repos/:owner/:repo/git/trees', {owner: user, repo: repo, tree: updates, base_tree: shaBaseTree}, options)
  }).then(function (res) {
    shaNewTree = res.sha
    return github('post', '/repos/:owner/:repo/git/commits', {owner: user, repo: repo, message: message, tree: shaNewTree, parents: [shaLatestCommit]}, options)
  }).then(function (res) {
    shaNewCommit = res.sha
    return github('patch', '/repos/:owner/:repo/git/refs/:ref', {owner: user, repo: repo, ref: 'heads/' + branch, sha: shaNewCommit, force: options.force || false})
  }).nodeify(callback)
}

exports.pull = pull
function pull(from, to, msg, options, callback) {
  var query = {
    owner: to.owner,
    repo: to.repo || from.repo,
    base: to.branch || 'master',
    head: from.user + ':' + (from.branch || 'master')
  }
  if (typeof msg.issue === 'number') {
    query.issue = msg.issue.toString()
  } else {
    query.title = msg.title
    query.body = msg.body || ''
  }
  return github('post', '/repos/:owner/:repo/pulls', query, options)
}<|endoftext|>


<commit_before>const fs = require('fs');
const _ = require('lodash');
const providers = require('./lib/providers');

class TorrentSearchApi {
  enableProvider(providerName, ...args) {
    return this._getProvider(providerName).enableProvider(...args);
  }

  enablePublicProviders() {
    let publicProviders = this.getProviders()
      .filter(p => p.public)
      .map(p => p.name);
    publicProviders.map(p => this.enableProvider(p));
  }

  disableProvider(providerName) {
    this._getProvider(providerName).disableProvider();
  }

  getProviders() {
    return providers.map(p => p.getInfos());
  }

  getActiveProviders() {
    return this._getActiveProviders().map(p => p.getInfos());
  }

  isProviderActive(name) {
    let provider = this._getProvider(name, false);
    if (provider && provider.isActive) {
      return true;
    }
    return false;
  }

  search(param, ...args) {
    if (typeof param === 'string') {
      return this._search(this._getActiveProviders(), param, ...args);
    } else if (param instanceof Array) {
      return this._search(
        this._getActiveProvidersByName(arguments[0]),
        ...args
      );
    }
    return Promise.reject(
      'First param must be a query or an array of providers.'
    );
  }

  getTorrentDetails(torrent) {
    return this._getProvider(torrent.provider).getTorrentDetails(torrent);
  }

  downloadTorrent(torrent, filenamePath) {
    return this._getProvider(torrent.provider).downloadTorrent(
      torrent,
      filenamePath
    );
  }

  getMagnet(torrent) {
    return this._getProvider(torrent.provider).getMagnet(torrent);
  }

  _search(selectedProviders, query, category, limit) {
    query = query === '' ? undefined : query;
    category = category === '' ? undefined : category;
    limit = limit === '' ? undefined : limit;

    return Promise.all(
      selectedProviders.map(p => p.search(query, category, limit))
    )
      .then(results => _.flatten(results))
      .then(results => _.orderBy(results, ['seeds'], ['desc']))
      .then(results => (limit ? results.slice(0, limit) : results));
  }

  _getActiveProviders() {
    return _.filter(providers, 'isActive');
  }

  _getProvider(name, throwOnError = true) {
    let provider = _.find(
      providers,
      p => p.getName().toUpperCase() === name.toUpperCase()
    );
    if (provider) {
      return provider;
    }

    if (throwOnError) {
      throw new Error(`Couldn't find '${name}' provider`);
    }

    return null;
  }

  _getActiveProvidersByName(providerNames) {
    return this._getActiveProviders().filter(p =>
      providerNames
        .map(m => m.toUpperCase())
        .includes(p.getName().toUpperCase())
    );
  }
}

module.exports = TorrentSearchApi;
<commit_msg>Added disableAllProviders()<commit_after>const fs = require('fs');
const _ = require('lodash');
const providers = require('./lib/providers');

class TorrentSearchApi {
  enableProvider(providerName, ...args) {
    return this._getProvider(providerName).enableProvider(...args);
  }

  enablePublicProviders() {
    let publicProviders = this.getProviders()
      .filter(p => p.public)
      .map(p => p.name);
    publicProviders.map(p => this.enableProvider(p));
  }

  disableProvider(providerName) {
    this._getProvider(providerName).disableProvider();
  }

  disableAllProviders() {
    this.getProviders()
      .map(p => this.disableProvider(p.name))
  }

  getProviders() {
    return providers.map(p => p.getInfos());
  }

  getActiveProviders() {
    return this._getActiveProviders().map(p => p.getInfos());
  }

  isProviderActive(name) {
    let provider = this._getProvider(name, false);
    if (provider && provider.isActive) {
      return true;
    }
    return false;
  }

  search(param, ...args) {
    if (typeof param === 'string') {
      return this._search(this._getActiveProviders(), param, ...args);
    } else if (param instanceof Array) {
      return this._search(
        this._getActiveProvidersByName(arguments[0]),
        ...args
      );
    }
    return Promise.reject(
      'First param must be a query or an array of providers.'
    );
  }

  getTorrentDetails(torrent) {
    return this._getProvider(torrent.provider).getTorrentDetails(torrent);
  }

  downloadTorrent(torrent, filenamePath) {
    return this._getProvider(torrent.provider).downloadTorrent(
      torrent,
      filenamePath
    );
  }

  getMagnet(torrent) {
    return this._getProvider(torrent.provider).getMagnet(torrent);
  }

  _search(selectedProviders, query, category, limit) {
    query = query === '' ? undefined : query;
    category = category === '' ? undefined : category;
    limit = limit === '' ? undefined : limit;

    return Promise.all(
      selectedProviders.map(p => p.search(query, category, limit))
    )
      .then(results => _.flatten(results))
      .then(results => _.orderBy(results, ['seeds'], ['desc']))
      .then(results => (limit ? results.slice(0, limit) : results));
  }

  _getActiveProviders() {
    return _.filter(providers, 'isActive');
  }

  _getProvider(name, throwOnError = true) {
    let provider = _.find(
      providers,
      p => p.getName().toUpperCase() === name.toUpperCase()
    );
    if (provider) {
      return provider;
    }

    if (throwOnError) {
      throw new Error(`Couldn't find '${name}' provider`);
    }

    return null;
  }

  _getActiveProvidersByName(providerNames) {
    return this._getActiveProviders().filter(p =>
      providerNames
        .map(m => m.toUpperCase())
        .includes(p.getName().toUpperCase())
    );
  }
}

module.exports = TorrentSearchApi;
<|endoftext|>


<commit_before>'use strict';

var reg = /%(?:(\d+)\$|\((\w+)\))?([+ #-]*)('(.)|0)?((?:\d|\*)+)?(?:\.([\d*]*))?([bdiuoxXfFeEgGaAcsp%])/g;

function repeat(str, num) {
	if (num < 0) {
		return '';
	}
	return new Array(num + 1).join(str);
}

function paddLeft(str, length, what) {
	if (length <= str.length) {
		return str;
	}
	what = what || ' ';
	return repeat(what, length - str.length) + str;
}

function paddRight(str, length, what) {
	if (length <= str.length) {
		return str;
	}
	what = what || ' ';
	return str + repeat(what, length - str.length);
}

function contains(str, what) {
	return str.indexOf(what) !== -1;
}

var types = {
	number: 0,
	string: 1
};

function precBase(base, value, precision) {
	var val = value.toString(base);
	var floatingPoint = val.indexOf('.');
	return val.substring(0, floatingPoint + precision + 1);
}

var specifiers = {
	d: {
		transform: function(a) { return a | 0; },
		allowSign: true,
		type: types.number
	},
	u: {
		transform: function(a) { return a >>> 0; },
		allowSign: true,
		type: types.number
	},
	o: {
		transform: function(a) { return a.toString(8); },
		prefix: '0',
		type: types.number
	},
	x: {
		transform: function(a) { return Math.floor(a).toString(16); },
		prefix: '0x',
		type: types.number
	},
	X: {
		transform: function(a) { return specifiers.x.transform(a).toUpperCase(); },
		prefix: '0X',
		type: types.number
	},
	f: {
		transform: function(a, b) { return precBase(10, a.toLocaleString(), b); },
		allowSign: true,
		type: types.number
	},
	F: {
		transform: function(a, b) { return a.toFixed(b); },
		allowSign: true,
		type: types.number
	},
	e: {
		transform: function(a, b) { return a.toExponential(b); },
		allowSign: true
	},
	E: {
		transform: function(a, b) { return specifiers.e.transform(a, b).toUpperCase(); },
		allowSign: true,
		type: types.number
	},
	g: {
		transform: function(a, b) { return a.toPrecision(b); },
		allowSign: true,
		type: types.number
	},
	G: {
		transform: function(a, b) { return specifiers.g.transform(a, b).toUpperCase(); },
		allowSign: true,
		type: types.number
	},
	a: {
		transform: function(a, b) {
			return precBase(16, a, b) + 'p0';
		},
		allowSign: true,
		prefix: '0x',
		type: types.number
	},
	A: {
		transform: function(a, b) { return specifiers.a.transform(a, b).toUpperCase(); },
		allowSign: true,
		prefix: '0X',
		type: types.number
	},
	c: {
		transform: String.fromCharCode
	},
	s: {
		type: types.string
	},
	b: {
		transform: function(a, b) { return precBase(2, a, b); },
		type: types.number
	}
};

specifiers.i = specifiers.d;

function esprintf(formatString) {
	var valueIdx = 1;
	var parentArguments = arguments;
	var isAssoc = arguments[1] instanceof Object;
	// jshint maxparams:10
	return formatString.replace(reg,
		function(wholeMatch, reference, assocReference, flags, zeroPadding, customPadding, width, precision, type) {
		// jshint maxparams: 4
		if (type === '%') {
			return '%';
		}
		reference = parseInt(reference) || valueIdx;

		flags = flags || '';

		var leftJustify = contains(flags, '-');
		var forceSign = contains(flags, '+');
		var blankFill = contains(flags, ' ');
		var forcePrecisionOrPrefix = contains(flags, '#');

		customPadding = customPadding || zeroPadding;

		var padding = customPadding || ' ';

		var value;

		if (isAssoc) {
			if (!assocReference) {
				throw new Error('Cannot use associative parameters mixed with non associative');
			}
			value = parentArguments[1][assocReference];
			if (value === undefined) {
				throw new Error('No value for format parameter \'' + assocReference + '\'');
			}
		} else {
			if (assocReference) {
				throw new Error('Cannot use associative parameters mixed with non associative');
			}
			value = parentArguments[reference];
		}

		if (width === '*') {
			width = parentArguments[reference++];
			if (!width) {
				throw new Error('No value for dynamic width for parameter no. ' + (reference - 2));
			}
		}
		width = parseInt(width) || 0;

		precision = parseInt(precision) || 6;
		if (precision === '*') {
			precision = parentArguments[reference++];
			if (!precision) {
				throw new Error('No value for dynamic precision for parameter no. ' + (reference - 3));
			}
		}

		var specifier = specifiers[type];
		if (!specifier) {
			throw new Error('Unsupport identified \'' + type + '\'');
		}

		if (value === undefined) {
			throw new Error('No value for format parameter no. ' + (reference - 1));
		}

		if (specifier.type === types.number && !parseInt(value)) {
			throw new TypeError('Invalid value for format parameter no. ' + (reference - 1) + ' expected number, got string');
		}
		var ret = specifier.transform ? specifier.transform(value, precision) : value;
		var allowSign = specifier.allowSign;
		var prefix = specifier.prefix;

		ret = ret.toString().replace('-', '');

		var fullPrefix = (forcePrecisionOrPrefix ? prefix : '') +
		(
			(forceSign && allowSign === '+' && value > 0) ? '+' : (
				(value < 0) ? '-' : (blankFill ? ' ' : '')
			)
		);

		var method = leftJustify ? paddRight : paddLeft;

		return padding === '0' ? fullPrefix + method(ret, width, '0') : method(fullPrefix + ret, width, padding);
	});
}

module.exports = esprintf;
<commit_msg>probably fixed index glitch<commit_after>'use strict';

var reg = /%(?:(\d+)\$|\((\w+)\))?([+ #-]*)('(.)|0)?((?:\d|\*)+)?(?:\.([\d*]*))?([bdiuoxXfFeEgGaAcsp%])/g;

function repeat(str, num) {
	if (num < 0) {
		return '';
	}
	return new Array(num + 1).join(str);
}

function paddLeft(str, length, what) {
	if (length <= str.length) {
		return str;
	}
	what = what || ' ';
	return repeat(what, length - str.length) + str;
}

function paddRight(str, length, what) {
	if (length <= str.length) {
		return str;
	}
	what = what || ' ';
	return str + repeat(what, length - str.length);
}

function contains(str, what) {
	return str.indexOf(what) !== -1;
}

var types = {
	number: 0,
	string: 1
};

function precBase(base, value, precision) {
	var val = value.toString(base);
	var floatingPoint = val.indexOf('.');
	return val.substring(0, floatingPoint + precision + 1);
}

var specifiers = {
	d: {
		transform: function(a) { return a | 0; },
		allowSign: true,
		type: types.number
	},
	u: {
		transform: function(a) { return a >>> 0; },
		allowSign: true,
		type: types.number
	},
	o: {
		transform: function(a) { return a.toString(8); },
		prefix: '0',
		type: types.number
	},
	x: {
		transform: function(a) { return Math.floor(a).toString(16); },
		prefix: '0x',
		type: types.number
	},
	X: {
		transform: function(a) { return specifiers.x.transform(a).toUpperCase(); },
		prefix: '0X',
		type: types.number
	},
	f: {
		transform: function(a, b) { return precBase(10, a.toLocaleString(), b); },
		allowSign: true,
		type: types.number
	},
	F: {
		transform: function(a, b) { return a.toFixed(b); },
		allowSign: true,
		type: types.number
	},
	e: {
		transform: function(a, b) { return a.toExponential(b); },
		allowSign: true
	},
	E: {
		transform: function(a, b) { return specifiers.e.transform(a, b).toUpperCase(); },
		allowSign: true,
		type: types.number
	},
	g: {
		transform: function(a, b) { return a.toPrecision(b); },
		allowSign: true,
		type: types.number
	},
	G: {
		transform: function(a, b) { return specifiers.g.transform(a, b).toUpperCase(); },
		allowSign: true,
		type: types.number
	},
	a: {
		transform: function(a, b) {
			return precBase(16, a, b) + 'p0';
		},
		allowSign: true,
		prefix: '0x',
		type: types.number
	},
	A: {
		transform: function(a, b) { return specifiers.a.transform(a, b).toUpperCase(); },
		allowSign: true,
		prefix: '0X',
		type: types.number
	},
	c: {
		transform: String.fromCharCode
	},
	s: {
		type: types.string
	},
	b: {
		transform: function(a, b) { return precBase(2, a, b); },
		type: types.number
	}
};

specifiers.i = specifiers.d;

function esprintf(formatString) {
	var valueIdx = 1;
	var parentArguments = arguments;
	var isAssoc = arguments[1] instanceof Object;
	// jshint maxparams:10
	return formatString.replace(reg,
		function(wholeMatch, reference, assocReference, flags, zeroPadding, customPadding, width, precision, type) {
		// jshint maxparams: 4
		if (type === '%') {
			return '%';
		}
		reference = parseInt(reference) || valueIdx;

		flags = flags || '';

		var leftJustify = contains(flags, '-');
		var forceSign = contains(flags, '+');
		var blankFill = contains(flags, ' ');
		var forcePrecisionOrPrefix = contains(flags, '#');

		customPadding = customPadding || zeroPadding;

		var padding = customPadding || ' ';

		var value;

		if (isAssoc) {
			if (!assocReference) {
				throw new Error('Cannot use associative parameters mixed with non associative');
			}
			value = parentArguments[1][assocReference];
			if (value === undefined) {
				throw new Error('No value for format parameter \'' + assocReference + '\'');
			}
		} else {
			if (assocReference) {
				throw new Error('Cannot use associative parameters mixed with non associative');
			}
			value = parentArguments[valueIdx++];
		}

		if (width === '*') {
			width = parentArguments[valueIdx++];
			if (!width) {
				throw new Error('No value for dynamic width for parameter no. ' + (reference - 2));
			}
		}
		width = parseInt(width) || 0;

		precision = parseInt(precision) || 6;
		if (precision === '*') {
			precision = parentArguments[valueIdx++];
			if (!precision) {
				throw new Error('No value for dynamic precision for parameter no. ' + (reference - 3));
			}
		}

		var specifier = specifiers[type];
		if (!specifier) {
			throw new Error('Unsupport identified \'' + type + '\'');
		}

		if (value === undefined) {
			throw new Error('No value for format parameter no. ' + (reference - 1));
		}

		if (specifier.type === types.number && !parseInt(value)) {
			throw new TypeError('Invalid value for format parameter no. ' + (reference - 1) + ' expected number, got string');
		}
		var ret = specifier.transform ? specifier.transform(value, precision) : value;
		var allowSign = specifier.allowSign;
		var prefix = specifier.prefix;

		ret = ret.toString().replace('-', '');

		var fullPrefix = (forcePrecisionOrPrefix ? prefix : '') +
		(
			(forceSign && allowSign === '+' && value > 0) ? '+' : (
				(value < 0) ? '-' : (blankFill ? ' ' : '')
			)
		);

		var method = leftJustify ? paddRight : paddLeft;

		return padding === '0' ? fullPrefix + method(ret, width, '0') : method(fullPrefix + ret, width, padding);
	});
}

module.exports = esprintf;
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var Duplex = require('stream').Duplex;
var gutil = require('gulp-util');
var Mocha = require('mocha');

module.exports = function (options) {

    var duplex = new Duplex({ objectMode: true });

    var errorCount = 0;

    duplex._write = function _write(file, encoding, done) {
        var mocha = new Mocha(options);
        delete require.cache[require.resolve(path.resolve(file.path))];
        mocha.addFile(file.path);
        try {
            mocha.run(function (errCount) {
                duplex.push(file);
                errorCount += errCount;
                done();
            }.bind(this));
        } catch (err) {
            this.emit('error', err);
            done();
        }
    };

    duplex.on('finish', function () {
        if (errorCount === 0) { return; }
        var ec = errorCount;
        errorCount = 0;
        duplex.emit('error',
            new gutil.PluginError('gulp-mocha', [
                ec,
                (ec === 1 ? 'test' : 'tests'),
                'failed.'
            ].join(' '))
        );
    });

    duplex._read = function _read() {};

    return duplex;
};
<commit_msg>code style<commit_after>'use strict';
var path = require('path');
var Duplex = require('stream').Duplex;
var gutil = require('gulp-util');
var Mocha = require('mocha');

module.exports = function (options) {
	var duplex = new Duplex({objectMode: true});
	var errorCount = 0;

	duplex._write = function (file, encoding, done) {
		var mocha = new Mocha(options);
		delete require.cache[require.resolve(path.resolve(file.path))];
		mocha.addFile(file.path);

		try {
			mocha.run(function (errCount) {
				duplex.push(file);
				errorCount += errCount;
				done();
			}.bind(this));
		} catch (err) {
			this.emit('error', err);
			done();
		}
	};

	duplex.on('finish', function () {
		if (errorCount === 0) {
			return;
		}

		var ec = errorCount;
		errorCount = 0;

		duplex.emit('error', new gutil.PluginError('gulp-mocha', [ec, (ec === 1 ? 'test' : 'tests'), 'failed.'].join(' ')));
	});

	duplex._read = function () {};

	return duplex;
};
<|endoftext|>


<commit_before>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')({
    transports: ['websocket'],
});

//app.get('/', function(req, res){
//  res.sendFile(__dirname + '/index.html');
//	res.send(process.env.PORT);
//});
var roomList = [];
var playerList = [];
io.on('connection', function (socket)
{
    //socket.emit('newplayer');
    //socket.broadcast.emit('newplayer');
    var playerId = String(new Date().getTime());
    playerList.push(playerId);
    socket.emit('connected', {playerid: playerId});
    //socket.to('others').emit('newplayer');
//    socket.on('beep', function ()
//    {
//        socket.emit('boopeeeee');
//    });
    socket.on('createroom', function (msg)
    {
        var roomId = String(new Date().getTime());
        roomList.push(new room(roomId, msg.roomname, [msg.playerid]));
        socket.emit('roomid', {roomid: roomId});
    });

    socket.on('addme', function (msg)
    {
        var newPlayerId = String(new Date().getTime());
        socket.emit('playeradded', {playerid: newPlayerId});
        socket.broadcast.emit('newplayer', {playerid: newPlayerId});
        //socket.emit('roomlist', JSON.stringify(roomList));
    });
    socket.on('getrooms', function (msg)
    {
//        socket.emit('roomlist', JSON.stringify(roomList));
        socket.emit('roomlist', {roomlist: roomList});
    });
    socket.on('joinroom', function (msg)
    {
//        var roomId = String(new Date().getTime());
//        roomList.push(roomId);
//        socket.emit('roomid', {roomid: roomId});
        var roomListSize = roomList.length;
        for (var i = 0; i < roomListSize; i++) {
            if (roomList[i].roomId == msg.roomname) {
                if (!roomList[i].isPlayerHere(msg.playerid))
                {
                    roomList[i].userList.push(msg.playerid);
                    socket.broadcast.emit('newplayer', {playerid: msg.playerid});
                    socket.emit('joined', {roomid: msg.roomname, otherplayers: roomList[i].getOtherPlayers(msg.playerid)});
                }
            }
        }
    });

    socket.on('position', function (msg)
    {
        var roomListSize = roomList.length;
        for (var i = 0; i < roomListSize; i++) {
            if (roomList[i].roomId == msg.roomid) {
                socket.emit('joined');
                socket.broadcast.emit('position', msg);
                //io.emit('position', msg);
            }
        }
    });
});
io.attach(process.env.PORT || 5000);
//http.listen(process.env.PORT || 5000);
class room {
    constructor(roomId, roomName, userList) {
        this.roomId = roomId;
        this.roomName = roomName;
        this.userList = userList;
    }
    isPlayerHere(playerid) {
        var playerListSize = this.userList.length;
        for (var i = 0; i < playerListSize; i++) {
            if (this.userList[i] == playerid) {
                return true;
            }
        }
        return false;
    }
    getOtherPlayers(playerid) {
        var playerListSize = this.userList.length;
        var playerList=[];
        for (var i = 0; i < playerListSize; i++) {
            if (userList[i] != playerid) {
                playerList.push(this.userList[i]);
            }
        }
        return playerList;
    }
}<commit_msg>bug fixed<commit_after>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')({
    transports: ['websocket'],
});

//app.get('/', function(req, res){
//  res.sendFile(__dirname + '/index.html');
//	res.send(process.env.PORT);
//});
var roomList = [];
var playerList = [];
io.on('connection', function (socket)
{
    //socket.emit('newplayer');
    //socket.broadcast.emit('newplayer');
    var playerId = String(new Date().getTime());
    playerList.push(playerId);
    socket.emit('connected', {playerid: playerId});
    //socket.to('others').emit('newplayer');
//    socket.on('beep', function ()
//    {
//        socket.emit('boopeeeee');
//    });
    socket.on('createroom', function (msg)
    {
        var roomId = String(new Date().getTime());
        roomList.push(new room(roomId, msg.roomname, [msg.playerid]));
        socket.emit('roomid', {roomid: roomId});
    });

    socket.on('addme', function (msg)
    {
        var newPlayerId = String(new Date().getTime());
        socket.emit('playeradded', {playerid: newPlayerId});
        socket.broadcast.emit('newplayer', {playerid: newPlayerId});
        //socket.emit('roomlist', JSON.stringify(roomList));
    });
    socket.on('getrooms', function (msg)
    {
//        socket.emit('roomlist', JSON.stringify(roomList));
        socket.emit('roomlist', {roomlist: roomList});
    });
    socket.on('joinroom', function (msg)
    {
//        var roomId = String(new Date().getTime());
//        roomList.push(roomId);
//        socket.emit('roomid', {roomid: roomId});
        var roomListSize = roomList.length;
        for (var i = 0; i < roomListSize; i++) {
            if (roomList[i].roomId == msg.roomname) {
                if (!roomList[i].isPlayerHere(msg.playerid))
                {
                    roomList[i].userList.push(msg.playerid);
                    socket.broadcast.emit('newplayer', {playerid: msg.playerid});
                    socket.emit('joined', {roomid: msg.roomname, otherplayers: roomList[i].getOtherPlayers(msg.playerid)});
                }
            }
        }
    });

    socket.on('position', function (msg)
    {
        var roomListSize = roomList.length;
        for (var i = 0; i < roomListSize; i++) {
            if (roomList[i].roomId == msg.roomid) {
                //socket.emit('joined');
                socket.broadcast.emit('position', msg);
                //io.emit('position', msg);
            }
        }
    });
});
io.attach(process.env.PORT || 5000);
//http.listen(process.env.PORT || 5000);
class room {
    constructor(roomId, roomName, userList) {
        this.roomId = roomId;
        this.roomName = roomName;
        this.userList = userList;
    }
    isPlayerHere(playerid) {
        var playerListSize = this.userList.length;
        for (var i = 0; i < playerListSize; i++) {
            if (this.userList[i] == playerid) {
                return true;
            }
        }
        return false;
    }
    getOtherPlayers(playerid) {
        var playerListSize = this.userList.length;
        var playerList=[];
        for (var i = 0; i < playerListSize; i++) {
            if (userList[i] != playerid) {
                playerList.push(this.userList[i]);
            }
        }
        return playerList;
    }
}<|endoftext|>


<commit_before>/**
 * d3.tip
 * Copyright (c) 2013-2017 Justin Palmer
 *
 * Tooltips for d3.js SVG visualizations
 */
// eslint-disable-next-line no-extra-semi
import { map } from 'd3-collection'
import { selection, select } from 'd3-selection'
// Public - constructs a new tooltip
//
// Returns a tip
export default function() {
  var direction   = d3TipDirection,
      offset      = d3TipOffset,
      html        = d3TipHTML,
      rootElement = document.body,
      node        = initNode(),
      svg         = null,
      point       = null,
      target      = null

  function tip(vis) {
    svg = getSVGNode(vis)
    if (!svg) return
    point = svg.createSVGPoint()
    rootElement.appendChild(node)
  }

  // Public - show the tooltip on the screen
  //
  // Returns a tip
  tip.show = function() {
    var args = Array.prototype.slice.call(arguments)
    if (args[args.length - 1] instanceof SVGElement) target = args.pop()

    var content = html.apply(this, args),
        poffset = offset.apply(this, args),
        dir     = direction.apply(this, args),
        nodel   = getNodeEl(),
        i       = directions.length,
        coords,
        scrollTop  = document.documentElement.scrollTop ||
      rootElement.scrollTop,
        scrollLeft = document.documentElement.scrollLeft ||
      rootElement.scrollLeft

    nodel.html(content)
      .style('opacity', 1).style('pointer-events', 'all')

    while (i--) nodel.classed(directions[i], false)
    coords = directionCallbacks.get(dir).apply(this)
    nodel.classed(dir, true)
      .style('top', (coords.top + poffset[0]) + scrollTop + 'px')
      .style('left', (coords.left + poffset[1]) + scrollLeft + 'px')

    return tip
  }

  // Public - hide the tooltip
  //
  // Returns a tip
  tip.hide = function() {
    var nodel = getNodeEl()
    nodel.style('opacity', 0).style('pointer-events', 'none')
    return tip
  }

  // Public: Proxy attr calls to the d3 tip container.
  // Sets or gets attribute value.
  //
  // n - name of the attribute
  // v - value of the attribute
  //
  // Returns tip or attribute value
  // eslint-disable-next-line no-unused-vars
  tip.attr = function(n, v) {
    if (arguments.length < 2 && typeof n === 'string') {
      return getNodeEl().attr(n)
    }

    var args =  Array.prototype.slice.call(arguments)
    selection.prototype.attr.apply(getNodeEl(), args)
    return tip
  }

  // Public: Proxy style calls to the d3 tip container.
  // Sets or gets a style value.
  //
  // n - name of the property
  // v - value of the property
  //
  // Returns tip or style property value
  // eslint-disable-next-line no-unused-vars
  tip.style = function(n, v) {
    if (arguments.length < 2 && typeof n === 'string') {
      return getNodeEl().style(n)
    }

    var args = Array.prototype.slice.call(arguments)
    selection.prototype.style.apply(getNodeEl(), args)
    return tip
  }

  // Public: Set or get the direction of the tooltip
  //
  // v - One of n(north), s(south), e(east), or w(west), nw(northwest),
  //     sw(southwest), ne(northeast) or se(southeast)
  //
  // Returns tip or direction
  tip.direction = function(v) {
    if (!arguments.length) return direction
    direction = v == null ? v : functor(v)

    return tip
  }

  // Public: Sets or gets the offset of the tip
  //
  // v - Array of [x, y] offset
  //
  // Returns offset or
  tip.offset = function(v) {
    if (!arguments.length) return offset
    offset = v == null ? v : functor(v)

    return tip
  }

  // Public: sets or gets the html value of the tooltip
  //
  // v - String value of the tip
  //
  // Returns html value or tip
  tip.html = function(v) {
    if (!arguments.length) return html
    html = v == null ? v : functor(v)

    return tip
  }

  // Public: sets or gets the root element anchor of the tooltip
  //
  // v - root element of the tooltip
  //
  // Returns root node of tip
  tip.rootElement = function(v) {
    if (!arguments.length) return rootElement
    rootElement = v == null ? v : functor(v)

    return tip
  }

  // Public: destroys the tooltip and removes it from the DOM
  //
  // Returns a tip
  tip.destroy = function() {
    if (node) {
      getNodeEl().remove()
      node = null
    }
    return tip
  }

  function d3TipDirection() { return 'n' }
  function d3TipOffset() { return [0, 0] }
  function d3TipHTML() { return ' ' }

  var directionCallbacks = map({
        n:  directionNorth,
        s:  directionSouth,
        e:  directionEast,
        w:  directionWest,
        nw: directionNorthWest,
        ne: directionNorthEast,
        sw: directionSouthWest,
        se: directionSouthEast
      }),
      directions = directionCallbacks.keys()

  function directionNorth() {
    var bbox = getScreenBBox(this)
    return {
      top:  bbox.n.y - node.offsetHeight,
      left: bbox.n.x - node.offsetWidth / 2
    }
  }

  function directionSouth() {
    var bbox = getScreenBBox(this)
    return {
      top:  bbox.s.y,
      left: bbox.s.x - node.offsetWidth / 2
    }
  }

  function directionEast() {
    var bbox = getScreenBBox(this)
    return {
      top:  bbox.e.y - node.offsetHeight / 2,
      left: bbox.e.x
    }
  }

  function directionWest() {
    var bbox = getScreenBBox(this)
    return {
      top:  bbox.w.y - node.offsetHeight / 2,
      left: bbox.w.x - node.offsetWidth
    }
  }

  function directionNorthWest() {
    var bbox = getScreenBBox(this)
    return {
      top:  bbox.nw.y - node.offsetHeight,
      left: bbox.nw.x - node.offsetWidth
    }
  }

  function directionNorthEast() {
    var bbox = getScreenBBox(this)
    return {
      top:  bbox.ne.y - node.offsetHeight,
      left: bbox.ne.x
    }
  }

  function directionSouthWest() {
    var bbox = getScreenBBox(this)
    return {
      top:  bbox.sw.y,
      left: bbox.sw.x - node.offsetWidth
    }
  }

  function directionSouthEast() {
    var bbox = getScreenBBox(this)
    return {
      top:  bbox.se.y,
      left: bbox.se.x
    }
  }

  function initNode() {
    var div = select(document.createElement('div'))
    div
      .style('position', 'absolute')
      .style('top', 0)
      .style('opacity', 0)
      .style('pointer-events', 'none')
      .style('box-sizing', 'border-box')

    return div.node()
  }

  function getSVGNode(element) {
    var svgNode = element.node()
    if (!svgNode) return null
    if (svgNode.tagName.toLowerCase() === 'svg') return svgNode
    return svgNode.ownerSVGElement
  }

  function getNodeEl() {
    if (node == null) {
      node = initNode()
      // re-add node to DOM
      rootElement.appendChild(node)
    }
    return select(node)
  }

  // Private - gets the screen coordinates of a shape
  //
  // Given a shape on the screen, will return an SVGPoint for the directions
  // n(north), s(south), e(east), w(west), ne(northeast), se(southeast),
  // nw(northwest), sw(southwest).
  //
  //    +-+-+
  //    |   |
  //    +   +
  //    |   |
  //    +-+-+
  //
  // Returns an Object {n, s, e, w, nw, sw, ne, se}
  function getScreenBBox(targetShape) {
    var targetel   = target || targetShape

    while (targetel.getScreenCTM == null && targetel.parentNode == null) {
      targetel = targetel.parentNode
    }

    var bbox       = {},
        matrix     = targetel.getScreenCTM(),
        tbbox      = targetel.getBBox(),
        width      = tbbox.width,
        height     = tbbox.height,
        x          = tbbox.x,
        y          = tbbox.y

    point.x = x
    point.y = y
    bbox.nw = point.matrixTransform(matrix)
    point.x += width
    bbox.ne = point.matrixTransform(matrix)
    point.y += height
    bbox.se = point.matrixTransform(matrix)
    point.x -= width
    bbox.sw = point.matrixTransform(matrix)
    point.y -= height / 2
    bbox.w = point.matrixTransform(matrix)
    point.x += width
    bbox.e = point.matrixTransform(matrix)
    point.x -= width / 2
    point.y -= height / 2
    bbox.n = point.matrixTransform(matrix)
    point.y += height
    bbox.s = point.matrixTransform(matrix)

    return bbox
  }

  // Private - replace D3JS 3.X d3.functor() function
  function functor(v) {
    return typeof v === 'function' ? v : function() {
      return v
    }
  }

  return tip
}
<commit_msg>Fix while loop condition in getScreenBox<commit_after>/**
 * d3.tip
 * Copyright (c) 2013-2017 Justin Palmer
 *
 * Tooltips for d3.js SVG visualizations
 */
// eslint-disable-next-line no-extra-semi
import { map } from 'd3-collection'
import { selection, select } from 'd3-selection'
// Public - constructs a new tooltip
//
// Returns a tip
export default function() {
  var direction   = d3TipDirection,
      offset      = d3TipOffset,
      html        = d3TipHTML,
      rootElement = document.body,
      node        = initNode(),
      svg         = null,
      point       = null,
      target      = null

  function tip(vis) {
    svg = getSVGNode(vis)
    if (!svg) return
    point = svg.createSVGPoint()
    rootElement.appendChild(node)
  }

  // Public - show the tooltip on the screen
  //
  // Returns a tip
  tip.show = function() {
    var args = Array.prototype.slice.call(arguments)
    if (args[args.length - 1] instanceof SVGElement) target = args.pop()

    var content = html.apply(this, args),
        poffset = offset.apply(this, args),
        dir     = direction.apply(this, args),
        nodel   = getNodeEl(),
        i       = directions.length,
        coords,
        scrollTop  = document.documentElement.scrollTop ||
      rootElement.scrollTop,
        scrollLeft = document.documentElement.scrollLeft ||
      rootElement.scrollLeft

    nodel.html(content)
      .style('opacity', 1).style('pointer-events', 'all')

    while (i--) nodel.classed(directions[i], false)
    coords = directionCallbacks.get(dir).apply(this)
    nodel.classed(dir, true)
      .style('top', (coords.top + poffset[0]) + scrollTop + 'px')
      .style('left', (coords.left + poffset[1]) + scrollLeft + 'px')

    return tip
  }

  // Public - hide the tooltip
  //
  // Returns a tip
  tip.hide = function() {
    var nodel = getNodeEl()
    nodel.style('opacity', 0).style('pointer-events', 'none')
    return tip
  }

  // Public: Proxy attr calls to the d3 tip container.
  // Sets or gets attribute value.
  //
  // n - name of the attribute
  // v - value of the attribute
  //
  // Returns tip or attribute value
  // eslint-disable-next-line no-unused-vars
  tip.attr = function(n, v) {
    if (arguments.length < 2 && typeof n === 'string') {
      return getNodeEl().attr(n)
    }

    var args =  Array.prototype.slice.call(arguments)
    selection.prototype.attr.apply(getNodeEl(), args)
    return tip
  }

  // Public: Proxy style calls to the d3 tip container.
  // Sets or gets a style value.
  //
  // n - name of the property
  // v - value of the property
  //
  // Returns tip or style property value
  // eslint-disable-next-line no-unused-vars
  tip.style = function(n, v) {
    if (arguments.length < 2 && typeof n === 'string') {
      return getNodeEl().style(n)
    }

    var args = Array.prototype.slice.call(arguments)
    selection.prototype.style.apply(getNodeEl(), args)
    return tip
  }

  // Public: Set or get the direction of the tooltip
  //
  // v - One of n(north), s(south), e(east), or w(west), nw(northwest),
  //     sw(southwest), ne(northeast) or se(southeast)
  //
  // Returns tip or direction
  tip.direction = function(v) {
    if (!arguments.length) return direction
    direction = v == null ? v : functor(v)

    return tip
  }

  // Public: Sets or gets the offset of the tip
  //
  // v - Array of [x, y] offset
  //
  // Returns offset or
  tip.offset = function(v) {
    if (!arguments.length) return offset
    offset = v == null ? v : functor(v)

    return tip
  }

  // Public: sets or gets the html value of the tooltip
  //
  // v - String value of the tip
  //
  // Returns html value or tip
  tip.html = function(v) {
    if (!arguments.length) return html
    html = v == null ? v : functor(v)

    return tip
  }

  // Public: sets or gets the root element anchor of the tooltip
  //
  // v - root element of the tooltip
  //
  // Returns root node of tip
  tip.rootElement = function(v) {
    if (!arguments.length) return rootElement
    rootElement = v == null ? v : functor(v)

    return tip
  }

  // Public: destroys the tooltip and removes it from the DOM
  //
  // Returns a tip
  tip.destroy = function() {
    if (node) {
      getNodeEl().remove()
      node = null
    }
    return tip
  }

  function d3TipDirection() { return 'n' }
  function d3TipOffset() { return [0, 0] }
  function d3TipHTML() { return ' ' }

  var directionCallbacks = map({
        n:  directionNorth,
        s:  directionSouth,
        e:  directionEast,
        w:  directionWest,
        nw: directionNorthWest,
        ne: directionNorthEast,
        sw: directionSouthWest,
        se: directionSouthEast
      }),
      directions = directionCallbacks.keys()

  function directionNorth() {
    var bbox = getScreenBBox(this)
    return {
      top:  bbox.n.y - node.offsetHeight,
      left: bbox.n.x - node.offsetWidth / 2
    }
  }

  function directionSouth() {
    var bbox = getScreenBBox(this)
    return {
      top:  bbox.s.y,
      left: bbox.s.x - node.offsetWidth / 2
    }
  }

  function directionEast() {
    var bbox = getScreenBBox(this)
    return {
      top:  bbox.e.y - node.offsetHeight / 2,
      left: bbox.e.x
    }
  }

  function directionWest() {
    var bbox = getScreenBBox(this)
    return {
      top:  bbox.w.y - node.offsetHeight / 2,
      left: bbox.w.x - node.offsetWidth
    }
  }

  function directionNorthWest() {
    var bbox = getScreenBBox(this)
    return {
      top:  bbox.nw.y - node.offsetHeight,
      left: bbox.nw.x - node.offsetWidth
    }
  }

  function directionNorthEast() {
    var bbox = getScreenBBox(this)
    return {
      top:  bbox.ne.y - node.offsetHeight,
      left: bbox.ne.x
    }
  }

  function directionSouthWest() {
    var bbox = getScreenBBox(this)
    return {
      top:  bbox.sw.y,
      left: bbox.sw.x - node.offsetWidth
    }
  }

  function directionSouthEast() {
    var bbox = getScreenBBox(this)
    return {
      top:  bbox.se.y,
      left: bbox.se.x
    }
  }

  function initNode() {
    var div = select(document.createElement('div'))
    div
      .style('position', 'absolute')
      .style('top', 0)
      .style('opacity', 0)
      .style('pointer-events', 'none')
      .style('box-sizing', 'border-box')

    return div.node()
  }

  function getSVGNode(element) {
    var svgNode = element.node()
    if (!svgNode) return null
    if (svgNode.tagName.toLowerCase() === 'svg') return svgNode
    return svgNode.ownerSVGElement
  }

  function getNodeEl() {
    if (node == null) {
      node = initNode()
      // re-add node to DOM
      rootElement.appendChild(node)
    }
    return select(node)
  }

  // Private - gets the screen coordinates of a shape
  //
  // Given a shape on the screen, will return an SVGPoint for the directions
  // n(north), s(south), e(east), w(west), ne(northeast), se(southeast),
  // nw(northwest), sw(southwest).
  //
  //    +-+-+
  //    |   |
  //    +   +
  //    |   |
  //    +-+-+
  //
  // Returns an Object {n, s, e, w, nw, sw, ne, se}
  function getScreenBBox(targetShape) {
    var targetel   = target || targetShape

    while (targetel.getScreenCTM == null && targetel.parentNode != null) {
      targetel = targetel.parentNode
    }

    var bbox       = {},
        matrix     = targetel.getScreenCTM(),
        tbbox      = targetel.getBBox(),
        width      = tbbox.width,
        height     = tbbox.height,
        x          = tbbox.x,
        y          = tbbox.y

    point.x = x
    point.y = y
    bbox.nw = point.matrixTransform(matrix)
    point.x += width
    bbox.ne = point.matrixTransform(matrix)
    point.y += height
    bbox.se = point.matrixTransform(matrix)
    point.x -= width
    bbox.sw = point.matrixTransform(matrix)
    point.y -= height / 2
    bbox.w = point.matrixTransform(matrix)
    point.x += width
    bbox.e = point.matrixTransform(matrix)
    point.x -= width / 2
    point.y -= height / 2
    bbox.n = point.matrixTransform(matrix)
    point.y += height
    bbox.s = point.matrixTransform(matrix)

    return bbox
  }

  // Private - replace D3JS 3.X d3.functor() function
  function functor(v) {
    return typeof v === 'function' ? v : function() {
      return v
    }
  }

  return tip
}
<|endoftext|>


<commit_before>const supportedMethods = ['GET', 'POST', 'PUT', 'DELETE']
const validTypes = ['', 'arraybuffer', 'blob', 'document', 'text', 'json']

/**
 * Validate HTTP method
 * @param {String} method – HTTP method
 */
function validateMethod (method) {
  if (!method) {
    throw Error(`HTTP method is not specified`)
  }
  if (typeof method !== 'string') {
    throw Error(`HTTP method should be type of string`)
  }
  if (method in supportedMethods < 0) {
    throw Error(`Http method  ${method} is not supported`)
  }
}

/**
 * Basicly validate url
 * @param {String} url – URL
 */
function validateUrl (url) {
  if (!url) {
    throw Error(`Url is not specified`)
  }
  if (typeof url !== 'string') {
    throw Error(`Url should be type of string`)
  }
}

/**
 * Validate header to all parts be strings
 * @param {String} key – Header key
 * @param {String} value – Header value
 */
function validateHeader (key, value) {
  if (typeof key !== 'string' || typeof value !== 'string')
    throw new Error('Headers must be strings')
}

/**
 * Validate headers
 * @param {Object} headers – headers
 */
function validateHeaders (headers) {
  for (let [key, value] of headers.entries()) {
    validateHeader(key, value)
  }
}

/**
 * Validates response type
 * @param {string} type - response type
 */
function validateResponseType (type) {
  if (type !== null || !(type in validTypes))
    throw Error(`Response content type ${type} is not currently supported`)
}

/**
 * Validate HTTP request model
 * @param {Object} http – Http object
 */
function validate (http) {
  validateUrl(http.url)
  validateMethod(http.method)
  validateHeaders(http.headers)
  validateResponseType(http.responseType)
}

export default validate
<commit_msg>Fix ckeck<commit_after>const supportedMethods = ['GET', 'POST', 'PUT', 'DELETE']
const validTypes = ['', 'arraybuffer', 'blob', 'document', 'text', 'json']

/**
 * Validate HTTP method
 * @param {String} method – HTTP method
 */
function validateMethod (method) {
  if (!method) {
    throw Error(`HTTP method is not specified`)
  }
  if (typeof method !== 'string') {
    throw Error(`HTTP method should be type of string`)
  }
  if (method in supportedMethods) {
    throw Error(`Http method  ${method} is not supported`)
  }
}

/**
 * Basicly validate url
 * @param {String} url – URL
 */
function validateUrl (url) {
  if (!url) {
    throw Error(`Url is not specified`)
  }
  if (typeof url !== 'string') {
    throw Error(`Url should be type of string`)
  }
}

/**
 * Validate header to all parts be strings
 * @param {String} key – Header key
 * @param {String} value – Header value
 */
function validateHeader (key, value) {
  if (typeof key !== 'string' || typeof value !== 'string')
    throw new Error('Headers must be strings')
}

/**
 * Validate headers
 * @param {Object} headers – headers
 */
function validateHeaders (headers) {
  for (let [key, value] of headers.entries()) {
    validateHeader(key, value)
  }
}

/**
 * Validates response type
 * @param {string} type - response type
 */
function validateResponseType (type) {
  if (type !== null || !(type in validTypes))
    throw Error(`Response content type ${type} is not currently supported`)
}

/**
 * Validate HTTP request model
 * @param {Object} http – Http object
 */
function validate (http) {
  validateUrl(http.url)
  validateMethod(http.method)
  validateHeaders(http.headers)
  validateResponseType(http.responseType)
}

export default validate
<|endoftext|>


<commit_before>/*
 * Copyright: Vitaly Puzrin
 * Author: Sergey Batishchev <snb2003@rambler.ru>
 *
 * Written for fontello.com project.
 */

'use strict';

var _       = require('lodash');
var SvgPath = require('svgpath');
var ucs2 = require('./lib/ucs2');
var svg     = require('./lib/svg');
var sfnt    = require('./lib/sfnt');

var VERSION_RE = /^(Version )?(\d+[.]\d+)$/i;

function svg2ttf(svgString, options) {
  var font = new sfnt.Font();
  var svgFont = svg.load(svgString);

  options = options || {};

  font.id = options.id || svgFont.id;
  font.familyName = options.familyname || svgFont.familyName || svgFont.id;
  font.copyright = options.copyright || svgFont.metadata;
  font.description = options.description || 'Generated by svg2ttf from Fontello project.';
  font.url = options.url || 'http://fontello.com';
  font.sfntNames.push({ id: 2, value: options.subfamilyname || svgFont.subfamilyName || 'Regular' }); // subfamily name
  font.sfntNames.push({ id: 4, value: options.fullname || svgFont.id }); // full name

  var versionString = options.version || 'Version 1.0';

  if (typeof versionString !== 'string') {
    throw new Error('svg2ttf: version option should be a string');
  }
  if (!VERSION_RE.test(versionString)) {
    throw new Error('svg2ttf: invalid option, version - "' + options.version + '"');
  }

  versionString = 'Version ' + versionString.match(VERSION_RE)[2];
  font.sfntNames.push({ id: 5, value: versionString }); // version ID for TTF name table
  font.sfntNames.push({ id: 6, value: (options.fullname || svgFont.id).replace(/[\s\(\)\[\]<>%\/]/g, '').substr(0, 62) }); // Postscript name for the font, required for OSX Font Book

  if (typeof options.ts !== 'undefined') {
    font.createdDate = font.modifiedDate = new Date(parseInt(options.ts, 10) * 1000);
  }

  // Try to fill font metrics or guess defaults
  //
  font.unitsPerEm   = svgFont.unitsPerEm || 1000;
  font.horizOriginX = svgFont.horizOriginX || 0;
  font.horizOriginY = svgFont.horizOriginY || 0;
  font.vertOriginX  = svgFont.vertOriginX || 0;
  font.vertOriginY  = svgFont.vertOriginY || 0;
  // need to correctly convert text values, use default (400) until compleete
  //font.weightClass = svgFont.weightClass;
  font.width    = svgFont.width || svgFont.unitsPerEm;
  font.height   = svgFont.height || svgFont.unitsPerEm;
  font.descent  = !isNaN(svgFont.descent) ? svgFont.descent : -font.vertOriginY;
  font.ascent   = svgFont.ascent || (font.unitsPerEm - font.vertOriginY);

  if (typeof svgFont.underlinePosition !== 'undefined') {
    font.underlinePosition = svgFont.underlinePosition;
  }
  if (typeof svgFont.underlineThickness !== 'undefined') {
    font.underlineThickness = svgFont.underlineThickness;
  }

  var glyphs = font.glyphs;
  var codePoints = font.codePoints;
  var ligatures = font.ligatures;

  function addCodePoint(codePoint, glyph) {
    if (codePoints[codePoint]) {
      // Ignore code points already defined
      return false;
    }
    codePoints[codePoint] = glyph;
    return true;
  }

  // add SVG glyphs to SFNT font
  _.forEach(svgFont.glyphs, function (svgGlyph) {
    var glyph = new sfnt.Glyph();

    glyph.name = svgGlyph.name;
    glyph.d = svgGlyph.d;
    glyph.height = !isNaN(svgGlyph.height) ? svgGlyph.height : font.height;
    glyph.width = !isNaN(svgGlyph.width) ? svgGlyph.width : font.width;
    glyphs.push(glyph);

    svgGlyph.sfntGlyph = glyph;

    _.forEach(svgGlyph.unicode, function (codePoint) {
      addCodePoint(codePoint, glyph);
    });
  });

  var missingGlyph;

  // add missing glyph to SFNT font
  // also, check missing glyph existance and single instance
  if (svgFont.missingGlyph) {
    missingGlyph = new sfnt.Glyph();
    missingGlyph.d = svgFont.missingGlyph.d;
    missingGlyph.height = !isNaN(svgFont.missingGlyph.height) ? svgFont.missingGlyph.height : font.height;
    missingGlyph.width = !isNaN(svgFont.missingGlyph.width) ? svgFont.missingGlyph.width : font.width;
  } else {
    missingGlyph = _.find(glyphs, function (glyph) {
      return glyph.name === '.notdef';
    });
  }
  if (!missingGlyph) { // no missing glyph and .notdef glyph, we need to create missing glyph
    missingGlyph = new sfnt.Glyph();
  }

  // Create glyphs for all characters used in ligatures
  _.forEach(svgFont.ligatures, function (svgLigature) {
    var ligature = {
      ligature: svgLigature.ligature,
      unicode: svgLigature.unicode,
      glyph: svgLigature.glyph.sfntGlyph
    };

    _.forEach(ligature.unicode, function (charPoint) {
      // We need to have a distinct glyph for each code point so we can reference it in GSUB
      var glyph = new sfnt.Glyph();
      var added = addCodePoint(charPoint, glyph);

      if (added) {
        glyph.name = ucs2.encode([ charPoint ]);
        glyphs.push(glyph);
      }
    });
    ligatures.push(ligature);
  });

  // Missing Glyph needs to have index 0
  if (glyphs.indexOf(missingGlyph) !== -1) {
    glyphs.splice(glyphs.indexOf(missingGlyph), 1);
  }
  glyphs.unshift(missingGlyph);

  var nextID = 0;

  //add IDs
  _.forEach(glyphs, function (glyph) {
    glyph.id = nextID;
    nextID++;
  });

  _.forEach(glyphs, function (glyph) {

    // Calculate accuracy for cubicToQuad transformation
    // For glyphs with height and width smaller than 500 use relative 0.06% accuracy,
    // for larger glyphs use fixed accuracy 0.3.
    var glyphSize = Math.max(glyph.width, glyph.height);
    var accuracy = (glyphSize > 500) ? 0.3 : glyphSize * 0.0006;

    //SVG transformations
    var svgPath = new SvgPath(glyph.d)
      .abs()
      .unshort()
      .unarc()
      .iterate(function (segment, index, x, y) {
        return svg.cubicToQuad(segment, index, x, y, accuracy);
      });
    var sfntContours = svg.toSfntCoutours(svgPath);

    // Add contours to SFNT font
    glyph.contours = _.map(sfntContours, function (sfntContour) {
      var contour = new sfnt.Contour();

      contour.points = _.map(sfntContour, function (sfntPoint) {
        var point = new sfnt.Point();

        point.x = sfntPoint.x;
        point.y = sfntPoint.y;
        point.onCurve = sfntPoint.onCurve;
        return point;
      });

      return contour;
    });
  });

  var ttf = sfnt.toTTF(font);

  return ttf;
}

module.exports = svg2ttf;
<commit_msg>Use `font-weight` attr when possible<commit_after>/*
 * Copyright: Vitaly Puzrin
 * Author: Sergey Batishchev <snb2003@rambler.ru>
 *
 * Written for fontello.com project.
 */

'use strict';

var _       = require('lodash');
var SvgPath = require('svgpath');
var ucs2 = require('./lib/ucs2');
var svg     = require('./lib/svg');
var sfnt    = require('./lib/sfnt');

var VERSION_RE = /^(Version )?(\d+[.]\d+)$/i;

function svg2ttf(svgString, options) {
  var font = new sfnt.Font();
  var svgFont = svg.load(svgString);

  options = options || {};

  font.id = options.id || svgFont.id;
  font.familyName = options.familyname || svgFont.familyName || svgFont.id;
  font.copyright = options.copyright || svgFont.metadata;
  font.description = options.description || 'Generated by svg2ttf from Fontello project.';
  font.url = options.url || 'http://fontello.com';
  font.sfntNames.push({ id: 2, value: options.subfamilyname || svgFont.subfamilyName || 'Regular' }); // subfamily name
  font.sfntNames.push({ id: 4, value: options.fullname || svgFont.id }); // full name

  var versionString = options.version || 'Version 1.0';

  if (typeof versionString !== 'string') {
    throw new Error('svg2ttf: version option should be a string');
  }
  if (!VERSION_RE.test(versionString)) {
    throw new Error('svg2ttf: invalid option, version - "' + options.version + '"');
  }

  versionString = 'Version ' + versionString.match(VERSION_RE)[2];
  font.sfntNames.push({ id: 5, value: versionString }); // version ID for TTF name table
  font.sfntNames.push({ id: 6, value: (options.fullname || svgFont.id).replace(/[\s\(\)\[\]<>%\/]/g, '').substr(0, 62) }); // Postscript name for the font, required for OSX Font Book

  if (typeof options.ts !== 'undefined') {
    font.createdDate = font.modifiedDate = new Date(parseInt(options.ts, 10) * 1000);
  }

  // Try to fill font metrics or guess defaults
  //
  font.unitsPerEm   = svgFont.unitsPerEm || 1000;
  font.horizOriginX = svgFont.horizOriginX || 0;
  font.horizOriginY = svgFont.horizOriginY || 0;
  font.vertOriginX  = svgFont.vertOriginX || 0;
  font.vertOriginY  = svgFont.vertOriginY || 0;
  font.width    = svgFont.width || svgFont.unitsPerEm;
  font.height   = svgFont.height || svgFont.unitsPerEm;
  font.descent  = !isNaN(svgFont.descent) ? svgFont.descent : -font.vertOriginY;
  font.ascent   = svgFont.ascent || (font.unitsPerEm - font.vertOriginY);

  if (typeof svgFont.weightClass !== 'undefined') {
    var wght = parseInt(svgFont.weightClass, 10);

    if (!isNaN(wght)) font.weightClass = wght;
    else {
      // Unknown names are silently ignored
      if (svgFont.weightClass === 'normal') font.weightClass = 400;
      if (svgFont.weightClass === 'bold') font.weightClass = 700;
    }
  }

  if (typeof svgFont.underlinePosition !== 'undefined') {
    font.underlinePosition = svgFont.underlinePosition;
  }
  if (typeof svgFont.underlineThickness !== 'undefined') {
    font.underlineThickness = svgFont.underlineThickness;
  }

  var glyphs = font.glyphs;
  var codePoints = font.codePoints;
  var ligatures = font.ligatures;

  function addCodePoint(codePoint, glyph) {
    if (codePoints[codePoint]) {
      // Ignore code points already defined
      return false;
    }
    codePoints[codePoint] = glyph;
    return true;
  }

  // add SVG glyphs to SFNT font
  _.forEach(svgFont.glyphs, function (svgGlyph) {
    var glyph = new sfnt.Glyph();

    glyph.name = svgGlyph.name;
    glyph.d = svgGlyph.d;
    glyph.height = !isNaN(svgGlyph.height) ? svgGlyph.height : font.height;
    glyph.width = !isNaN(svgGlyph.width) ? svgGlyph.width : font.width;
    glyphs.push(glyph);

    svgGlyph.sfntGlyph = glyph;

    _.forEach(svgGlyph.unicode, function (codePoint) {
      addCodePoint(codePoint, glyph);
    });
  });

  var missingGlyph;

  // add missing glyph to SFNT font
  // also, check missing glyph existance and single instance
  if (svgFont.missingGlyph) {
    missingGlyph = new sfnt.Glyph();
    missingGlyph.d = svgFont.missingGlyph.d;
    missingGlyph.height = !isNaN(svgFont.missingGlyph.height) ? svgFont.missingGlyph.height : font.height;
    missingGlyph.width = !isNaN(svgFont.missingGlyph.width) ? svgFont.missingGlyph.width : font.width;
  } else {
    missingGlyph = _.find(glyphs, function (glyph) {
      return glyph.name === '.notdef';
    });
  }
  if (!missingGlyph) { // no missing glyph and .notdef glyph, we need to create missing glyph
    missingGlyph = new sfnt.Glyph();
  }

  // Create glyphs for all characters used in ligatures
  _.forEach(svgFont.ligatures, function (svgLigature) {
    var ligature = {
      ligature: svgLigature.ligature,
      unicode: svgLigature.unicode,
      glyph: svgLigature.glyph.sfntGlyph
    };

    _.forEach(ligature.unicode, function (charPoint) {
      // We need to have a distinct glyph for each code point so we can reference it in GSUB
      var glyph = new sfnt.Glyph();
      var added = addCodePoint(charPoint, glyph);

      if (added) {
        glyph.name = ucs2.encode([ charPoint ]);
        glyphs.push(glyph);
      }
    });
    ligatures.push(ligature);
  });

  // Missing Glyph needs to have index 0
  if (glyphs.indexOf(missingGlyph) !== -1) {
    glyphs.splice(glyphs.indexOf(missingGlyph), 1);
  }
  glyphs.unshift(missingGlyph);

  var nextID = 0;

  //add IDs
  _.forEach(glyphs, function (glyph) {
    glyph.id = nextID;
    nextID++;
  });

  _.forEach(glyphs, function (glyph) {

    // Calculate accuracy for cubicToQuad transformation
    // For glyphs with height and width smaller than 500 use relative 0.06% accuracy,
    // for larger glyphs use fixed accuracy 0.3.
    var glyphSize = Math.max(glyph.width, glyph.height);
    var accuracy = (glyphSize > 500) ? 0.3 : glyphSize * 0.0006;

    //SVG transformations
    var svgPath = new SvgPath(glyph.d)
      .abs()
      .unshort()
      .unarc()
      .iterate(function (segment, index, x, y) {
        return svg.cubicToQuad(segment, index, x, y, accuracy);
      });
    var sfntContours = svg.toSfntCoutours(svgPath);

    // Add contours to SFNT font
    glyph.contours = _.map(sfntContours, function (sfntContour) {
      var contour = new sfnt.Contour();

      contour.points = _.map(sfntContour, function (sfntPoint) {
        var point = new sfnt.Point();

        point.x = sfntPoint.x;
        point.y = sfntPoint.y;
        point.onCurve = sfntPoint.onCurve;
        return point;
      });

      return contour;
    });
  });

  var ttf = sfnt.toTTF(font);

  return ttf;
}

module.exports = svg2ttf;
<|endoftext|>


<commit_before>var browserify = require('browserify')
  , path       = require('path')
  , watchify   = require('watchify')
  , shim       = require('browserify-shim')
  , ejsify     = require('ejsify')
  , hbsfy      = require('hbsfy')
  , jadeify    = require('jadeify')
  , envify     = require('envify')
  , partialify = require('partialify')
  , brfs       = require('brfs')
  , writer     = require('write-to-path')

module.exports = function (opts, cb) {
  if (Array.isArray(opts)) opts = {entries: opts}
  if (typeof opts === 'string') opts = {entries: [opts]}
  if (opts.entry) opts.entries = [opts.entry]

  if (typeof cb === 'string') opts.output = cb

  opts.shim = opts.shim || {}
  opts.debug = opts.debug || false

  var b = shim(opts.watch ? watchify() : browserify(), opts.shim)

  if (opts.watch) {
    b.on('update', function () {
      b.bundle(opts, cb)
    })
  }

  opts.entries.forEach(function (entry) {
    b.add(path.resolve(process.cwd(), entry))
  })

  // ensure brfs runs last because it requires valid js
  var transforms = [envify, ejsify, hbsfy, jadeify, partialify].concat(opts.transforms || []).concat([brfs])
  transforms.forEach(function (transform) {
    b.transform(transform)
  })

  if (opts.output) {
    b.bundle(opts, writer(path.resolve(process.cwd(), opts.output), {debug: opts.debug}))
  } else {
    b.bundle(opts, cb)
  }
}
<commit_msg>Completely skip browserify-shim if opts.shim not provided<commit_after>var browserify = require('browserify')
  , path       = require('path')
  , watchify   = require('watchify')
  , shim       = require('browserify-shim')
  , ejsify     = require('ejsify')
  , hbsfy      = require('hbsfy')
  , jadeify    = require('jadeify')
  , envify     = require('envify')
  , partialify = require('partialify')
  , brfs       = require('brfs')
  , writer     = require('write-to-path')

module.exports = function (opts, cb) {
  if (Array.isArray(opts)) opts = {entries: opts}
  if (typeof opts === 'string') opts = {entries: [opts]}
  if (opts.entry) opts.entries = [opts.entry]

  if (typeof cb === 'string') opts.output = cb

  opts.debug = opts.debug || false

  var b = opts.watch ? watchify() : browserify()
  if (opts.shim) b = shim(b, opts.shim)

  if (opts.watch) {
    b.on('update', function () {
      b.bundle(opts, cb)
    })
  }

  opts.entries.forEach(function (entry) {
    b.add(path.resolve(process.cwd(), entry))
  })

  // ensure brfs runs last because it requires valid js
  var transforms = [envify, ejsify, hbsfy, jadeify, partialify].concat(opts.transforms || []).concat([brfs])
  transforms.forEach(function (transform) {
    b.transform(transform)
  })

  if (opts.output) {
    b.bundle(opts, writer(path.resolve(process.cwd(), opts.output), {debug: opts.debug}))
  } else {
    b.bundle(opts, cb)
  }
}
<|endoftext|>


<commit_before>// partie serveur : Envoie les pages HTML au client web et au client mobile

var express = require('express');
var app = express();
var server = require('http').createServer(app);

var io = require('socket.io')(server);

// lit les fichiers HTML à envoyer aux clients
var path = require('path');
var fs = require('fs');
var publicFolder = path.join(__dirname, 'public');

// permet de detecter si PC ou mobile
var device = require('express-device');
app.use(device.capture());

// toutes les requêtes à des fichiers (js, css, etc) iront les chercher dans le dossier public
app.use(express.static(publicFolder));

// si on se connecte sur www.monsite.com/
app.get('/', function(req, res) {
	// verifie le type d'appareil
	if (req.device.type === 'tablet' || req.device.type === 'phone') {
		res.redirect('phone.html');
	}

	else {
		res.redirect('web.html');
	}
});

// quand une connexion socket.io (communication temps réel) arrive
io.on('connection', function(socket)
{
	// quand un message de type 'gyro' arrrive
	socket.on('gyro', function(data) {
		// le renvoie à tous les autres clients connectés
		// (faudra le changer, avec le systeme de code de dadagafa pour les faire marcher par paire)
		socket.broadcast.emit('gyro', data);
	});
})

server.listen(3000);
<commit_msg>changed comments<commit_after>// partie serveur : Envoie les pages HTML au client web et au client mobile

var express = require('express');
var app = express();
var server = require('http').createServer(app);

var io = require('socket.io')(server);

// récupère le nom complet du sous-dossier public/
var path = require('path');
var publicFolder = path.join(__dirname, 'public');

// toutes les requêtes à des fichiers (html, js, css, etc) iront les chercher dans le dossier public
app.use(express.static(publicFolder));

// permet de detecter si PC ou mobile
var device = require('express-device');
app.use(device.capture());

// si on se connecte sur www.monsite.com/
app.get('/', function(req, res) {
	// verifie le type d'appareil
	if (req.device.type === 'tablet' || req.device.type === 'phone') {
		res.redirect('phone.html');
	}

	else {
		res.redirect('web.html');
	}
});

// quand une connexion socket.io (communication temps réel) arrive
io.on('connection', function(socket)
{
	// quand un message de type 'gyro' arrrive
	socket.on('gyro', function(data) {
		// le renvoie à tous les autres clients connectés
		// (faudra le changer, avec le systeme de code de dadagafa pour les faire marcher par paire)
		socket.broadcast.emit('gyro', data);
	});
})

server.listen(3000);
<|endoftext|>


<commit_before>'use strict';

var Stream = require('stream');
var gutil = require('gulp-util');
var _ = require('lodash');

var PLUGIN_NAME = 'gulp-cordova-app-loader-manifest';

var calManifest = function calManifest(options) {
    options = options || {};

    options.prefixSplit = options.prefixSplit || '/';

    if (!options.load) {
        options.load = ['**'];
    } else if (!(options.load instanceof Array)) {
        options.load = [options.load];
    }

    var manifest = {
        files: {},
        load: _.cloneDeep(options.load),
        root: options.root || './'
    };

    var stream = new Stream.Transform({objectMode: true});

    stream._transform = function (file, unused, done) {
        if (file.isNull() || !file.stat.isFile()) {
            return done();
        }

        if (file.isStream()) {
            this.emit('error', new gutil.PluginError(PLUGIN_NAME, 'Streams are not supported!'));
            return done();
        }

        var hasher = require('crypto').createHash('sha256');
        var filename = encodeURI(file.relative);
        var key = filename.replace(/\//g, '_');
        manifest.files[key] = {
            filename: filename,
            version: hasher.update(file.contents).digest('hex')
        };
        var i, pattern;
        for (i = 0; i < options.load.length; i++) {
            pattern = options.load[i];
            if (pattern.indexOf(filename) > -1) {
                manifest.load.push(pattern.split(options.prefixSplit).pop())
            }
        }

        done();
    };

    stream._flush = function (done) {
        var file = new gutil.File({
            path: 'manifest.json',
            contents: new Buffer(JSON.stringify(manifest, null, 4))
        });
        stream.push(file);
        return done();
    };

    return stream;
};

module.exports = calManifest;
<commit_msg>changed from cloneDeep to clone<commit_after>'use strict';

var Stream = require('stream');
var gutil = require('gulp-util');
var _ = require('lodash');

var PLUGIN_NAME = 'gulp-cordova-app-loader-manifest';

var calManifest = function calManifest(options) {
    options = options || {};

    options.prefixSplit = options.prefixSplit || '/';

    if (!options.load) {
        options.load = ['**'];
    } else if (!(options.load instanceof Array)) {
        options.load = [options.load];
    }

    var manifest = {
        files: {},
        load: _.clone(options.load),
        root: options.root || './'
    };

    var stream = new Stream.Transform({objectMode: true});

    stream._transform = function (file, unused, done) {
        if (file.isNull() || !file.stat.isFile()) {
            return done();
        }

        if (file.isStream()) {
            this.emit('error', new gutil.PluginError(PLUGIN_NAME, 'Streams are not supported!'));
            return done();
        }

        var hasher = require('crypto').createHash('sha256');
        var filename = encodeURI(file.relative);
        var key = filename.replace(/\//g, '_');
        manifest.files[key] = {
            filename: filename,
            version: hasher.update(file.contents).digest('hex')
        };
        var i, pattern;
        for (i = 0; i < options.load.length; i++) {
            pattern = options.load[i];
            if (pattern.indexOf(filename) > -1) {
                manifest.load.push(pattern.split(options.prefixSplit).pop())
            }
        }

        done();
    };

    stream._flush = function (done) {
        var file = new gutil.File({
            path: 'manifest.json',
            contents: new Buffer(JSON.stringify(manifest, null, 4))
        });
        stream.push(file);
        return done();
    };

    return stream;
};

module.exports = calManifest;
<|endoftext|>


<commit_before>var express = require('express');
var pg = require('pg');
var fs = require('fs');

var app = express();

app.use(express.static(__dirname + '/public'));

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

app.post('/receiver', function (request, response) {
	var body = '';
	request.on('data', function (data) {
		body += data;
	});
	request.on('end', function () {
		var data = JSON.parse(body);
		function cb(a, b){
			response.send(a || b);
		}
		pg.connect(process.env.DATABASE_URL, function (err, client, done) {
			client.query("INSERT INTO results VALUES ($1, $2, $3, $4)",
				[data.guid, data.username, data.video, JSON.stringify(data.score)],
				function (err, result) {
				done();
				if (err) {
					cb(err, null);
				} else {
					cb(null, result.rows);
				}
			});
		});
	});
});

app.get('/movies', function (request, response) {
	var movieList = fs.readdirSync("/public/movies");
	response.send(movieList);
});

app.get('/data', function (request, response) {
	pg.connect(process.env.DATABASE_URL, function (err, client, done) {
		client.query('TABLE results;', function (err, result) {
			done();
			if (err) {
				console.error(err);
				response.send("Error " + err);
			} else {
				response.send(result.rows);
			}
		});
	});
})
app.listen(app.get('port'), function () {
	console.log("Node app is running at localhost:" + app.get('port'));
});
<commit_msg>Fix movie lookup<commit_after>var express = require('express');
var pg = require('pg');
var fs = require('fs');

var app = express();

app.use(express.static(__dirname + '/public'));

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

app.post('/receiver', function (request, response) {
	var body = '';
	request.on('data', function (data) {
		body += data;
	});
	request.on('end', function () {
		var data = JSON.parse(body);
		function cb(a, b){
			response.send(a || b);
		}
		pg.connect(process.env.DATABASE_URL, function (err, client, done) {
			client.query("INSERT INTO results VALUES ($1, $2, $3, $4)",
				[data.guid, data.username, data.video, JSON.stringify(data.score)],
				function (err, result) {
				done();
				if (err) {
					cb(err, null);
				} else {
					cb(null, result.rows);
				}
			});
		});
	});
});

app.get('/movies.json', function (request, response) {
	var movieList = fs.readdirSync("/app/public/movies");
	response.send(movieList);
});

app.get('/data', function (request, response) {
	pg.connect(process.env.DATABASE_URL, function (err, client, done) {
		client.query('TABLE results;', function (err, result) {
			done();
			if (err) {
				console.error(err);
				response.send("Error " + err);
			} else {
				response.send(result.rows);
			}
		});
	});
})
app.listen(app.get('port'), function () {
	console.log("Node app is running at localhost:" + app.get('port'));
});
<|endoftext|>