<commit_before>"use strict";

/*  ------------------------------------------------------------------------ */

const [processPath, , exchangeId = null, exchangeSymbol = null] = process.argv.filter (x => !x.startsWith ('--'))
const ccxtFile = process.argv.includes ('--es6') ? 'ccxt.js' : 'ccxt-es5.js'

/*  ------------------------------------------------------------------------ */

const ccxt      = require ('./' + ccxtFile)
const countries = require ('./countries')

/*  ------------------------------------------------------------------------ */

const asTable   = require ('as-table')
const util      = require ('util')
const log       = require ('ololog')
const ansi      = require ('ansicolor').nice;
const fs        = require ('fs')

/*  ------------------------------------------------------------------------ */

const warn = log.bright.yellow.error // .error goes to stderr

/*  ------------------------------------------------------------------------ */

process.on ('uncaughtException',  e => { log.bright.red.error (e); process.exit (1) })
process.on ('unhandledRejection', e => { log.bright.red.error (e); process.exit (1) })

/*  ------------------------------------------------------------------------ */

log.bright ('\nTESTING', ccxtFile.magenta, { exchange: exchangeId || 'all', symbol: exchangeSymbol || 'all' }, '\n')

/*  ------------------------------------------------------------------------ */

let exchanges = {}
let proxies = [
    '',
    'https://cors-anywhere.herokuapp.com/',
    'https://crossorigin.me/',
    // 'http://cors-proxy.htmldriven.com/?url=', // we don't want this for now
]

// instantiate all exchanges
ccxt.exchanges.forEach (id => {
    exchanges[id] = new (ccxt)[id] ({ verbose: true })
})

// load api keys from config
let config = JSON.parse (fs.readFileSync ('./keys.json', 'utf8'))

// set up api keys appropriately
for (let id in config)
    for (let key in config[id])
        if (typeof exchanges[id] != 'undefined')
            exchanges[id][key] = config[id][key]

// move gdax to sandbox
exchanges['gdax'].urls['api'] = 'https://api-public.sandbox.gdax.com'

//-----------------------------------------------------------------------------

var countryName = function (code) {
    return ((typeof countries[code] !== 'undefined') ? countries[code] : code)
}

//-----------------------------------------------------------------------------

let sleep = (ms) => new Promise (resolve => setTimeout (resolve, ms));

//-----------------------------------------------------------------------------

let human_value = function (price) {
    return typeof price == 'undefined' ? 'N/A' : price
}

//-----------------------------------------------------------------------------

let testExchangeSymbolTicker = async (exchange, symbol) => {
    await sleep (exchange.rateLimit)
    log (exchange.id.green, symbol.green, 'fetching ticker...')
    let ticker = await exchange.fetchTicker (symbol)
    log (exchange.id.green, symbol.green, 'ticker',
        ticker['datetime'],
        'high: '    + human_value (ticker['high']),
        'low: '     + human_value (ticker['low']),
        'bid: '     + human_value (ticker['bid']),
        'ask: '     + human_value (ticker['ask']),
        'volume: '  + human_value (ticker['quoteVolume']))

    if (ticker['bid'] > ticker['ask'])
        log (this.id, symbol, 'ticker', 'bid is greater than ask!')

    return ticker;
}

let testExchangeSymbolOrderbook = async (exchange, symbol) => {
    await sleep (exchange.rateLimit)
    log (exchange.id.green, symbol.green, 'fetching order book...')
    let orderbook = await exchange.fetchOrderBook (symbol)
    log (exchange.id.green, symbol.green,
        orderbook['datetime'],
        'bid: '       + ((orderbook.bids.length > 0) ? human_value (orderbook.bids[0][0]) : 'N/A'),
        'bidVolume: ' + ((orderbook.bids.length > 0) ? human_value (orderbook.bids[0][1]) : 'N/A'),
        'ask: '       + ((orderbook.asks.length > 0) ? human_value (orderbook.asks[0][0]) : 'N/A'),
        'askVolume: ' + ((orderbook.asks.length > 0) ? human_value (orderbook.asks[0][1]) : 'N/A'))

    let bids = orderbook.bids
    if (bids.length > 1) {
        let first = 0
        let last = bids.length - 1
        if (bids[first][0] < bids[last][0])
            log (exchange.id, symbol, 'bids reversed!'.red.bright, bids[first][0], bids[last][0])
        else if (bids[first][0] > bids[last][0])
            log (exchange.id.green, symbol.green, 'bids ok')
    }
    let asks = orderbook.asks
    if (asks.length > 1) {
        let first = 0
        let last = asks.length - 1
        if (asks[first][0] > asks[last][0])
            log (exchange.id, symbol, 'asks reversed!'.red.bright, asks[first][0], asks[last][0])
        else if (asks[first][0] < asks[last][0])
            log (exchange.id.green, symbol.green, 'asks ok')
    }

    if (bids.length && asks.length)
        if (bids[0][0] > asks[0][0])
            log (this.id, symbol, 'order book', 'bid is greater than ask!'.red.bright)

    return orderbook
}

//-----------------------------------------------------------------------------

let testExchangeSymbolTrades = async (exchange, symbol) => {
    log (exchange.id.green, symbol.green, 'fetching trades...')
    let trades = await exchange.fetchTrades (symbol)
    log (exchange.id.green, symbol.green, 'fetched', Object.values (trades).length.toString ().green, 'trades')
    return trades
}

//-----------------------------------------------------------------------------

let testExchangeSymbol = async (exchange, symbol) => {
    await sleep (exchange.rateLimit)
    await testExchangeSymbolTicker (exchange, symbol)
    if (exchange.id == 'coinmarketcap') {
        // log (await exchange.fetchTickers ());
        log (await exchange.fetchGlobal ());
    } else {
        await testExchangeSymbolOrderbook (exchange, symbol)

        try {
            await testExchangeSymbolTrades (exchange, symbol)
        } catch (e) {
            if (e instanceof ccxt.ExchangeError) {
                warn (exchange.id, '[Exchange Error] ' + e.message)
            } else {
                throw e;
            }
        }

    }
    try {
        log (exchange.id.green, 'fetching all tickers at once...')
        let tickers = await exchange.fetchTickers ()
        log (exchange.id.green, 'fetched', Object.keys (tickers).length.toString ().green, 'tickers...')
    } catch (e) {
        if (e instanceof ccxt.ExchangeError) {
            log (exchange.id.green, 'fetching all tickers at once not supported.')
            // do nothing
        } else {
            throw e // rethrow
        }
    }
}

//-----------------------------------------------------------------------------

let testExchangeBalance = async (exchange, symbol) => {
    await sleep (exchange.rateLimit)
    log (exchange.id.green, 'fetching balance...')
    let balance = await exchange.fetchBalance ()

    let currencies = [
        'USD',
        'CNY',
        'EUR',
        'BTC',
        'ETH',
        'JPY',
        'LTC',
        'DASH',
        'DOGE',
        'UAH',
        'RUB',
    ]

    if ('info' in balance) {

        let result = currencies
            .filter (currency => (currency in balance) &&
                (typeof balance[currency]['total'] != 'undefined'))

        if (result.length > 0) {
            result = result.map (currency => currency + ': ' + human_value (balance[currency]['total']))
            if (exchange.currencies.length > result.length)
                result = result.join (', ') + ' + more...'
            else
                result = result.join (', ')

        } else {

            result = 'zero balance'
        }

        log (exchange.id.green, result)

    } else {

        log (exchange.id.green, exchange.omit (balance, 'info'))
    }
}

//-----------------------------------------------------------------------------

let loadExchange = async exchange => {
    let markets  = await exchange.loadMarkets ()
    let symbols = [
        'BTC/USD',
        'BTC/CNY',
        'BTC/EUR',
        'BTC/ETH',
        'ETH/BTC',
        'BTC/JPY',
        'ETH/EUR',
        'ETH/JPY',
        'ETH/CNY',
        'LTC/CNY',
        'DASH/BTC',
        'DOGE/BTC',
        'BTC/AUD',
        'BTC/PLN',
        'USD/SLL',
        'BTC/RUB',
        'BTC/UAH',
        'LTC/BTC',
    ]
    let result = exchange.symbols.filter (symbol => symbols.indexOf (symbol) >= 0)
    if (result.length > 0)
        if (exchange.symbols.length > result.length)
            result = result.join (', ') + ' + more...'
        else
            result = result.join (', ')
    log (exchange.id.green, exchange.symbols.length.toString ().bright.green, 'symbols', result)
}

//-----------------------------------------------------------------------------

let testExchange = async exchange => {

    let delay = exchange.rateLimit
    let symbol = exchange.symbols[0]
    let symbols = [
        'BTC/USD',
        'BTC/CNY',
        'BTC/EUR',
        'BTC/ETH',
        'ETH/BTC',
        'BTC/JPY',
        'LTC/BTC',
    ]
    for (let s in symbols) {
        if (exchange.symbols.includes (symbols[s])) {
            symbol = symbols[s]
            break
        }
    }

    log.green ('SYMBOL:', symbol)
    if ((symbol.indexOf ('.d') < 0)) {
        await testExchangeSymbol (exchange, symbol)
    }

    if (!exchange.apiKey || (exchange.apiKey.length < 1))
        return true

    await testExchangeBalance (exchange)

    // sleep (delay)
    // try {
    //     let marketSellOrder =
    //         await exchange.createMarketSellOrder (exchange.symbols[0], 1)
    //     console.log (exchange.id, 'ok', marketSellOrder)
    // } catch (e) {
    //     console.log (exchange.id, 'error', 'market sell', e)
    // }

    // sleep (delay)
    // try {
    //     let marketBuyOrder = await exchange.createMarketBuyOrder (exchange.symbols[0], 1)
    //     console.log (exchange.id, 'ok', marketBuyOrder)
    // } catch (e) {
    //     console.log (exchange.id, 'error', 'market buy', e)
    // }

    // sleep (delay)
    // try {
    //     let limitSellOrder = await exchange.createLimitSellOrder (exchange.symbols[0], 1, 3000)
    //     console.log (exchange.id, 'ok', limitSellOrder)
    // } catch (e) {
    //     console.log (exchange.id, 'error', 'limit sell', e)
    // }

    // sleep (delay)
    // try {
    //     let limitBuyOrder = await exchange.createLimitBuyOrder (exchange.symbols[0], 1, 3000)
    //     console.log (exchange.id, 'ok', limitBuyOrder)
    // } catch (e) {
    //     console.log (exchange.id, 'error', 'limit buy', e)
    // }

}

//-----------------------------------------------------------------------------

let printExchangesTable = function () {
    let astable = asTable.configure ({ delimiter: ' | ' })
    console.log (astable (Object.values (exchanges).map (exchange => {
        let website = Array.isArray (exchange.urls.www) ?
            exchange.urls.www[0] :
            exchange.urls.www
        let countries = Array.isArray (exchange.countries) ?
            exchange.countries.map (countryName).join (', ') :
            countryName (exchange.countries)
        let doc = Array.isArray (exchange.urls.doc) ?
            exchange.urls.doc[0] :
            exchange.urls.doc
        return {
            'id':        exchange.id,
            'name':      exchange.name,
            'countries': countries,
        }
    })))
}

//-----------------------------------------------------------------------------

let tryAllProxies = async function (exchange, proxies) {

    let currentProxy = 0
    let maxRetries   = proxies.length

    // a special case for ccex
    if (exchange.id == 'ccex')
        currentProxy = 1

    for (let numRetries = 0; numRetries < maxRetries; numRetries++) {

        try {

            exchange.proxy = proxies[currentProxy]
            await loadExchange (exchange)
            await testExchange (exchange)
            break

        } catch (e) {

            currentProxy = ++currentProxy % proxies.length
            if (e instanceof ccxt.DDoSProtection) {
                warn (exchange.id, '[DDoS Protection] ' + e.message)
            } else if (e instanceof ccxt.RequestTimeout) {
                warn (exchange.id, '[Request Timeout] ' + e.message)
            } else if (e instanceof ccxt.AuthenticationError) {
                warn (exchange.id, '[Authentication Error] ' + e.message)
            } else if (e instanceof ccxt.ExchangeNotAvailable) {
                warn (exchange.id, '[Exchange Not Available] ' + e.message)
            } else if (e instanceof ccxt.ExchangeError) {
                warn (exchange.id, '[Exchange Error] ' + e.message)
            } else {
                throw e;
            }
        }

    }
}

//-----------------------------------------------------------------------------

var test = async function () {

    // printExchangesTable ()

    if (exchangeId) {

        const exchange = exchanges[exchangeId]

        if (!exchange)
            throw new Error ('Exchange `' + exchangeId + '` not found')

        if (exchangeSymbol) {

            await loadExchange (exchange)
            await (exchangeSymbol == 'balance') ?
                testExchangeBalance (exchange) :
                testExchangeSymbol (exchange, exchangeSymbol)

        } else {

            await tryAllProxies (exchange, proxies)
        }

    } else {

        for (const id of Object.keys (exchanges)) {

            log.bright.green ('EXCHANGE:', id)
            const exchange = exchanges[id]
            await tryAllProxies (exchange, proxies)

        }
    }

    process.exit ();

} ()

<commit_msg>test verbosity off [ci skip]<commit_after>"use strict";

/*  ------------------------------------------------------------------------ */

const [processPath, , exchangeId = null, exchangeSymbol = null] = process.argv.filter (x => !x.startsWith ('--'))
const ccxtFile = process.argv.includes ('--es6') ? 'ccxt.js' : 'ccxt-es5.js'

/*  ------------------------------------------------------------------------ */

const ccxt      = require ('./' + ccxtFile)
const countries = require ('./countries')

/*  ------------------------------------------------------------------------ */

const asTable   = require ('as-table')
const util      = require ('util')
const log       = require ('ololog')
const ansi      = require ('ansicolor').nice;
const fs        = require ('fs')

/*  ------------------------------------------------------------------------ */

const warn = log.bright.yellow.error // .error goes to stderr

/*  ------------------------------------------------------------------------ */

process.on ('uncaughtException',  e => { log.bright.red.error (e); process.exit (1) })
process.on ('unhandledRejection', e => { log.bright.red.error (e); process.exit (1) })

/*  ------------------------------------------------------------------------ */

log.bright ('\nTESTING', ccxtFile.magenta, { exchange: exchangeId || 'all', symbol: exchangeSymbol || 'all' }, '\n')

/*  ------------------------------------------------------------------------ */

let exchanges = {}
let proxies = [
    '',
    'https://cors-anywhere.herokuapp.com/',
    'https://crossorigin.me/',
    // 'http://cors-proxy.htmldriven.com/?url=', // we don't want this for now
]

// instantiate all exchanges
ccxt.exchanges.forEach (id => {
    exchanges[id] = new (ccxt)[id] ({ verbose: false })
})

// load api keys from config
let config = JSON.parse (fs.readFileSync ('./keys.json', 'utf8'))

// set up api keys appropriately
for (let id in config)
    for (let key in config[id])
        if (typeof exchanges[id] != 'undefined')
            exchanges[id][key] = config[id][key]

// move gdax to sandbox
exchanges['gdax'].urls['api'] = 'https://api-public.sandbox.gdax.com'

//-----------------------------------------------------------------------------

var countryName = function (code) {
    return ((typeof countries[code] !== 'undefined') ? countries[code] : code)
}

//-----------------------------------------------------------------------------

let sleep = (ms) => new Promise (resolve => setTimeout (resolve, ms));

//-----------------------------------------------------------------------------

let human_value = function (price) {
    return typeof price == 'undefined' ? 'N/A' : price
}

//-----------------------------------------------------------------------------

let testExchangeSymbolTicker = async (exchange, symbol) => {
    await sleep (exchange.rateLimit)
    log (exchange.id.green, symbol.green, 'fetching ticker...')
    let ticker = await exchange.fetchTicker (symbol)
    log (exchange.id.green, symbol.green, 'ticker',
        ticker['datetime'],
        'high: '    + human_value (ticker['high']),
        'low: '     + human_value (ticker['low']),
        'bid: '     + human_value (ticker['bid']),
        'ask: '     + human_value (ticker['ask']),
        'volume: '  + human_value (ticker['quoteVolume']))

    if (ticker['bid'] > ticker['ask'])
        log (this.id, symbol, 'ticker', 'bid is greater than ask!')

    return ticker;
}

let testExchangeSymbolOrderbook = async (exchange, symbol) => {
    await sleep (exchange.rateLimit)
    log (exchange.id.green, symbol.green, 'fetching order book...')
    let orderbook = await exchange.fetchOrderBook (symbol)
    log (exchange.id.green, symbol.green,
        orderbook['datetime'],
        'bid: '       + ((orderbook.bids.length > 0) ? human_value (orderbook.bids[0][0]) : 'N/A'),
        'bidVolume: ' + ((orderbook.bids.length > 0) ? human_value (orderbook.bids[0][1]) : 'N/A'),
        'ask: '       + ((orderbook.asks.length > 0) ? human_value (orderbook.asks[0][0]) : 'N/A'),
        'askVolume: ' + ((orderbook.asks.length > 0) ? human_value (orderbook.asks[0][1]) : 'N/A'))

    let bids = orderbook.bids
    if (bids.length > 1) {
        let first = 0
        let last = bids.length - 1
        if (bids[first][0] < bids[last][0])
            log (exchange.id, symbol, 'bids reversed!'.red.bright, bids[first][0], bids[last][0])
        else if (bids[first][0] > bids[last][0])
            log (exchange.id.green, symbol.green, 'bids ok')
    }
    let asks = orderbook.asks
    if (asks.length > 1) {
        let first = 0
        let last = asks.length - 1
        if (asks[first][0] > asks[last][0])
            log (exchange.id, symbol, 'asks reversed!'.red.bright, asks[first][0], asks[last][0])
        else if (asks[first][0] < asks[last][0])
            log (exchange.id.green, symbol.green, 'asks ok')
    }

    if (bids.length && asks.length)
        if (bids[0][0] > asks[0][0])
            log (this.id, symbol, 'order book', 'bid is greater than ask!'.red.bright)

    return orderbook
}

//-----------------------------------------------------------------------------

let testExchangeSymbolTrades = async (exchange, symbol) => {
    log (exchange.id.green, symbol.green, 'fetching trades...')
    let trades = await exchange.fetchTrades (symbol)
    log (exchange.id.green, symbol.green, 'fetched', Object.values (trades).length.toString ().green, 'trades')
    return trades
}

//-----------------------------------------------------------------------------

let testExchangeSymbol = async (exchange, symbol) => {
    await sleep (exchange.rateLimit)
    await testExchangeSymbolTicker (exchange, symbol)
    if (exchange.id == 'coinmarketcap') {
        // log (await exchange.fetchTickers ());
        log (await exchange.fetchGlobal ());
    } else {
        await testExchangeSymbolOrderbook (exchange, symbol)

        try {
            await testExchangeSymbolTrades (exchange, symbol)
        } catch (e) {
            if (e instanceof ccxt.ExchangeError) {
                warn (exchange.id, '[Exchange Error] ' + e.message)
            } else {
                throw e;
            }
        }

    }
    try {
        log (exchange.id.green, 'fetching all tickers at once...')
        let tickers = await exchange.fetchTickers ()
        log (exchange.id.green, 'fetched', Object.keys (tickers).length.toString ().green, 'tickers...')
    } catch (e) {
        if (e instanceof ccxt.ExchangeError) {
            log (exchange.id.green, 'fetching all tickers at once not supported.')
            // do nothing
        } else {
            throw e // rethrow
        }
    }
}

//-----------------------------------------------------------------------------

let testExchangeBalance = async (exchange, symbol) => {
    await sleep (exchange.rateLimit)
    log (exchange.id.green, 'fetching balance...')
    let balance = await exchange.fetchBalance ()

    let currencies = [
        'USD',
        'CNY',
        'EUR',
        'BTC',
        'ETH',
        'JPY',
        'LTC',
        'DASH',
        'DOGE',
        'UAH',
        'RUB',
    ]

    if ('info' in balance) {

        let result = currencies
            .filter (currency => (currency in balance) &&
                (typeof balance[currency]['total'] != 'undefined'))

        if (result.length > 0) {
            result = result.map (currency => currency + ': ' + human_value (balance[currency]['total']))
            if (exchange.currencies.length > result.length)
                result = result.join (', ') + ' + more...'
            else
                result = result.join (', ')

        } else {

            result = 'zero balance'
        }

        log (exchange.id.green, result)

    } else {

        log (exchange.id.green, exchange.omit (balance, 'info'))
    }
}

//-----------------------------------------------------------------------------

let loadExchange = async exchange => {
    let markets  = await exchange.loadMarkets ()
    let symbols = [
        'BTC/USD',
        'BTC/CNY',
        'BTC/EUR',
        'BTC/ETH',
        'ETH/BTC',
        'BTC/JPY',
        'ETH/EUR',
        'ETH/JPY',
        'ETH/CNY',
        'LTC/CNY',
        'DASH/BTC',
        'DOGE/BTC',
        'BTC/AUD',
        'BTC/PLN',
        'USD/SLL',
        'BTC/RUB',
        'BTC/UAH',
        'LTC/BTC',
    ]
    let result = exchange.symbols.filter (symbol => symbols.indexOf (symbol) >= 0)
    if (result.length > 0)
        if (exchange.symbols.length > result.length)
            result = result.join (', ') + ' + more...'
        else
            result = result.join (', ')
    log (exchange.id.green, exchange.symbols.length.toString ().bright.green, 'symbols', result)
}

//-----------------------------------------------------------------------------

let testExchange = async exchange => {

    let delay = exchange.rateLimit
    let symbol = exchange.symbols[0]
    let symbols = [
        'BTC/USD',
        'BTC/CNY',
        'BTC/EUR',
        'BTC/ETH',
        'ETH/BTC',
        'BTC/JPY',
        'LTC/BTC',
    ]
    for (let s in symbols) {
        if (exchange.symbols.includes (symbols[s])) {
            symbol = symbols[s]
            break
        }
    }

    log.green ('SYMBOL:', symbol)
    if ((symbol.indexOf ('.d') < 0)) {
        await testExchangeSymbol (exchange, symbol)
    }

    if (!exchange.apiKey || (exchange.apiKey.length < 1))
        return true

    await testExchangeBalance (exchange)

    // sleep (delay)
    // try {
    //     let marketSellOrder =
    //         await exchange.createMarketSellOrder (exchange.symbols[0], 1)
    //     console.log (exchange.id, 'ok', marketSellOrder)
    // } catch (e) {
    //     console.log (exchange.id, 'error', 'market sell', e)
    // }

    // sleep (delay)
    // try {
    //     let marketBuyOrder = await exchange.createMarketBuyOrder (exchange.symbols[0], 1)
    //     console.log (exchange.id, 'ok', marketBuyOrder)
    // } catch (e) {
    //     console.log (exchange.id, 'error', 'market buy', e)
    // }

    // sleep (delay)
    // try {
    //     let limitSellOrder = await exchange.createLimitSellOrder (exchange.symbols[0], 1, 3000)
    //     console.log (exchange.id, 'ok', limitSellOrder)
    // } catch (e) {
    //     console.log (exchange.id, 'error', 'limit sell', e)
    // }

    // sleep (delay)
    // try {
    //     let limitBuyOrder = await exchange.createLimitBuyOrder (exchange.symbols[0], 1, 3000)
    //     console.log (exchange.id, 'ok', limitBuyOrder)
    // } catch (e) {
    //     console.log (exchange.id, 'error', 'limit buy', e)
    // }

}

//-----------------------------------------------------------------------------

let printExchangesTable = function () {
    let astable = asTable.configure ({ delimiter: ' | ' })
    console.log (astable (Object.values (exchanges).map (exchange => {
        let website = Array.isArray (exchange.urls.www) ?
            exchange.urls.www[0] :
            exchange.urls.www
        let countries = Array.isArray (exchange.countries) ?
            exchange.countries.map (countryName).join (', ') :
            countryName (exchange.countries)
        let doc = Array.isArray (exchange.urls.doc) ?
            exchange.urls.doc[0] :
            exchange.urls.doc
        return {
            'id':        exchange.id,
            'name':      exchange.name,
            'countries': countries,
        }
    })))
}

//-----------------------------------------------------------------------------

let tryAllProxies = async function (exchange, proxies) {

    let currentProxy = 0
    let maxRetries   = proxies.length

    // a special case for ccex
    if (exchange.id == 'ccex')
        currentProxy = 1

    for (let numRetries = 0; numRetries < maxRetries; numRetries++) {

        try {

            exchange.proxy = proxies[currentProxy]
            await loadExchange (exchange)
            await testExchange (exchange)
            break

        } catch (e) {

            currentProxy = ++currentProxy % proxies.length
            if (e instanceof ccxt.DDoSProtection) {
                warn (exchange.id, '[DDoS Protection] ' + e.message)
            } else if (e instanceof ccxt.RequestTimeout) {
                warn (exchange.id, '[Request Timeout] ' + e.message)
            } else if (e instanceof ccxt.AuthenticationError) {
                warn (exchange.id, '[Authentication Error] ' + e.message)
            } else if (e instanceof ccxt.ExchangeNotAvailable) {
                warn (exchange.id, '[Exchange Not Available] ' + e.message)
            } else if (e instanceof ccxt.ExchangeError) {
                warn (exchange.id, '[Exchange Error] ' + e.message)
            } else {
                throw e;
            }
        }

    }
}

//-----------------------------------------------------------------------------

var test = async function () {

    // printExchangesTable ()

    if (exchangeId) {

        const exchange = exchanges[exchangeId]

        if (!exchange)
            throw new Error ('Exchange `' + exchangeId + '` not found')

        if (exchangeSymbol) {

            await loadExchange (exchange)
            await (exchangeSymbol == 'balance') ?
                testExchangeBalance (exchange) :
                testExchangeSymbol (exchange, exchangeSymbol)

        } else {

            await tryAllProxies (exchange, proxies)
        }

    } else {

        for (const id of Object.keys (exchanges)) {

            log.bright.green ('EXCHANGE:', id)
            const exchange = exchanges[id]
            await tryAllProxies (exchange, proxies)

        }
    }

    process.exit ();

} ()

<|endoftext|>


<commit_before>/* eslint-env mocha */
/* eslint-disable new-cap, max-nested-callbacks */

'use strict';

const fs = require('fs');
const path = require('path');
const expect = require('chai').expect;
const tempy = require('tempy');
const unzipper = require('unzipper');
const execa = require('execa');
const scow = require('.');

describe('scow()', () => {
  const outputDir = tempy.directory();
  const zipPath = path.join(outputDir, 'index.zip');
  let outputHtml;
  let outputHtmlCompressed;

  const createTestFile = opts => {
    const output = opts.compress ? tempy.directory() : outputDir;

    return scow('fixtures/*.html', output, opts).then(() => new Promise((resolve, reject) => {
      fs.createReadStream(path.join(output, 'index.zip'))
        .pipe(unzipper.ParseOne(/index.html/))
        .on('entry', entry => {
          entry.buffer().then(contents => {
            resolve(contents.toString());
          }).catch(reject);
        })
        .on('error', reject);
    }));
  };

  before(() => {
    return Promise.all([
      createTestFile({}),
      createTestFile({compress: true})
    ]).then(res => {
      outputHtml = res[0];
      outputHtmlCompressed = res[1];
    });
  });

  it('names the ZIP file the same as the original HTML file', done => {
    fs.access(zipPath, fs.F_OK, err => {
      expect(err).to.equal(null);
      done();
    });
  });

  it('inlines CSS into HTML', () => {
    expect(outputHtml).to.contain('style="width: 100vw');
  });

  it('holds media query CSS in a <style> tag', () => {
    expect(outputHtml).to.contain('@media screen');
  });

  it('removes unused CSS from <style> tag', () => {
    expect(outputHtml).to.not.contain('.unused');
  });

  it('allows HTML to be compressed', () => {
    expect(outputHtmlCompressed).to.contain('<!doctype html>\n<html>\n<head>');
  });

  it('allows media queries to be meregd', () => {
    expect(outputHtmlCompressed.match(/@media/g)).to.have.a.lengthOf(1);
  });

  it('bundles referenced images', done => {
    let found = false;

    fs.createReadStream(zipPath)
      .pipe(unzipper.ParseOne(/kitty.jpg/))
      .on('entry', () => {
        found = true;
      })
      .on('finish', () => {
        expect(found).to.equal(true);
        done();
      })
      .on('error', done);
  });
});

describe('scow CLI', () => {
  it('creates a ZIP file', done => {
    const outputDir = tempy.directory();
    execa(path.join(__dirname, 'cli.js'), ['fixtures/*.html', outputDir])
      .then(() => {
        const zipPath = path.join(outputDir, 'index.zip');

        fs.stat(zipPath, fs.F_OK, err => {
          expect(err).to.equal(null);
          done();
        });
      })
      .catch(done);
  });

  it('allows HTML to be compressed', done => {
    const outputDir = tempy.directory();
    const zipPath = path.join(outputDir, 'index.zip');
    const test = () => {
      fs.createReadStream(zipPath)
        .pipe(unzipper.ParseOne(/index.html/))
        .on('entry', entry => {
          entry.buffer().then(contents => {
            expect(contents.toString()).to.contain('<!doctype html>\n<html>\n<head>');
            done();
          }).catch(done);
        })
        .on('error', done);
    };

    execa(path.join(__dirname, 'cli.js'), ['fixtures/*.html', outputDir, '--compress'])
      .then(test)
      .catch(done);
  });
});
<commit_msg>Use fs.access instead of fs.stat to check file existence<commit_after>/* eslint-env mocha */
/* eslint-disable new-cap, max-nested-callbacks */

'use strict';

const fs = require('fs');
const path = require('path');
const expect = require('chai').expect;
const tempy = require('tempy');
const unzipper = require('unzipper');
const execa = require('execa');
const scow = require('.');

describe('scow()', () => {
  const outputDir = tempy.directory();
  const zipPath = path.join(outputDir, 'index.zip');
  let outputHtml;
  let outputHtmlCompressed;

  const createTestFile = opts => {
    const output = opts.compress ? tempy.directory() : outputDir;

    return scow('fixtures/*.html', output, opts).then(() => new Promise((resolve, reject) => {
      fs.createReadStream(path.join(output, 'index.zip'))
        .pipe(unzipper.ParseOne(/index.html/))
        .on('entry', entry => {
          entry.buffer().then(contents => {
            resolve(contents.toString());
          }).catch(reject);
        })
        .on('error', reject);
    }));
  };

  before(() => {
    return Promise.all([
      createTestFile({}),
      createTestFile({compress: true})
    ]).then(res => {
      outputHtml = res[0];
      outputHtmlCompressed = res[1];
    });
  });

  it('names the ZIP file the same as the original HTML file', done => {
    fs.access(zipPath, fs.F_OK, err => {
      expect(err).to.equal(null);
      done();
    });
  });

  it('inlines CSS into HTML', () => {
    expect(outputHtml).to.contain('style="width: 100vw');
  });

  it('holds media query CSS in a <style> tag', () => {
    expect(outputHtml).to.contain('@media screen');
  });

  it('removes unused CSS from <style> tag', () => {
    expect(outputHtml).to.not.contain('.unused');
  });

  it('allows HTML to be compressed', () => {
    expect(outputHtmlCompressed).to.contain('<!doctype html>\n<html>\n<head>');
  });

  it('allows media queries to be meregd', () => {
    expect(outputHtmlCompressed.match(/@media/g)).to.have.a.lengthOf(1);
  });

  it('bundles referenced images', done => {
    let found = false;

    fs.createReadStream(zipPath)
      .pipe(unzipper.ParseOne(/kitty.jpg/))
      .on('entry', () => {
        found = true;
      })
      .on('finish', () => {
        expect(found).to.equal(true);
        done();
      })
      .on('error', done);
  });
});

describe('scow CLI', () => {
  it('creates a ZIP file', done => {
    const outputDir = tempy.directory();
    execa(path.join(__dirname, 'cli.js'), ['fixtures/*.html', outputDir])
      .then(() => {
        const zipPath = path.join(outputDir, 'index.zip');

        fs.access(zipPath, (fs.constants || fs).F_OK, err => {
          expect(err).to.equal(null);
          done();
        });
      })
      .catch(done);
  });

  it('allows HTML to be compressed', done => {
    const outputDir = tempy.directory();
    const zipPath = path.join(outputDir, 'index.zip');
    const test = () => {
      fs.createReadStream(zipPath)
        .pipe(unzipper.ParseOne(/index.html/))
        .on('entry', entry => {
          entry.buffer().then(contents => {
            expect(contents.toString()).to.contain('<!doctype html>\n<html>\n<head>');
            done();
          }).catch(done);
        })
        .on('error', done);
    };

    execa(path.join(__dirname, 'cli.js'), ['fixtures/*.html', outputDir, '--compress'])
      .then(test)
      .catch(done);
  });
});
<|endoftext|>


<commit_before>var unirest = require('unirest');
var moment = require('moment');

var sections = [];
var classes = {};
var innerFlag = 0;
var please = "11";

/*

{
    className: [
        {
            section: CMSC132-0101
            times: [
                {
                    days: MWF,
                    start: fdsa,
                    end: fewage
                },
                ...
            ]
        },
        ...
    ],
    ...
}

*/

testFunction = function(classNames) {
    for (let k = 0; k < classNames.length; k++) {
        unirest
        .get('http://api.umd.io/v0/courses/' + classNames[k])
        .end((response) => {
            sections = response.body['sections'];
            //console.log(response.body['sections']);
            var className = response.body['course_id'];
            innerFlag += sections.length;
            classes[className] = [];
            sections.map(function(section) {
                unirest
                .get('http://api.umd.io/v0/courses/sections/' + section)
                .end(function(response) {
                    //console.log(response.body);
                    //console.log(response.body['section_id']);
                    //console.log(response.body['meetings'][0]['start_time']);
                    //console.log(response.body['meetings'][0]['end_time']);

                    var sectionName = response.body['section_id'];
                    var meetingTimes = [];
                    response.body['meetings'].map((meeting) => {
                        var startTime = meeting['start_time'];
                        if (startTime == "")
                            return;

                        var endTime = meeting['end_time']
                        var startTimeFormatted = moment(startTime, ["h:mmA"]).format("HHmm");
                        var endTimeFormatted = moment(endTime, ["h:mmA"]).format("HHmm");
                        //console.log(response.body['meetings'][0]['days']);

                        var dayString = response.body['meetings'][0]['days'].toString();

                        for (let i = 0; i < dayString.length - 1; i++) {
                            var dayChar = "";
                            if (dayString[i] != 'T') {
                                dayChar = dayString[i];
                            } else {
                                dayChar = dayString[i] + dayString[i + 1];
                                i++;
                            }

                            var sectionObj = {
                                days: dayChar,
                                start: startTimeFormatted,
                                end: endTimeFormatted
                            }
                            //console.log(sectionObj);

                            meetingTimes.push(sectionObj);
                        }
                    });

                    classes[className].push({
                        section: sectionName,
                        times: meetingTimes
                    });

                    innerFlag--;
                    if (innerFlag == 0) {
                        //console.log(classes)
                        asdf(classes);
                        return classes;
                    }
                });
            });
        });
    }
};

/*
while (flag != 0) {
    console.log(flag);
}
console.log(classes);*/

// Contains functions to help filter one person
validateFirst = function(classes) {
    var goodOnes = [[]];
    var notPossible = false;
    //contains sets of valid MeetingTimes
    var count;
    //Go through all classes
    for (count = 0; count < classes.length; count++) {
        var newGoodOnes = [[]];
        //Go through all the section times per class
        c.forEach(meeting) {
            var foundMatch = false;
            //MeetingTimes in the class
            if (count == 0) { //add array with the single meeting to goodOnes
                var tmp = [];
                tmp.push(meeting);
                goodOnes.push(tmp);
            } else {
                //Current  set of already compatible section times in goodOnes
                goodOnes.forEach(possibleMeetings) {
                    //no conflicts with this possibleMeeting combination
                    if (!hasConflict(meeting, possibleMeetings)) {
                       newGoodOnes.push(possibleMeetings.push(meeting));
                       foundMatch = true;
                    }
                }
            }

            if (!foundMatch) {
                return null;
            }
        }

        goodOnes = newGoodOnes;
    }

    return goodOnes;
}

//Determines if a meeting conflicts with a set of already validated meetings
hasConflict = function(curr, sections) {
    curr.forEach(t) { // times is a field in the meetingTimes object.
        sections.forEach(s) {
            st.forEach(s.times) {
                if (t.day == st.day) {
                    if ((t.start > st.start && t.start < st.end) || (t.end > st.start && t.end < st.end)) {
                        return true;
                    }
                }
            }
        }
    }
    return false;
}

testFunction(['ENES100', 'CMSC131']);

<commit_msg>hasConflict method for each fixes<commit_after>var unirest = require('unirest');
var moment = require('moment');

var sections = [];
var classes = {};
var innerFlag = 0;
var please = "11";

/*

{
    className: [
        {
            section: CMSC132-0101
            times: [
                {
                    days: MWF,
                    start: fdsa,
                    end: fewage
                },
                ...
            ]
        },
        ...
    ],
    ...
}

*/

testFunction = function(classNames) {
    for (let k = 0; k < classNames.length; k++) {
        unirest
        .get('http://api.umd.io/v0/courses/' + classNames[k])
        .end((response) => {
            sections = response.body['sections'];
            //console.log(response.body['sections']);
            var className = response.body['course_id'];
            innerFlag += sections.length;
            classes[className] = [];
            sections.map(function(section) {
                unirest
                .get('http://api.umd.io/v0/courses/sections/' + section)
                .end(function(response) {
                    //console.log(response.body);
                    //console.log(response.body['section_id']);
                    //console.log(response.body['meetings'][0]['start_time']);
                    //console.log(response.body['meetings'][0]['end_time']);

                    var sectionName = response.body['section_id'];
                    var meetingTimes = [];
                    response.body['meetings'].map((meeting) => {
                        var startTime = meeting['start_time'];
                        if (startTime == "")
                            return;

                        var endTime = meeting['end_time']
                        var startTimeFormatted = moment(startTime, ["h:mmA"]).format("HHmm");
                        var endTimeFormatted = moment(endTime, ["h:mmA"]).format("HHmm");
                        //console.log(response.body['meetings'][0]['days']);

                        var dayString = response.body['meetings'][0]['days'].toString();

                        for (let i = 0; i < dayString.length - 1; i++) {
                            var dayChar = "";
                            if (dayString[i] != 'T') {
                                dayChar = dayString[i];
                            } else {
                                dayChar = dayString[i] + dayString[i + 1];
                                i++;
                            }

                            var sectionObj = {
                                days: dayChar,
                                start: startTimeFormatted,
                                end: endTimeFormatted
                            }
                            //console.log(sectionObj);

                            meetingTimes.push(sectionObj);
                        }
                    });

                    classes[className].push({
                        section: sectionName,
                        times: meetingTimes
                    });

                    innerFlag--;
                    if (innerFlag == 0) {
                        //console.log(classes)
                        asdf(classes);
                        return classes;
                    }
                });
            });
        });
    }
};

/*
while (flag != 0) {
    console.log(flag);
}
console.log(classes);*/

// Contains functions to help filter one person
validateFirst = function(classes) {
    var goodOnes = [[]];
    var notPossible = false;
    //contains sets of valid MeetingTimes
    var count;
    //Go through all classes
    for (count = 0; count < classes.length; count++) {
        var newGoodOnes = [[]];
        //Go through all the section times per class
        c.forEach((meeting) => {
            var foundMatch = false;
            //MeetingTimes in the class
            if (count == 0) { //add array with the single meeting to goodOnes
                var tmp = [];
                tmp.push(meeting);
                goodOnes.push(tmp);
            } else {
                //Current  set of already compatible section times in goodOnes
                goodOnes.forEach((possibleMeetings) => {
                    //no conflicts with this possibleMeeting combination
                    if (!hasConflict(meeting, possibleMeetings)) {
                       newGoodOnes.push(possibleMeetings.push(meeting));
                       foundMatch = true;
                    }
                });
            }

            if (!foundMatch) {
                return null;
            }
        });

        goodOnes = newGoodOnes;
    }

    return goodOnes;
}

//Determines if a meeting conflicts with a set of already validated meetings
hasConflict = function(curr, sections) {
    let returnValue = false;
    sections.forEach((section) => {
        section.times.forEach((st) => {
            if (curr.day == st.day) {
                if ((curr.start > st.start && curr.start < st.end) || (curr.end > st.start && curr.end < st.end)) {
                    returnValue = true;
                }
            }
        });
    });
    return returnValue;
}

/* TEST CASES FOR hasConflict

var tempCurr = {
    day: "M",
    start: 1100,
    end: 1150
}

var tempSections = [
    {
        section: "Myclass100",
        times: [{
            day: "Tu",
            start: 1000,
            end: 1050
        },
        {
            day: "Th",
            start: 1100,
            end: 1150
        },
        {
            day: "M",
            start: 1000,
            end: 1050
        }]
    },
    {
        section: "Myclass101",
        times: [{
            day: "Tu",
            start: 1030,
            end: 1130
        },
        {
            day: "Th",
            start: 1100,
            end: 1150
        },
        {
            day: "M",
            start: 1200,
            end: 1230
        }]
    }
]

console.log(hasConflict(tempCurr, tempSections));
*/
testFunction(['ENES100', 'CMSC131']);

<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-7-3 11:11:45<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>var abstractTests = require('abstract-chunk-store/tests')
var Queued = require('./')
var MemoryChunkStore = require('memory-chunk-store')
var FSChunkStore = require('fs-chunk-store')
var test = require('tape')

abstractTests(test, function (chunkLength) {
  return new Queued(new MemoryChunkStore(chunkLength))
})

abstractTests(test, function (chunkLength) {
  return new Queued(new FSChunkStore(chunkLength))
})

test('get before put', function (t) {
  var store = new Queued(new MemoryChunkStore(10))

  store.get(0, function(err, buf) {
    t.error(err)
    t.deepEqual(buf, new Buffer('0123456789'))
  })

  store.get(1, function(err, buf) {
    t.error(err)
    t.deepEqual(buf, new Buffer('0123456789'))
  })

  store.put(0, new Buffer('0123456789'))

  store.put(1, new Buffer('0123456789'))

  t.end()
})
<commit_msg>add test for immediate<commit_after>var abstractTests = require('abstract-chunk-store/tests')
var Queued = require('./')
var Immediate = require('immediate-chunk-store')
var MemoryChunkStore = require('memory-chunk-store')
var FSChunkStore = require('fs-chunk-store')
var test = require('tape')

abstractTests(test, function (chunkLength) {
  return new Queued(new MemoryChunkStore(chunkLength))
})

abstractTests(test, function (chunkLength) {
  return new Queued(new FSChunkStore(chunkLength))
})

abstractTests(test, function (chunkLength) {
  return new Queued(Immediate(MemoryChunkStore(chunkLength)));
})

test('get before put', function (t) {
  var store = new Queued(new MemoryChunkStore(10))

  store.get(0, function(err, buf) {
    t.error(err)
    t.deepEqual(buf, new Buffer('0123456789'))
  })

  store.get(1, function(err, buf) {
    t.error(err)
    t.deepEqual(buf, new Buffer('0123456789'))
  })

  store.put(0, new Buffer('0123456789'))

  store.put(1, new Buffer('0123456789'))

  t.end()
})
<|endoftext|>


<commit_before>'use strict';

var assert  = require('assert');
var sfid    = require('.');

assert.equal('80120000000testAAA' , sfid('80120000000testAAA'));
assert.equal('80120000000testAAA' , sfid('80120000000test'));
assert.equal('80120000000testAAA' , sfid('80120000000TESTAAA'));
assert.equal('80120000000tEsTAAU' , sfid('80120000000TESTAAU'));
assert.equal('80120000000TestAAC' , sfid('80120000000TESTAAC'));
assert.equal('80120000000tEstAAE' , sfid('80120000000TESTAAE'));
assert.equal('80120000000teStAAI' , sfid('80120000000TESTAAI'));
assert.equal('80120000000tesTAAQ' , sfid('80120000000TESTAAQ'));
assert.equal('80120000000testAAA' , sfid('80120000000testaaa'));
assert.equal(''                   , sfid('80120000000testAA7'));
assert.equal(''                   , sfid('80120000000T4STAAP'));
assert.equal(''                   , sfid('80120000000testXYZ'));
assert.equal(''                   , sfid('xyz'));
assert.equal(''                   , sfid(null));

assert.equal('80120000000testAAA' , sfid.long('80120000000testAAA'));
assert.equal('80120000000testAAA' , sfid.long('80120000000test'));
assert.equal('80120000000testAAA' , sfid.long('80120000000TESTAAA'));
assert.equal('80120000000testAAA' , sfid.long('80120000000testaaa'));
assert.equal(''                   , sfid.long('80120000000testAA7'));
assert.equal(''                   , sfid.long('80120000000T4STAAP'));
assert.equal(''                   , sfid.long('80120000000testXYZ'));
assert.equal(''                   , sfid.long('xyz'));
assert.equal(''                   , sfid.long(null));

assert.equal('80120000000test' , sfid.short('80120000000testAAA'));
assert.equal('80120000000test' , sfid.short('80120000000test'));
assert.equal('80120000000test' , sfid.short('80120000000TESTAAA'));
assert.equal('80120000000test' , sfid.short('80120000000testaaa'));
assert.equal(''                , sfid.short('80120000000testAA7'));
assert.equal(''                , sfid.short('80120000000T4STAAP'));
assert.equal(''                , sfid.short('80120000000testXYZ'));
assert.equal(''                , sfid.short('xyz'));
assert.equal(''                , sfid.short(null));

assert.equal(true  , sfid.isValid('80120000000testAAA'));
assert.equal(true  , sfid.isValid('80120000000test'));
assert.equal(true  , sfid.isValid('80120000000TESTAAA'));
assert.equal(true  , sfid.isValid('80120000000testaaa'));
assert.equal(false , sfid.isValid('80120000000testXYZ'));
assert.equal(false , sfid.isValid('xyz'));
assert.equal(false , sfid.isValid(null));

assert.equal('Order' , sfid.guessType('80120000000testAAA'));
assert.equal('Order' , sfid.guessType('80120000000test'));
assert.equal('Order' , sfid.guessType('80120000000TESTAAA'));
assert.equal('Order' , sfid.guessType('80120000000testaaa'));
assert.equal(null    , sfid.guessType('80120000000testXYZ'));
assert.equal(null    , sfid.guessType('xyz'));
assert.equal(null    , sfid.guessType(null));

assert.throws(function() { sfid.registerPrefix('Invalid'); });
assert.throws(function() { sfid.registerPrefix(''); });
assert.throws(function() { sfid.registerPrefix(null); });
sfid.registerPrefix('tst', 'MyType1');
sfid.registerPrefix('TST', [ 'MyType2', 'MyType3' ]);
assert.equal('MyType1' , sfid.guessType('tst20000000testAAA'));
assert.equal('MyType2' , sfid.guessType('TST20000000testHAA')[0]);
assert.equal('MyType3' , sfid.guessType('TST20000000testHAA')[1]);

assert.equal('AAA' , sfid.checksum('80120000000testAAA'));
assert.equal('AAA' , sfid.checksum('80120000000test'));
assert.equal('AAA' , sfid.checksum('80120000000testXYZ'));
assert.equal('555' , sfid.checksum(''));
assert.throws(function() { sfid.checksum(null); });

assert.equal(true  , sfid.regexp().test(' 80120000000testAAA '));
assert.equal(true  , sfid.regexp().test(' 80120000000test '));
assert.equal(true  , sfid.regexp().test(' 80120000000testXYZ '));
assert.equal(false , sfid.regexp().test(' xyz '));
assert.equal(true  , sfid.regexp(true).test('80120000000testAAA'));
assert.equal(true  , sfid.regexp(true).test('80120000000test'));
assert.equal(true  , sfid.regexp(true).test('80120000000testXYZ'));
assert.equal(false , sfid.regexp(true).test('xyz'));
assert.equal(false , sfid.regexp(true).test(' 80120000000testAAA '));
assert.equal(false , sfid.regexp(true).test(' 80120000000test '));
<commit_msg>Regression tests<commit_after>'use strict';

var assert  = require('assert');
var sfid    = require('.');

assert.equal('80120000000testAAA' , sfid('80120000000testAAA'));
assert.equal('80120000000testAAA' , sfid('80120000000test'));
assert.equal('80120000000testAAA' , sfid('80120000000TESTAAA'));
assert.equal('80120000000tEsTAAU' , sfid('80120000000TESTAAU'));
assert.equal('80120000000TestAAC' , sfid('80120000000TESTAAC'));
assert.equal('80120000000tEstAAE' , sfid('80120000000TESTAAE'));
assert.equal('80120000000teStAAI' , sfid('80120000000TESTAAI'));
assert.equal('80120000000tesTAAQ' , sfid('80120000000TESTAAQ'));
assert.equal('80120000000testAAA' , sfid('80120000000testaaa'));
assert.equal(''                   , sfid('80120000000testAA7'));
assert.equal(''                   , sfid('80120000000T4STAAP'));
assert.equal(''                   , sfid('80120000000testXYZ'));
assert.equal(''                   , sfid('xyz'));
assert.equal(''                   , sfid(null));

assert.equal('80120000000testAAA' , sfid.long('80120000000testAAA'));
assert.equal('80120000000testAAA' , sfid.long('80120000000test'));
assert.equal('80120000000testAAA' , sfid.long('80120000000TESTAAA'));
assert.equal('80120000000testAAA' , sfid.long('80120000000testaaa'));
assert.equal(''                   , sfid.long('80120000000testAA7'));
assert.equal(''                   , sfid.long('80120000000T4STAAP'));
assert.equal(''                   , sfid.long('80120000000testXYZ'));
assert.equal(''                   , sfid.long('xyz'));
assert.equal(''                   , sfid.long(null));

assert.equal('80120000000test' , sfid.short('80120000000testAAA'));
assert.equal('80120000000test' , sfid.short('80120000000test'));
assert.equal('80120000000test' , sfid.short('80120000000TESTAAA'));
assert.equal('80120000000test' , sfid.short('80120000000testaaa'));
assert.equal(''                , sfid.short('80120000000testAA7'));
assert.equal(''                , sfid.short('80120000000T4STAAP'));
assert.equal(''                , sfid.short('80120000000testXYZ'));
assert.equal(''                , sfid.short('xyz'));
assert.equal(''                , sfid.short(null));

assert.equal(true  , sfid.isValid('80120000000testAAA'));
assert.equal(true  , sfid.isValid('80120000000test'));
assert.equal(true  , sfid.isValid('80120000000TESTAAA'));
assert.equal(true  , sfid.isValid('80120000000testaaa'));
assert.equal(false , sfid.isValid('80120000000testXYZ'));
assert.equal(false , sfid.isValid('xyz'));
assert.equal(false , sfid.isValid(null));

assert.equal('Order' , sfid.guessType('80120000000testAAA'));
assert.equal('Order' , sfid.guessType('80120000000test'));
assert.equal('Order' , sfid.guessType('80120000000TESTAAA'));
assert.equal('Order' , sfid.guessType('80120000000testaaa'));
assert.equal(null    , sfid.guessType('80120000000testXYZ'));
assert.equal(null    , sfid.guessType('xyz'));
assert.equal(null    , sfid.guessType(null));

assert.throws(function() { sfid.registerPrefix('Invalid'); });
assert.throws(function() { sfid.registerPrefix(''); });
assert.throws(function() { sfid.registerPrefix(null); });
sfid.registerPrefix('tst', 'MyType1');
sfid.registerPrefix('TST', [ 'MyType2', 'MyType3' ]);
assert.equal('MyType1' , sfid.guessType('tst20000000testAAA'));
assert.equal('MyType2' , sfid.guessType('TST20000000testHAA')[0]);
assert.equal('MyType3' , sfid.guessType('TST20000000testHAA')[1]);

assert.equal('AAA' , sfid.checksum('80120000000testAAA'));
assert.equal('AAA' , sfid.checksum('80120000000test'));
assert.equal('AAA' , sfid.checksum('80120000000testXYZ'));
assert.equal('555' , sfid.checksum(''));
assert.throws(function() { sfid.checksum(null); });

assert.equal(true  , sfid.regexp().test(' 80120000000testAAA '));
assert.equal(true  , sfid.regexp().test(' 80120000000test '));
assert.equal(true  , sfid.regexp().test(' 80120000000testXYZ '));
assert.equal(false , sfid.regexp().test(' xyz '));
assert.equal(true  , sfid.regexp(true).test('80120000000testAAA'));
assert.equal(true  , sfid.regexp(true).test('80120000000test'));
assert.equal(true  , sfid.regexp(true).test('80120000000testXYZ'));
assert.equal(false , sfid.regexp(true).test('xyz'));
assert.equal(false , sfid.regexp(true).test(' 80120000000testAAA '));
assert.equal(false , sfid.regexp(true).test(' 80120000000test '));

/***** Check a lot of well-formed id patterns *****/

var ids = {
    '0012A00001aaAaaQAE' : 'Account',
    '0012000001A10aAAAR' : 'Account',
    '0012000001A1AA0AAN' : 'Account',
    '0012000001AAaa1AAD' : 'Account',
    '0012000001Aa011AAB' : 'Account',
    '0012000001Aa1AaAAJ' : 'Account',
    '0012000001AaAA1AAN' : 'Account',
    '0012000001AaAAaAAN' : 'Account',
    '0012000001aA1aaAAC' : 'Account',
    '0012000001aAAaaAAG' : 'Account',
    '0032A00001aAAAAQA4' : 'Contact',
    '0032000001AAaaAAAT' : 'Contact',
    '0032000001AaAAAAA3' : 'Contact',
    '0032000001AaaaaAAB' : 'Contact',
    '0032000001a1aAAAAY' : 'Contact',
    '0032000001aAAAAAA4' : 'Contact',
    '0032000001aAAAaAAO' : 'Contact',
    '0032000001aAaaAAAS' : 'Contact',
    '0032000001aaaA1AAI' : 'Contact',
    '0032000001aaaaaAAA' : 'Contact',
    '0052A00000111aAQAQ' : 'User',
    '005200000010AaaAAE' : 'User',
    '0052000000111AaAAI' : 'User',
    '005200000011AAAAA2' : 'User',
    '005200000011AAaAAM' : 'User',
    '005200000011aAAAAY' : 'User',
    '00520000001AAA1AAO' : 'User',
    '00520000001AaAAAA0' : 'User',
    '00520000001a1a1AAA' : 'User',
    '00520000001aAaaAAE' : 'User',
    '0062A00000aAaAaQAK' : 'Opportunity',
    '0062A00000aa1AaQAI' : 'Opportunity',
    '0062000000a1AAaAAM' : 'Opportunity',
    '0062000000a1AaaAAE' : 'Opportunity',
    '0062000000a1a1aAAA' : 'Opportunity',
    '0062000000aA1AAAA0' : 'Opportunity',
    '0062000000aAAAAAA4' : 'Opportunity',
    '0062000000aa1aAAAQ' : 'Opportunity',
    '0062000000aaa0AAAQ' : 'Opportunity',
    '0062000000aaaaaAAA' : 'Opportunity',
    '00Q2A00000a11aAUAQ' : 'Lead',
    '00Q2000000a1AAAEA2' : 'Lead',
    '00Q2000000a1aAAEAY' : 'Lead',
    '00Q2000000aAAa1EAG' : 'Lead',
    '00Q2000000aAa1aEAC' : 'Lead',
    '00Q2000000aAaAAEA0' : 'Lead',
    '00Q2000000aAaaaEAC' : 'Lead',
    '00Q2000000aaAaAEAU' : 'Lead',
    '00Q2000000aaaAAEAY' : 'Lead',
    '00Q2000000aaaAaEAI' : 'Lead',
    '8012A000001AAAaQAO' : 'Order',
    '801200000001AaaAAE' : 'Order',
    '801200000001a1AAAQ' : 'Order',
    '801200000001aaAAAQ' : 'Order',
    '80120000000AAaAAAW' : 'Order',
    '80120000000Aa11AAC' : 'Order',
    '80120000000aAaaAAE' : 'Order',
    '80120000000aaAaAAI' : 'Order',
    '80120000000aaaaAAA' : 'Order',
    '80120000001AAA1AAO' : 'Order',
    'a012A00000A11aAQAR' : 'custom',
    'a012A00000AAAA1QAP' : 'custom',
    'a012A00000AAaAaQAL' : 'custom',
    'a012000000A11aAAAR' : 'custom',
    'a012000000AAAaAAAX' : 'custom',
    'a01200000aAAAaAAAX' : 'custom',
    'a012000000Aa1aaAAB' : 'custom',
    'a012000000AaAA1AAN' : 'custom',
    'a012000000AaAAAAA3' : 'custom',
    'a012000000AaaAaAAJ' : 'custom'
};

Object.keys(ids).forEach(function(id) {
    assert.equal(id, sfid(id));
    assert.equal(id, sfid(id.toUpperCase()));
    assert.equal(id, sfid(id.toLowerCase()));
    assert.equal(id, sfid(id.substring(0, 15)));

    assert.equal(id, sfid.long(id));
    assert.equal(id, sfid.long(id.toUpperCase()));
    assert.equal(id, sfid.long(id.toLowerCase()));
    assert.equal(id, sfid.long(id.substring(0, 15)));

    assert.equal(id.substring(0, 15), sfid.short(id));
    assert.equal(id.substring(0, 15), sfid.short(id.substring(0, 15)));

    assert.equal(ids[id], sfid.guessType(id));
    assert.equal(ids[id], sfid.guessType(id.toUpperCase()));
    assert.equal(ids[id], sfid.guessType(id.toLowerCase()));
    assert.equal(ids[id], sfid.guessType(id.substring(0, 15)));
});
<|endoftext|>


<commit_before>'use strict';

var Lab      = require('lab');
var lab      = exports.lab = Lab.script();
var describe = lab.describe;
var it       = lab.it;
var before   = lab.before;
var expect   = Lab.expect;
var Promise  = require('bluebird');
var hapi     = require('hapi');
var joi      = require('joi');

describe('hapi-as-promised', function () {

  var server;
  before(function (done) {
    server = new hapi.Server();
    server.pack.register(require('./'), done);
  });

  it('ignores non-thenable replies', function (done) {
    server.route({
      method: 'GET',
      path: '/default',
      handler: function (request, reply) {
        reply('Normal response');
      }
    });

    server.inject('/default', function (response) {
      expect(response.result).to.equal('Normal response');
      done();
    });
  });

  it('ignores empty replies', function (done) {
    server.route({
      method: 'GET',
      path: '/empty',
      handler: function (request, reply) {
        reply();
      }
    });

    server.inject('/empty', function (response) {
      expect(response.result).to.equal(null);
      done();
    });
  });

  it('handles promises that resolve', function (done) {
    server.route({
      method: 'GET',
      path: '/resolve',
      handler: function (request, reply) {
        reply(Promise.resolve('Promised response')).code(201);
      }
    });

    server.inject('/resolve', function (response) {
      expect(response.result).to.equal('Promised response');
      expect(response.statusCode).to.equal(201);
      done();
    });
  });

  it('handles promises that reject', function (done) {
    var err = hapi.error.forbidden();
    server.route({
      method: 'GET',
      path: '/error',
      handler: function (request, reply) {
        // Use a fake rejecting thenable b/c Bluebird's unhandled detection
        // catches a normal rejection
        reply({
          then: function () {
            return Promise.reject(err);
          }
        });
      }
    });

    server.inject('/error', function (response) {
      expect(response.statusCode).to.equal(403);
      expect(response.result).to.have.property('error', err.message);
      done();
    });
  });

  it('handles promises with response validation', function (done) {
    server.route({
      method: 'GET',
      path: '/validate',
      handler: function (request, reply) {
        reply(Promise.resolve({ key: 'value' })).code(201);
      },
      config: {
        response: {
          schema: joi.object().keys({ key: joi.string() })
        }
      }
    });

    server.inject('/validate', function (response) {
      expect(response.result).to.deep.equal({ key: 'value' });
      expect(response.statusCode).to.equal(201);
      done();
    });
  });

});
<commit_msg>Verify that response is discarded for errors<commit_after>'use strict';

var Lab      = require('lab');
var lab      = exports.lab = Lab.script();
var describe = lab.describe;
var it       = lab.it;
var before   = lab.before;
var expect   = Lab.expect;
var Promise  = require('bluebird');
var hapi     = require('hapi');
var joi      = require('joi');

describe('hapi-as-promised', function () {

  var server;
  before(function (done) {
    server = new hapi.Server();
    server.pack.register(require('./'), done);
  });

  it('ignores non-thenable replies', function (done) {
    server.route({
      method: 'GET',
      path: '/default',
      handler: function (request, reply) {
        reply('Normal response');
      }
    });

    server.inject('/default', function (response) {
      expect(response.result).to.equal('Normal response');
      done();
    });
  });

  it('ignores empty replies', function (done) {
    server.route({
      method: 'GET',
      path: '/empty',
      handler: function (request, reply) {
        reply();
      }
    });

    server.inject('/empty', function (response) {
      expect(response.result).to.equal(null);
      done();
    });
  });

  it('handles promises that resolve', function (done) {
    server.route({
      method: 'GET',
      path: '/resolve',
      handler: function (request, reply) {
        reply(Promise.resolve('Promised response')).code(201);
      }
    });

    server.inject('/resolve', function (response) {
      expect(response.result).to.equal('Promised response');
      expect(response.statusCode).to.equal(201);
      done();
    });
  });

  it('handles promises that reject', function (done) {
    var err = hapi.error.forbidden();
    server.route({
      method: 'GET',
      path: '/error',
      handler: function (request, reply) {
        // Use a fake rejecting thenable b/c Bluebird's unhandled detection
        // catches a normal rejection
        reply({
          then: function () {
            return Promise.reject(err);
          }
        })
        .code(200);
      }
    });

    server.inject('/error', function (response) {
      expect(response.statusCode).to.equal(403);
      expect(response.result).to.have.property('error', err.message);
      done();
    });
  });

  it('handles promises with response validation', function (done) {
    server.route({
      method: 'GET',
      path: '/validate',
      handler: function (request, reply) {
        reply(Promise.resolve({ key: 'value' })).code(201);
      },
      config: {
        response: {
          schema: joi.object().keys({ key: joi.string() })
        }
      }
    });

    server.inject('/validate', function (response) {
      expect(response.result).to.deep.equal({ key: 'value' });
      expect(response.statusCode).to.equal(201);
      done();
    });
  });

});
<|endoftext|>


<commit_before>import test from 'ava';
import {LMLayer} from './';

const TYPE_D = { insert: 'D', deleteLeft: 0, deleteRight: 0 };
const EMPTY_CONTEXT = { left: '' };

test('It provide context to LMLayer', async t => {
  t.plan(2);

  const lm = new LMLayer;

  // Wait for the language model to initialize and declare its configuration.
  let configuration = await lm.initialize({ model: 'en-x-derek' });
  // The model should as for 32 code units of context to the left of the
  // cursor.
  t.is(configuration.leftContextCodeUnits, 32);

  // Now tell it the user typed 'D'.
  let message = await lm.predict({
    transform: TYPE_D, contexts: [EMPTY_CONTEXT]
  });

  // This dummy language model will always suggest 'Derek' as its return.
  let {suggestions} = message;
  t.deepEqual(suggestions, [
    { insert: 'Derek', deleteLeft: 1, deleteRight: 0, displayAs: 'Derek' }
  ]);
});

test('It should not be able to predict() before initialized', async t => {
  t.plan(1);

  const lm = new LMLayer;
  try {
    await lm.predict({
      transform: TYPE_D, contexts: [EMPTY_CONTEXT], customToken: null
    });
    t.fail();
  } catch (e) {
    t.regex(e.message, /(not |un)initialized/i);
  }
});

test('It should reject when predictions crash', async t => {
  t.plan(1);

  const lm = new LMLayer;
  await lm.initialize({ model: 'en-x-derek' });

  try {
    await lm.predict({
      transform: TYPE_D, contexts: [EMPTY_CONTEXT], customToken: null
    });
    t.fail();
  } catch (e) {
    t.regex(e.message, /invalid/i);
  }
});

<commit_msg>Better designed context.<commit_after>import test from 'ava';
import {LMLayer} from './';

const TYPE_D = { insert: 'D', deleteLeft: 0, deleteRight: 0 };
const EMPTY_CONTEXT = { left: '', right: '', probability: 0.00 };

test('It provide context to LMLayer', async t => {
  t.plan(2);

  const lm = new LMLayer;

  // Wait for the language model to initialize and declare its configuration.
  let configuration = await lm.initialize({ model: 'en-x-derek' });
  // The model should as for 32 code units of context to the left of the
  // cursor.
  t.is(configuration.leftContextCodeUnits, 32);

  // Now tell it the user typed 'D'.
  let message = await lm.predict({
    transform: TYPE_D, contexts: [EMPTY_CONTEXT]
  });

  // This dummy language model will always suggest 'Derek' as its return.
  let {suggestions} = message;
  t.deepEqual(suggestions, [
    { insert: 'Derek', deleteLeft: 1, deleteRight: 0, displayAs: 'Derek' }
  ]);
});

test('It should not be able to predict() before initialized', async t => {
  t.plan(1);

  const lm = new LMLayer;
  try {
    await lm.predict({
      transform: TYPE_D, contexts: [EMPTY_CONTEXT], customToken: null
    });
    t.fail();
  } catch (e) {
    t.regex(e.message, /(not |un)initialized/i);
  }
});

test('It should reject when predictions crash', async t => {
  t.plan(1);

  const lm = new LMLayer;
  await lm.initialize({ model: 'en-x-derek' });

  try {
    await lm.predict({
      transform: TYPE_D, contexts: [EMPTY_CONTEXT], customToken: null
    });
    t.fail();
  } catch (e) {
    t.regex(e.message, /invalid/i);
  }
});

<|endoftext|>


<commit_before>function init() {
    handleResizing();
    testComponents();
}

function handleResizing() {
    var
    canvas = document.getElementById("c"),
    context = canvas.getContext("2d");

    initialize();

    function initialize() {
        window.addEventListener("resize", resizeCanvas, false);
        resizeCanvas();
    }

    function resizeCanvas() {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
    }
}

function testComponents() {
    var stage = new createjs.Stage("c");
    stage.enableMouseOver();

    stage.addChild(createChartA0());
    stage.addChild(createChartB0());
    stage.addChild(createChartB1());
    stage.addChild(createChartB2());

    createjs.Ticker.on("tick", function() {
        stage.update();
    });
}

function createChartA0() {
    var size = {width: window.innerWidth - 50, height: 300};
    var point = {width: size.width / 60, height: 0.50};
    var axis = {offset: 0, dynamic: 10, calculateDynamic: true};
    var style = {
        background: {color: "#00AAFF", alpha: 0.1},
        axis: {thickness: 3, color: "#00FFFF", alpha: 0.75},
        grid: {thickness: 0.5, color: "#00FFFF", alpha: 0.5, width: 50, height: 100, dash: [1, 0]},
        extreme: {thickness: 1, maxColor: "#FF0000", minColor: "#000000", alpha: 0},
        chart: {thickness: 1, radius: 0, color: "#003333", alpha: 0.75, bounds: "full"}
    };

    var chart = new charts.StreamingChart(size, point, axis, style);
    chart.y = 20;
    chart.x = 25;

    var t = 0;
    setInterval(function() {
        chart.append([Math.sin(t) * Math.abs(Math.cos(t)) * 2500]);
        t += 0.05;
    }, 50);

    return chart;
}

function createChartB0() {
    var size = {width: (window.innerWidth - 100) / 3, height: 100};
    var point = {width: 10, height: 0.1};
    var axis = {offset: 0,  dynamic: 0, calculateDynamic: false};
    var style = {
        background: {color: "#FF0000", alpha: 0.1},
        axis: {thickness: 4, color: "#FF0000", alpha: 0.8},
        grid: {thickness: 0.1, color: "#FF0000", alpha: 0.5, width: 2, height: 200, dash: [1, 0]},
        extreme: {thickness: 1, maxColor: "#FF0000", minColor: "#000000", alpha: 0},
        chart: {thickness: 2, radius: 2, color: "#000000", alpha: 0.8, bounds: "none"}
    };

    var chart = new charts.StreamingChart(size, point, axis, style);
    chart.y = 450;
    chart.x = 25;

    var t = 0;
    var shift = size.height / point.height / 2;
    setInterval(function() {
        chart.append([Math.cos(t) * 600 + shift]);
        t += 0.33;
    }, 50);

    return chart;
}

function createChartB1() {
    var size = {width: (window.innerWidth - 100) / 3, height: 100};
    var point = {width: 10, height: 0.1};
    var axis = {offset: 0,  dynamic: 0, calculateDynamic: false};
    var style = {
        background: {color: "#FF0000", alpha: 0.1},
        axis: {thickness: 4, color: "#FF0000", alpha: 0.8},
        grid: {thickness: 0.1, color: "#FF0000", alpha: 0.5, width: 2, height: 500, dash: [1, 0]},
        extreme: {thickness: 1, maxColor: "#FF0000", minColor: "#000000", alpha: 0},
        chart: {thickness: 2, radius: 2, color: "#000000", alpha: 0.8, bounds: "points"}
    };

    var chart = new charts.StreamingChart(size, point, axis, style);
    chart.y = 450;
    chart.x = 50 + (window.innerWidth - 100) / 3;

    var t = 0;
    var shift = size.height / point.height / 2;
    setInterval(function() {
        chart.append([Math.cos(t) * 600 + shift]);
        t += 0.33;
    }, 50);

    return chart;
}

function createChartB2() {
    var size = {width: (window.innerWidth - 100) / 3, height: 100};
    var point = {width: 10, height: 0.1};
    var axis = {offset: 0,  dynamic: 0, calculateDynamic: false};
    var style = {
        background: {color: "#FF0000", alpha: 0.1},
        axis: {thickness: 4, color: "#FF0000", alpha: 0.8},
        grid: {thickness: 0.1, color: "#FF0000", alpha: 0.5, width: 5, height: 500, dash: [1, 0]},
        extreme: {thickness: 1, maxColor: "#FF0000", minColor: "#000000", alpha: 0},
        chart: {thickness: 2, radius: 2, color: "#000000", alpha: 0.8, bounds: "full"}
    };

    var chart = new charts.StreamingChart(size, point, axis, style);
    chart.y = 450;
    chart.x = 75 + (window.innerWidth - 100) / 3 * 2;

    var t = 0;
    var shift = size.height / point.height / 2;
    setInterval(function() {
        chart.append([Math.cos(t) * 600 + shift]);
        t += 0.33;
    }, 50);

    return chart;
}
<commit_msg>Fix grid of example chart <commit_after>function init() {
    handleResizing();
    testComponents();
}

function handleResizing() {
    var
    canvas = document.getElementById("c"),
    context = canvas.getContext("2d");

    initialize();

    function initialize() {
        window.addEventListener("resize", resizeCanvas, false);
        resizeCanvas();
    }

    function resizeCanvas() {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
    }
}

function testComponents() {
    var stage = new createjs.Stage("c");
    stage.enableMouseOver();

    stage.addChild(createChartA0());
    stage.addChild(createChartB0());
    stage.addChild(createChartB1());
    stage.addChild(createChartB2());

    createjs.Ticker.on("tick", function() {
        stage.update();
    });
}

function createChartA0() {
    var size = {width: window.innerWidth - 50, height: 300};
    var point = {width: size.width / 60, height: 0.50};
    var axis = {offset: 0, dynamic: 10, calculateDynamic: true};
    var style = {
        background: {color: "#00AAFF", alpha: 0.1},
        axis: {thickness: 3, color: "#00FFFF", alpha: 0.75},
        grid: {thickness: 0.5, color: "#00FFFF", alpha: 0.5, width: 10, height: 100, dash: [1, 0]},
        extreme: {thickness: 1, maxColor: "#FF0000", minColor: "#000000", alpha: 0},
        chart: {thickness: 1, radius: 0, color: "#003333", alpha: 0.75, bounds: "full"}
    };

    var chart = new charts.StreamingChart(size, point, axis, style);
    chart.y = 20;
    chart.x = 25;

    var t = 0;
    setInterval(function() {
        chart.append([Math.sin(t) * Math.abs(Math.cos(t)) * 2500]);
        t += 0.05;
    }, 50);

    return chart;
}

function createChartB0() {
    var size = {width: (window.innerWidth - 100) / 3, height: 100};
    var point = {width: 10, height: 0.1};
    var axis = {offset: 0,  dynamic: 0, calculateDynamic: false};
    var style = {
        background: {color: "#FF0000", alpha: 0.1},
        axis: {thickness: 4, color: "#FF0000", alpha: 0.8},
        grid: {thickness: 0.1, color: "#FF0000", alpha: 0.5, width: 2, height: 200, dash: [1, 0]},
        extreme: {thickness: 1, maxColor: "#FF0000", minColor: "#000000", alpha: 0},
        chart: {thickness: 2, radius: 2, color: "#000000", alpha: 0.8, bounds: "none"}
    };

    var chart = new charts.StreamingChart(size, point, axis, style);
    chart.y = 450;
    chart.x = 25;

    var t = 0;
    var shift = size.height / point.height / 2;
    setInterval(function() {
        chart.append([Math.cos(t) * 600 + shift]);
        t += 0.33;
    }, 50);

    return chart;
}

function createChartB1() {
    var size = {width: (window.innerWidth - 100) / 3, height: 100};
    var point = {width: 10, height: 0.1};
    var axis = {offset: 0,  dynamic: 0, calculateDynamic: false};
    var style = {
        background: {color: "#FF0000", alpha: 0.1},
        axis: {thickness: 4, color: "#FF0000", alpha: 0.8},
        grid: {thickness: 0.1, color: "#FF0000", alpha: 0.5, width: 2, height: 500, dash: [1, 0]},
        extreme: {thickness: 1, maxColor: "#FF0000", minColor: "#000000", alpha: 0},
        chart: {thickness: 2, radius: 2, color: "#000000", alpha: 0.8, bounds: "points"}
    };

    var chart = new charts.StreamingChart(size, point, axis, style);
    chart.y = 450;
    chart.x = 50 + (window.innerWidth - 100) / 3;

    var t = 0;
    var shift = size.height / point.height / 2;
    setInterval(function() {
        chart.append([Math.cos(t) * 600 + shift]);
        t += 0.33;
    }, 50);

    return chart;
}

function createChartB2() {
    var size = {width: (window.innerWidth - 100) / 3, height: 100};
    var point = {width: 10, height: 0.1};
    var axis = {offset: 0,  dynamic: 0, calculateDynamic: false};
    var style = {
        background: {color: "#FF0000", alpha: 0.1},
        axis: {thickness: 4, color: "#FF0000", alpha: 0.8},
        grid: {thickness: 0.1, color: "#FF0000", alpha: 0.5, width: 5, height: 500, dash: [1, 0]},
        extreme: {thickness: 1, maxColor: "#FF0000", minColor: "#000000", alpha: 0},
        chart: {thickness: 2, radius: 2, color: "#000000", alpha: 0.8, bounds: "full"}
    };

    var chart = new charts.StreamingChart(size, point, axis, style);
    chart.y = 450;
    chart.x = 75 + (window.innerWidth - 100) / 3 * 2;

    var t = 0;
    var shift = size.height / point.height / 2;
    setInterval(function() {
        chart.append([Math.cos(t) * 600 + shift]);
        t += 0.33;
    }, 50);

    return chart;
}
<|endoftext|>


<commit_before>var browserEnv = typeof window === 'object';

if (browserEnv) {
  mocha.setup('bdd');
} else {
  var sinon = require('sinon');
  var chai = require('chai');
  var sinonDoublist = require('./build/sinon-doublist');
}

var should = chai.should();
chai.Assertion.includeStack = true;

describe('sinon-doublist', function() {
  'use strict';

  before(function(done) {
    sinonDoublist(sinon, this);
    done();
  });

  describe('#stubWithReturn()', function() {
    it('should detect unspecified method', function(testDone) {
      var self = this;
      (function() {
        self.stubWithReturn();
      }).should.Throw(Error, 'method not specified');
      testDone();
    });

    it('should handle custom target object', function(testDone) {
      var obj = {foo: function() {}};
      var stub = this.stubWithReturn({obj: obj, method: 'foo'});
      stub.foo.should.not.have.been.called;
      stub.target.foo();
      stub.foo.should.have.been.called;
      testDone();
    });

    it('should handle missing target object', function(testDone) {
      var stub = this.stubWithReturn({method: 'foo'});
      stub.foo.should.not.have.been.called;
      stub.target.foo();
      stub.foo.should.have.been.called;
      testDone();
    });

    it('should handle plain-string spy name', function(testDone) {
      var stub = this.stubWithReturn({method: 'foo', spies: 'bond'});
      var returned = stub.target.foo();
      returned.bond();
      returned.bond.should.have.been.called;
      testDone();
    });

    it('should handle namespace-string spy name', function(testDone) {
      var stub = this.stubWithReturn({method: 'foo', spies: 'james.bond'});
      var returned = stub.target.foo();
      returned.james.bond();
      returned.james.bond.should.have.been.called;
      testDone();
    });

    it('should handle plain-string spy name array', function(testDone) {
      var stub = this.stubWithReturn({method: 'foo', spies: ['james', 'bond']});
      var returned = stub.target.foo();
      returned.james();
      returned.james.should.have.been.called;
      returned.bond();
      returned.bond.should.have.been.called;
      testDone();
    });

    it('should handle expected args', function(testDone) {
      var stub = this.stubWithReturn({method: 'foo', args: ['bar', 'baz']});
      should.not.exist(stub.target.foo());
      var spy = stub.target.foo('bar', 'baz');
      spy.should.not.have.been.called;
      spy();
      spy.should.have.been.called;
      testDone();
    });

    it('should handle custom stub return value', function(testDone) {
      var expected = noOp;
      var stub = this.stubWithReturn({method: 'foo', returns: expected});
      var returned = stub.target.foo();
      returned.should.deep.equal(expected);
      testDone();
    });
  });
});

if (browserEnv) {
  mocha.run();
}

function noOp() {}
<commit_msg>Add sandbox restoration to tests<commit_after>var browserEnv = typeof window === 'object';

if (browserEnv) {
  mocha.setup('bdd');
} else {
  var sinon = require('sinon');
  var chai = require('chai');
  var sinonDoublist = require('./build/sinon-doublist');
}

var should = chai.should();
chai.Assertion.includeStack = true;

describe('sinon-doublist', function() {
  'use strict';

  beforeEach(function(done) {
    sinonDoublist(sinon, this);
    done();
  });

  afterEach(function(done) {
    this.sandbox.restore();
    done();
  });

  describe('#stubWithReturn()', function() {
    it('should detect unspecified method', function(testDone) {
      var self = this;
      (function() {
        self.stubWithReturn();
      }).should.Throw(Error, 'method not specified');
      testDone();
    });

    it('should handle custom target object', function(testDone) {
      var obj = {foo: function() {}};
      var stub = this.stubWithReturn({obj: obj, method: 'foo'});
      stub.foo.should.not.have.been.called;
      stub.target.foo();
      stub.foo.should.have.been.called;
      testDone();
    });

    it('should handle missing target object', function(testDone) {
      var stub = this.stubWithReturn({method: 'foo'});
      stub.foo.should.not.have.been.called;
      stub.target.foo();
      stub.foo.should.have.been.called;
      testDone();
    });

    it('should handle plain-string spy name', function(testDone) {
      var stub = this.stubWithReturn({method: 'foo', spies: 'bond'});
      var returned = stub.target.foo();
      returned.bond();
      returned.bond.should.have.been.called;
      testDone();
    });

    it('should handle namespace-string spy name', function(testDone) {
      var stub = this.stubWithReturn({method: 'foo', spies: 'james.bond'});
      var returned = stub.target.foo();
      returned.james.bond();
      returned.james.bond.should.have.been.called;
      testDone();
    });

    it('should handle plain-string spy name array', function(testDone) {
      var stub = this.stubWithReturn({method: 'foo', spies: ['james', 'bond']});
      var returned = stub.target.foo();
      returned.james();
      returned.james.should.have.been.called;
      returned.bond();
      returned.bond.should.have.been.called;
      testDone();
    });

    it('should handle expected args', function(testDone) {
      var stub = this.stubWithReturn({method: 'foo', args: ['bar', 'baz']});
      should.not.exist(stub.target.foo());
      var spy = stub.target.foo('bar', 'baz');
      spy.should.not.have.been.called;
      spy();
      spy.should.have.been.called;
      testDone();
    });

    it('should handle custom stub return value', function(testDone) {
      var expected = noOp;
      var stub = this.stubWithReturn({method: 'foo', returns: expected});
      var returned = stub.target.foo();
      returned.should.deep.equal(expected);
      testDone();
    });
  });
});

if (browserEnv) {
  mocha.run();
}

function noOp() {}
<|endoftext|>


<commit_before>var Modem = require('./');
var async = require('async');

var modem = new Modem('/dev/tty.usbserial', function(err, data) {
  err && console.error(err);
});

// do a voicecall
async.waterfall([
  function(cb) {
    modem.command('ATD+393420011223;', cb);
  },
  function(junk, cb) {
    setTimeout(cb, 60 * 1000);
  },
  function(junk, cb) {
    modem.command('AT+CHUP', cb);
  }
], function(err) {
  err && console.error(err);
});

// send a text message
async.waterfall([
  function(cb) {
    // activate text mode
    modem.command('AT+CMGF=1', cb);
  },
  function(junk, cb) {
    modem.command('AT+CMGS="+393420011223"', {
      expect: '>'
    }, cb)
  },
  function(junk, cb) {
    modem.command('CIAO MONDO!', cb);
  }
], function(err) {
  err && console.error(err);
});

// listen for a serial port event, ie: RING
modem.on('RING', function() {
  console.log('Ringing!!!!');
});

// sequence

modem.sequence([
  {
    command: 'AT+CMGS="+393420011223"',
    options: {
      expect: '>'
    }
  },
  {
    command: 'CIAO MONDO!'
  }
], function(err) {
  err && console.error(err);
  console.log('done');
});<commit_msg>fixed example with PDU<commit_after>var Modem = require('./');
var async = require('async');

var modem = new Modem('/dev/tty.usbserial', function(err, data) {
  err && console.error(err);
});

// do a voicecall
async.waterfall([
  function(cb) {
    modem.command('ATD+393420011223;', cb);
  },
  function(junk, cb) {
    setTimeout(cb, 60 * 1000);
  },
  function(junk, cb) {
    modem.command('AT+CHUP', cb);
  }
], function(err) {
  err && console.error(err);
});

// send a text message
async.waterfall([
  function(cb) {
    // activate text mode
    modem.command('AT+CMGF=1', cb);
  },
  function(junk, cb) {
    modem.command('AT+CMGS="+393420011223"', {
      expect: '>'
    }, cb)
  },
  function(junk, cb) {
    modem.command('CIAO MONDO!', cb);
  }
], function(err) {
  err && console.error(err);
});

// listen for a serial port event, ie: RING
modem.on('RING', function() {
  console.log('Ringing!!!!');
});

// sequence
modem.sequence([
  {
    command: 'AT+CMGS="+393420011223"',
    options: {
      expect: '>'
    }
  },
  {
    command: 'CIAO MONDO!'
  }
], function(err) {
  err && console.error(err);
  console.log('done');
});

// sending with PDU

var pdu = require('sms-pdu-node');
var PDU = pdu('ciao', '393420011223', null, 7);
modem.sequence([
  {
    command: PDU.command,
    expect: '>'
  },
  {
    command: PDU.pdu
  }
], console.log.bind(console));<|endoftext|>


<commit_before>import net from 'net'

import test from 'ava'

import portScanner from './lib/portscanner.js'

test.before('Set #1 test server', t => {
  const server = net.createServer()
  server.listen(3000, '127.0.0.1', () => t.end())
})

test.before('Set #2 test server', t => {
  const server2 = net.createServer()
  server2.listen(2999, '127.0.0.1', () => t.end())
})

/* checkPortStatus */

test('checkPortStatus - taken', t => {
  t.plan(2)

  portScanner.checkPortStatus(3000, '127.0.0.1', (error, port) => {
    t.is(error, null)
    t.is(port, 'open')
  })
})

test('checkPortStatus - free', t => {
  t.plan(2)

  portScanner.checkPortStatus(3001, '127.0.0.1', (error, port) => {
    t.is(error, null)
    t.is(port, 'closed')
  })
})

/* findPortInUse */

test('findPortInUse - taken port in range', t => {
  t.plan(2)

  portScanner.findAPortInUse(3000, 3010, '127.0.0.1', (error, port) => {
    t.is(error, null)
    t.is(port, 3000)
  })
})

test('findPortInUse - taken port in range - ports as array', t => {
  t.plan(2)

  portScanner.findAPortInUse([2999, 3000, 3001], '127.0.0.1', (error, port) => {
    t.is(error, null)
    t.is(port, 2999)
  })
})

test('findPortInUse - all ports in range free', t => {
  t.plan(2)

  portScanner.findAPortInUse(3001, 3010, '127.0.0.1', (error, port) => {
    t.is(error, null)
    t.false(port)
  })
})

test('findPortInUse - all ports in range free - ports as array', t => {
  t.plan(2)

  portScanner.findAPortInUse([3001, 3005, 3008], '127.0.0.1', (error, port) => {
    t.is(error, null)
    t.false(port)
  })
})

/* findPortNotInUse */

test('findAPortNotInUse - start from free port', t => {
  t.plan(2)

  portScanner.findAPortNotInUse(3001, 3010, '127.0.0.1', (error, port) => {
    t.is(error, null)
    t.is(port, 3001)
  })
})

test('findAPortNotInUse - start from taken port', t => {
  t.plan(2)

  portScanner.findAPortNotInUse(3000, 3010, '127.0.0.1', (error, port) => {
    t.is(error, null)
    t.is(port, 3001)
  })
})

test('findAPortNotInUse - all ports in range taken', t => {
  t.plan(2)

  portScanner.findAPortNotInUse(2999, 3000, '127.0.0.1', (error, port) => {
    t.is(error, null)
    t.false(port)
  })
})

test('findAPortNotInUse - with array as parameter', t => {
  t.plan(2)

  portScanner.findAPortNotInUse([3000, 3002, 2999], '127.0.0.1', (error, port) => {
    t.is(error, null)
    t.is(port, 3002)
  })
})
<commit_msg>more tests for different argument signatures<commit_after>import net from 'net'

import test from 'ava'

import portScanner from './lib/portscanner.js'

test.before('Set #1 test server', t => {
  const server = net.createServer()
  server.listen(3000, '127.0.0.1', () => t.end())
})

test.before('Set #2 test server', t => {
  const server2 = net.createServer()
  server2.listen(2999, '127.0.0.1', () => t.end())
})

/* checkPortStatus */

test('checkPortStatus - taken', t => {
  t.plan(2)

  portScanner.checkPortStatus(3000, '127.0.0.1', (error, port) => {
    t.is(error, null)
    t.is(port, 'open')
  })
})

test('checkPortStatus - taken (without host)', t => {
  t.plan(2)

  portScanner.checkPortStatus(3000, (error, port) => {
    t.is(error, null)
    t.is(port, 'open')
  })
})

test('checkPortStatus - free', t => {
  t.plan(2)

  portScanner.checkPortStatus(3001, '127.0.0.1', (error, port) => {
    t.is(error, null)
    t.is(port, 'closed')
  })
})

test('checkPortStatus - free (without host)', t => {
  t.plan(2)

  portScanner.checkPortStatus(3001, (error, port) => {
    t.is(error, null)
    t.is(port, 'closed')
  })
})

/* findPortInUse */

test('findPortInUse - taken port in range', t => {
  t.plan(2)

  portScanner.findAPortInUse(3000, 3010, '127.0.0.1', (error, port) => {
    t.is(error, null)
    t.is(port, 3000)
  })
})

test('findPortInUse - taken port in range (without host)', t => {
  t.plan(2)

  portScanner.findAPortInUse(3000, 3010, (error, port) => {
    t.is(error, null)
    t.is(port, 3000)
  })
})

test('findPortInUse - taken port in range (without endPort)', t => {
  t.plan(2)

  portScanner.findAPortInUse(3000, '127.0.0.1', (error, port) => {
    t.is(error, null)
    t.is(port, 3000)
  })
})

test('findPortInUse - taken port in range (without endPort and host) ', t => {
  t.plan(2)

  portScanner.findAPortInUse(3000, (error, port) => {
    t.is(error, null)
    t.is(port, 3000)
  })
})

test('findPortInUse - taken port in range - ports as array', t => {
  t.plan(2)

  portScanner.findAPortInUse([2999, 3000, 3001], '127.0.0.1', (error, port) => {
    t.is(error, null)
    t.is(port, 2999)
  })
})

test('findPortInUse - taken port in range - ports as array (without host)', t => {
  t.plan(2)

  portScanner.findAPortInUse([2999, 3000, 3001], (error, port) => {
    t.is(error, null)
    t.is(port, 2999)
  })
})

test('findPortInUse - all ports in range free', t => {
  t.plan(2)

  portScanner.findAPortInUse(3001, 3010, '127.0.0.1', (error, port) => {
    t.is(error, null)
    t.false(port)
  })
})

test('findPortInUse - all ports in range free - ports as array', t => {
  t.plan(2)

  portScanner.findAPortInUse([3001, 3005, 3008], '127.0.0.1', (error, port) => {
    t.is(error, null)
    t.false(port)
  })
})

test('findPortInUse - all ports in range free - ports as array (without host)', t => {
  t.plan(2)

  portScanner.findAPortInUse([3001, 3005, 3008], (error, port) => {
    t.is(error, null)
    t.false(port)
  })
})

/* findPortNotInUse */

test('findAPortNotInUse - start from free port', t => {
  t.plan(2)

  portScanner.findAPortNotInUse(3001, 3010, '127.0.0.1', (error, port) => {
    t.is(error, null)
    t.is(port, 3001)
  })
})

test('findAPortNotInUse - start from taken port', t => {
  t.plan(2)

  portScanner.findAPortNotInUse(3000, 3010, '127.0.0.1', (error, port) => {
    t.is(error, null)
    t.is(port, 3001)
  })
})

test('findAPortNotInUse - all ports in range taken', t => {
  t.plan(2)

  portScanner.findAPortNotInUse(2999, 3000, '127.0.0.1', (error, port) => {
    t.is(error, null)
    t.false(port)
  })
})

test('findAPortNotInUse - with array as parameter', t => {
  t.plan(2)

  portScanner.findAPortNotInUse([3000, 3002, 2999], '127.0.0.1', (error, port) => {
    t.is(error, null)
    t.is(port, 3002)
  })
})
<|endoftext|>


<commit_before>'use strict';

var Bin = require('./');
var exists = require('fs').exists;
var path = require('path');
var test = require('ava');

test('expose a constructor', function (t) {
	t.plan(1);
	t.assert(typeof Bin === 'function');
});

test('add a source', function (t) {
	t.plan(1);

	var bin = new Bin()
		.src('http://foo.com/bar.tar.gz');

	t.assert(bin._src[0].url === 'http://foo.com/bar.tar.gz');
});

test('add a source to a specific os', function (t) {
	t.plan(1);

	var bin = new Bin()
		.src('http://foo.com', process.platform);

	t.assert(bin._src[0].os === process.platform);
});

test('set destination directory', function (t) {
	t.plan(1);

	var bin = new Bin()
		.dest(path.join(__dirname, 'foo'));

	t.assert(bin._dest === path.join(__dirname, 'foo'));
});

test('set which file to use as the binary', function (t) {
	t.plan(1);

	var bin = new Bin()
		.use('foo');

	t.assert(bin._use === 'foo');
});

test('should verify that a binary is working', function (t) {
	t.plan(2);

	var base = 'https://github.com/imagemin/gifsicle-bin/raw/master/vendor';
	var bin = new Bin()
		.src(base + '/osx/gifsicle', 'darwin')
		.src(base + '/linux/x64/gifsicle', 'linux', 'x64')
		.src(base + '/win/x64/gifsicle.exe', 'win32', 'x64')
		.dest(path.join(__dirname, 'tmp'))
		.use(process.platform === 'win32' ? 'gifsicle.exe' : 'gifsicle');

	bin.run(function (err) {
		t.assert(!err, err);

		exists(bin.path(), function (exist) {
			t.assert(exist);
		});
	});
});

test('should download and extract an archive', function (t) {
	t.plan(2);

	var base = 'https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-1.9.7';
	var bin = new Bin({ strip: 1 })
		.src(base + '-macosx.zip', 'darwin')
		.src(base + '-windows.zip', 'win32')
		.src(base + '-linux-x86_64.tar.bz2', 'linux', 'x64')
		.src(base + '-linux-i686.tar.bz2', 'linux', 'x86')
		.dest(path.join(__dirname, 'tmp'))
		.use(process.platform === 'win32' ? 'phantomjs.exe' : 'bin/phantomjs');

	bin.run(function (err) {
		t.assert(!err, err);

		exists(bin.path(), function (exist) {
			t.assert(exist);
		});
	});
});

test('should meet the desired version', function (t) {
	t.plan(2);

	var base = 'https://github.com/imagemin/gifsicle-bin/raw/master/vendor';
	var bin = new Bin()
		.src(base + '/osx/gifsicle', 'darwin')
		.src(base + '/linux/x64/gifsicle', 'linux', 'x64')
		.src(base + '/win/x64/gifsicle.exe', 'win32', 'x64')
		.dest(path.join(__dirname, 'tmp'))
		.use(process.platform === 'win32' ? 'gifsicle.exe' : 'gifsicle')
		.version('>=1.71');

	bin.run(function (err) {
		t.assert(!err, err);

		exists(bin.path(), function (exist) {
			t.assert(exist);
		});
	});
});
<commit_msg>Add global binary test<commit_after>'use strict';

var Bin = require('./');
var fs = require('fs');
var path = require('path');
var test = require('ava');

test('expose a constructor', function (t) {
	t.plan(1);
	t.assert(typeof Bin === 'function');
});

test('add a source', function (t) {
	t.plan(1);

	var bin = new Bin()
		.src('http://foo.com/bar.tar.gz');

	t.assert(bin._src[0].url === 'http://foo.com/bar.tar.gz');
});

test('add a source to a specific os', function (t) {
	t.plan(1);

	var bin = new Bin()
		.src('http://foo.com', process.platform);

	t.assert(bin._src[0].os === process.platform);
});

test('set destination directory', function (t) {
	t.plan(1);

	var bin = new Bin()
		.dest(path.join(__dirname, 'foo'));

	t.assert(bin._dest === path.join(__dirname, 'foo'));
});

test('set which file to use as the binary', function (t) {
	t.plan(1);

	var bin = new Bin()
		.use('foo');

	t.assert(bin._use === 'foo');
});

test('should verify that a binary is working', function (t) {
	t.plan(2);

	var base = 'https://github.com/imagemin/gifsicle-bin/raw/master/vendor';
	var bin = new Bin()
		.src(base + '/osx/gifsicle', 'darwin')
		.src(base + '/linux/x64/gifsicle', 'linux', 'x64')
		.src(base + '/win/x64/gifsicle.exe', 'win32', 'x64')
		.dest(path.join(__dirname, 'tmp'))
		.use(process.platform === 'win32' ? 'gifsicle.exe' : 'gifsicle');

	bin.run(function (err) {
		t.assert(!err, err);

		fs.exists(bin.path(), function (exists) {
			t.assert(exists);
		});
	});
});

test('should download and extract an archive', function (t) {
	t.plan(2);

	var base = 'https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-1.9.7';
	var bin = new Bin({ strip: 1 })
		.src(base + '-macosx.zip', 'darwin')
		.src(base + '-windows.zip', 'win32')
		.src(base + '-linux-x86_64.tar.bz2', 'linux', 'x64')
		.src(base + '-linux-i686.tar.bz2', 'linux', 'x86')
		.dest(path.join(__dirname, 'tmp'))
		.use(process.platform === 'win32' ? 'phantomjs.exe' : 'bin/phantomjs');

	bin.run(function (err) {
		t.assert(!err, err);

		fs.exists(bin.path(), function (exists) {
			t.assert(exists);
		});
	});
});

test('should meet the desired version', function (t) {
	t.plan(2);

	var base = 'https://github.com/imagemin/gifsicle-bin/raw/master/vendor';
	var bin = new Bin()
		.src(base + '/osx/gifsicle', 'darwin')
		.src(base + '/linux/x64/gifsicle', 'linux', 'x64')
		.src(base + '/win/x64/gifsicle.exe', 'win32', 'x64')
		.dest(path.join(__dirname, 'tmp'))
		.use(process.platform === 'win32' ? 'gifsicle.exe' : 'gifsicle')
		.version('>=1.71');

	bin.run(function (err) {
		t.assert(!err, err);

		fs.exists(bin.path(), function (exists) {
			t.assert(exists);
		});
	});
});

test('should symlink a global binary', function (t) {
	t.plan(3);

	var bin = new Bin({ global: true })
		.dest(path.join(__dirname, 'tmp'))
		.use('bash');

	bin.run(function (err) {
		t.assert(!err, err);

		fs.lstat(bin.path(), function (err, stats) {
			t.assert(!err, err);
			t.assert(stats.isSymbolicLink());
		});
	});
});
<|endoftext|>