<commit_before>/**
 * Module Dependencies
 */

var SandGrain = require('sand-grain');
var mysql = require('mysql2');

/**
 * Initialize a new `MySQL`.
 *
 * @api public
 */
module.exports = SandGrain.extend({
  name: 'mysql',

  construct: function() {
    this.super();

    this.defaultConfig = require('./default');
    this.version = require('../package').version;
  },

  ///**
  // * Initialize MySQL module
  // *
  // * @param config
  // * @returns {MySQL}
  // */
  //init: function(config) {
  //  this.super(config);
  //
  //  //this.pool = mysql.createPool(this.config);
  //
  //  return this;
  //},

  //shutdown: function(done) {
  //  this.pool.end(done);
  //},

  query: function(query, params, callback) {
    var connection = null;

    if (process.domain) {
      if (process.domain.mysqlConnection) {
        connection = process.domain.mysqlConnection;
      } else {
        connection = process.domain.mysqlConnection = mysql.createConnection(this.config);
      }
    } else {
      connection = mysql.createConnection(this.config)
    }

    connection.execute(query, params, function(err, rows) {
      callback(err, rows);

      if (!process.domain || !process.domain.mysqlConnection) {
        connection.end();
      }
    });

    if (process.domain && process.domain.mysqlConnection) {
      if (!process.domain.res) {
        process.domain.mysqlConnection = null;
      } else {
        process.domain.res.on('finish', function() {
          process.domain.mysqlConnection.end();
          process.domain.mysqlConnection = null;
        })
      }
    }
  }
});<commit_msg>fixed issue with conn closed multiple times<commit_after>/**
 * Module Dependencies
 */

var SandGrain = require('sand-grain');
var mysql = require('mysql2');

/**
 * Initialize a new `MySQL`.
 *
 * @api public
 */
module.exports = SandGrain.extend({
  name: 'mysql',

  construct: function() {
    this.super();

    this.defaultConfig = require('./default');
    this.version = require('../package').version;
  },

  ///**
  // * Initialize MySQL module
  // *
  // * @param config
  // * @returns {MySQL}
  // */
  //init: function(config) {
  //  this.super(config);
  //
  //  //this.pool = mysql.createPool(this.config);
  //
  //  return this;
  //},

  //shutdown: function(done) {
  //  this.pool.end(done);
  //},

  query: function(query, params, callback) {
    var connection = null;

    if (process.domain) {
      if (process.domain.mysqlConnection) {
        connection = process.domain.mysqlConnection;
      } else {
        connection = process.domain.mysqlConnection = mysql.createConnection(this.config);

        if (process.domain.res) {
          process.domain.res.on('finish', function () {
            if (process.domain.mysqlConnection) {
              process.domain.mysqlConnection.end();
              process.domain.mysqlConnection = null;
            }
          });
        } else {
          process.domain.mysqlConnection = null;
        }
      }
    } else {
      connection = mysql.createConnection(this.config)
    }

    connection.execute(query, params, function(err, rows) {
      callback(err, rows);

      if (!process.domain || !process.domain.mysqlConnection) {
        connection.end();
      }
    });

  }
});<|endoftext|>


<commit_before>// es6 runtime requirements
import 'babel-polyfill'

// their code
import express from 'express'
import sockets from 'socket.io'
import { json } from 'body-parser'
import { Server as http } from 'http'
import remail from 'email-regex'
import dom from 'vd'
import cors from 'cors'

// our code
import Slack from './slack'
import invite from './slack-invite'
import badge from './badge'
import splash from './splash'
import iframe from './iframe'
import log from './log'

export default function slackin ({
  token,
  interval = 5000, // jshint ignore:line
  org,
  css,
  coc,
  cors: useCors = true,
  path='/',
  channels,
  emails,
  silent = false // jshint ignore:line,
}){
  // must haves
  if (!token) throw new Error('Must provide a `token`.')
  if (!org) throw new Error('Must provide an `org`.')

  if (channels) {
    // convert to an array
    channels = channels.split(',').map((channel) => {
      // sanitize channel name
      if ('#' === channel[0]) return channel.substr(1)
      return channel
    })
  }

  if (emails) {
    // convert to an array
    emails = emails.split(',')
  }

  // setup app
  let app = express()
  let router = express.Router()
  let srv = http(app)
  srv.app = app

  let assets = __dirname + '/assets'

  // fetch data
  let slack = new Slack({ token, interval, org })

  slack.setMaxListeners(Infinity)

  // capture stats
  log(slack, silent)

  // middleware for waiting for slack
  router.use((req, res, next) => {
    if (slack.ready) return next()
    slack.once('ready', next)
  })

  if (useCors) {
    app.options('https://lemonlabs.io', cors())
    app.use(cors())
  }

  // splash page
  router.get('/', (req, res) => {
    let { name, logo } = slack.org
    let { active, total } = slack.users
    if (!name) return res.send(404)

    // Generated using http://arthurclemens.github.io/mithril-template-converter/index.html
    let nav = dom("nav.navbar.navbar-default style='padding: 10px 0;'",
      dom(".container",
        [
          dom(".navbar-header.page-scroll",
            [
              dom("button.navbar-toggle data-target='#bs-example-navbar-collapse-1' data-toggle='collapse' type='button'",
                [
                  dom("span.sr-only",
                    "Toggle navigation"
                  ),
                  dom("span.icon-bar"),
                  dom("span.icon-bar"),
                  dom("span.icon-bar")
                ]
              )
            ]
          ),
          dom(".collapse.navbar-collapse id='bs-example-navbar-collapse-1'",
            dom("ul.nav.navbar-nav.navbar-right",
              [
                dom("li.hidden",
                  dom("a href='#page-top'")
                ),
                dom("li.page-scroll",
                  dom("a href='//lemonlabs.io/#whatwedo'",
                    "What we do"
                  )
                ),
                dom("li.page-scroll",
                  dom("a href='//lemonlabs.io/#team'",
                    "The team"
                  )
                ),
                dom("li.page-scroll",
                  dom("a href='//lemonlabs.io/#contact'",
                    "Contact"
                  )
                )
              ]
            )
          )
        ]
      )
    );

    let footer = dom("footer.text-center",
      [
        dom(".footer-above",
          dom(".container",
            dom(".row",
              [
                dom(".footer-col.col-md-4",
                  [
                    dom("h3", "Lemon Labs Limited"),
                    dom("p", "Fleet, Hampshire")
                  ]
                ),
                dom(".footer-col.col-md-4",
                  [
                    dom("h3",
                      "Around the Web"
                    ),
                    dom("ul.list-inline",
                      [
                        dom("li",
                          dom("a.btn-social.btn-outline href='http://github.com/lemonlabsuk'",
                            dom("i.fa.fa-fw.fa-github")
                          )
                        ),
                        dom("li",
                          dom("a.btn-social.btn-outline href='https://www.linkedin.com/company/lemon-labs-limited'",
                            dom("i.fa.fa-fw.fa-linkedin")
                          )
                        )
                      ]
                    )
                  ]
                ),
                dom(".footer-col.col-md-4",
                  [
                    dom("h3",
                      "Credits"
                    ),
                    dom("p",
                      [
                        "Modified version of the ",
                        dom("a href='https://github.com/jeromelachaud/freelancer-theme/blob/master/LICENCE'",
                          "Apache 2.0"
                        ),
                        " licensed ",
                        dom("a href='https://github.com/jeromelachaud/freelancer-theme/'",
                          "freelancer"
                        ),
                        " theme for Jekyll"
                      ]
                    )
                  ]
                )
              ]
            )
          )
        ),
        dom(".footer-below",
          dom(".container",
            dom(".row style='margin-bottom:10px;'", dom(".col-lg-12", 'Powered by ', dom('a href=http://rauchg.com/slackin target=_blank', 'slackin'))),
            dom(".row", dom(".col-lg-12", "Copyright © Lemon Labs Limited 2017"))
          )
        ),
        dom('script src="//lemonlabs.io/js/jquery-1.11.0.js"'),
        dom('script src="//lemonlabs.io/js/bootstrap.min.js"'),
        dom('script src="//lemonlabs.io/js/freelancer.js"')
      ]
    )

    let page = dom('html',
      dom('head',
        dom('title',
          'Join ', name, ' on Slack!'
        ),
        dom('meta name=viewport content="width=device-width,initial-scale=1.0,minimum-scale=1.0,user-scalable=no"'),
        dom('link rel="shortcut icon" href=//lemonlabs.io/img/favicon.ico'),
        css && dom('link rel=stylesheet', { href: css }),
        dom('link rel="stylesheet" href="//lemonlabs.io/css/font-awesome/css/font-awesome.min.css"'),
        dom('link href="//fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"'),
        dom('link href="//fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css"'),
        dom('link rel="stylesheet" href="//lemonlabs.io/style.css"')
      ),
      nav,
      splash({ coc, path, css, name, org, logo, channels, active, total }),
      footer
    )
    res.type('html')
    res.send(page.toHTML())
  })

  router.get('/data', (req, res) => {
    let { name, logo } = slack.org
    let { active, total } = slack.users
    res.send({
      name,
      org,
      coc,
      logo,
      channels,
      active,
      total
    })
  })

  // static files
  router.use('/assets', express.static(assets))

  // invite endpoint
  router.post('/invite', json(), (req, res, next) => {
    let chanId
    if (channels) {
      let channel = req.body.channel
      if (!channels.includes(channel)) {
        return res
        .status(400)
        .json({ msg: 'Not a permitted channel' })
      }
      chanId = slack.getChannelId(channel)
      if (!chanId) {
        return res
        .status(400)
        .json({ msg: `Channel not found "${channel}"` })
      }
    }

    let email = req.body.email

    if (!email) {
      return res
      .status(400)
      .json({ msg: 'No email provided' })
    }

    if (!remail().test(email)) {
      return res
      .status(400)
      .json({ msg: 'Invalid email' })
    }

    // Restricting email invites?
    if (emails && emails.indexOf(email) === -1) {
      return res
      .status(400)
      .json({ msg: 'Your email is not on the accepted email list' })
    }

    if (coc && '1' != req.body.coc) {
      return res
      .status(400)
      .json({ msg: 'Agreement to CoC is mandatory' })
    }

    invite({ token, org, email, channel: chanId }, err => {
      if (err) {
        if (err.message === `Sending you to Slack...`) {
          return res
          .status(303)
          .json({ msg: err.message, redirectUrl: `https://${org}.slack.com` })
        }

        return res
        .status(400)
        .json({ msg: err.message })
      }

      res
      .status(200)
      .json({ msg: 'WOOT. Check your email!' })
    })
  })

  // iframe
  router.get('/iframe', (req, res) => {
    let large = 'large' in req.query
    let { active, total } = slack.users
    res.type('html')
    res.send(iframe({ path, active, total, large }).toHTML())
  })

  router.get('/iframe/dialog', (req, res) => {
    let large = 'large' in req.query
    let { name } = slack.org
    let { active, total } = slack.users
    if (!name) return res.send(404)
    let dom = splash({ coc, path, name, org, channels, active, total, large, iframe: true })
    res.type('html')
    res.send(dom.toHTML())
  })

  router.get('/.well-known/acme-challenge/:id', (req, res) => {
    res.send(process.env.LETSENCRYPT_CHALLENGE)
  })

  // badge js
  router.use('/slackin.js', express.static(assets + '/badge.js'))

  // badge rendering
  router.get('/badge.svg', (req, res) => {
    res.type('svg')
    res.set('Cache-Control', 'max-age=0, no-cache')
    res.set('Pragma', 'no-cache')
    res.send(badge(slack.users).toHTML())
  })

  // realtime
  var io = sockets(srv, {path: path + 'socket.io'})
  io.set('origins', 'https://lemonlabs.io:*')
  io.on('connection', socket => {
    socket.emit('data', slack.users)
    let change = (key, val) => socket.emit(key, val)
    slack.on('change', change)
    socket.on('disconnect', () => {
      slack.removeListener('change', change)
    })
  })

  app.use(path, router);

  return srv
}
<commit_msg>Add 'open source' link to the nav bar<commit_after>// es6 runtime requirements
import 'babel-polyfill'

// their code
import express from 'express'
import sockets from 'socket.io'
import { json } from 'body-parser'
import { Server as http } from 'http'
import remail from 'email-regex'
import dom from 'vd'
import cors from 'cors'

// our code
import Slack from './slack'
import invite from './slack-invite'
import badge from './badge'
import splash from './splash'
import iframe from './iframe'
import log from './log'

export default function slackin ({
  token,
  interval = 5000, // jshint ignore:line
  org,
  css,
  coc,
  cors: useCors = true,
  path='/',
  channels,
  emails,
  silent = false // jshint ignore:line,
}){
  // must haves
  if (!token) throw new Error('Must provide a `token`.')
  if (!org) throw new Error('Must provide an `org`.')

  if (channels) {
    // convert to an array
    channels = channels.split(',').map((channel) => {
      // sanitize channel name
      if ('#' === channel[0]) return channel.substr(1)
      return channel
    })
  }

  if (emails) {
    // convert to an array
    emails = emails.split(',')
  }

  // setup app
  let app = express()
  let router = express.Router()
  let srv = http(app)
  srv.app = app

  let assets = __dirname + '/assets'

  // fetch data
  let slack = new Slack({ token, interval, org })

  slack.setMaxListeners(Infinity)

  // capture stats
  log(slack, silent)

  // middleware for waiting for slack
  router.use((req, res, next) => {
    if (slack.ready) return next()
    slack.once('ready', next)
  })

  if (useCors) {
    app.options('https://lemonlabs.io', cors())
    app.use(cors())
  }

  // splash page
  router.get('/', (req, res) => {
    let { name, logo } = slack.org
    let { active, total } = slack.users
    if (!name) return res.send(404)

    // Generated using http://arthurclemens.github.io/mithril-template-converter/index.html
    let nav = dom("nav.navbar.navbar-default style='padding: 10px 0;'",
      dom(".container",
        [
          dom(".navbar-header.page-scroll",
            [
              dom("button.navbar-toggle data-target='#bs-example-navbar-collapse-1' data-toggle='collapse' type='button'",
                [
                  dom("span.sr-only",
                    "Toggle navigation"
                  ),
                  dom("span.icon-bar"),
                  dom("span.icon-bar"),
                  dom("span.icon-bar")
                ]
              )
            ]
          ),
          dom(".collapse.navbar-collapse id='bs-example-navbar-collapse-1'",
            dom("ul.nav.navbar-nav.navbar-right",
              [
                dom("li.hidden",
                  dom("a href='#page-top'")
                ),
                dom("li.page-scroll",
                  dom("a href='//lemonlabs.io/#whatwedo'",
                    "What we do"
                  )
                ),
                dom("li.page-scroll",
                  dom("a href='//lemonlabs.io/#team'",
                    "The team"
                  )
                ),
                dom("li",
                  dom("a href='//lemonlabs.io/opensource/'",
                    "Open Source"
                  )
                ),
                dom("li.page-scroll",
                  dom("a href='//lemonlabs.io/#contact'",
                    "Contact"
                  )
                )
              ]
            )
          )
        ]
      )
    );

    let footer = dom("footer.text-center",
      [
        dom(".footer-above",
          dom(".container",
            dom(".row",
              [
                dom(".footer-col.col-md-4",
                  [
                    dom("h3", "Lemon Labs Limited"),
                    dom("p", "Fleet, Hampshire")
                  ]
                ),
                dom(".footer-col.col-md-4",
                  [
                    dom("h3",
                      "Around the Web"
                    ),
                    dom("ul.list-inline",
                      [
                        dom("li",
                          dom("a.btn-social.btn-outline href='http://github.com/lemonlabsuk'",
                            dom("i.fa.fa-fw.fa-github")
                          )
                        ),
                        dom("li",
                          dom("a.btn-social.btn-outline href='https://www.linkedin.com/company/lemon-labs-limited'",
                            dom("i.fa.fa-fw.fa-linkedin")
                          )
                        )
                      ]
                    )
                  ]
                ),
                dom(".footer-col.col-md-4",
                  [
                    dom("h3",
                      "Credits"
                    ),
                    dom("p",
                      [
                        "Modified version of the ",
                        dom("a href='https://github.com/jeromelachaud/freelancer-theme/blob/master/LICENCE'",
                          "Apache 2.0"
                        ),
                        " licensed ",
                        dom("a href='https://github.com/jeromelachaud/freelancer-theme/'",
                          "freelancer"
                        ),
                        " theme for Jekyll"
                      ]
                    )
                  ]
                )
              ]
            )
          )
        ),
        dom(".footer-below",
          dom(".container",
            dom(".row style='margin-bottom:10px;'", dom(".col-lg-12", 'Powered by ', dom('a href=http://rauchg.com/slackin target=_blank', 'slackin'))),
            dom(".row", dom(".col-lg-12", "Copyright © Lemon Labs Limited 2017"))
          )
        ),
        dom('script src="//lemonlabs.io/js/jquery-1.11.0.js"'),
        dom('script src="//lemonlabs.io/js/bootstrap.min.js"'),
        dom('script src="//lemonlabs.io/js/freelancer.js"')
      ]
    )

    let page = dom('html',
      dom('head',
        dom('title',
          'Join ', name, ' on Slack!'
        ),
        dom('meta name=viewport content="width=device-width,initial-scale=1.0,minimum-scale=1.0,user-scalable=no"'),
        dom('link rel="shortcut icon" href=//lemonlabs.io/img/favicon.ico'),
        css && dom('link rel=stylesheet', { href: css }),
        dom('link rel="stylesheet" href="//lemonlabs.io/css/font-awesome/css/font-awesome.min.css"'),
        dom('link href="//fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"'),
        dom('link href="//fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css"'),
        dom('link rel="stylesheet" href="//lemonlabs.io/style.css"')
      ),
      nav,
      splash({ coc, path, css, name, org, logo, channels, active, total }),
      footer
    )
    res.type('html')
    res.send(page.toHTML())
  })

  router.get('/data', (req, res) => {
    let { name, logo } = slack.org
    let { active, total } = slack.users
    res.send({
      name,
      org,
      coc,
      logo,
      channels,
      active,
      total
    })
  })

  // static files
  router.use('/assets', express.static(assets))

  // invite endpoint
  router.post('/invite', json(), (req, res, next) => {
    let chanId
    if (channels) {
      let channel = req.body.channel
      if (!channels.includes(channel)) {
        return res
        .status(400)
        .json({ msg: 'Not a permitted channel' })
      }
      chanId = slack.getChannelId(channel)
      if (!chanId) {
        return res
        .status(400)
        .json({ msg: `Channel not found "${channel}"` })
      }
    }

    let email = req.body.email

    if (!email) {
      return res
      .status(400)
      .json({ msg: 'No email provided' })
    }

    if (!remail().test(email)) {
      return res
      .status(400)
      .json({ msg: 'Invalid email' })
    }

    // Restricting email invites?
    if (emails && emails.indexOf(email) === -1) {
      return res
      .status(400)
      .json({ msg: 'Your email is not on the accepted email list' })
    }

    if (coc && '1' != req.body.coc) {
      return res
      .status(400)
      .json({ msg: 'Agreement to CoC is mandatory' })
    }

    invite({ token, org, email, channel: chanId }, err => {
      if (err) {
        if (err.message === `Sending you to Slack...`) {
          return res
          .status(303)
          .json({ msg: err.message, redirectUrl: `https://${org}.slack.com` })
        }

        return res
        .status(400)
        .json({ msg: err.message })
      }

      res
      .status(200)
      .json({ msg: 'WOOT. Check your email!' })
    })
  })

  // iframe
  router.get('/iframe', (req, res) => {
    let large = 'large' in req.query
    let { active, total } = slack.users
    res.type('html')
    res.send(iframe({ path, active, total, large }).toHTML())
  })

  router.get('/iframe/dialog', (req, res) => {
    let large = 'large' in req.query
    let { name } = slack.org
    let { active, total } = slack.users
    if (!name) return res.send(404)
    let dom = splash({ coc, path, name, org, channels, active, total, large, iframe: true })
    res.type('html')
    res.send(dom.toHTML())
  })

  router.get('/.well-known/acme-challenge/:id', (req, res) => {
    res.send(process.env.LETSENCRYPT_CHALLENGE)
  })

  // badge js
  router.use('/slackin.js', express.static(assets + '/badge.js'))

  // badge rendering
  router.get('/badge.svg', (req, res) => {
    res.type('svg')
    res.set('Cache-Control', 'max-age=0, no-cache')
    res.set('Pragma', 'no-cache')
    res.send(badge(slack.users).toHTML())
  })

  // realtime
  var io = sockets(srv, {path: path + 'socket.io'})
  io.set('origins', 'https://lemonlabs.io:*')
  io.on('connection', socket => {
    socket.emit('data', slack.users)
    let change = (key, val) => socket.emit(key, val)
    slack.on('change', change)
    socket.on('disconnect', () => {
      slack.removeListener('change', change)
    })
  })

  app.use(path, router);

  return srv
}
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Sun Mar 23 2014 16:10:54 GMT+0000 (GMT)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['mocha'],

    // list of files / patterns to load in the browser
    files: [
      'node_modules/typescript/bin/typescript.js',
      'lib/libd.js',
      'lib/date.format.js',
      'test/gen/bundle-tests.js'
    ],

    // list of files to exclude
    exclude: [

    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['dots', 'osx'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Firefox'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};

// vim: set ts=2 sw=2 sts=2 et :
<commit_msg>Add longer batch delay to karma<commit_after>// Karma configuration
// Generated on Sun Mar 23 2014 16:10:54 GMT+0000 (GMT)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['mocha'],

    // list of files / patterns to load in the browser
    files: [
      'node_modules/typescript/bin/typescript.js',
      'lib/libd.js',
      'lib/date.format.js',
      'test/gen/bundle-tests.js'
    ],

    // list of files to exclude
    exclude: [

    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['dots', 'osx'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,
    // Increase the batch delay
    autoWatchBatchDelay: 500,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Firefox'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};

// vim: set ts=2 sw=2 sts=2 et :
<|endoftext|>


<commit_before>var cluster = require('cluster');
var menubar = require('menubar');
var path = require('path');
var dir = path.join(process.cwd(), 'public');
var icon = path.join(process.cwd(), 'icon.png');
var screencap = require('adb-screencap').default;
var DEBUG = true;
var electron = require('electron');
var ipcMain = electron.ipcMain;
var mb = menubar({
  dir:dir, width:360, height:540,
  "always-on-top": true, icon: icon
});
mb.on('after-create-window', function(){
  if(DEBUG) mb.window.openDevTools();
});
ipcMain.on("screencap", function(ev, arg){
  screencap(function(err, path){
    console.log(path);
    ev.sender.send("screencap-ready", path);
  });
});
<commit_msg>remove console.log<commit_after>var cluster = require('cluster');
var menubar = require('menubar');
var path = require('path');
var dir = path.join(process.cwd(), 'public');
var icon = path.join(process.cwd(), 'icon.png');
var screencap = require('adb-screencap').default;
var DEBUG = true;
var electron = require('electron');
var ipcMain = electron.ipcMain;
var mb = menubar({
  dir:dir, width:360, height:540,
  "always-on-top": true, icon: icon
});
mb.on('after-create-window', function(){
  if(DEBUG) mb.window.openDevTools();
});
ipcMain.on("screencap", function(ev, arg){
  screencap(function(err, path){
    ev.sender.send("screencap-ready", path);
  });
});
<|endoftext|>


<commit_before>/*!
* Turkuaz Framework v1.0
* www.turkuazcss.com
*/

/*!
*    Turkuaz Framework - JavaScript Kod Duzeni
*
*   1. Form
*   2. Menu
*   3. Notlar
*
*/

/* ============= 1. Form */

// Radio ve checkbox haric diger inputlari ve textarea'yi degiskene atar.
$formEtiketleri = "input[type=text],input[type=password],input[type=email],input[type=url],input[type=date],input[type=tel],input[type=number],input[type=search],textarea";

// Inputlarin Labellerinin Ilk Hareketleri
$($formEtiketleri).focus(function(){
    //inputlara ve textarea'ya imlec geldiginde bu tag'lara 'aktif dolu' sinifini ekler ve labeller uste gecer.
    $(this).addClass("aktif dolu");
});

// Input Labellerinin Sonraki Hareketleri
$($formEtiketleri).focusout(function(){
    //inputtan veya textarea'dan ayrilindiginda icerisinde yazi yoksa 'dolu' sinifini kaldirir ve label alta gecer, yazi varsa kaldirmaz.
    if($(this).val() == ""){
        $(this).removeClass("dolu");
    }
    //inputtan veya textarea'dan ayrilindiginda aktif class'ini kaldirir.
    $(this).removeClass("aktif");
});

/* ============= 2. Menu */

// Menuyu Acar
$("nav.menu>img.logo").click(function(){
    //mobil menuyu acmak icin butona basilinca butonu gizler.
    $(this).hide();
    //menuyu 0 left'e getirir (eskisi left:-240px) yani mobil menu gorunur.
    $(this).parent().animate({left:"0"});
    //body'e karart divini ekler ve menu harici her yeri karartir.
    $("body").append("

");
});

// Menuyu Gizler
$("body").on('click', '.karart', function(){
    //menuyu 240px sola tasir yani gizler.
    $("nav.menu").animate({left:"-240px"});
    //karart divini kaldirir.
    $(".karart").remove();
    //400 milisaniye sonra logoyu gosterir.
    $("nav.menu>img.logo").delay(400).fadeIn();
});

// Acilir Menulerin Oklari
//menudeki li'lerin icerisinde alt menu var ise o li'ye 'acilir' class'ini ekler ve sagina minik bir ok gelir.
$("nav.menu ul li").find("ul li a").parent().parent().parent().addClass("acilir");

// Akordiyon Menu
// Mobile menu de hover kalkar akkordiyon devreye girer

$(".acilir").click(function() {

    var lisayisi = $(this).find("li").length;
    var yukseklik = lisayisi * 50;

    $(this).find("ul").css({
        "height": yukseklik + "px",
        "position": "relative",
        "width": "100%"
    }).slideToggle("slow").parent().siblings(".acilir").find("ul:visible").slideUp("fast");;
});

/* ============= 3. Notlar */

// Notlara Kapatma Butonu Getirir
//not class'ina ait tag'lari kapatmak icin sag ustune 'x' butonunu ekler.
$("div.not").append("×");

// Notlarin Kaldirilmasi
//'x' butonuna basinca o notu kaldirir.
$("div.not span.kaldir").click(function(){
    $(this).parent().remove();
});
<commit_msg>JS düzenlemeleri<commit_after>/*!
* Turkuaz Framework v1.0
* www.turkuazcss.com
*/

/*!
*    Turkuaz Framework - JavaScript Kod Duzeni
*
*   1. Form
*   2. Menu
*   3. Notlar
*
*/

/* ============= 1. Form */

// Radio ve checkbox haric diger inputlari ve textarea'yi degiskene atar.
$formEtiketleri = "input[type=text],input[type=password],input[type=email],input[type=url],input[type=date],input[type=tel],input[type=number],input[type=search],textarea";

// Inputlarin Labellerinin Ilk Hareketleri
$($formEtiketleri).focus(function(){
    //inputlara ve textarea'ya imlec geldiginde bu tag'lara 'aktif dolu' sinifini ekler ve labeller uste gecer.
    $(this).addClass("aktif dolu");
});

// Input Labellerinin Sonraki Hareketleri
$($formEtiketleri).focusout(function(){
    //inputtan veya textarea'dan ayrilindiginda icerisinde yazi yoksa 'dolu' sinifini kaldirir ve label alta gecer, yazi varsa kaldirmaz.
    if($(this).val() == ""){
        $(this).removeClass("dolu");
    }
    //inputtan veya textarea'dan ayrilindiginda aktif class'ini kaldirir.
    $(this).removeClass("aktif");
});

/* ============= 2. Menu */

// Menuyu Acar
$("nav.menu>img.logo").click(function(){
    //mobil menuyu acmak icin butona basilinca butonu gizler.
    $(this).hide();
    //menuyu 0 left'e getirir (eskisi left:-240px) yani mobil menu gorunur.
    $(this).parent().animate({left:"0"});
    //body'e karart divini ekler ve menu harici her yeri karartir.
    $("body").append("

");
});

// Menuyu Gizler
$("body").on('click', '.karart', function(){
    //menuyu 240px sola tasir yani gizler.
    $("nav.menu").animate({left:"-240px"});
    //karart divini kaldirir.
    $(".karart").remove();
    //400 milisaniye sonra logoyu gosterir.
    $("nav.menu>img.logo").delay(400).fadeIn();
});

// Acilir Menulerin Oklari
//menudeki li'lerin icerisinde alt menu var ise o li'ye 'acilir' class'ini ekler ve sagina minik bir ok gelir.
$("nav.menu ul li").find("ul li a").parent().parent().parent().addClass("acilir");

// Akordiyon Menu
$("body").on('click', 'nav.menu.mobil ul li.acilir', function(){
    //alt menudeki link sayisina gore ul'nin yuksekligini hesaplar.
    var yukseklik = $(this).find("li").length * 50;
    //alt menuye yukseklik degerini verir.
    $(this).find("ul").css({
        "height": yukseklik + "px"
        //500ms hizinda acilir menuyu gorunur yapar, diger acilir menuleri gizler.
    }).slideToggle("500").parent().siblings(".acilir").find("ul:visible").slideToggle("500");
});

// Mobil Menu
function mobil(){
    if ($(window).width() <= 1000) {
        //cozunurluk 1000px'in altina indiginde menuye mobil sinifini ekler.
        $("nav.menu").addClass("mobil");
    }
    else {
        //cozunurluk 1000px'in ustunde mobil sinifini kaldirir.
        $("nav.menu").removeClass("mobil");
    }
    $("nav.menu ul li.acilir ul").each(function(){
        //cozunurluk degistiginde acilir menuler gizlenir.
        $(this).hide("600");
    });
}

//cozunurluk her degistiginde mobil fonksiyonunu calistir.
mobil(); $(window).resize(function() { mobil(); });

/* ============= 3. Notlar */

// Notlara Kapatma Butonu Getirir
//not class'ina ait tag'lari kapatmak icin sag ustune 'x' butonunu ekler.
$("div.not").append("×");

// Notlarin Kaldirilmasi
//'x' butonuna basinca o notu kaldirir.
$("div.not span.kaldir").click(function(){
    $(this).parent().remove();
});
<|endoftext|>


<commit_before>

var initialBag = JSON.parse(bag);
// console.log(initialBag);

// test dictionary
var dictionary = ["cat", "tree", "rain", "wind"];

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

function Bag() {
  this.bagTiles = initialBag;
};

function Game() {
  this.board = [];
  this.currentPlayer = {};
  this.players = [];
};

function Player(name) {
  this.name = name;
  this.score = 0;
  this.rack = [];
  this.partialWord = [];
  this.currentWord = [];

};

function Tile() {
  this.id;
  this.letter;
  this.letterValue;
};

function Cell(x, y) {
  this.x = x;
  this.y = y;
  this.pointMultiplier;
  this.occupied = false;
  this.tile = {};
}

// function Rack() {
//   this.rackTiles = [];
//   this.needNumber = 7;
// };

Player.prototype.getTilebyId = function (tileId) {
  for (var i = 0; i < this.rack.length; i++) {
   if (this.rack[i].id === tileId) {
     return this.rack[i];
   }
  }
};

Game.prototype.Turn = function (player) {
  this.currentPlayer = player;

    if (this.checkHorizontalPosition()) {
            this.completeHorizontalWord(this.currentPlayer.partialWord);
    }
    if (this.checkVerticalPosition()) {
      this.completeVerticalWord(this.currentPlayer.partialWord);
    }
  if ( this.checkValidWord(this.currentPlayer.completeWord)) {
      countScore();
      console.log(countScore());
  }

}; // TURN function

Game.prototype.generateBoard = function () {
  this.board = [];
  for (var i = 0; i < 15; i++) {
    var array = [];
    for (var j = 0; j < 15; j++) {
      var cell = new Cell (i, j)
      array.push(cell);
    }
    this.board.push(array);
  }
};

Game.prototype.completeHorizontalWord = function (partialWord) {
  var completeWord = [];
  var horizontal = this.board[partialWord[0].y];// take whole horizontal array from board with y coord
  var firstX = partialWord[0].x;
  var lastX = partialWord[partialWord.length-1].x;
  // TODO: sort (cells) partialWord array
  // because a user might not drop in a straightforward order
  for (var i = partialWord[0].x; i <= partialWord[partialWord.length-1].x; i++) {
    if (typeof horizontal[i].tile != 'undefined') {
      completeWord.push(horizontal[i]);
    } else {
      return false;
    }
  }
  // debugger;
  // Check the beginning of horiz array to see if empty
  // also check if we're at the edge of the board
  while ((firstX-1)>=0 && (typeof horizontal[firstX-1].tile != 'undefined')) {
    completeWord.unshift(horizontal[firstX-1]);
    firstX--;
  }
  // Check the end of horiz array to see if empty

  while ((lastX+1<=14)&& (typeof horizontal[lastX+1].tile != 'undefined')) {
    completeWord.push(horizontal[lastX+1]);
    lastX++;
  }
  return completeWord;
};

Game.prototype.completeVerticalWord = function (partialWord) {
  var completeWord = [];
  var xCoord = partialWord[0].x;
  var firstY = partialWord[0].y;
  var lastY = partialWord[partialWord.length-1].y;

  // TODO: sort (cells) partialWord array
  // because a user might not drop in a straightforward order

  for (var i = firstY; i <= lastY; i++) {
    if (typeof this.board[i][xCoord].tile != 'undefined') {
      completeWord.push(this.board[i][xCoord]);
    } else {
      return false;
    }
  }

  while ( (firstY-1)>=0 && (typeof this.board[firstY-1][xCoord].tile != 'undefined')) {
    completeWord.unshift(this.board[firstY-1][xCoord]);
    firstY--;
  }
  while ( (lastY+1<=14) && (typeof this.board[firstY+1][xCoord].tile != 'undefined')) {
    completeWord.push(this.board[firstY+1][xCoord]);
    lastY++;
  }
  return completeWord;
};

Player.prototype.buildPartialWord = function (cell) {
  this.partialWord.push(cell);
  this.removeTilefromRack(cell)
};

Player.prototype.removeTilefromRack = function (cell) {
  var index = this.rack.indexOf(this.getTilebyId(cell.tile.id));
  if (index >= 0) {
  this.rack.splice(index, 1);
  }
};

Player.prototype.playerScore = function (wordScore) {
  return this.score += wordScore;
};

Player.prototype.refillRack = function (initialBag) {
  var needNumber = 7-this.rack.length;
  for (var i = 0; i < needNumber; i++) {
    var currentRandomInt = getRandomInt(0, initialBag.length-1);
    this.rack.push(initialBag[currentRandomInt]);
    initialBag.splice(currentRandomInt, 1);
  };
}

Game.prototype.checkVerticalPosition = function () {
  var checkVertical;
  for (var i = 0; i < this.currentPlayer.partialWord.length-1; i++) {

    if ([i].x === [i+1].x) {
      checkVertical = true;
    } else {
      checkVertical = false;
    }
  }
  return checkVertical;
};

Game.prototype.checkHorizontalPosition = function () {
  var checkHorizontal;

  for (var i = 0; i < this.currentPlayer.partialWord.length-1; i++) {

    if ([i].y === [i+1].y) {
      checkHorizontal = true;
    } else {
      checkHorizontal = false;
    }
  }
  return checkHorizontal;
};

Game.prototype.checkValidWord = function () {
  var wordString ="";

  for (var i = 0; i < this.currentPlayer.currentWord.length; i++) {
    wordString+=this.currentPlayer.currentWord[i].tile.letter;
    console.log("this.currentPlayer.currentWord[i].tile.letter = ",  this.currentPlayer.currentWord[i].tile.letter);

  }
  return dictionary.includes(wordString);

};

Game.prototype.countScore = function() {
  var wordScoreMultiplier = 1;
  var currentWordScore = 0;
  // debugger;
  console.log("this.currentPlayer.currentWord[0] = ", this.currentPlayer.currentWord[0]);
  for (var i = 0; i <= this.currentPlayer.currentWord.length-1; i++) {

    console.log("current letter value = ", this.currentPlayer.currentWord[i].tile.letterValue);

    if (this.currentPlayer.currentWord[i].pointMultiplier === "2L") {
      currentWordScore += this.currentPlayer.currentWord[i].tile.letterValue * 2
    }
    else if (this.currentPlayer.currentWord[i].pointMultiplier === "3L") {
      currentWordScore += this.currentPlayer.currentWord[i].tile.letterValue * 3
    }
    else if (this.currentPlayer.currentWord[i].pointMultiplier === "2W") {
      currentWordScore += this.currentPlayer.currentWord[i].tile.letterValue;
      var wordScoreMultiplier = 2;
    }
    else if (this.currentPlayer.currentWord[i].pointMultiplier === "3W") {
      currentWordScore += this.currentPlayer.currentWord[i].tile.letterValue;
      var wordScoreMultiplier = 3;
    }
    else {
      currentWordScore += this.currentPlayer.currentWord[i].tile.letterValue;
      }
  };
  currentWordScore *= wordScoreMultiplier;
  console.log("currentWordScore = ", currentWordScore);
  return currentWordScore;
};

Game.prototype.startNewGame = function () {
  this.generateBoard();
  var playerOne = new Player ("Tom");
  var playerOne = new Player ("Jarry");
  this.currentPlayer = playerOne;
};
Game.prototype.checkEndGame = function () {
  var emptyRack;
  for (var i = 0; i < this.players.length; i++) {
    if (this.players[i].rack.length<=0) {
      emptyRack = true;
    }
  }
  if (initialBag.length<=0 && emptyRack) {
    return true;
  } else {
    return false;
  }
};

//===========================================================================

////////////////////// USER INTERFACE

$(document).ready(function(){
    var scrabbleGame = new Game();
    scrabbleGame.startNewGame();

//TILE BAG USER INTERFACE
  $(".clickable img").click(function(){
    var currentPlayer = scrabbleGame.currentPlayer;
    currentPlayer.refillRack(initialBag);
    for(i=0; i <= currentPlayer.rack.length-1; i++){
      $("#playerOneRack").append("
" + currentPlayer.rack[i].letter + '' + currentPlayer.rack[i].letterValue.sub() + '' + "

");
      console.log();
    }
    $(".draggable").draggable();
  });
  //DRAG AND DROP SQUARES
  $("div.draggable").draggable( {
    opacity: .4,
    create: function(){
      $(this).data('position',$(this).position())
    },
    cursorAt: {left:15},
    cursor: 'move',
    start: function(){
      $(this).stop(true,true);
    }
  });

  $('div.row').find('.cell').droppable({
    drop:function(event, ui){
      snapToMiddle(ui.draggable,$(this));
      console.log(ui.draggable);
      var inputCellTileString = $(this).droppable(0).attr('id').split('-');
      console.log(inputCellTileString);

      var cellYAxis = parseInt(inputCellTileString[0]);
      var cellXAxis = parseInt(inputCellTileString[1]);
      var cellScoreVariant = inputCellTileString[2];
      var tileId = $(ui.draggable)[0].id;
      var chosenTile = scrabbleGame.currentPlayer.getTilebyId(tileId);

      scrabbleGame.board[cellYAxis][cellXAxis].tile = chosenTile;
      scrabbleGame.board[cellYAxis][cellXAxis].pointMultiplier = cellScoreVariant;

      scrabbleGame.currentPlayer.buildPartialWord(scrabbleGame.board[cellYAxis][cellXAxis]);
      console.log(scrabbleGame.currentPlayer);
      console.log(scrabbleGame.currentPlayer.partialWord);
      // console.log(scrabbleGame.currentPlayer.buildPartialWord(newCell));

      // console.log(scrabbleGame.currentPlayer.buildPartialWord(newCell));

      // console.log("The cell is occupied on the y axis at: " + cellYAxis);
      // console.log("The cell is occupied on the x axis at: " + cellXAxis);
      // console.log("The cell has a score variant of: " + cellScoreVariant);
    }
  });

  function snapToMiddle(dragger, target){
    var offset = target.offset();
    var topMove = (target.outerHeight(true) - dragger.outerHeight(true)) / 2;
    var leftMove= (target.outerWidth(true) - dragger.outerWidth(true)) / 2;
    dragger.offset({ top: topMove + offset.top, left: leftMove + offset.left });
  };

//PLAYER BUTTON INPUT
  $("button#score").click(function(){
    // console.log("SCORE!");

  });

  $("button#reset").click(function(){
    console.log("RESET");
    $("#playerOneRack").empty("");
  });

  $("button#pass").click(function(){
    var turnType = "pass";

    console.log("PASS");
  });
});
<commit_msg>fix horizontal and vertical checkPosition<commit_after>

var initialBag = JSON.parse(bag);
// console.log(initialBag);

// test dictionary
var dictionary = ["cat", "tree", "rain", "wind"];

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

function Bag() {
  this.bagTiles = initialBag;
};

function Game() {
  this.board = [];
  this.currentPlayer = {};
  this.players = [];
};

function Player(name) {
  this.name = name;
  this.score = 0;
  this.rack = [];
  this.partialWord = [];
  this.currentWord = [];

};

function Tile() {
  this.id;
  this.letter;
  this.letterValue;
};

function Cell(x, y) {
  this.x = x;
  this.y = y;
  this.pointMultiplier;
  this.occupied = false;
  this.tile = {};
}

// function Rack() {
//   this.rackTiles = [];
//   this.needNumber = 7;
// };

Player.prototype.getTilebyId = function (tileId) {
  for (var i = 0; i < this.rack.length; i++) {
   if (this.rack[i].id === tileId) {
     return this.rack[i];
   }
  }
};

Game.prototype.Turn = function (player) {
  this.currentPlayer = player;

    if (this.checkHorizontalPosition()) {
            this.completeHorizontalWord(this.currentPlayer.partialWord);
    }
    if (this.checkVerticalPosition()) {
      this.completeVerticalWord(this.currentPlayer.partialWord);
    }
  if ( this.checkValidWord(this.currentPlayer.completeWord)) {
      countScore();
      console.log(countScore());
  }

}; // TURN function

Game.prototype.generateBoard = function () {
  this.board = [];
  for (var i = 0; i < 15; i++) {
    var array = [];
    for (var j = 0; j < 15; j++) {
      var cell = new Cell (i, j)
      array.push(cell);
    }
    this.board.push(array);
  }
};

Game.prototype.completeHorizontalWord = function (partialWord) {
  var completeWord = [];
  var horizontal = this.board[partialWord[0].y];// take whole horizontal array from board with y coord
  var firstX = partialWord[0].x;
  var lastX = partialWord[partialWord.length-1].x;
  // TODO: sort (cells) partialWord array
  // because a user might not drop in a straightforward order
  for (var i = partialWord[0].x; i <= partialWord[partialWord.length-1].x; i++) {
    if (typeof horizontal[i].tile != 'undefined') {
      completeWord.push(horizontal[i]);
    } else {
      return false;
    }
  }
  // debugger;
  // Check the beginning of horiz array to see if empty
  // also check if we're at the edge of the board
  while ((firstX-1)>=0 && (typeof horizontal[firstX-1].tile != 'undefined')) {
    completeWord.unshift(horizontal[firstX-1]);
    firstX--;
  }
  // Check the end of horiz array to see if empty

  while ((lastX+1<=14)&& (typeof horizontal[lastX+1].tile != 'undefined')) {
    completeWord.push(horizontal[lastX+1]);
    lastX++;
  }
  return completeWord;
};

Game.prototype.completeVerticalWord = function (partialWord) {
  var completeWord = [];
  var xCoord = partialWord[0].x;
  var firstY = partialWord[0].y;
  var lastY = partialWord[partialWord.length-1].y;

  // TODO: sort (cells) partialWord array
  // because a user might not drop in a straightforward order

  for (var i = firstY; i <= lastY; i++) {
    if (typeof this.board[i][xCoord].tile != 'undefined') {
      completeWord.push(this.board[i][xCoord]);
    } else {
      return false;
    }
  }

  while ( (firstY-1)>=0 && (typeof this.board[firstY-1][xCoord].tile != 'undefined')) {
    completeWord.unshift(this.board[firstY-1][xCoord]);
    firstY--;
  }
  while ( (lastY+1<=14) && (typeof this.board[firstY+1][xCoord].tile != 'undefined')) {
    completeWord.push(this.board[firstY+1][xCoord]);
    lastY++;
  }
  return completeWord;
};

Player.prototype.buildPartialWord = function (cell) {
  this.partialWord.push(cell);
  this.removeTilefromRack(cell)
};

Player.prototype.removeTilefromRack = function (cell) {
  var index = this.rack.indexOf(this.getTilebyId(cell.tile.id));
  if (index >= 0) {
  this.rack.splice(index, 1);
  }
};

Player.prototype.playerScore = function (wordScore) {
  return this.score += wordScore;
};

Player.prototype.refillRack = function (initialBag) {
  var needNumber = 7-this.rack.length;
  for (var i = 0; i < needNumber; i++) {
    var currentRandomInt = getRandomInt(0, initialBag.length-1);
    this.rack.push(initialBag[currentRandomInt]);
    initialBag.splice(currentRandomInt, 1);
  };
}

Game.prototype.checkHorizontalPosition = function () {
  // debugger;
  var checkHorizontal;
  for (var i = 0; i < this.currentPlayer.partialWord.length-1; i++) {
    if (this.currentPlayer.partialWord[i].x === this.currentPlayer.partialWord[i+1].x) {
      checkHorizontal = true;
    } else {
      checkHorizontal = false;
    }
  }
  return checkHorizontal;
};

Game.prototype.checkVerticalPosition = function () {
  var checkVertical;
  for (var i = 0; i < this.currentPlayer.partialWord.length-1; i++) {
    if (this.currentPlayer.partialWord[i].y === this.currentPlayer.partialWord[i+1].y) {
      checkVertical = true;
    } else {
      checkVertical = false;
    }
  }
  return checkVertical;
};

Game.prototype.checkValidWord = function () {
  var wordString ="";

  for (var i = 0; i < this.currentPlayer.currentWord.length; i++) {
    wordString+=this.currentPlayer.currentWord[i].tile.letter;
    console.log("this.currentPlayer.currentWord[i].tile.letter = ",  this.currentPlayer.currentWord[i].tile.letter);

  }
  return dictionary.includes(wordString);

};

Game.prototype.countScore = function() {
  var wordScoreMultiplier = 1;
  var currentWordScore = 0;
  // debugger;
  console.log("this.currentPlayer.currentWord[0] = ", this.currentPlayer.currentWord[0]);
  for (var i = 0; i <= this.currentPlayer.currentWord.length-1; i++) {

    console.log("current letter value = ", this.currentPlayer.currentWord[i].tile.letterValue);

    if (this.currentPlayer.currentWord[i].pointMultiplier === "2L") {
      currentWordScore += this.currentPlayer.currentWord[i].tile.letterValue * 2
    }
    else if (this.currentPlayer.currentWord[i].pointMultiplier === "3L") {
      currentWordScore += this.currentPlayer.currentWord[i].tile.letterValue * 3
    }
    else if (this.currentPlayer.currentWord[i].pointMultiplier === "2W") {
      currentWordScore += this.currentPlayer.currentWord[i].tile.letterValue;
      var wordScoreMultiplier = 2;
    }
    else if (this.currentPlayer.currentWord[i].pointMultiplier === "3W") {
      currentWordScore += this.currentPlayer.currentWord[i].tile.letterValue;
      var wordScoreMultiplier = 3;
    }
    else {
      currentWordScore += this.currentPlayer.currentWord[i].tile.letterValue;
      }
  };
  currentWordScore *= wordScoreMultiplier;
  console.log("currentWordScore = ", currentWordScore);
  return currentWordScore;
};

Game.prototype.startNewGame = function () {
  this.generateBoard();
  var playerOne = new Player ("Tom");
  var playerOne = new Player ("Jarry");
  this.currentPlayer = playerOne;
};
Game.prototype.checkEndGame = function () {
  var emptyRack;
  for (var i = 0; i < this.players.length; i++) {
    if (this.players[i].rack.length<=0) {
      emptyRack = true;
    }
  }
  if (initialBag.length<=0 && emptyRack) {
    return true;
  } else {
    return false;
  }
};

//===========================================================================

////////////////////// USER INTERFACE

$(document).ready(function(){
    var scrabbleGame = new Game();
    scrabbleGame.startNewGame();

//TILE BAG USER INTERFACE
  $(".clickable img").click(function(){
    var currentPlayer = scrabbleGame.currentPlayer;
    currentPlayer.refillRack(initialBag);
    for(i=0; i <= currentPlayer.rack.length-1; i++){
      $("#playerOneRack").append("
" + currentPlayer.rack[i].letter + '' + currentPlayer.rack[i].letterValue.sub() + '' + "

");
      console.log();
    }
    $(".draggable").draggable();
  });
  //DRAG AND DROP SQUARES
  $("div.draggable").draggable( {
    opacity: .4,
    create: function(){
      $(this).data('position',$(this).position())
    },
    cursorAt: {left:15},
    cursor: 'move',
    start: function(){
      $(this).stop(true,true);
    }
  });

  $('div.row').find('.cell').droppable({
    drop:function(event, ui){
      snapToMiddle(ui.draggable,$(this));
      console.log(ui.draggable);
      var inputCellTileString = $(this).droppable(0).attr('id').split('-');
      console.log(inputCellTileString);

      var cellYAxis = parseInt(inputCellTileString[0]);
      var cellXAxis = parseInt(inputCellTileString[1]);
      var cellScoreVariant = inputCellTileString[2];
      var tileId = $(ui.draggable)[0].id;
      var chosenTile = scrabbleGame.currentPlayer.getTilebyId(tileId);

      scrabbleGame.board[cellYAxis][cellXAxis].tile = chosenTile;
      scrabbleGame.board[cellYAxis][cellXAxis].pointMultiplier = cellScoreVariant;

      scrabbleGame.currentPlayer.buildPartialWord(scrabbleGame.board[cellYAxis][cellXAxis]);
      console.log(scrabbleGame.currentPlayer);
      console.log(scrabbleGame.currentPlayer.partialWord);
    }
  });

  function snapToMiddle(dragger, target){
    var offset = target.offset();
    var topMove = (target.outerHeight(true) - dragger.outerHeight(true)) / 2;
    var leftMove= (target.outerWidth(true) - dragger.outerWidth(true)) / 2;
    dragger.offset({ top: topMove + offset.top, left: leftMove + offset.left });
  };

//PLAYER BUTTON INPUT
  $("button#score").click(function(){
    // console.log("SCORE!");
    console.log(scrabbleGame.checkVerticalPosition());
    console.log(scrabbleGame.checkHorizontalPosition());

  });

  $("button#reset").click(function(){
    console.log("RESET");
    $("#playerOneRack").empty("");
  });

  $("button#pass").click(function(){
    var turnType = "pass";

    console.log("PASS");
  });
});
<|endoftext|>


<commit_before>// Mocha tests
// Note - currently the checks rely upon checking the

var expect    = require("chai").expect;
var PelcoD_Decoder = require("../pelcod_decoder.js");

describe("Pelco D Decoder", function() {

  describe("Test Checksum", function() {
    it("tests checksum", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var bytes = [0xFF,0x42,0x42,0x42,0x42,0x42,0x42];
      var buf = new Buffer(bytes);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test Cam 1 Pan Left", function() {
    it("tests Pan Left", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var bytes = [0xFF,0x01,0x00,0x04,0x20,0x00,0x25];
      var buf = new Buffer(bytes);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test Cam 1 Pan Right", function() {
    it("tests Pan right", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var bytes = [0xFF,0x01,0x00,0x02,0x20,0x00,0x23];
      var buf = new Buffer(bytes);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test Cam 1 Up", function() {
    it("tests up", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var buf = new Buffer([0xFF,0x01,0x00,0x08,0x00,0x20,0x29]);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test Cam 1 Down", function() {
    it("tests down", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var buf = new Buffer([0xFF,0x01,0x00,0x10,0x00,0x20,0x31]);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test Cam 1 Stop", function() {
    it("tests stop", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var buf = new Buffer([0xFF,0x01,0x00,0x00,0x00,0x00,0x01]);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test Cam 1 Iris Open", function() {
    it("tests iris open", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var buf = new Buffer([0xFF,0x01,0x02,0x00,0x00,0x00,0x03]);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test Cam 1 Iris Close", function() {
    it("tests iris close", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var buf = new Buffer([0xFF,0x01,0x04,0x00,0x00,0x00,0x05]);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test Cam 1 Focus Near", function() {
    it("tests focus near", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var buf = new Buffer([0xFF,0x01,0x01,0x00,0x00,0x00,0x02]);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test Cam 1 Focus Far", function() {
    it("tests focus far", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var buf = new Buffer([0xFF,0x01,0x00,0x80,0x00,0x00,0x81]);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test Cam 1 Zoom in", function() {
    it("tests Zoom in", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var buf = new Buffer([0xFF,0x01,0x00,0x20,0x00,0x00,0x21]);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test Cam 1 Zoom Out", function() {
    it("tests Zoom Out", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var buf = new Buffer([0xFF,0x01,0x00,0x40,0x00,0x00,0x41]);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test Extended Command Coverage", function() {
    it("tests extended commands", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      // Aux On
      var buf = new Buffer([0xFF,0x01,0x00,0x09,0x00,0x05,0x0F]);
      pelcod_decoder.processBuffer(buf);

      // Aux Off
      var buf = new Buffer([0xFF,0x01,0x00,0x0B,0x00,0x05,0x11]);
      pelcod_decoder.processBuffer(buf);

      // Set Preset
      var buf = new Buffer([0xFF,0x01,0x00,0x03,0x00,0x01,0x05]);
      pelcod_decoder.processBuffer(buf);

      // Goto Preset
      var buf = new Buffer([0xFF,0x01,0x00,0x07,0x00,0x01,0x09]);
      pelcod_decoder.processBuffer(buf);

      // Clear Preset
      var buf = new Buffer([0xFF,0x01,0x00,0x05,0x00,0x01,0x07]);
      pelcod_decoder.processBuffer(buf);

      // Learn Tour
      var buf = new Buffer([0xFF,0x01,0x00,0x1F,0x00,0x00,0x20]);
      pelcod_decoder.processBuffer(buf);

      // Stop Learning the tour
      var buf = new Buffer([0xFF,0x01,0x00,0x21,0x00,0x00,0x22]);
      pelcod_decoder.processBuffer(buf);

      // Start Tour
      var buf = new Buffer([0xFF,0x01,0x00,0x23,0x00,0x00,0x24]);
      pelcod_decoder.processBuffer(buf);

      // Set Zoom Speed
      var buf = new Buffer([0xFF,0x01,0x00,0x25,0x00,0x03,0x29]);
      pelcod_decoder.processBuffer(buf);

      // Unknown extended command (with valid checksum)
      var buf = new Buffer([0xFF,0x01,0x00,0x01,0x00,0x01,0x03]);
      pelcod_decoder.processBuffer(buf);

      // Set left and right, up and down, zoom in and zoom out, iris open and iris close, focus near and focus far ALL AT SAME TIME
      var buf = new Buffer([0xFF,0x01,0xFF,0xFE,0x00,0x01,0xFF]);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test byte cache with split bytes (Pan Left)", function() {
    it("tests split command", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var bytes1 = [0xFF,0x01,0x00,0x04];
      var bytes2 = [0x20,0x00,0x25];
      var buf1 = new Buffer(bytes1);
      var buf2 = new Buffer(bytes2);
      pelcod_decoder.processBuffer(buf1);
      pelcod_decoder.processBuffer(buf2);
    });
  });

  describe("Test byte cache with Pan Left and Stop", function() {
    it("tests multiple commands", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var bytes = [0xFF,0x01,0x00,0x04,0x20,0x00,0x25,0xFF,0x01,0x00,0x00,0x00,0x00,0x01];
      var buf = new Buffer(bytes);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test byte cache with garbage then real command (stop)", function() {
    it("tests garbage then data", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var bytes = [0x01,0x02,0x03,0xFF,0x01,0x00,0x00,0x00,0x00,0x01];
      var buf = new Buffer(bytes);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Pelco P Test Pan Left", function() {
    it("tests Pan Left", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var bytes = [0xA0,0x00,0x00,0x04,0x20,0x00,0xAF,0x2B];
      var buf = new Buffer(bytes);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Pelco P Test Pan Right", function() {
    it("tests Pan Right", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var bytes = [0xA0,0x00,0x00,0x02,0x20,0x00,0xAF,0x2D];
      var buf = new Buffer(bytes);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Pelco P Test Tilt Up", function() {
    it("tests Tilt Up", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var bytes = [0xA0,0x00,0x00,0x08,0x00,0x20,0xAF,0x27];
      var buf = new Buffer(bytes);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Pelco P Test Tilt Down", function() {
    it("tests Tilt Down", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var bytes = [0xA0,0x00,0x00,0x10,0x00,0x20,0xAF,0x3F];
      var buf = new Buffer(bytes);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Pelco P Test Stop", function() {
    it("tests Stop", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var bytes = [0xA0,0x00,0x00,0x00,0x00,0x00,0xAF,0x0F];
      var buf = new Buffer(bytes);
      pelcod_decoder.processBuffer(buf);
    });
  });

});
<commit_msg>Add Pelco P checksum invalid test. 100% coverage<commit_after>// Mocha tests
// Note - currently the checks rely upon checking the

var expect    = require("chai").expect;
var PelcoD_Decoder = require("../pelcod_decoder.js");

describe("Pelco D Decoder", function() {

  describe("Test Checksum", function() {
    it("tests checksum", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var bytes = [0xFF,0x42,0x42,0x42,0x42,0x42,0x42];
      var buf = new Buffer(bytes);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test Cam 1 Pan Left", function() {
    it("tests Pan Left", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var bytes = [0xFF,0x01,0x00,0x04,0x20,0x00,0x25];
      var buf = new Buffer(bytes);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test Cam 1 Pan Right", function() {
    it("tests Pan right", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var bytes = [0xFF,0x01,0x00,0x02,0x20,0x00,0x23];
      var buf = new Buffer(bytes);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test Cam 1 Up", function() {
    it("tests up", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var buf = new Buffer([0xFF,0x01,0x00,0x08,0x00,0x20,0x29]);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test Cam 1 Down", function() {
    it("tests down", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var buf = new Buffer([0xFF,0x01,0x00,0x10,0x00,0x20,0x31]);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test Cam 1 Stop", function() {
    it("tests stop", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var buf = new Buffer([0xFF,0x01,0x00,0x00,0x00,0x00,0x01]);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test Cam 1 Iris Open", function() {
    it("tests iris open", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var buf = new Buffer([0xFF,0x01,0x02,0x00,0x00,0x00,0x03]);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test Cam 1 Iris Close", function() {
    it("tests iris close", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var buf = new Buffer([0xFF,0x01,0x04,0x00,0x00,0x00,0x05]);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test Cam 1 Focus Near", function() {
    it("tests focus near", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var buf = new Buffer([0xFF,0x01,0x01,0x00,0x00,0x00,0x02]);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test Cam 1 Focus Far", function() {
    it("tests focus far", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var buf = new Buffer([0xFF,0x01,0x00,0x80,0x00,0x00,0x81]);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test Cam 1 Zoom in", function() {
    it("tests Zoom in", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var buf = new Buffer([0xFF,0x01,0x00,0x20,0x00,0x00,0x21]);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test Cam 1 Zoom Out", function() {
    it("tests Zoom Out", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var buf = new Buffer([0xFF,0x01,0x00,0x40,0x00,0x00,0x41]);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test Extended Command Coverage", function() {
    it("tests extended commands", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      // Aux On
      var buf = new Buffer([0xFF,0x01,0x00,0x09,0x00,0x05,0x0F]);
      pelcod_decoder.processBuffer(buf);

      // Aux Off
      var buf = new Buffer([0xFF,0x01,0x00,0x0B,0x00,0x05,0x11]);
      pelcod_decoder.processBuffer(buf);

      // Set Preset
      var buf = new Buffer([0xFF,0x01,0x00,0x03,0x00,0x01,0x05]);
      pelcod_decoder.processBuffer(buf);

      // Goto Preset
      var buf = new Buffer([0xFF,0x01,0x00,0x07,0x00,0x01,0x09]);
      pelcod_decoder.processBuffer(buf);

      // Clear Preset
      var buf = new Buffer([0xFF,0x01,0x00,0x05,0x00,0x01,0x07]);
      pelcod_decoder.processBuffer(buf);

      // Learn Tour
      var buf = new Buffer([0xFF,0x01,0x00,0x1F,0x00,0x00,0x20]);
      pelcod_decoder.processBuffer(buf);

      // Stop Learning the tour
      var buf = new Buffer([0xFF,0x01,0x00,0x21,0x00,0x00,0x22]);
      pelcod_decoder.processBuffer(buf);

      // Start Tour
      var buf = new Buffer([0xFF,0x01,0x00,0x23,0x00,0x00,0x24]);
      pelcod_decoder.processBuffer(buf);

      // Set Zoom Speed
      var buf = new Buffer([0xFF,0x01,0x00,0x25,0x00,0x03,0x29]);
      pelcod_decoder.processBuffer(buf);

      // Unknown extended command (with valid checksum)
      var buf = new Buffer([0xFF,0x01,0x00,0x01,0x00,0x01,0x03]);
      pelcod_decoder.processBuffer(buf);

      // Set left and right, up and down, zoom in and zoom out, iris open and iris close, focus near and focus far ALL AT SAME TIME
      var buf = new Buffer([0xFF,0x01,0xFF,0xFE,0x00,0x01,0xFF]);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test byte cache with split bytes (Pan Left)", function() {
    it("tests split command", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var bytes1 = [0xFF,0x01,0x00,0x04];
      var bytes2 = [0x20,0x00,0x25];
      var buf1 = new Buffer(bytes1);
      var buf2 = new Buffer(bytes2);
      pelcod_decoder.processBuffer(buf1);
      pelcod_decoder.processBuffer(buf2);
    });
  });

  describe("Test byte cache with Pan Left and Stop", function() {
    it("tests multiple commands", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var bytes = [0xFF,0x01,0x00,0x04,0x20,0x00,0x25,0xFF,0x01,0x00,0x00,0x00,0x00,0x01];
      var buf = new Buffer(bytes);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Test byte cache with garbage then real command (stop)", function() {
    it("tests garbage then data", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var bytes = [0x01,0x02,0x03,0xFF,0x01,0x00,0x00,0x00,0x00,0x01];
      var buf = new Buffer(bytes);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Pelco P Test Pan Left", function() {
    it("tests Pan Left", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var bytes = [0xA0,0x00,0x00,0x04,0x20,0x00,0xAF,0x2B];
      var buf = new Buffer(bytes);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Pelco P Test Pan Right", function() {
    it("tests Pan Right", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var bytes = [0xA0,0x00,0x00,0x02,0x20,0x00,0xAF,0x2D];
      var buf = new Buffer(bytes);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Pelco P Test Tilt Up", function() {
    it("tests Tilt Up", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var bytes = [0xA0,0x00,0x00,0x08,0x00,0x20,0xAF,0x27];
      var buf = new Buffer(bytes);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Pelco P Test Tilt Down", function() {
    it("tests Tilt Down", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var bytes = [0xA0,0x00,0x00,0x10,0x00,0x20,0xAF,0x3F];
      var buf = new Buffer(bytes);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Pelco P Test Stop", function() {
    it("tests Stop", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var bytes = [0xA0,0x00,0x00,0x00,0x00,0x00,0xAF,0x0F];
      var buf = new Buffer(bytes);
      pelcod_decoder.processBuffer(buf);
    });
  });

  describe("Pelco P bad checksum", function() {
    it("tests bad checksum", function() {
      var pelcod_decoder = new PelcoD_Decoder();
      var bytes = [0xA0,0x00,0x00,0x00,0xFF,0x00,0xAF,0x0F];
      var buf = new Buffer(bytes);
      pelcod_decoder.processBuffer(buf);
    });
  });

});
<|endoftext|>


<commit_before>ApiHandler = function (url) {
  var self = this;
  self.url = url;

  function apiRequest (route) {
    var request = d3.xhr(self.url+"/"+route);
    request.header('Content-Type', 'application/json');
    return request;
  }

  this.offersExercised = function (params, load, error) {
    var request = apiRequest("offersExercised");

    request.post(JSON.stringify(params))
      .on('load', function(xhr){
        var response = JSON.parse(xhr.response), data = [];

        if (response.length>1) {
          if (params.reduce===false) {

            response.shift(); //remove header row
            data = response.map(function(d) {

              return {
                time    : moment.utc(d[0]),
                price   : d[1],
                amount  : d[2],
                amount2 : d[3],
                tx      : d[4],
                id      : d[5],
                type    : ''
              }
            });

            var prev = null;
            for (var i=data.length; i>-1; i--) {
              if (prev && prev.price>data[i].price)      data[i].type = 'bid';
              else if (prev && prev.price<data[i].price) data[i].type = 'ask';
            //else if (prev)                             data[i].type = prev.type;
              prev = data[i];
            }

          } else {
            response.splice(0,1); //remove first

            //remove null row, if we get one
            if (response.length==1 && !response[0][1]) response.shift();

            data = response.map(function(d) {
              return {
                startTime     : moment.utc(d[0]),
                baseVolume    : d[1],
                counterVolume : d[2],
                count         : d[3],
                open          : d[4],
                high          : d[5],
                low           : d[6],
                close         : d[7],
                vwap          : d[8],
                openTime      : d[9],
                closeTime     : d[10],
                partial       : d[11]
              };
            });
          }
        }

        load(data);
      })
      .on('error', function(xhr){
        if (error) error({status:xhr.status,text:xhr.statusText,message:xhr.response})
      });

    return request;
  }

  this.valueSent = function (params, load, error) {

    var request = apiRequest("valueSent");
    return handleRequest(request, params, function (err, response){
      if (err) error(err);
      else load(response);
    });
  }

  this.paymentVolume = function (params, load, error) {

    var request = apiRequest("payments");
    return handleRequest(request, params, function (err, response){
      if (err) error(err);
      else load(response);
    });
  }

  this.issuerCapitalization = function (params, load, error) {

    var request = apiRequest("issuerCapitalization");
    return handleRequest(request, params, function (err, response){
      if (err) error(err);
      else load(response);
    });
  }

  this.getTotalAccounts = function(time, callback){
    var request = apiRequest("accountsCreated");
    time = time || moment.utc().format();

    request.post(JSON.stringify({
      startTime     : moment.utc('2013-01-01').format(),
      timeIncrement : "all"

    })).on('load', function(xhr){
      data  = JSON.parse(xhr.response);
      callback (null, data || 0);

    }).on('error', function(xhr){
      callback({status:xhr.status,text:xhr.statusText,message:xhr.response});
    });

    return request;
  }

  this.accountsCreated = function (params, callback) {
    var request = apiRequest("accountsCreated");
    return handleRequest(request, params, callback);
  }

  this.getTopMarkets = function (ex, callback) {
    var request = apiRequest("topMarkets");
    return handleRequest(request, { exchange : ex }, callback);
  }

  this.getVolume24Hours = function (ex, callback) {
    var request = apiRequest("totalValueSent");
    return handleRequest(request, { exchange : ex }, callback);
  }

  this.getPaymentVolume = function (ex, callback) {
    var request = apiRequest("totalPaymentVolume");
    return handleRequest(request, { exchange : ex }, callback);
  }

  this.getVolume30Days = function (ex, callback) {
    var request = apiRequest("totalValueSent");
    return handleRequest(request, {
      endTime   : moment.utc(),
      startTime : moment.utc().subtract(30, "days"),
      exchange  : ex
    }, callback);
  }

  this.historicalMetrics = function(metric, currency, issuer, start, end, inc, callback){
      var request = apiRequest("historicalMetrics");
      start = start || new Date();
      json = {
          startTime     : start,
          endTime       : end,
          timeIncrement : inc,
          metric: metric
      };
      if (currency !== "XRP"){
          json.exchange = {currency: currency, issuer: issuer}
      }
      request.post(JSON.stringify(json)).on('load', function(xhr){
          data  = JSON.parse(xhr.response);
          callback (null, data);

      }).on('error', function(xhr){
          callback({status:xhr.status,text:xhr.statusText,message:xhr.response});
      });

      return request;
  }

  this.accountsCreated = function (params, callback) {
      var request = apiRequest("accountsCreated");
      return handleRequest(request, params, callback);
  }

  this.getTopMarkets = function (ex, callback) {
      var request = apiRequest("topMarkets");
      return handleRequest(request, { exchange : ex }, callback);
  }

  this.getVolume24Hours = function (ex, callback) {
      var request = apiRequest("totalValueSent");
      return handleRequest(request, { exchange : ex }, callback);
  }

  this.getVolume30Days = function (ex, callback) {
      var request = apiRequest("totalValueSent");
      return handleRequest(request, {
          endTime   : moment.utc(),
          startTime : moment.utc().subtract(30, "days"),
          exchange  : ex
      }, callback);
  }

  this.getNetworkValue = function (ex, callback) {
      var request = apiRequest("totalNetworkValue");
      return handleRequest(request, { exchange : ex }, callback);
  }

  this.getIssuedValue = function (ex, callback) {
      var request = apiRequest("totalIssued");
      return handleRequest(request, { exchange : ex }, callback);
  }

  this.exchangeRates = function (params, callback) {
      var request = apiRequest("exchangeRates");
      return handleRequest(request, params, callback);
  }

  this.marketTraders = function (params, callback) {
      var request = apiRequest("marketTraders");
      return handleRequest(request, params, callback);
  }

  function handleRequest(request, params, callback) {

      request.post(JSON.stringify(params))
      .on('load', function(xhr){
        var response = xhr.response ? JSON.parse(xhr.response) : undefined;
        callback (null, response);
      })
      .on('error', function(xhr){
        callback({status:xhr.status,text:xhr.statusText,message:xhr.response});
      });

      return request;
  }
}
<commit_msg>fix accounts created basis count bug<commit_after>ApiHandler = function (url) {
  var self = this;
  self.url = url;

  function apiRequest (route) {
    var request = d3.xhr(self.url+"/"+route);
    request.header('Content-Type', 'application/json');
    return request;
  }

  this.offersExercised = function (params, load, error) {
    var request = apiRequest("offersExercised");

    request.post(JSON.stringify(params))
      .on('load', function(xhr){
        var response = JSON.parse(xhr.response), data = [];

        if (response.length>1) {
          if (params.reduce===false) {

            response.shift(); //remove header row
            data = response.map(function(d) {

              return {
                time    : moment.utc(d[0]),
                price   : d[1],
                amount  : d[2],
                amount2 : d[3],
                tx      : d[4],
                id      : d[5],
                type    : ''
              }
            });

            var prev = null;
            for (var i=data.length; i>-1; i--) {
              if (prev && prev.price>data[i].price)      data[i].type = 'bid';
              else if (prev && prev.price<data[i].price) data[i].type = 'ask';
            //else if (prev)                             data[i].type = prev.type;
              prev = data[i];
            }

          } else {
            response.splice(0,1); //remove first

            //remove null row, if we get one
            if (response.length==1 && !response[0][1]) response.shift();

            data = response.map(function(d) {
              return {
                startTime     : moment.utc(d[0]),
                baseVolume    : d[1],
                counterVolume : d[2],
                count         : d[3],
                open          : d[4],
                high          : d[5],
                low           : d[6],
                close         : d[7],
                vwap          : d[8],
                openTime      : d[9],
                closeTime     : d[10],
                partial       : d[11]
              };
            });
          }
        }

        load(data);
      })
      .on('error', function(xhr){
        if (error) error({status:xhr.status,text:xhr.statusText,message:xhr.response})
      });

    return request;
  }

  this.valueSent = function (params, load, error) {

    var request = apiRequest("valueSent");
    return handleRequest(request, params, function (err, response){
      if (err) error(err);
      else load(response);
    });
  }

  this.paymentVolume = function (params, load, error) {

    var request = apiRequest("payments");
    return handleRequest(request, params, function (err, response){
      if (err) error(err);
      else load(response);
    });
  }

  this.issuerCapitalization = function (params, load, error) {

    var request = apiRequest("issuerCapitalization");
    return handleRequest(request, params, function (err, response){
      if (err) error(err);
      else load(response);
    });
  }

  this.getTotalAccounts = function(time, callback){
    var request = apiRequest("accountsCreated");
    time = time || moment.utc().format();

    request.post(JSON.stringify({
      startTime: moment.utc('2013-01-01').format(),
      endTime: time,
      timeIncrement: "all"
    })).on('load', function(xhr){
      data  = JSON.parse(xhr.response);
      callback (null, data || 0);

    }).on('error', function(xhr){
      callback({status:xhr.status,text:xhr.statusText,message:xhr.response});
    });

    return request;
  }

  this.accountsCreated = function (params, callback) {
    var request = apiRequest("accountsCreated");
    return handleRequest(request, params, callback);
  }

  this.getTopMarkets = function (ex, callback) {
    var request = apiRequest("topMarkets");
    return handleRequest(request, { exchange : ex }, callback);
  }

  this.getVolume24Hours = function (ex, callback) {
    var request = apiRequest("totalValueSent");
    return handleRequest(request, { exchange : ex }, callback);
  }

  this.getPaymentVolume = function (ex, callback) {
    var request = apiRequest("totalPaymentVolume");
    return handleRequest(request, { exchange : ex }, callback);
  }

  this.getVolume30Days = function (ex, callback) {
    var request = apiRequest("totalValueSent");
    return handleRequest(request, {
      endTime   : moment.utc(),
      startTime : moment.utc().subtract(30, "days"),
      exchange  : ex
    }, callback);
  }

  this.historicalMetrics = function(metric, currency, issuer, start, end, inc, callback){
      var request = apiRequest("historicalMetrics");
      start = start || new Date();
      json = {
          startTime     : start,
          endTime       : end,
          timeIncrement : inc,
          metric: metric
      };
      if (currency !== "XRP"){
          json.exchange = {currency: currency, issuer: issuer}
      }
      request.post(JSON.stringify(json)).on('load', function(xhr){
          data  = JSON.parse(xhr.response);
          callback (null, data);

      }).on('error', function(xhr){
          callback({status:xhr.status,text:xhr.statusText,message:xhr.response});
      });

      return request;
  }

  this.accountsCreated = function (params, callback) {
      var request = apiRequest("accountsCreated");
      return handleRequest(request, params, callback);
  }

  this.getTopMarkets = function (ex, callback) {
      var request = apiRequest("topMarkets");
      return handleRequest(request, { exchange : ex }, callback);
  }

  this.getVolume24Hours = function (ex, callback) {
      var request = apiRequest("totalValueSent");
      return handleRequest(request, { exchange : ex }, callback);
  }

  this.getVolume30Days = function (ex, callback) {
      var request = apiRequest("totalValueSent");
      return handleRequest(request, {
          endTime   : moment.utc(),
          startTime : moment.utc().subtract(30, "days"),
          exchange  : ex
      }, callback);
  }

  this.getNetworkValue = function (ex, callback) {
      var request = apiRequest("totalNetworkValue");
      return handleRequest(request, { exchange : ex }, callback);
  }

  this.getIssuedValue = function (ex, callback) {
      var request = apiRequest("totalIssued");
      return handleRequest(request, { exchange : ex }, callback);
  }

  this.exchangeRates = function (params, callback) {
      var request = apiRequest("exchangeRates");
      return handleRequest(request, params, callback);
  }

  this.marketTraders = function (params, callback) {
      var request = apiRequest("marketTraders");
      return handleRequest(request, params, callback);
  }

  function handleRequest(request, params, callback) {

      request.post(JSON.stringify(params))
      .on('load', function(xhr){
        var response = xhr.response ? JSON.parse(xhr.response) : undefined;
        callback (null, response);
      })
      .on('error', function(xhr){
        callback({status:xhr.status,text:xhr.statusText,message:xhr.response});
      });

      return request;
  }
}
<|endoftext|>