<commit_before>/* eslint-env mocha */

const { assert } = require('chai')
const nodeFetch = require('node-fetch')
var { CookieJar, Cookie } = require('tough-cookie')
const fetch = require('../')(nodeFetch)
const app = require('./test-server')

describe('fetch-cookie', () => {
  let server

  before('start test server', async () => {
    return new Promise((resolve, reject) => {
      server = app.listen(9999, (err) => {
        if (err) { reject(err) } else { resolve() }
      })
    })
  })

  it('should accept a Request object as only parameter', async () => {
    const req = new nodeFetch.Request('http://localhost:9999/get')
    const res = await fetch(req)
    assert.propertyVal(res, 'status', 200)
  })

  it('should handle cookies (using internal cookie jar)', async () => {
    await fetch('http://localhost:9999/set?name=foo&value=bar')
    const res = await fetch('http://localhost:9999/get')
    assert.deepEqual(await res.json(), ['foo=bar'])
  })

  // This test esentially tests if to clients with different jars are completely separated and don't share state
  it('should handle cookies (using custom cookie jar)', async () => {
    // Client 1
    const jar1 = new CookieJar()
    const fetch1 = require('../index')(nodeFetch, jar1)
    await fetch1('http://localhost:9999/set?name=foo&value=bar')
    const cookies1 = jar1.store.idx.localhost['/']
    assert.property(cookies1, 'foo')
    /** @type {Cookie} */
    const cookie1 = cookies1.foo
    assert.instanceOf(cookie1, Cookie)
    assert.propertyVal(cookie1, 'value', 'bar')

    // Client 2
    const jar2 = new CookieJar()
    const fetch2 = require('../index')(nodeFetch, jar2)
    await fetch2('http://localhost:9999/set?name=tuna&value=can')
    const cookies2 = jar2.store.idx.localhost['/']
    assert.property(cookies2, 'tuna')
    /** @type {Cookie} */
    const cookie2 = cookies2.tuna
    assert.instanceOf(cookie2, Cookie)
    assert.propertyVal(cookie2, 'value', 'can')

    // Compare the two clients (jars)
    assert.notEqual(cookie1, cookie2)
    assert.notStrictEqual(cookie1.key, cookie2.key)

    Object.keys(cookies1).forEach(cookie1Key => {
      assert.notProperty(cookie2, cookie1Key)
    })

    Object.keys(cookies2).forEach(cookie2Key => {
      assert.notProperty(cookie1, cookie2Key)
    })
  })

  // TODO: Remove this test once node-fetch v1 is not supported anymore
  it('should handle cookies jars (DEPRECATED)', async () => {
    const cookieJar1 = {}
    const cookieJar2 = {}
    await fetch('http://localhost:9999/set?name=foo&value=bar', cookieJar1)
    const res1 = await fetch('http://localhost:9999/get', cookieJar1)

    await fetch('http://localhost:9999/set?name=foo&value=bar2', cookieJar2)
    const res2 = await fetch('http://localhost:9999/get', cookieJar2)

    assert.deepEqual(await res1.json(), ['foo=bar'])
    assert.equal(cookieJar1.headers.cookie, 'foo=bar')

    assert.deepEqual(await res2.json(), ['foo=bar2'])
    assert.equal(cookieJar2.headers.cookie, 'foo=bar2')
  })

  it("should handle multiple cookies (including comma in 'expires' option)", async () => {
    const jar = new CookieJar()
    const fetch = require('../index')(nodeFetch, jar)
    await fetch('http://localhost:9999/set-multiple')
    const cookies = jar.store.idx.localhost['/']

    assert.property(cookies, 'foo')
    /** @type {Cookie} */
    const cookie1 = cookies.foo
    assert.instanceOf(cookie1, Cookie)
    assert.propertyVal(cookie1, 'value', 'bar')
    assert.property(cookie1, 'expires')
    assert.instanceOf(cookie1.expires, Date)

    assert.property(cookies, 'tuna')
    /** @type {Cookie} */
    const cookie2 = cookies.tuna
    assert.instanceOf(cookie2, Cookie)
    assert.propertyVal(cookie2, 'value', 'can')

    // Compare the two cookies
    assert.notEqual(cookie1, cookie2)
    assert.notStrictEqual(cookie1.key, cookie2.key)
  })

  it('should ignore error when there is error in setCookie', async () => {
    const jar = new CookieJar()
    const fetch = require('../index')(nodeFetch, jar)
    let error = null
    try {
      await fetch('http://localhost:9999/cookie')
    } catch (err) {
      error = err
    }
    assert.isNull(error)
  })

  it('should throw error when there is error in setCookie', async () => {
    const jar = new CookieJar()
    const fetch = require('../index')(nodeFetch, jar, false)
    let error = null
    try {
      await fetch('http://localhost:9999/cookie')
    } catch (err) {
      error = err
    }
    assert.instanceOf(error, Error)
  })

  after('stop test server', () => {
    if (server) { server.close() }
  })
})
<commit_msg>Update test<commit_after>/* eslint-env mocha */

const { assert } = require('chai')
const nodeFetch = require('node-fetch')
var { CookieJar, Cookie } = require('tough-cookie')
const fetch = require('../')(nodeFetch)
const app = require('./test-server')

describe('fetch-cookie', () => {
  let server

  before('start test server', async () => {
    return new Promise((resolve, reject) => {
      server = app.listen(9999, (err) => {
        if (err) { reject(err) } else { resolve() }
      })
    })
  })

  it('should accept a Request object as only parameter', async () => {
    const req = new nodeFetch.Request('http://localhost:9999/get')
    const res = await fetch(req)
    assert.propertyVal(res, 'status', 200)
  })

  it('should not send empty cookie header', async () => {
    const req = new nodeFetch.Request('http://localhost:9999/ok-if-empty')
    const res = await fetch(req)

    assert.deepEqual(await res.json(), {"status": "ok"})
  })

  it('should handle cookies (using internal cookie jar)', async () => {
    await fetch('http://localhost:9999/set?name=foo&value=bar')
    const res = await fetch('http://localhost:9999/get')
    assert.deepEqual(await res.json(), ['foo=bar'])
  })

  // This test esentially tests if to clients with different jars are completely separated and don't share state
  it('should handle cookies (using custom cookie jar)', async () => {
    // Client 1
    const jar1 = new CookieJar()
    const fetch1 = require('../index')(nodeFetch, jar1)
    await fetch1('http://localhost:9999/set?name=foo&value=bar')
    const cookies1 = jar1.store.idx.localhost['/']
    assert.property(cookies1, 'foo')
    /** @type {Cookie} */
    const cookie1 = cookies1.foo
    assert.instanceOf(cookie1, Cookie)
    assert.propertyVal(cookie1, 'value', 'bar')

    // Client 2
    const jar2 = new CookieJar()
    const fetch2 = require('../index')(nodeFetch, jar2)
    await fetch2('http://localhost:9999/set?name=tuna&value=can')
    const cookies2 = jar2.store.idx.localhost['/']
    assert.property(cookies2, 'tuna')
    /** @type {Cookie} */
    const cookie2 = cookies2.tuna
    assert.instanceOf(cookie2, Cookie)
    assert.propertyVal(cookie2, 'value', 'can')

    // Compare the two clients (jars)
    assert.notEqual(cookie1, cookie2)
    assert.notStrictEqual(cookie1.key, cookie2.key)

    Object.keys(cookies1).forEach(cookie1Key => {
      assert.notProperty(cookie2, cookie1Key)
    })

    Object.keys(cookies2).forEach(cookie2Key => {
      assert.notProperty(cookie1, cookie2Key)
    })
  })

  // TODO: Remove this test once node-fetch v1 is not supported anymore
  it('should handle cookies jars (DEPRECATED)', async () => {
    const cookieJar1 = {}
    const cookieJar2 = {}
    await fetch('http://localhost:9999/set?name=foo&value=bar', cookieJar1)
    const res1 = await fetch('http://localhost:9999/get', cookieJar1)

    await fetch('http://localhost:9999/set?name=foo&value=bar2', cookieJar2)
    const res2 = await fetch('http://localhost:9999/get', cookieJar2)

    assert.deepEqual(await res1.json(), ['foo=bar'])
    assert.equal(cookieJar1.headers.cookie, 'foo=bar')

    assert.deepEqual(await res2.json(), ['foo=bar2'])
    assert.equal(cookieJar2.headers.cookie, 'foo=bar2')
  })

  it("should handle multiple cookies (including comma in 'expires' option)", async () => {
    const jar = new CookieJar()
    const fetch = require('../index')(nodeFetch, jar)
    await fetch('http://localhost:9999/set-multiple')
    const cookies = jar.store.idx.localhost['/']

    assert.property(cookies, 'foo')
    /** @type {Cookie} */
    const cookie1 = cookies.foo
    assert.instanceOf(cookie1, Cookie)
    assert.propertyVal(cookie1, 'value', 'bar')
    assert.property(cookie1, 'expires')
    assert.instanceOf(cookie1.expires, Date)

    assert.property(cookies, 'tuna')
    /** @type {Cookie} */
    const cookie2 = cookies.tuna
    assert.instanceOf(cookie2, Cookie)
    assert.propertyVal(cookie2, 'value', 'can')

    // Compare the two cookies
    assert.notEqual(cookie1, cookie2)
    assert.notStrictEqual(cookie1.key, cookie2.key)
  })

  it('should ignore error when there is error in setCookie', async () => {
    const jar = new CookieJar()
    const fetch = require('../index')(nodeFetch, jar)
    let error = null
    try {
      await fetch('http://localhost:9999/cookie')
    } catch (err) {
      error = err
    }
    assert.isNull(error)
  })

  it('should throw error when there is error in setCookie', async () => {
    const jar = new CookieJar()
    const fetch = require('../index')(nodeFetch, jar, false)
    let error = null
    try {
      await fetch('http://localhost:9999/cookie')
    } catch (err) {
      error = err
    }
    assert.instanceOf(error, Error)
  })

  after('stop test server', () => {
    if (server) { server.close() }
  })
})
<|endoftext|>


<commit_before>module.exports = function (grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        env : {
            sauceLabs : (grunt.file.exists('.sauce-labs.creds') ?
                    grunt.file.readJSON('.sauce-labs.creds') : {})
        },
        karma : {
            options: {
                browserNoActivityTimeout: 60000,
                browserDisconnectTimeout: 10000,
                browserDisconnectTolerance: 2,
                frameworks: ['qunit'],
                files: [
                    'min/moment-with-locales.js',
                    'min/tests.js'
                ],
                sauceLabs: {
                    startConnect: true,
                    testName: 'MomentJS'
                },
                customLaunchers: {
                    slChromeWinXp: {
                        base: 'SauceLabs',
                        browserName: 'chrome',
                        platform: 'Windows XP'
                    },
                    slIe10Win7: {
                        base: 'SauceLabs',
                        browserName: 'internet explorer',
                        platform: 'Windows 7',
                        version: '10'
                    },
                    slIe9Win7: {
                        base: 'SauceLabs',
                        browserName: 'internet explorer',
                        platform: 'Windows 7',
                        version: '9'
                    },
                    slIe8Win7: {
                        base: 'SauceLabs',
                        browserName: 'internet explorer',
                        platform: 'Windows 7',
                        version: '8'
                    },
                    slIe11Win10: {
                        base: 'SauceLabs',
                        browserName: 'internet explorer',
                        platform: 'Windows 10',
                        version: '11'
                    },
                    slME25Win10: {
                        base: 'SauceLabs',
                        browserName: 'MicrosoftEdge',
                        platform: 'Windows 10',
                        version: '20.10240'
                    },
                    slFfLinux: {
                        base: 'SauceLabs',
                        browserName: 'firefox',
                        platform: 'Linux'
                    },
                    slSafariOsx: {
                        base: 'SauceLabs',
                        browserName: 'safari',
                        platform: 'OS X 10.8'
                    },
                    slSafariOsx11: {
                        base: 'SauceLabs',
                        browserName: 'safari',
                        platform: 'OS X 10.11'
                    }
                }
            },
            server: {
                browsers: []
            },
            chrome: {
                singleRun: true,
                browsers: ['Chrome']
            },
            firefox: {
                singleRun: true,
                browsers: ['Firefox']
            },
            sauce: {
                options: {
                    reporters: ['dots']
                },
                singleRun: true,
                browsers: [
                    'slChromeWinXp',
                    'slIe10Win7',
                    'slIe9Win7',
                    'slIe8Win7',
                    'slIe11Win10',
                    'slME25Win10',
                    'slFfLinux',
                    'slSafariOsx'
                ]
            }
        },
        uglify : {
            main: {
                files: {
                    'min/moment-with-locales.min.js'     : 'min/moment-with-locales.js',
                    'min/locales.min.js'                 : 'min/locales.js',
                    'min/moment.min.js'                  : 'moment.js'
                }
            },
            options: {
                mangle: true,
                compress: {
                    dead_code: false // jshint ignore:line
                },
                output: {
                    ascii_only: true // jshint ignore:line
                },
                report: 'min',
                preserveComments: /^!|@preserve|@license|@cc_on/i
            }
        },
        jshint: {
            all: [
                'Gruntfile.js',
                'tasks/**.js',
                'src/**/*.js'
            ],
            options: {
                jshintrc: true
            }
        },
        jscs: {
            all: [
                'Gruntfile.js',
                'tasks/**.js',
                'src/**/*.js'
            ],
            options: {
                config: '.jscs.json'
            }
        },
        watch : {
            test : {
                files : [
                    'src/**/*.js'
                ],
                tasks: ['test']
            },
            jshint : {
                files : '<%= jshint.all %>',
                tasks: ['jshint']
            }
        },
        benchmark: {
            all: {
                src: ['benchmarks/*.js']
            }
        },
        exec: {
            'meteor-init': {
                // Make sure Meteor is installed, per https://meteor.com/install.
                // The curl'ed script is safe; takes 2 minutes to read source & check.
                command: 'type meteor >/dev/null 2>&1 || { curl https://install.meteor.com/ | sh; }'
            },
            'meteor-test': {
                command: 'spacejam --mongo-url mongodb:// test-packages ./meteor'
            },
            'meteor-publish': {
                command: 'cd meteor && meteor publish'
            },
            'typescript-test': {
                command: 'npm run typescript-test'
            },
            'ts3.1-typescript-test': {
                command: 'npm run ts3.1-typescript-test'
            },
            'coveralls': {
                command: 'npm run coveralls'
            }
        }

    });

    grunt.loadTasks('tasks');

    // These plugins provide necessary tasks.
    require('load-grunt-tasks')(grunt);

    // Default task.
    grunt.registerTask('default', ['lint', 'test']);

    // linting
    grunt.registerTask('lint', ['jshint', 'jscs']);

    // test tasks
    grunt.registerTask('test', ['test:node', 'test:typescript', 'test:typescript-3.1']);
    grunt.registerTask('test:node', ['transpile', 'qtest']);
    grunt.registerTask('test:typescript', ['exec:typescript-test']);
    grunt.registerTask('test:typescript-3.1', ['exec:ts3.1-typescript-test']);
    // TODO: For some weird reason karma doesn't like the files in
    // build/umd/min/* but works with min/*, so update-index, then git checkout
    grunt.registerTask('test:server', ['transpile', 'update-index', 'karma:server']);
    grunt.registerTask('test:browser', ['transpile', 'update-index', 'karma:chrome', 'karma:firefox']);
    grunt.registerTask('test:sauce-browser', ['transpile', 'update-index', 'env:sauceLabs', 'karma:sauce']);
    grunt.registerTask('test:meteor', ['exec:meteor-init', 'exec:meteor-test', 'exec:meteor-cleanup']);

    // travis build task
    grunt.registerTask('build:travis', ['lint', 'exec:coveralls']);
    grunt.registerTask('meteor-publish', ['exec:meteor-init', 'exec:meteor-publish', 'exec:meteor-cleanup']);

    // Task to be run when releasing a new version
    grunt.registerTask('release', [
        'default',
        'update-index',
        'component',
        'uglify:main'
    ]);
};
<commit_msg>Disable TS3 tests for now<commit_after>module.exports = function (grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        env : {
            sauceLabs : (grunt.file.exists('.sauce-labs.creds') ?
                    grunt.file.readJSON('.sauce-labs.creds') : {})
        },
        karma : {
            options: {
                browserNoActivityTimeout: 60000,
                browserDisconnectTimeout: 10000,
                browserDisconnectTolerance: 2,
                frameworks: ['qunit'],
                files: [
                    'min/moment-with-locales.js',
                    'min/tests.js'
                ],
                sauceLabs: {
                    startConnect: true,
                    testName: 'MomentJS'
                },
                customLaunchers: {
                    slChromeWinXp: {
                        base: 'SauceLabs',
                        browserName: 'chrome',
                        platform: 'Windows XP'
                    },
                    slIe10Win7: {
                        base: 'SauceLabs',
                        browserName: 'internet explorer',
                        platform: 'Windows 7',
                        version: '10'
                    },
                    slIe9Win7: {
                        base: 'SauceLabs',
                        browserName: 'internet explorer',
                        platform: 'Windows 7',
                        version: '9'
                    },
                    slIe8Win7: {
                        base: 'SauceLabs',
                        browserName: 'internet explorer',
                        platform: 'Windows 7',
                        version: '8'
                    },
                    slIe11Win10: {
                        base: 'SauceLabs',
                        browserName: 'internet explorer',
                        platform: 'Windows 10',
                        version: '11'
                    },
                    slME25Win10: {
                        base: 'SauceLabs',
                        browserName: 'MicrosoftEdge',
                        platform: 'Windows 10',
                        version: '20.10240'
                    },
                    slFfLinux: {
                        base: 'SauceLabs',
                        browserName: 'firefox',
                        platform: 'Linux'
                    },
                    slSafariOsx: {
                        base: 'SauceLabs',
                        browserName: 'safari',
                        platform: 'OS X 10.8'
                    },
                    slSafariOsx11: {
                        base: 'SauceLabs',
                        browserName: 'safari',
                        platform: 'OS X 10.11'
                    }
                }
            },
            server: {
                browsers: []
            },
            chrome: {
                singleRun: true,
                browsers: ['Chrome']
            },
            firefox: {
                singleRun: true,
                browsers: ['Firefox']
            },
            sauce: {
                options: {
                    reporters: ['dots']
                },
                singleRun: true,
                browsers: [
                    'slChromeWinXp',
                    'slIe10Win7',
                    'slIe9Win7',
                    'slIe8Win7',
                    'slIe11Win10',
                    'slME25Win10',
                    'slFfLinux',
                    'slSafariOsx'
                ]
            }
        },
        uglify : {
            main: {
                files: {
                    'min/moment-with-locales.min.js'     : 'min/moment-with-locales.js',
                    'min/locales.min.js'                 : 'min/locales.js',
                    'min/moment.min.js'                  : 'moment.js'
                }
            },
            options: {
                mangle: true,
                compress: {
                    dead_code: false // jshint ignore:line
                },
                output: {
                    ascii_only: true // jshint ignore:line
                },
                report: 'min',
                preserveComments: /^!|@preserve|@license|@cc_on/i
            }
        },
        jshint: {
            all: [
                'Gruntfile.js',
                'tasks/**.js',
                'src/**/*.js'
            ],
            options: {
                jshintrc: true
            }
        },
        jscs: {
            all: [
                'Gruntfile.js',
                'tasks/**.js',
                'src/**/*.js'
            ],
            options: {
                config: '.jscs.json'
            }
        },
        watch : {
            test : {
                files : [
                    'src/**/*.js'
                ],
                tasks: ['test']
            },
            jshint : {
                files : '<%= jshint.all %>',
                tasks: ['jshint']
            }
        },
        benchmark: {
            all: {
                src: ['benchmarks/*.js']
            }
        },
        exec: {
            'meteor-init': {
                // Make sure Meteor is installed, per https://meteor.com/install.
                // The curl'ed script is safe; takes 2 minutes to read source & check.
                command: 'type meteor >/dev/null 2>&1 || { curl https://install.meteor.com/ | sh; }'
            },
            'meteor-test': {
                command: 'spacejam --mongo-url mongodb:// test-packages ./meteor'
            },
            'meteor-publish': {
                command: 'cd meteor && meteor publish'
            },
            'typescript-test': {
                command: 'npm run typescript-test'
            },
            'ts3.1-typescript-test': {
                command: 'npm run ts3.1-typescript-test'
            },
            'coveralls': {
                command: 'npm run coveralls'
            }
        }

    });

    grunt.loadTasks('tasks');

    // These plugins provide necessary tasks.
    require('load-grunt-tasks')(grunt);

    // Default task.
    grunt.registerTask('default', ['lint', 'test']);

    // linting
    grunt.registerTask('lint', ['jshint', 'jscs']);

    // test tasks
    grunt.registerTask('test', ['test:node', 'test:typescript' /*, 'test:typescript-3.1' */]);
    grunt.registerTask('test:node', ['transpile', 'qtest']);
    grunt.registerTask('test:typescript', ['exec:typescript-test']);
    grunt.registerTask('test:typescript-3.1', ['exec:ts3.1-typescript-test']);
    // TODO: For some weird reason karma doesn't like the files in
    // build/umd/min/* but works with min/*, so update-index, then git checkout
    grunt.registerTask('test:server', ['transpile', 'update-index', 'karma:server']);
    grunt.registerTask('test:browser', ['transpile', 'update-index', 'karma:chrome', 'karma:firefox']);
    grunt.registerTask('test:sauce-browser', ['transpile', 'update-index', 'env:sauceLabs', 'karma:sauce']);
    grunt.registerTask('test:meteor', ['exec:meteor-init', 'exec:meteor-test', 'exec:meteor-cleanup']);

    // travis build task
    grunt.registerTask('build:travis', ['lint', 'exec:coveralls']);
    grunt.registerTask('meteor-publish', ['exec:meteor-init', 'exec:meteor-publish', 'exec:meteor-cleanup']);

    // Task to be run when releasing a new version
    grunt.registerTask('release', [
        'default',
        'update-index',
        'component',
        'uglify:main'
    ]);
};
<|endoftext|>


<commit_before>var common = require('../shared/common.js');

exports.get = function(request, response) {
    var fromDateInput = request.query.from;
    var fromDate = common.queryStringDateToSqlDate(fromDateInput);
    var sqlFromDate = common.formatSqlDate(fromDate);

    var toDateInput = request.query.to;
    var toDate = common.queryStringDateToSqlDate(toDateInput);
    var sqlToDate = common.formatSqlDate(toDate);

    var sql = 'SELECT errorCode, count(*) AS occurrences from availabilitylog WHERE ' +
        '? >= CONVERT(DATE, timeOfRequest) AND CONVERT(DATE, timeOfRequest) >= ? ' +
        ' GROUP BY errorCode';

    if (sqlFromDate !== 'undefined' && sqlToDate !== 'undefined' && sqlFromDate <= sqlToDate) {
        request.service.mssql.query(sql, [sqlFromDate, sqlToDate],{
                success: function(results) {
                    response.send(statusCodes.OK, results);
                },
                error: function(error) {
                    console.error(error);
                    response.send(statusCodes.NOT_FOUND, "Query Error");
                }
            });
    } else {
        response.send(statusCodes.INTERNAL_SERVER_ERROR, "Invalid date parameters specified");
    }
};<commit_msg>Fix parameter ordering<commit_after>var common = require('../shared/common.js');

exports.get = function(request, response) {
    var fromDateInput = request.query.from;
    var fromDate = common.queryStringDateToSqlDate(fromDateInput);
    var sqlFromDate = common.formatSqlDate(fromDate);

    var toDateInput = request.query.to;
    var toDate = common.queryStringDateToSqlDate(toDateInput);
    var sqlToDate = common.formatSqlDate(toDate);

    var sql = 'SELECT errorCode, count(*) AS occurrences from availabilitylog WHERE ' +
        '? >= CONVERT(DATE, timeOfRequest) AND CONVERT(DATE, timeOfRequest) >= ? ' +
        ' GROUP BY errorCode';

    if (sqlFromDate !== 'undefined' && sqlToDate !== 'undefined' && sqlFromDate <= sqlToDate) {
        request.service.mssql.query(sql, [sqlToDate, sqlFromDate],{
                success: function(results) {
                    response.send(statusCodes.OK, results);
                },
                error: function(error) {
                    console.error(error);
                    response.send(statusCodes.NOT_FOUND, "Query Error");
                }
            });
    } else {
        response.send(statusCodes.INTERNAL_SERVER_ERROR, "Invalid date parameters specified");
    }
};<|endoftext|>


<commit_before>'use strict'

var commander = require('commander')
var nailgun = require('./node-nailgun-server')
var pack = require('../package.json')

commander
  .version(pack.version)
  .option('-a, --address [address]', 'the address at which to listen')
  .option('-p, --port [port]', 'the port on which to listen', parseInt)
  .parse(process.argv)

var server = nailgun.createServer(commander)
server.out.pipe(process.stdout)

console.log('hello')

process.on('exit', server.shutdown)
<commit_msg>Remove hello log message<commit_after>'use strict'

var commander = require('commander')
var nailgun = require('./node-nailgun-server')
var pack = require('../package.json')

commander
  .version(pack.version)
  .option('-a, --address [address]', 'the address at which to listen')
  .option('-p, --port [port]', 'the port on which to listen', parseInt)
  .parse(process.argv)

var server = nailgun.createServer(commander)
server.out.pipe(process.stdout)

process.on('exit', server.shutdown)
<|endoftext|>


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

var OPC = new require('./opc')

var fc = new OPC('localhost', 7890);

var sp = require('serialport');
var SerialPort = require('serialport').SerialPort;
var portName = "/dev/ttyArduino";

var runState = "down";

var BRIGHTEN = 100;
var DARKEN = 101;

var BRIGHTEN_S = 200;
var DARKEN_S = 201;

var SWEEP = 300;

var SENSORTEST = false;
var POSITIONTEST = false;
var USESENSOR = true;

var sensorCount = 8;

var pixelLength = 300;
var particleCount = 400;

var environmentLength = 3000;

var defaultScale = 7;

var pixels = [];
var particles = [];

var lookup = [];

var coordT = [];

var dist_v = [];

var timerIdle = true;

// MAIN COMPUTER PROGRAM!

initialize();
setInterval(evaluate, 30);

function initialize() {

	if ( process.argv.length > 2 ) {
			for ( var i=2; i<process.argv.length; i++ ) {
				var current = process.argv[i];
				if ( current == "sensorTest" ) { SENSORTEST = true; }
				else if ( current == "positionTest" ) { POSITIONTEST = true; }
				else if ( current == "noSensors") { USESENSOR = false; }
			}
	}

	serialport = new SerialPort(portName , { baudrate : 115200, parser: sp.parsers.readline("|") }, false);
	openPort();

	for ( var i=0; i<8; i++ ) { dist_v[i] = 0; }

	// Init coord lookup
	var coordRatio = ( ( pixelLength ) / environmentLength );
	for ( var t=0; t<environmentLength+1; t++ ){ coordT[t] = Math.floor( t * coordRatio ); }

	// Init scaling lookup

	lookup[defaultScale] = { 'environmentLength': defaultScale * pixelLength, 'positions': [] };

	for ( var p=0; p < lookup[defaultScale].environmentLength; p++ ){
		var div = p / defaultScale;
		var calc = {
			'left': Math.floor( div ),
			'right': Math.floor( div ) + 1,
			'wleft': 1 - ( div ) % 1,
			'wright': ( div ) % 1
		};

		lookup[defaultScale].positions.push( calc );
	}

	// Init pixel array
	for ( var i=0; i<pixelLength + 3; i++ ) { pixels.push({ 'r':0, 'g':0, 'b':0 }); }
}

function evaluate() {
	if ( runState == "open") {
  	updateParticles();
  	evaluateEnvironment();
  	draw();
	} else {
		if ( timerIdle ) {
			setTimeout( function() {
				openPort();
				timerIdle = true;
			}, 5000);
			timerIdle = false;
		}
	}
}

function updateParticles() {
  for ( var i=0; i<particles.length; i++ ){
		particles[i].update( i );
  }
}

function evaluateEnvironment() {
	// fill particle list
	if ( particles.length < particleCount ) {
		particles.push( getRandParticle() );
	}

	if ( USESENSOR ) {
		for ( var s=0; s < sensorCount; s++ ) {
				if ( dist_v[s] > 0 && dist_v[s] < 50 ) {
					particles.push( getProximateParticle( s, dist_v[s] ));
				}
		}
	}

	if ( POSITIONTEST ) {
		var out = "";
		for ( var s=0; s < sensorCount; s++ ) {
			var p = getProximateParticle( s, dist_v[s] );
			out += s + "=" + dist_v[s] + "-" + p.position + "  :  ";
		}
		console.log( out );
	}

}

function draw() {
  if ( runState == "open" ) {

		// Initialize
		initAllPixels( 20, 20, 40 );

	  // Compose
	  for ( var i=0; i<particles.length; i++ ){ particles[i].method(); }

	  // Render
	//	try {
	    for ( var i=0; i<pixels.length; i++ ){
	      fc.setPixel( pixels.length-i, pixels[i].red, pixels[i].green, pixels[i].blue );
	    }
	    fc.writePixels();
	//	} catch( err ) {
	//		console.log('fc write err: ' + error);
	//		runState = "fc write err";
	//	}

  } else {
    // display runstate graphics

  }
}

// update methods

function update_Discrete( i ) {
	this.position += this.vel;

	// recycle rules
	if ( this.position > environmentLength ) {
		particles[i] = getRandParticle();
	}
}

function update_Smooth( i ) {
	this.position += this.vel;

	// recycle rules
	if ( this.position > lookup[this.scale].environmentLength-1 ) {
    particles[i] = getRandParticle();
	}
}

function update_Glower( i ) {
	this.position += this.vel;

	// recycle rules
	if ( this.position > lookup[this.scale].environmentLength-1 ) {
    particles[i] = getRandParticle();
	}
}

function update_React( i ) {
	this.position += this.vel;

	// recycle rules
	if ( this.position > lookup[this.scale].environmentLength-1 ) {
    particles[i] = getRandParticle();
	}
}

// draw methods

function method_Brighten() {
	var dest = coordT[this.position];

	pixels[dest].red += this.color.r;
	pixels[dest].green += this.color.g;
	pixels[dest].blue += this.color.b;
}

function method_Darken() {
	var dest = coordT[this.position];

	pixels[dest].red -= this.color.r;
	pixels[dest].green -= this.color.g;
	pixels[dest].blue -= this.color.b;
}

function method_BrightenSmooth() {
	var pcalc = lookup[this.scale].positions[this.position];
	methodValueSmooth( this, pcalc );
}

function method_DarkenSmooth() {
	var pcalc = lookup[this.scale].positions[this.position];
	if ( this.method == DARKEN_S ) {
		pcalc.wleft *= -1;
		pcalc.wright *= -1;
	}
	methodValueSmooth( this, pcalc );
}

function methodValueSmooth( tgt, pcalc ){
	pixels[pcalc.left].red += tgt.color.r * pcalc.wleft;
	pixels[pcalc.left].green += tgt.color.g * pcalc.wleft;
	pixels[pcalc.left].blue += tgt.color.b * pcalc.wleft;

	pixels[pcalc.right].red += tgt.color.r * pcalc.wright;
	pixels[pcalc.right].green += tgt.color.g * pcalc.wright;
	pixels[pcalc.right].blue += tgt.color.b * pcalc.wright;
}

function method_Sweep() {
	var pcalc = lookup[this.scale].positions[this.position];

	var taillen = 6;
	var fraction = 1/taillen;

	for ( var t=0; t < taillen; t++ ) {
		try {
		var tail = pcalc.right - t;
	} catch ( err ) {
		console.log( i + " | " + this.position );
	}
		if ( tail > 0 ) {
			var factor = ( 6 - t ) * ( fraction );
			pixels[tail].red += this.color.r * factor;
			pixels[tail].green += this.color.g * factor;
			pixels[tail].blue += this.color.b * factor;
		}
	}
	var frontedge = pcalc.right + 1;
	if ( frontedge < pixelLength - 2 ) {
		pixels[frontedge].red = 0;
		pixels[frontedge].green = 0;
		pixels[frontedge].blue = 0;
	}
}

function setPixel( i, r, g, b ) {
	pixels[i].red = r;
	pixels[i].green = g;
	pixels[i].blue = b;
}

function initAllPixels( r, g, b ){
	for ( var i=0; i<pixels.length; i++ ) {
		pixels[i].red = r;
		pixels[i].green = g;
		pixels[i].blue = b;
	}
}

function getProximateParticle( s, dist ) {
	var pos = Math.floor( s * ( environmentLength / sensorCount ) );
	return getParticle( 4, pos, 2,  method_BrightenSmooth, update_React, defaultScale, 85, 55, 15, 20 );
}

function getRandParticle() {
	var r = Math.random();

	if ( r < .10 ) {
		return getParticle( 4, 0, 1, method_BrightenSmooth, update_Smooth, defaultScale, 10, 10, 85, 0 );
//	} else if ( r < .15 ) {
//		return getParticle( 3, 0, 1, method_Sweep, update_Smooth, defaultScale, 60, 10, 15, 0 );
//	} else if ( r < .30 ) {
//		return getParticle( 3, 0, 1, method_Sweep, update_Smooth, defaultScale, 30, 30, 95, 0 );
	} else if ( r < .50 ) {
		return getParticle( 4, 0, 1, method_BrightenSmooth, update_Smooth, defaultScale, 45, 25, 100, 0 )
	} else {
		return getParticle( 2, 0, 1, method_BrightenSmooth, update_Smooth, defaultScale, 5, 5, 10, 0 );
	}
}

function getParticle( v, p, r, g, b ) {
	return getParticle( v, p, 1, method_Brighten, update_Discrete, defaultScale, r, g, b, 0 );
}

function getParticle( v, p, i, m, u, s, r, g, b, l ) {
  var p = {
    'vel': v,
    'position': p,
    'intensity': i,
		'method': m,
		'update': u,
		'scale': s,
    'color': { 'r': r, 'g': g, 'b': b },
		'life': l
  };
  return p;
}

// Serial Access

function listPorts() {
  serialport.list(function (err, ports) {
    ports.forEach(function(port) {
      console.log(port.comName);
    });
  });
  return ports;
}

function openPort() {
	serialport.on('error', function(err){
		console.log('serialport general error' + err);
	});

  serialport.open(function (error) {
    if ( error ) {
      console.log('open err: ' + error);
//			runState = "conn open err";
	runState = "open";
    } else {
      console.log('open');
			runState = "open";

      serialport.on('data', function(data) {
    		var c = data.trim();
				try{
					//console.log('rcv: ' + c);
	    		dist_v = JSON.parse(c);
					//dist_v = {};

					if ( SENSORTEST ) {
						var out = "";
						for ( var s=0; s < sensorCount; s++ ) {
							out += s + '=' + dist_v[s] + '  :  ';
						}
						console.log( out );
					}
				} catch( err ){
					console.log('parse err ' + err);
				}
	    });

    }
  });

}
<commit_msg>new lifetime rules<commit_after>#!/usr/bin/env node

var OPC = new require('./opc')

var fc = new OPC('localhost', 7890);

var sp = require('serialport');
var SerialPort = require('serialport').SerialPort;
var portName = "/dev/ttyArduino";

var runState = "down";

var BRIGHTEN = 100;
var DARKEN = 101;

var BRIGHTEN_S = 200;
var DARKEN_S = 201;

var SWEEP = 300;

var SENSORTEST = false;
var POSITIONTEST = false;
var USESENSOR = true;

var sensorCount = 8;

var pixelLength = 300;
var particleCount = 400;

var environmentLength = 3000;

var defaultScale = 7;

var pixels = [];
var particles = [];

var lookup = [];

var coordT = [];

var dist_v = [];

var timerIdle = true;

// MAIN COMPUTER PROGRAM!

initialize();
setInterval(evaluate, 30);

function initialize() {

	if ( process.argv.length > 2 ) {
			for ( var i=2; i<process.argv.length; i++ ) {
				var current = process.argv[i];
				if ( current == "sensorTest" ) { SENSORTEST = true; }
				else if ( current == "positionTest" ) { POSITIONTEST = true; }
				else if ( current == "noSensors") { USESENSOR = false; }
			}
	}

	serialport = new SerialPort(portName , { baudrate : 115200, parser: sp.parsers.readline("|") }, false);
	openPort();

	for ( var i=0; i<8; i++ ) { dist_v[i] = 0; }

	// Init coord lookup
	var coordRatio = ( ( pixelLength ) / environmentLength );
	for ( var t=0; t<environmentLength+1; t++ ){ coordT[t] = Math.floor( t * coordRatio ); }

	// Init scaling lookup

	lookup[defaultScale] = { 'environmentLength': defaultScale * pixelLength, 'positions': [] };

	for ( var p=0; p < lookup[defaultScale].environmentLength; p++ ){
		var div = p / defaultScale;
		var calc = {
			'left': Math.floor( div ),
			'right': Math.floor( div ) + 1,
			'wleft': 1 - ( div ) % 1,
			'wright': ( div ) % 1
		};

		lookup[defaultScale].positions.push( calc );
	}

	// Init pixel array
	for ( var i=0; i<pixelLength + 3; i++ ) { pixels.push({ 'r':0, 'g':0, 'b':0 }); }
}

function evaluate() {
	if ( runState == "open") {
  	updateParticles();
  	evaluateEnvironment();
  	draw();
	} else {
		if ( timerIdle ) {
			setTimeout( function() {
				openPort();
				timerIdle = true;
			}, 5000);
			timerIdle = false;
		}
	}
}

function updateParticles() {
  for ( var i=0; i<particles.length; i++ ){
		particles[i].update( i );
  }
}

function evaluateEnvironment() {
	// fill particle list
	if ( particles.length < particleCount ) {
		addParticle( getRandParticle() );
	}

	if ( USESENSOR ) {
		for ( var s=0; s < sensorCount; s++ ) {
				if ( dist_v[s] > 0 && dist_v[s] < 50 ) {
					particles.push( getProximateParticle( s, dist_v[s] ));
				}
		}
	}

	if ( POSITIONTEST ) {
		var out = "";
		for ( var s=0; s < sensorCount; s++ ) {
			var p = getProximateParticle( s, dist_v[s] );
			out += s + "=" + dist_v[s] + "-" + p.position + "  :  ";
		}
		console.log( out );
	}

}

function draw() {
  if ( runState == "open" ) {

		// Initialize
		initAllPixels( 20, 20, 40 );

	  // Compose
	  for ( var i=0; i<particles.length; i++ ){ particles[i].method(); }

	  // Render
	//	try {
	    for ( var i=0; i<pixels.length; i++ ){
	      fc.setPixel( pixels.length-i, pixels[i].red, pixels[i].green, pixels[i].blue );
	    }
	    fc.writePixels();
	//	} catch( err ) {
	//		console.log('fc write err: ' + error);
	//		runState = "fc write err";
	//	}

  } else {
    // display runstate graphics
  }
}

// update methods

function update_Discrete( i ) {
	this.position += this.vel;

	// recycle rules
	if ( this.position > environmentLength ) {
		deleteParticle[i];
	}
}

function update_Smooth( i ) {
	this.position += this.vel;

	// recycle rules
	if ( this.position > lookup[this.scale].environmentLength-1 ) {
		deleteParticle[i];
	}
}

function update_Glower( i ) {
	this.position += this.vel;

	// recycle rules
	if ( this.position > lookup[this.scale].environmentLength-1 ) {
		deleteParticle[i];
	}
}

function update_React( i ) {
	this.position += this.vel;
	this.life--;

	// recycle rules
	if ( this.position < 1 || this.position > lookup[this.scale].environmentLength-1 || life < 1 ) {
		deleteParticle[i];
	}
}

// draw methods

function method_Brighten() {
	var dest = coordT[this.position];

	pixels[dest].red += this.color.r;
	pixels[dest].green += this.color.g;
	pixels[dest].blue += this.color.b;
}

function method_Darken() {
	var dest = coordT[this.position];

	pixels[dest].red -= this.color.r;
	pixels[dest].green -= this.color.g;
	pixels[dest].blue -= this.color.b;
}

function method_BrightenSmooth() {
	var pcalc = lookup[this.scale].positions[this.position];
	methodValueSmooth( this, pcalc );
}

function method_DarkenSmooth() {
	var pcalc = lookup[this.scale].positions[this.position];
	if ( this.method == DARKEN_S ) {
		pcalc.wleft *= -1;
		pcalc.wright *= -1;
	}
	methodValueSmooth( this, pcalc );
}

function methodValueSmooth( tgt, pcalc ){
	pixels[pcalc.left].red += tgt.color.r * pcalc.wleft;
	pixels[pcalc.left].green += tgt.color.g * pcalc.wleft;
	pixels[pcalc.left].blue += tgt.color.b * pcalc.wleft;

	pixels[pcalc.right].red += tgt.color.r * pcalc.wright;
	pixels[pcalc.right].green += tgt.color.g * pcalc.wright;
	pixels[pcalc.right].blue += tgt.color.b * pcalc.wright;
}

function method_Sweep() {
	var pcalc = lookup[this.scale].positions[this.position];

	var taillen = 6;
	var fraction = 1/taillen;

	for ( var t=0; t < taillen; t++ ) {
		try {
		var tail = pcalc.right - t;
	} catch ( err ) {
		console.log( i + " | " + this.position );
	}
		if ( tail > 0 ) {
			var factor = ( 6 - t ) * ( fraction );
			pixels[tail].red += this.color.r * factor;
			pixels[tail].green += this.color.g * factor;
			pixels[tail].blue += this.color.b * factor;
		}
	}
	var frontedge = pcalc.right + 1;
	if ( frontedge < pixelLength - 2 ) {
		pixels[frontedge].red = 0;
		pixels[frontedge].green = 0;
		pixels[frontedge].blue = 0;
	}
}

function setPixel( i, r, g, b ) {
	pixels[i].red = r;
	pixels[i].green = g;
	pixels[i].blue = b;
}

function initAllPixels( r, g, b ){
	for ( var i=0; i<pixels.length; i++ ) {
		pixels[i].red = r;
		pixels[i].green = g;
		pixels[i].blue = b;
	}
}

function addParticle( p ) {
	particles.push( p );
}

function deleteParticle( i ) {
	particles[i] = null;
	particles.splice( i, 1 );
}

function getProximateParticle( s, dist ) {
	var pos = Math.floor( s * ( environmentLength / sensorCount ) );
	return getParticle( 4, pos, 2,  method_BrightenSmooth, update_React, defaultScale, 85, 55, 15, 20 );
}

function getRandParticle() {
	var r = Math.random();

	if ( r < .10 ) {
		return getParticle( 4, 0, 1, method_BrightenSmooth, update_Smooth, defaultScale, 10, 10, 85, 0 );
//	} else if ( r < .15 ) {
//		return getParticle( 3, 0, 1, method_Sweep, update_Smooth, defaultScale, 60, 10, 15, 0 );
//	} else if ( r < .30 ) {
//		return getParticle( 3, 0, 1, method_Sweep, update_Smooth, defaultScale, 30, 30, 95, 0 );
	} else if ( r < .50 ) {
		return getParticle( 4, 0, 1, method_BrightenSmooth, update_Smooth, defaultScale, 45, 25, 100, 0 )
	} else {
		return getParticle( 2, 0, 1, method_BrightenSmooth, update_Smooth, defaultScale, 5, 5, 10, 0 );
	}
}

function getParticle( v, p, r, g, b ) {
	return getParticle( v, p, 1, method_Brighten, update_Discrete, defaultScale, r, g, b, 0 );
}

function getParticle( v, p, i, m, u, s, r, g, b, l ) {
  var p = {
    'vel': v,
    'position': p,
    'intensity': i,
		'method': m,
		'update': u,
		'scale': s,
    'color': { 'r': r, 'g': g, 'b': b },
		'life': l
  };
  return p;
}

// Serial Access

function listPorts() {
  serialport.list(function (err, ports) {
    ports.forEach(function(port) {
      console.log(port.comName);
    });
  });
  return ports;
}

function openPort() {
	serialport.on('error', function(err){
		console.log('serialport general error' + err);
	});

  serialport.open(function (error) {
    if ( error ) {
      console.log('open err: ' + error);
//			runState = "conn open err";
			runState = "open";
    } else {
      console.log('open');
			runState = "open";

      serialport.on('data', function(data) {
    		var c = data.trim();
				try{
					//console.log('rcv: ' + c);
	    		dist_v = JSON.parse(c);
					//dist_v = {};

					if ( SENSORTEST ) {
						var out = "";
						for ( var s=0; s < sensorCount; s++ ) {
							out += s + '=' + dist_v[s] + '  :  ';
						}
						console.log( out );
					}
				} catch( err ){
					console.log('parse err ' + err);
				}
	    });

    }
  });

}
<|endoftext|>


<commit_before>/**
 * Created by bdilday on 2/11/16.
 */

var margin = {top: 100, right: 10, bottom: 100, left: 300},
    width = 1100 - margin.left - margin.right,
    height = 800 - margin.top - margin.bottom;

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var x = d3.scale.linear()
    .range([0, width]);
var y = d3.scale.linear()
    .range([height, 0])
    .domain([0,1]);

var ynav = d3.scale.linear()
    .rangeRound([height, 0])
;

var ynavboxes = d3.scale.ordinal()
        .rangeRoundBands([height, 0])
    ;

var xaxis = d3.svg.axis()
    .orient("bottom")
    .scale(x);

var yaxis = d3.svg.axis()
    .orient("left")
    .scale(y);

var ynavaxis = d3.svg.axis()
    .orient("left")
    .scale(ynav);

var interpolate_type = 'linear';
var line = d3.svg.line()
    .x(function(d) {
        return x(d.x);
    })
    .y(function(d) {
        return y(d.y);
    })
    .interpolate(interpolate_type);

d3.json("pobguy.json", function(error, data) {
    console.log(data);

    var lines = {}
    var xd = [9999, -9999];
    var yd = [9999, -9999];

    var all_iys = _.uniq(
        _.map(data, function(d) {
            if (d.x > xd[1]) {
                xd[1] = d.x;
            }
            if (d.x < xd[0]) {
                xd[0] = d.x;
            }

            if (d.y > yd[1]) {
                yd[1] = d.y;
            }
            if (d.y < xd[0]) {
                yd[0] = d.y;
            }

            return parseInt(d.iy);
        })
    );

    var all_ixs = _.uniq(
        _.map(data, function(d) {
            return d.ix;
        })
    );

    console.log('all_iys', all_iys);
    console.log('min', _.min(all_iys));
    console.log('min', _.max(all_iys));
    console.log('ynav dom', [_.min(all_iys), _.max(all_iys)]);

    ynavboxes.domain(all_iys);
    x.domain(xd);
    ynav.domain(yd);

    var make_line = function(iy) {
        var t = [];
        _.forEach(data, function (d) {
            if (d.iy === iy) {
                var x = d.x;
                t.push({'x': d.x, 'y': d.v});
            }
        });

        return svg.append('path')
            .attr('d', line(t))
            .attr("stroke", function () {
                return 'black';
            })
            .attr("stroke-width", 2)
            .style('opacity', 0.1)
            .attr("fill", "none")
        ;

    }

    var make_lines = function() {
        _.forEach(all_iys, function(iy) {
            lines[iy] = make_line(iy);
        })
    };

    svg.append("g")
        .attr("class", "axis")
        .attr('transform', 'translate(0,' + height + ')')
        .call(xaxis)
        .append("text")
        .style("text-anchor", "middle")
        .text('Carry [ft]')
        .attr('x', 20)
        .attr('y', 20)
    ;

    svg.append("g")
        .attr("class", "axis")
        .attr('transform', 'translate(0,' + 0 + ')')
        .call(yaxis)
        .append("text")
        .style("text-anchor", "middle")
        .text('Batting Avg.')
        .attr('x', -50)
        .attr('y', 20)
        .attr('transform', 'rotate(-90)')
    ;

    svg.append("g")
        .attr("class", "axis")
        .attr('transform', 'translate(' + -100 + ',' + 0 + ')')
        .call(ynavaxis)
        .append("text")
        .style("text-anchor", "middle")
        .attr("x", -50)
        .text('Hang Time [s]')
    ;

    var col_gradient = ['#f4a582', '#b2182b',  'black', '#2166ac', '#d1e5f0'];

    var rect_mouse_in = function(d) {
        console.log('mouse in', d, d-col_gradient.length/2);
        _.forEach(col_gradient, function(e, i) {
            lines[d-parseInt(col_gradient.length/2)+i]
            .attr('stroke-width', 5)
            .style('opacity', 1)
            .attr('stroke', e);
        });
    };

    var rect_mouse_out = function(d) {
        console.log('mouse out', d);
        _.forEach(col_gradient, function(e, i) {
            lines[d-parseInt(col_gradient.length/2)+i]
                .attr('stroke-width', 1)
                .style('opacity', 0.2)
                .attr('stroke', 'black');
        });

    };

    var make_nav = function () {
        var dy = height/all_iys.length;
        _.forEach(all_iys, function(iy) {
            svg.append('rect')
                .attr('width', 52)
                .attr('height', dy)
                .attr('x', -97)
                .attr('y', function() {
                    return ynavboxes(iy);
                })
                .attr('id', 'rect-' + iy.toString())
                .attr('fill', 'black')
                .style('opacity', 0.3)
                .attr('cursor', 'pointer')
                .on('mouseover', function() {
                    rect_mouse_in(iy);
                })
                .on('mouseout', function() {
                    rect_mouse_out(iy);
                })
            ;
        });
    };

    make_lines();
    make_nav();

    svg.append('text')
        .attr('x', -150)
        .attr('y', -57)
        .text('mouseover here')
        .attr('font-weight', 'bold')
        .attr('transform', 'rotate(-90)')

});<commit_msg>colors on nav rects<commit_after>/**
 * Created by bdilday on 2/11/16.
 */

var margin = {top: 100, right: 10, bottom: 100, left: 300},
    width = 1100 - margin.left - margin.right,
    height = 800 - margin.top - margin.bottom;

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var x = d3.scale.linear()
    .range([0, width]);
var y = d3.scale.linear()
    .range([height, 0])
    .domain([0,1]);

var ynav = d3.scale.linear()
    .rangeRound([height, 0])
;

var ynavboxes = d3.scale.ordinal()
        .rangeRoundBands([height, 0])
    ;

var xaxis = d3.svg.axis()
    .orient("bottom")
    .scale(x);

var yaxis = d3.svg.axis()
    .orient("left")
    .scale(y);

var ynavaxis = d3.svg.axis()
    .orient("left")
    .scale(ynav);

var interpolate_type = 'linear';
var line = d3.svg.line()
    .x(function(d) {
        return x(d.x);
    })
    .y(function(d) {
        return y(d.y);
    })
    .interpolate(interpolate_type);

d3.json("pobguy.json", function(error, data) {
    console.log(data);

    var lines = {}
    var xd = [9999, -9999];
    var yd = [9999, -9999];

    var all_iys = _.uniq(
        _.map(data, function(d) {
            if (d.x > xd[1]) {
                xd[1] = d.x;
            }
            if (d.x < xd[0]) {
                xd[0] = d.x;
            }

            if (d.y > yd[1]) {
                yd[1] = d.y;
            }
            if (d.y < xd[0]) {
                yd[0] = d.y;
            }

            return parseInt(d.iy);
        })
    );

    var all_ixs = _.uniq(
        _.map(data, function(d) {
            return d.ix;
        })
    );

    console.log('all_iys', all_iys);
    console.log('min', _.min(all_iys));
    console.log('min', _.max(all_iys));
    console.log('ynav dom', [_.min(all_iys), _.max(all_iys)]);

    ynavboxes.domain(all_iys);
    x.domain(xd);
    ynav.domain(yd);

    var make_line = function(iy) {
        var t = [];
        _.forEach(data, function (d) {
            if (d.iy === iy) {
                var x = d.x;
                t.push({'x': d.x, 'y': d.v});
            }
        });

        return svg.append('path')
            .attr('d', line(t))
            .attr("stroke", function () {
                return 'black';
            })
            .attr("stroke-width", 2)
            .style('opacity', 0.1)
            .attr("fill", "none")
        ;

    }

    var make_lines = function() {
        _.forEach(all_iys, function(iy) {
            lines[iy] = make_line(iy);
        })
    };

    svg.append("g")
        .attr("class", "axis")
        .attr('transform', 'translate(0,' + height + ')')
        .call(xaxis)
        .append("text")
        .style("text-anchor", "middle")
        .text('Carry [ft]')
        .attr('x', 20)
        .attr('y', 20)
    ;

    svg.append("g")
        .attr("class", "axis")
        .attr('transform', 'translate(0,' + 0 + ')')
        .call(yaxis)
        .append("text")
        .style("text-anchor", "middle")
        .text('Batting Avg.')
        .attr('x', -50)
        .attr('y', 20)
        .attr('transform', 'rotate(-90)')
    ;

    svg.append("g")
        .attr("class", "axis")
        .attr('transform', 'translate(' + -100 + ',' + 0 + ')')
        .call(ynavaxis)
        .append("text")
        .style("text-anchor", "middle")
        .attr("x", -50)
        .text('Hang Time [s]')
    ;

    var col_gradient = ['#f4a582', '#b2182b',  'black', '#2166ac', '#d1e5f0'];
    var col_gradient_mid = parseInt(col_gradient.length/2);
    var opacity_scale = d3.scale.ordinal()
        .range([1, 0.5])
        .domain(_.range(col_gradient_mid));

    var rect_mouse_in = function(d) {
        console.log('mouse in', d, d-col_gradient.length/2);
        _.forEach(col_gradient, function(e, i) {

            var k = Math.abs(i-col_gradient_mid);
            lines[d+i-col_gradient_mid]
            .attr('stroke-width', 5)
            .style('opacity', opacity_scale(k))
            .attr('stroke', e);

            nav_rects[d+i-col_gradient_mid]
                .attr('stroke-width', 1)
                .style('opacity', opacity_scale(k))
                .attr('fill', e);

        });
    };

    var rect_mouse_out = function(d) {
        console.log('mouse out', d);
        _.forEach(col_gradient, function(e, i) {
            var k = Math.abs(i-col_gradient_mid);
            lines[d+i-col_gradient_mid]
                .attr('stroke-width', 1)
                .style('opacity', 0.2)
                .attr('stroke', 'black');

            nav_rects[d+i-col_gradient_mid]
                .attr('stroke-width', 1)
                .style('opacity', 0.3)
                .attr('fill', 'black');

        });

    };

    var nav_rects = {};
    var make_nav = function () {
        var dy = height/all_iys.length;
        _.forEach(all_iys, function(iy) {
            nav_rects[iy] = svg.append('rect')
                .attr('width', 52)
                .attr('height', dy)
                .attr('x', -97)
                .attr('y', function() {
                    return ynavboxes(iy);
                })
                .attr('id', 'rect-' + iy.toString())
                .attr('fill', 'black')
                .style('opacity', 0.3)
                .attr('cursor', 'pointer')
                .on('mouseover', function() {
                    rect_mouse_in(iy);
                })
                .on('mouseout', function() {
                    rect_mouse_out(iy);
                })
            ;
        });
    };

    make_lines();
    make_nav();

    svg.append('text')
        .attr('x', -150)
        .attr('y', -57)
        .text('mouseover here')
        .attr('font-weight', 'bold')
        .attr('transform', 'rotate(-90)')

});<|endoftext|>


<commit_before>/* line-store.js
 *
 * the store to put track lines into
 * different stores subtly alter the physics
 * so there needs to be old versions to remain backwards compatible
 */

var _ = require('lodash');

var { Grid, GridV62, GridV61, getCellHash } = require('./grid');

const GRID_SIZE = 14;

/* LineStore
 * - basic line store, no grid
 *
 * public:
 * - lines
 * - addLine(line)
 * - removeLine(line)
 * - getLines(x1, y1, x2 | r, [y2])
 * - selectCollidingLines(x, y, handler(line))
 */
class LineStore {
  constructor() {
    // if performance problems, will make this array sorted
    this.lines = [];
  }

  addLine(line) {
    this.lines.push(line);
  }

  removeLine(line) {
    this.lines = _.without(this.lines, line);
  }

  // returns an array of lines in this bounding box or radius
  getLines(x1, y1, x2, y2) {
    if (y2 === undefined) {
      let r = x2;
      return this.getLinesInRadius(x1, y1, r);
    }
    return this.getLinesInBox(x1, y1, x2, y2);
  }

  getLinesInRadius(x, y, r) {
    return _.filter(this.lines, line => line.inCircle(x, y, r));
  }

  getLinesInBox(x1, y1, x2, y2) {
    return _.filter(this.lines, line => line.inBox(x1, y1, x2, y2));
  }

  // the ordering of the lines affects the physics
  getSolidLinesAt(x, y, debug = false) {
    return _.filter(this.lines, line => line.isSolid);
  }

}

/* GridStore
 * - revision 6.2
 *
 * public:
 * - lines
 * - addLine(line) <- this adds property 'cells' to line
 * - removeLine(line)
 * - getLines(x1, y1, x2 | r, [y2])
 * - selectCollidingLines(x, y, handler(line))
 *
 * private:
 * - grid
 */
class GridStore extends LineStore {
  constructor() {
    super();

    // for solid lines
    this.solidGrid = new GridV62(GRID_SIZE, true);

    // for all lines
    // darn there was a clever data structure for this stuff what was it
    // i think it was 2d sorted arrays?
    // i'll do it later
    this.grid = new Grid(GRID_SIZE * 4, false);

    // for some reason, querying the grid is time consuming, so caching improves performance
    this.resetSolidLinesCache();
  }

  addLine(line) {
    super.addLine(line);

    this.grid.addLine(line);

    if (line.isSolid) {
      this.solidGrid.addLine(line);
      this.resetSolidLinesCache();
    }
  }

  removeLine(line) {
    super.removeLine(line);

    this.grid.removeLine(line);

    if (line.isSolid) {
      this.solidGrid.removeLine(line);
      this.resetSolidLinesCache();
    }
  }

  getSolidLinesAt(x, y, debug = false) {
    let cellPos = this.solidGrid.getCellPos(x, y);

    let key = getCellHash(cellPos.x, cellPos.y);
    let lines = this.solidLinesCache[key];
    if (lines) {
      return lines;
    }
    lines = [];

    let addLine = line => lines.push(line);

    // normally i would avoid for loops but lots of iterations here
    for (let i = -1; i <= 1; i++) {
      for (let j = -1; j <= 1; j++) {
        let lines = this.solidGrid.getLinesFromCell(i + cellPos.x, j + cellPos.y);
        for (let k = 0; k < lines.length; k++) {
          addLine(lines[k]);
        }
      }
    }

    this.solidLinesCache[key] = lines;

    return lines;
  }

  getLines(cPos) {
    return this.solidGrid.getLinesFromCell(cPos);
  }

  resetSolidLinesCache() {
    this.solidLinesCache = Object.create(null);
  }

}

/* OldGridStore
 * - revision 6.1
 * - grid bugs as feature
 *
 * public:
 * - lines
 * - addLine(line)
 * - removeLine(line)
 * - getLines(x1, y1, x2 | r, [y2])
 * - selectCollidingLines(x, y, handler(line))
 *
 * private:
 * - grid
 */
class OldGridStore extends GridStore {
  constructor() {
    super();

    this.solidGrid = new GridV61(GRID_SIZE, true);
  }

}

module.exports = {
  GRID_SIZE: GRID_SIZE,
  LineStore: LineStore,
  GridStore: GridStore,
  OldGridStore: OldGridStore
};
<commit_msg>add getLinesInRadius and getLinesInBox to GridStore<commit_after>/* line-store.js
 *
 * the store to put track lines into
 * different stores subtly alter the physics
 * so there needs to be old versions to remain backwards compatible
 */

var _ = require('lodash');

var { Grid, GridV62, GridV61, getCellHash } = require('./grid');

const GRID_SIZE = 14;

/* LineStore
 * - basic line store, no grid
 *
 * public:
 * - lines
 * - addLine(line)
 * - removeLine(line)
 * - getLines(x1, y1, x2 | r, [y2])
 * - selectCollidingLines(x, y, handler(line))
 */
class LineStore {
  constructor() {
    // if performance problems, will make this array sorted
    this.lines = [];
  }

  addLine(line) {
    this.lines.push(line);
  }

  removeLine(line) {
    this.lines = _.without(this.lines, line);
  }

  // returns an array of lines in this bounding box or radius
  getLines(x1, y1, x2, y2) {
    if (y2 === undefined) {
      let r = x2;
      return this.getLinesInRadius(x1, y1, r);
    }
    return this.getLinesInBox(x1, y1, x2, y2);
  }

  getLinesInRadius(x, y, r) {
    return _.filter(this.lines, line => line.inRadius(x, y, r));
  }

  getLinesInBox(x1, y1, x2, y2) {
    return _.filter(this.lines, line => line.inBox(x1, y1, x2, y2));
  }

  // the ordering of the lines affects the physics
  getSolidLinesAt(x, y, debug = false) {
    return _.filter(this.lines, line => line.isSolid);
  }

}

/* GridStore
 * - revision 6.2
 *
 * public:
 * - lines
 * - addLine(line) <- this adds property 'cells' to line
 * - removeLine(line)
 * - getLines(x1, y1, x2 | r, [y2])
 * - selectCollidingLines(x, y, handler(line))
 *
 * private:
 * - grid
 */
class GridStore extends LineStore {
  constructor() {
    super();

    // for solid lines
    this.solidGrid = new GridV62(GRID_SIZE, true);

    // for all lines
    // darn there was a clever data structure for this stuff what was it
    // i think it was 2d sorted arrays?
    // i'll do it later
    this.grid = new Grid(GRID_SIZE * 4, false);

    // for some reason, querying the grid is time consuming, so caching improves performance
    this.resetSolidLinesCache();
  }

  addLine(line) {
    super.addLine(line);

    this.grid.addLine(line);

    if (line.isSolid) {
      this.solidGrid.addLine(line);
      this.resetSolidLinesCache();
    }
  }

  removeLine(line) {
    super.removeLine(line);

    this.grid.removeLine(line);

    if (line.isSolid) {
      this.solidGrid.removeLine(line);
      this.resetSolidLinesCache();
    }
  }

  getSolidLinesAt(x, y, debug = false) {
    let cellPos = this.solidGrid.getCellPos(x, y);

    let key = getCellHash(cellPos.x, cellPos.y);
    let lines = this.solidLinesCache[key];
    if (lines) {
      return lines;
    }
    lines = [];

    let addLine = line => lines.push(line);

    // normally i would avoid for loops but lots of iterations here
    for (let i = -1; i <= 1; i++) {
      for (let j = -1; j <= 1; j++) {
        let lines = this.solidGrid.getLinesFromCell(i + cellPos.x, j + cellPos.y);
        for (let k = 0; k < lines.length; k++) {
          addLine(lines[k]);
        }
      }
    }

    this.solidLinesCache[key] = lines;

    return lines;
  }

  getLines(cPos) {
    return this.solidGrid.getLinesFromCell(cPos);
  }

  resetSolidLinesCache() {
    this.solidLinesCache = Object.create(null);
  }

  getLinesInRadius(x, y, r) {
    return this.grid.getLinesInRadius(x, y, r);
  }

  getLinesInBox(x1, y1, x2, y2) {
    return this.grid.getLinesInBox(x1, y1, x2, y2);
  }

}

/* OldGridStore
 * - revision 6.1
 * - grid bugs as feature
 *
 * public:
 * - lines
 * - addLine(line)
 * - removeLine(line)
 * - getLines(x1, y1, x2 | r, [y2])
 * - selectCollidingLines(x, y, handler(line))
 *
 * private:
 * - grid
 */
class OldGridStore extends GridStore {
  constructor() {
    super();

    this.solidGrid = new GridV61(GRID_SIZE, true);
  }

}

module.exports = {
  GRID_SIZE: GRID_SIZE,
  LineStore: LineStore,
  GridStore: GridStore,
  OldGridStore: OldGridStore
};
<|endoftext|>


<commit_before>describe("cdb.admin.Header", function() {

  beforeEach(function() {
    this.table = TestUtil.createTable();
    this.table.set({'description':''});
    this.user = TestUtil.createUser();
    this.container = $('
'+
      '

'+
      ''+
      'add tags'+
      '
');
    this.header = new cdb.admin.Header({
      el: this.container,
      $el: this.container,
      model: this.table,
      user: this.user,
      map: this.map,
      config: TestUtil.config,
      body: this.container
    });
    this.table.trigger('change');

  })

  afterEach(function() {
    this.header.clean();
    this.container.remove();
  });

  it("should contain a change_title link", function() {
    expect($(this.header.el).find('.change_title').length).toBeTruthy();
  })

  it("should create the title change dialog on click", function() {
    $(this.header.el).find('.change_title').click();
    waits(25);
    expect(this.header.title_dialog).toBeTruthy();
    $('.edit_name_dialog').remove();
  })

  it("should not let the user change the table name when the table is not writable", function() {
    this.header.table.sqlView = 'wadus';
    $(this.header.el).find('.change_title').click();
    waits(25);
    expect(this.header.title_dialog).toBeFalsy();
  })

  it("should open description_dialog on click", function() {
    $(this.header.el).find('.table_description p').click();
    waits(25);
    expect(this.header.description_dialog).toBeTruthy();
  })

  it("should not open description_dialog on click when sql aplied", function() {
    this.header.table.sqlView = 'wadus';
    $(this.header.el).find('.table_description p').click();
    waits(25);
    expect(this.header.description_dialog).toBeFalsy();
  })

  it("should open tags dialog on click", function() {
    $(this.header.el).find('.tags a').click();
    waits(25);
    expect(this.header.tags_dialog).toBeTruthy();
  })

  it("should not open tags dialog on click when sql aplied", function() {
    this.header.table.sqlView = 'wadus';
    $(this.header.el).find('.tags a').click();
    waits(25);
    expect(this.header.tags_dialog).toBeFalsy();
  })

  it("should add default description when no description", function() {
    expect($(this.header.el).find('.table_description p').html()).toEqual(this.header._TEXTS._DEFAULT_DESCRIPTION)
  })

  it("sh0uld add table description ", function() {
    this.table.set({'description': 'cachopada'});
    this.header.trigger('descriptionChanged');
    expect($(this.header.el).find('.table_description p').html()).toEqual('cachopada')
  })

  it("sh0uld add table description even when there's an sql ", function() {
    this.table.set({'description': 'cachopada'});
    this.table.sqlView = 'wadus';
    this.header.trigger('descriptionChanged');

    expect($(this.header.el).find('.table_description p').html()).toEqual('cachopada')
  })

  it("should add default tag button text when no tags", function() {
    expect($(this.header.el).find('.tags a').html()).toEqual(this.header._TEXTS._DEFAULT_ADD_TAG_BUTTON)
  })

  it("should remove tag button text when sql applied", function() {
    this.table.sqlView = 'wadus';
    this.table.trigger('change:dataSource');
    expect($(this.header.el).find('.tags a').html()).toBeFalsy();
  })

  it("should add tags", function() {
    this.table.set({'tags': 'cachopo,frixuelu'});
    this.header.trigger('tagsChanged');
    expect($(this.header.el).find('.tags a').html()).toEqual('2 tags');
  })

  it("should change tags button when there are tags", function() {
    this.table.set({'tags': 'cachopo,frixuelu'});
    this.header.trigger('tagsChanged');
    expect($(this.header.el).find('.tags a').html()).toEqual('2 tags')
  })

  it("should add the class empty when there are no tags", function() {
    this.table.set({'tags': ''});
    this.header.trigger('tagsChanged');
    expect($(this.header.el).find('.tags').hasClass("empty")).toEqual(true);
  })

  it("should remove the class empty when there are no tags", function() {
    this.table.set({'tags': ''});
    this.header.trigger('tagsChanged');

    this.table.set({'tags': 'cachopo'});
    this.header.trigger('tagsChanged');

    expect($(this.header.el).find('.tags').hasClass("empty")).toEqual(false);
  })

  it("should render the privacy", function() {
    expect($(this.header.el).find('.status').html()).toEqual('private')
  })

  it("should add the privacy class to the status selector link", function() {
    expect($(this.header.el).find('.status').hasClass('private')).toBeTruthy();
  })

  it("should update the privacy when changed", function() {
    this.table.set({'privacy':'public'}).trigger('privacyUpdated');
    expect($(this.header.el).find('.status').html()).toEqual('public')
  })

  it("should add the privacy class on the status selector link", function() {
    this.table.set({'privacy':'public'}).trigger('privacyUpdated');
    expect($(this.header.el).find('.status').hasClass('public')).toBeTruthy();
  })

  it("should remove the previous privacy  class when the status change", function() {
    this.table.set({'privacy':'public'}).trigger('privacyUpdated');
    expect($(this.header.el).find('.status').hasClass('private')).toBeFalsy();
  })

})
<commit_msg>fixed header tests<commit_after>describe("cdb.admin.Header", function() {

  beforeEach(function() {
    this.table = TestUtil.createTable();
    this.table.set({'description':''});
    this.user = TestUtil.createUser();
    this.container = $('
'+
      '

'+
      ''+
      'add tags'+
      '
');
    this.header = new cdb.admin.Header({
      el: this.container,
      $el: this.container,
      model: this.table,
      user: this.user,
      map: this.map,
      config: TestUtil.config,
      body: this.container
    });
    this.table.trigger('change');

  })

  afterEach(function() {
    this.header.clean();
    this.container.remove();
  });

  it("should contain a change_title link", function() {
    expect($(this.header.el).find('.change_title').length).toBeTruthy();
  })

  it("should create the title change dialog on click", function() {
    $(this.header.el).find('.change_title').click();
    waits(25);
    expect(this.header.title_dialog).toBeTruthy();
    $('.edit_name_dialog').remove();
  })

  it("should not let the user change the table name when the table is not writable", function() {
    this.header.table.sqlView = 'wadus';
    $(this.header.el).find('.change_title').click();
    waits(25);
    expect(this.header.title_dialog).toBeFalsy();
  })

  it("should open description_dialog on click", function() {
    $(this.header.el).find('.table_description p').click();
    waits(25);
    expect(this.header.description_dialog).toBeTruthy();
  })

  it("should not open description_dialog on click when sql aplied", function() {
    this.header.table.sqlView = 'wadus';
    $(this.header.el).find('.table_description p').click();
    waits(25);
    expect(this.header.description_dialog).toBeFalsy();
  })

  it("should open tags dialog on click", function() {
    $(this.header.el).find('.tags a').click();
    waits(25);
    expect(this.header.tags_dialog).toBeTruthy();
  })

  it("should not open tags dialog on click when sql aplied", function() {
    this.header.table.sqlView = 'wadus';
    $(this.header.el).find('.tags a').click();
    waits(25);
    expect(this.header.tags_dialog).toBeFalsy();
  })

  it("should add default description when no description", function() {
    expect($(this.header.el).find('.table_description p').html()).toEqual(this.header._TEXTS._DEFAULT_DESCRIPTION)
  })

  it("sh0uld add table description ", function() {
    this.table.set({'description': 'cachopada'});
    this.header.trigger('descriptionChanged');
    expect($(this.header.el).find('.table_description p').html()).toEqual('cachopada')
  })

  it("sh0uld add table description even when there's an sql ", function() {
    this.table.set({'description': 'cachopada'});
    this.table.sqlView = 'wadus';
    this.header.trigger('descriptionChanged');

    expect($(this.header.el).find('.table_description p').html()).toEqual('cachopada')
  })

  it("should add default tag button text when no tags", function() {
    expect($(this.header.el).find('.tags a').html()).toEqual(this.header._TEXTS._DEFAULT_ADD_TAG_BUTTON)
  })

  it("should not remove tag button text when sql applied", function() {
    this.table.sqlView = 'wadus';
    this.table.trigger('change:dataSource');
    expect($(this.header.el).find('.tags a').html()).toBeTrue();
  })

  it("should add tags", function() {
    this.table.set({'tags': 'cachopo,frixuelu'});
    this.header.trigger('tagsChanged');
    expect($(this.header.el).find('.tags a').html()).toEqual('2 tags');
  })

  it("should change tags button when there are tags", function() {
    this.table.set({'tags': 'cachopo,frixuelu'});
    this.header.trigger('tagsChanged');
    expect($(this.header.el).find('.tags a').html()).toEqual('2 tags')
  })

  it("should add the class empty when there are no tags", function() {
    this.table.set({'tags': ''});
    this.header.trigger('tagsChanged');
    expect($(this.header.el).find('.tags').hasClass("empty")).toEqual(true);
  })

  it("should remove the class empty when there are no tags", function() {
    this.table.set({'tags': ''});
    this.header.trigger('tagsChanged');

    this.table.set({'tags': 'cachopo'});
    this.header.trigger('tagsChanged');

    expect($(this.header.el).find('.tags').hasClass("empty")).toEqual(false);
  })

  it("should render the privacy", function() {
    expect($(this.header.el).find('.status').html()).toEqual('private')
  })

  it("should add the privacy class to the status selector link", function() {
    expect($(this.header.el).find('.status').hasClass('private')).toBeTruthy();
  })

  it("should update the privacy when changed", function() {
    this.table.set({'privacy':'public'}).trigger('privacyUpdated');
    expect($(this.header.el).find('.status').html()).toEqual('public')
  })

  it("should add the privacy class on the status selector link", function() {
    this.table.set({'privacy':'public'}).trigger('privacyUpdated');
    expect($(this.header.el).find('.status').hasClass('public')).toBeTruthy();
  })

  it("should remove the previous privacy  class when the status change", function() {
    this.table.set({'privacy':'public'}).trigger('privacyUpdated');
    expect($(this.header.el).find('.status').hasClass('private')).toBeFalsy();
  })

})
<|endoftext|>