<commit_before>!function(root) {
  function contains(str, needle) {
    return !!~str.indexOf(needle);
  }

  var common = typeof module != 'undefined' && !!module.exports
  var aok = common ? require('aok') : root.aok
  var eol = common ? require('./') : root.eol
  var isWindows = typeof process != 'undefined' && 'win32' === process.platform
  var meths = ['lf', 'cr', 'crlf', 'auto']
  var chars = ['\n', '\r', '\r\n', isWindows ? '\r\n' : '\n']
  var sample = ' ' + chars.join() + 'text' + chars.join()

  aok.prototype.fail = function() {
    throw new Error('FAILED TEST: ' + this.id)
  }

  aok('contains() sees contained text', contains('ab', 'a') === true)
  aok('sample contains newlines', contains(sample, '\n') && contains(sample, '\r'))
  aok('returns other strings as is', eol.auto('random') === 'random')
  aok('returns empty strings as is', eol.auto('') === '')
  aok('whitespace intact', eol.lf(' \t ') === ' \t ')
  aok('repeat newlines intact lf', eol.lf('\n\n\r\r') === '\n\n\n\n')
  aok('repeat newlines intact lf', eol.cr('\n\n\r\r') === '\r\r\r\r')
  aok('repeat newlines intact crlf', eol.crlf('\r\n\r\n') === '\r\n\r\n')

  aok.pass(meths, function(method, i) {
    var normalized = eol[method](sample)
    aok(method + ' retains', contains(normalized, chars[i]))
    aok(method + ' normalizes', !aok.fail(chars, function(c) {
      return contains(chars[i], c) === contains(normalized, c)
    }))

    return eol.auto(sample) === normalized
  })

  aok('auto is aware', eol[isWindows ? 'crlf' : 'lf'](sample) === eol.auto(sample))
  aok('auto matches only 1 and self', aok.pass(meths, function(method) {
    return eol.auto(sample) === eol[method](sample);
  }) === 2)

  aok.log('All tests passed =)')
}(this);
<commit_msg>correct cr repeat test id<commit_after>!function(root) {
  function contains(str, needle) {
    return !!~str.indexOf(needle);
  }

  var common = typeof module != 'undefined' && !!module.exports
  var aok = common ? require('aok') : root.aok
  var eol = common ? require('./') : root.eol
  var isWindows = typeof process != 'undefined' && 'win32' === process.platform
  var meths = ['lf', 'cr', 'crlf', 'auto']
  var chars = ['\n', '\r', '\r\n', isWindows ? '\r\n' : '\n']
  var sample = ' ' + chars.join() + 'text' + chars.join()

  aok.prototype.fail = function() {
    throw new Error('FAILED TEST: ' + this.id)
  }

  aok('contains() sees contained text', contains('ab', 'a') === true)
  aok('sample contains newlines', contains(sample, '\n') && contains(sample, '\r'))
  aok('returns other strings as is', eol.auto('random') === 'random')
  aok('returns empty strings as is', eol.auto('') === '')
  aok('whitespace intact', eol.lf(' \t ') === ' \t ')
  aok('repeat newlines intact lf', eol.lf('\n\n\r\r') === '\n\n\n\n')
  aok('repeat newlines intact cr', eol.cr('\n\n\r\r') === '\r\r\r\r')
  aok('repeat newlines intact crlf', eol.crlf('\r\n\r\n') === '\r\n\r\n')

  aok.pass(meths, function(method, i) {
    var normalized = eol[method](sample)
    aok(method + ' retains', contains(normalized, chars[i]))
    aok(method + ' normalizes', !aok.fail(chars, function(c) {
      return contains(chars[i], c) === contains(normalized, c)
    }))

    return eol.auto(sample) === normalized
  })

  aok('auto is aware', eol[isWindows ? 'crlf' : 'lf'](sample) === eol.auto(sample))
  aok('auto matches only 1 and self', aok.pass(meths, function(method) {
    return eol.auto(sample) === eol[method](sample);
  }) === 2)

  aok.log('All tests passed =)')
}(this);
<|endoftext|>


<commit_before>// @flow
import React, { Component, Element } from 'react';
import Subheader from 'material-ui/Subheader';
import { List, ListItem } from 'material-ui/List';
import styles from './Structure.css'; // eslint-disable-line flowtype-errors/show-errors

const stripJsonComments = require('strip-json-comments');

export default class Structure extends Component {
  props: {
    data: string
  }

  schema: string;
  contentVersion: string;
  parameters: any;
  variables: any;
  resources: any;
  outputs: any;

  displayVariables(): Element<any>[] {
    const variables = [];
    Object.keys(this.variables).forEach((k) => {
      variables.push(<ListItem className={styles.structureItem} key={k}>{k}</ListItem>);
    });

    return variables;
  }

  displayParameters(): Element<any>[] {
    const parameters = [];
    Object.keys(this.parameters).forEach((p) => {
      parameters.push(<ListItem className={styles.structureItem} key={p}>{p}</ListItem>);
    });

    return parameters;
  }

  displayOutputs(): Element<any>[] {
    const outputs = [];
    Object.keys(this.outputs).forEach((o) => {
      outputs.push(<ListItem className={styles.structureItem} key={o}>{o}</ListItem>);
    });

    return outputs;
  }

  parseJson(): void {
    const json = JSON.parse(stripJsonComments(this.props.data));
    this.schema = json.$schema;
    this.contentVersion = json.contentVersion;
    this.parameters = json.parameters || {};
    this.variables = json.variables || {};
    this.resources = json.resources;
    this.outputs = json.outputs || {};
  }

  render() {
    this.parseJson();

    return (

        <List>
          <Subheader>Structure</Subheader>
          <ListItem className={styles.structureHeader} primaryText="Schema" initiallyOpen={false} primaryTogglesNestedList={true} nestedItems={[<ListItem className={styles.structureItem} key={1} primaryText={this.schema} />]} />
          <ListItem className={styles.structureHeader} primaryText="Content Version" initiallyOpen={false} primaryTogglesNestedList={true} nestedItems={[<ListItem className={styles.structureItem} key={1} primaryText={this.contentVersion} />]} />
          <ListItem className={styles.structureHeader} primaryText="Variables" initiallyOpen={false} primaryTogglesNestedList={true} nestedItems={this.displayVariables()} />
          <ListItem className={styles.structureHeader} primaryText="Parameters" initiallyOpen={false} primaryTogglesNestedList={true} nestedItems={this.displayParameters()} />
          <ListItem className={styles.structureHeader} primaryText="Outputs" initiallyOpen={false} primaryTogglesNestedList={true} nestedItems={this.displayOutputs()} />
        </List>

);
  }
}
<commit_msg>#19 - eslint fixes<commit_after>// @flow
import React, { Component, Element } from 'react';
import Subheader from 'material-ui/Subheader';
import { List, ListItem } from 'material-ui/List';
import styles from './Structure.css'; // eslint-disable-line flowtype-errors/show-errors

const stripJsonComments = require('strip-json-comments');

export default class Structure extends Component {
  props: {
    data: string
  }

  schema: string;
  contentVersion: string;
  parameters: any;
  variables: any;
  resources: any;
  outputs: any;

  displayVariables(): Element<any>[] {
    const variables = [];
    Object.keys(this.variables).forEach((k) => {
      variables.push(<ListItem className={styles.structureItem} key={k}>{k}</ListItem>);
    });

    return variables;
  }

  displayParameters(): Element<any>[] {
    const parameters = [];
    Object.keys(this.parameters).forEach((p) => {
      parameters.push(<ListItem className={styles.structureItem} key={p}>{p}</ListItem>);
    });

    return parameters;
  }

  displayOutputs(): Element<any>[] {
    const outputs = [];
    Object.keys(this.outputs).forEach((o) => {
      outputs.push(<ListItem className={styles.structureItem} key={o}>{o}</ListItem>);
    });

    return outputs;
  }

  parseJson(): void {
    const json = JSON.parse(stripJsonComments(this.props.data));
    this.schema = json.$schema;
    this.contentVersion = json.contentVersion;
    this.parameters = json.parameters || {};
    this.variables = json.variables || {};
    this.resources = json.resources;
    this.outputs = json.outputs || {};
  }

  render() {
    this.parseJson();

    return (

        <List>
          <Subheader>Structure</Subheader>
          <ListItem className={styles.structureHeader} primaryText="Schema" initiallyOpen={false} nestedItems={[<ListItem className={styles.structureItem} key={1} primaryText={this.schema} />]} />
          <ListItem className={styles.structureHeader} primaryText="Content Version" initiallyOpen={false} nestedItems={[<ListItem className={styles.structureItem} key={1} primaryText={this.contentVersion} />]} />
          <ListItem className={styles.structureHeader} primaryText="Variables" initiallyOpen={false} nestedItems={this.displayVariables()} />
          <ListItem className={styles.structureHeader} primaryText="Parameters" initiallyOpen={false} nestedItems={this.displayParameters()} />
          <ListItem className={styles.structureHeader} primaryText="Outputs" initiallyOpen={false} nestedItems={this.displayOutputs()} />
        </List>

);
  }
}
<|endoftext|>


<commit_before>import numeral from 'numeral'
import WS from 'websocket'
import subscriptions from 'resources/subscriptions'

class LocalStorage {
	get(key) {
		var value = localStorage.getItem(key)
		if (typeof value !== 'undefined') {
			try {
				value = JSON.parse(value)
			}
			catch (e) {
				console.error('Invalid storage object')
				console.error(e)
			}
		}
		return value
	}
	set(key, value) {
		localStorage.setItem(key, JSON.stringify(value))
	}
	remove(key) {
		localStorage.removeItem(key)
	}
}

// Layout wrapper functions
function wrapper(type, cls='') {
	return function(...contents) {
		return {
			type: type,
			contents: contents,
			cls: cls,
		}
	}
}
var row = wrapper('row')
var rowExpand = wrapper('row', 'expand')
var col = wrapper('col')
var colExpand = wrapper('col', 'expand')
var section = wrapper('section')
var sectionExpand = wrapper('section', 'expand')
var module = function(id, config={}) {
	return {
		type: 'module',
		id: id,
		'module-config': config,
	}
}

var storage = new LocalStorage()

export default {
	template: require('./template.jade')({styles: require('./stylesheet.sass')}),
	components: {
		layout: require('../layout'),
		settings: require('../settings'),

		actiongroups: require('../modules/actiongroups'),
		history: require('../modules/history'),
		map: require('../modules/map'),
		navigation: require('../modules/navigation'),
		orbit: require('../modules/orbit'),
		resources: require('../modules/resources'),
		vessel: require('../modules/vessel'),
	},
	data() {
		var config = storage.get('config')
		var telemachusRefreshRate = config ? (config.telemachus.refreshRate || 1) : 1
		var telemachusRefreshInterval = parseInt(1 / telemachusRefreshRate * 1000)
		if (config) {
			config.telemachus.refreshInterval = telemachusRefreshInterval
		}

		return {
			config: config || {
				telemachus: {
					host: 'localhost',
					port: 8085,
					refreshRate: telemachusRefreshRate,
					refreshInterval: telemachusRefreshInterval,
				},
				rendering: {
					fps: 60,
					useNormalMaps: true,
					useSpecularMaps: true,
					showSkybox: true,
					showLensFlare: true,
					postProcessing: true,
				},
				modules: {
					map: {
						showBodyDetails: true,
					},
				},
			},

			storage: storage,
			ws: null,
			wsConnected: false,

			settingsVisible: false,

			data: {},

			layout: [
				col(
					row(
						section(module('map')),
						section(module('resources')),
						rowExpand(
							col(
								section(
									row(
										module('navigation'),
										module('orbit')
									)
								),
								rowExpand(
									section(module('vessel'))
								)
							)
						)
					)
				)
			],
		}
	},
	ready() {
		// Connect to Telemachus socket
		this.ws = new WS(`ws://${this.config.telemachus.host}:${this.config.telemachus.port}/datalink`)
		this.ws.addOpenHandler(() => {
			this.wsConnected = true

			// Subscribe to data from Telemachus
			this.ws.send({rate: this.config.telemachus.refreshInterval, '+': subscriptions})
		})
		this.ws.addCloseHandler(() => this.wsConnected = false)
		this.ws.addMessageHandler(ev => {
			var msg = JSON.parse(ev.data)

			Object.keys(msg).forEach(k => {
				if (!this.data[k]) {
					this.data.$add(k, null)
				}
				this.data[k] = msg[k]
			})
		})
		this.ws.connect().fail(msg => console.error(msg))
	},
	methods: {
		numeral: numeral,
		saveConfig() {
			this.storage.set('config', this.config)
		},
	},
}
<commit_msg>Temporarily remove history to shrink build<commit_after>import numeral from 'numeral'
import WS from 'websocket'
import subscriptions from 'resources/subscriptions'

class LocalStorage {
	get(key) {
		var value = localStorage.getItem(key)
		if (typeof value !== 'undefined') {
			try {
				value = JSON.parse(value)
			}
			catch (e) {
				console.error('Invalid storage object')
				console.error(e)
			}
		}
		return value
	}
	set(key, value) {
		localStorage.setItem(key, JSON.stringify(value))
	}
	remove(key) {
		localStorage.removeItem(key)
	}
}

// Layout wrapper functions
function wrapper(type, cls='') {
	return function(...contents) {
		return {
			type: type,
			contents: contents,
			cls: cls,
		}
	}
}
var row = wrapper('row')
var rowExpand = wrapper('row', 'expand')
var col = wrapper('col')
var colExpand = wrapper('col', 'expand')
var section = wrapper('section')
var sectionExpand = wrapper('section', 'expand')
var module = function(id, config={}) {
	return {
		type: 'module',
		id: id,
		'module-config': config,
	}
}

var storage = new LocalStorage()

export default {
	template: require('./template.jade')({styles: require('./stylesheet.sass')}),
	components: {
		layout: require('../layout'),
		settings: require('../settings'),

		actiongroups: require('../modules/actiongroups'),
		map: require('../modules/map'),
		navigation: require('../modules/navigation'),
		orbit: require('../modules/orbit'),
		resources: require('../modules/resources'),
		vessel: require('../modules/vessel'),
	},
	data() {
		var config = storage.get('config')
		var telemachusRefreshRate = config ? (config.telemachus.refreshRate || 1) : 1
		var telemachusRefreshInterval = parseInt(1 / telemachusRefreshRate * 1000)
		if (config) {
			config.telemachus.refreshInterval = telemachusRefreshInterval
		}

		return {
			config: config || {
				telemachus: {
					host: 'localhost',
					port: 8085,
					refreshRate: telemachusRefreshRate,
					refreshInterval: telemachusRefreshInterval,
				},
				rendering: {
					fps: 60,
					useNormalMaps: true,
					useSpecularMaps: true,
					showSkybox: true,
					showLensFlare: true,
					postProcessing: true,
				},
				modules: {
					map: {
						showBodyDetails: true,
					},
				},
			},

			storage: storage,
			ws: null,
			wsConnected: false,

			settingsVisible: false,

			data: {},

			layout: [
				col(
					row(
						section(module('map')),
						section(module('resources')),
						rowExpand(
							col(
								section(
									row(
										module('navigation'),
										module('orbit')
									)
								),
								rowExpand(
									section(module('vessel'))
								)
							)
						)
					)
				)
			],
		}
	},
	ready() {
		// Connect to Telemachus socket
		this.ws = new WS(`ws://${this.config.telemachus.host}:${this.config.telemachus.port}/datalink`)
		this.ws.addOpenHandler(() => {
			this.wsConnected = true

			// Subscribe to data from Telemachus
			this.ws.send({rate: this.config.telemachus.refreshInterval, '+': subscriptions})
		})
		this.ws.addCloseHandler(() => this.wsConnected = false)
		this.ws.addMessageHandler(ev => {
			var msg = JSON.parse(ev.data)

			Object.keys(msg).forEach(k => {
				if (!this.data[k]) {
					this.data.$add(k, null)
				}
				this.data[k] = msg[k]
			})
		})
		this.ws.connect().fail(msg => console.error(msg))
	},
	methods: {
		numeral: numeral,
		saveConfig() {
			this.storage.set('config', this.config)
		},
	},
}
<|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-17 10:44:31<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 assert = require("assert");
describe("ReactiveProperty", function() {
  describe("#indexOf()", function () {
    it("should return -1 when the value is not present", function () {
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    });
  });
});

var Graph = require("./graph.js");
var debounce = require("./debounce.js");

var graph = new Graph();
var nodeIdCounter = 0;
var changedNodes = {};
var nodes = {};

function digest(){
  var sourceNodes = Object.keys(changedNodes).map(parseInt);
  var ids = graph.topologicalSort(sourceNodes);
  ids.forEach(function (id){
    nodes[id].evaluate();
  });
}

var queueDigest = debounce(digest);

function nodeChanged(node){
  changedNodes[node.id] = true;
  queueDigest();
}

function ReactiveNode(evaluate){
  var node = {
    id: nodeIdCounter++,
    evaluate: evaluate || function (){}
  };
  nodes[node.id] = node;
  return node;
}

function ReactiveProperty(value){
  var node = ReactiveNode();
  var reactiveProperty = function(newValue){
    if(!arguments.length){
      return value;
    } else {
      value = newValue;
      nodeChanged(node);
    }
  };
  reactiveProperty.node = node;
  return reactiveProperty;
}

// ReactiveFunction(dependencies... , callback)
function ReactiveFunction(){

  // Parse arguments.
  var dependencies = [];
  for(var i = 0; i < arguments.length - 1; i++){
    dependencies.push(arguments[i]);
  }
  var callback = arguments[arguments.length - 1];

  var value;

  var node = ReactiveNode(function (){
    var args = dependencies.map(function (d){
      return d();
    });
    value = callback.apply(null, args);
  });

  dependencies.forEach(function (d){
    graph.addEdge(d.node.id, node.id);
  });

  var reactiveFunction = function (){
    return value;
  };

  reactiveFunction.node = node;

  return reactiveFunction;
}

// TODO add as unit tests
//graph.addEdge(1, 2);
//graph.addEdge(2, 3);
//graph.addEdge(3, 4);
//graph.addEdge(4, 7);
//
//graph.addEdge(1, 6);
//graph.addEdge(6, 7);
//
//console.log(graph.topologicalSort([1]));

var a = ReactiveProperty(5);
console.log(a());
a(6);
console.log(a());

var b = ReactiveProperty(10);

var c = ReactiveFunction(a, b, function (a, b){
  return a + b;
});

var d = ReactiveFunction(a, c, function (a, c){
  return a + c;
});

digest();

console.log(c());
console.log(d());

a(0);
digest();

console.log(d());
<commit_msg>restructure<commit_after>var assert = require("assert");
describe("ReactiveProperty", function() {
  describe("#indexOf()", function () {
    it("should return -1 when the value is not present", function () {
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    });
  });
});

var Graph = require("./graph.js");
var debounce = require("./debounce.js");

var graph = new Graph();

var ReactiveNode = (function (){
  var idCounter = 0;
  return function (){
    return idCounter++;
  }
}());

var changedNodes = {};
var evaluateNode = {};

function digest(){
  var sourceNodes = Object.keys(changedNodes).map(parseInt);
  graph.topologicalSort(sourceNodes).forEach(function (id){
    var fn = evaluateNode[id];
    if(fn) fn();
  });
}

var queueDigest = debounce(digest);

function nodeChanged(id){
  changedNodes[id] = true;
  queueDigest();
}

function ReactiveProperty(value){
  var id = ReactiveNode();
  var reactiveProperty = function(newValue){
    if(!arguments.length){
      return value;
    } else {
      value = newValue;
      nodeChanged(id);
    }
  };
  reactiveProperty.id = id;
  return reactiveProperty;
}

// ReactiveFunction(dependencies... , callback)
function ReactiveFunction(){

  // Parse arguments.
  var dependencies = [];
  for(var i = 0; i < arguments.length - 1; i++){
    dependencies.push(arguments[i]);
  }
  var callback = arguments[arguments.length - 1];

  var value;

  var id = ReactiveNode();

  var reactiveFunction = function (){
    return value;
  };

  dependencies.forEach(function (d){
    graph.addEdge(d.id, id);
  });

  evaluateNode[id] = function (){
    var args = dependencies.map(function (d){
      return d();
    });
    value = callback.apply(null, args);
  };

  reactiveFunction.id = id;

  return reactiveFunction;
}

// TODO add as unit tests
//graph.addEdge(1, 2);
//graph.addEdge(2, 3);
//graph.addEdge(3, 4);
//graph.addEdge(4, 7);
//
//graph.addEdge(1, 6);
//graph.addEdge(6, 7);
//
//console.log(graph.topologicalSort([1]));

var a = ReactiveProperty(5);
console.log(a());
a(6);
console.log(a());

var b = ReactiveProperty(10);

var c = ReactiveFunction(a, b, function (a, b){
  return a + b;
});

var d = ReactiveFunction(a, c, function (a, c){
  return a + c;
});

digest();

console.log(c());
console.log(d());

a(0);
digest();

console.log(d());
<|endoftext|>


<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: 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 ();

} ()

<commit_msg>ci retrigger<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>let jsroot = require("jsroot"),
    fs = require("fs"),
    xml_formatter = require('xml-formatter');

let examples_main = require("./../jsroot/demo/examples.json");

examples_main.TH1.push({ name: "B_local", file: "file://other/hsimple.root", item: "hpx;1", opt:"B,fill_green", title: "draw histogram as bar chart" });
examples_main.TTree.push({ name: "2d_local", asurl: true, file: "file://other/hsimple.root", item: "ntuple", opt: "px:py", title: "Two-dimensional TTree::Draw" });

console.log(`JSROOT version  ${jsroot.version_id} ${jsroot.version_date}`);

let init_style = null,
    test_mode = "verify", nmatch = 0, ndiff = 0, nnew = 0,
    keyid = 'TH1', theonlykey = false, optid = -1,
    theOnlyOption, theOnlyOptionId = -100, itemid = -1,
    entry, entry_name = "", testfile = null, testobj = null,
    all_diffs = [],
    last_time = new Date().getTime(),
    processNextOption;

if (process.argv && (process.argv.length > 2)) {

   for (let cnt=2;cnt<process.argv.length;++cnt)
      switch (process.argv[cnt]) {
        case "-v":
        case "--verify":  test_mode = "verify"; break;
        case "-c":
        case "--create": test_mode = "create"; break;
        case "-k":
        case "--key":
           keyid = process.argv[++cnt];
           theonlykey = true;
           if (!keyid || !examples_main[keyid])
              return console.log('Key not found', keyid);
           break;
        case "-o":
        case "--opt":
           theOnlyOption = process.argv[++cnt];
           theOnlyOptionId = parseInt(theOnlyOption);
           if (isNaN(theOnlyOptionId) || (theOnlyOptionId<0) || !examples_main[keyid][theOnlyOptionId]) {
              theOnlyOptionId = -100;
           } else {
              console.log('Select option', examples_main[keyid][theOnlyOptionId], 'for key', keyid);
              optid = theOnlyOptionId - 1;
              theOnlyOption = "";
           }
           break;
        case "-m":
        case "--more":
           let examples_more = require("./../jsroot/demo/examples_more.json");

           for (let key in examples_more) {
              if (examples_main[key])
                 examples_main[key].push(...examples_more[key]);
              else
                 examples_main[key] = examples_more[key];
           }
           break;
        case "-i":
        case "--ignore":
            process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;
            break;

        default:
           console.log('Usage: node test.js [options]');
           console.log('   -v | --verify : check stored content against current JSROOT version');
           console.log('   -c | --create : perform checks and overwrite when results differ');
           console.log('   -k | --key keyname : select specific key (class name) like TH1 or TProfile for testing');
           console.log('   -o | --opt id : select specific option id (number or name), only when key is specified');
           console.log('   -m | --more : use more tests');
           console.log('   -i | --ignore : ignore TLS checks');
           return;
      }
}

function ProduceGlobalStyleCopy() {
   // copy style when painter is loaded
   if (!init_style && jsroot.Painter) init_style = jsroot.gStyle;
}

function ProduceFile(content, extension, subid) {
   if (!entry_name) entry_name = keyid;

   entry_name = entry_name.replace(/ /g, '_')
                          .replace(/\+/g,'p').replace(/\>/g,'more')
                          .replace(/\</g,'less').replace(/\|/g,'I')
                          .replace(/\[/g,'L').replace(/\]/g,'J').replace(/\*/g,'star');

   let use_name = entry_name;
   if (subid)
      use_name += "_" + subid;

   if (extension != ".json")
      content = xml_formatter(content, {indentation: ' ', lineSeparator: '\n' });

   try {
      fs.accessSync(keyid, fs.constants.W_OK);
   } catch(err) {
      fs.mkdirSync(keyid);
   }

   let svgname = keyid + "/" + use_name + extension,
       svg0 = null, result = "MATCH";

   try {
     svg0 = fs.readFileSync(svgname, 'utf-8');
     if (svg0 != content) result = "DIFF";
   } catch(e) {
     svg0 = null;
     result = "NEW";
   }

//   // workaround to ignore alice variation, to let enable TGeo testings
// if ((result == "DIFF") && (keyid == "TGeo") && (entry_name == "alice") && (Math.abs(svg0.length - content.length) < 0.01*svg0.length)) {
//      console.log('!! Ignore alice variation for now !!');
//      content = svg0;
//      result = "MATCH";
//   }

   switch (result) {
      case "NEW": nnew++; break;
      case "DIFF": ndiff++; break;
      default: nmatch++;
   }

   let clen = content ? content.length : -1;
   console.log(keyid, use_name, 'result', result, 'len='+clen, (svg0 && result=='DIFF' ? 'rel0='+(clen/svg0.length*100).toFixed(1)+'\%' : ''));

   if (result === "DIFF") all_diffs.push(svgname);

   if ((result === "NEW") || ((test_mode === 'create') && (result!=='MATCH'))) {
      if (clen > 0)
         fs.writeFileSync(svgname, content);
      else if (result !== "NEW")
         fs.unlink(svgname);
   }

   if (subid === undefined) processNextOption();
}

function ProduceSVG(obj, opt) {

   // use only for object reading
   if ((theOnlyOptionId >= 0) && theOnlyOptionId !== optid)
      return processNextOption();

  if (entry.reset_funcs) obj.fFunctions = jsroot.create("TList");

   jsroot.makeSVG({ object: obj, option: opt, width: 1200, height: 800 })
         .then(svg => {
            ProduceFile(svg, ".svg");
            if (entry.reset_funcs) obj.fFunctions = jsroot.create("TList");
         });
}

function ProcessURL(url) {

   return jsroot.require('hierarchy').then(() => {

      let hpainter = new jsroot.HierarchyPainter("testing", null);
      let batch_disp = new JSROOT.BatchDisplay(1200, 800);
      hpainter.setDisplay(batch_disp);

      hpainter.startGUI(null, url).then(() => {
         if (batch_disp.numFrames() == 0) {
            console.log(' Processing url: ', url);
            console.log('   !!! BATCH URL CREATES NO FRAME !!!', keyid, entry_name);
         }
         for (let n = 0; n < batch_disp.numFrames(); ++n) {
            let json = batch_disp.makeJSON(n, 1);
            if (json) ProduceFile(json, ".json", n);
            let svg = json ? "" : batch_disp.makeSVG(n);
            if (svg) ProduceFile(svg, ".svg", n);
         }
         processNextOption();
      });
   });
}

processNextOption = reset_mathjax => {

   if (!keyid) {
      if (all_diffs.length) console.log("ALL DIFFS", all_diffs);
      console.log('No more data to process');
      console.log("SUMMARY: match", nmatch, "diff", ndiff, "new", nnew);
      return;
   }

   // make timeout to avoid deep callstack
   let curr_time = new Date().getTime();
   if ((curr_time - last_time > 10000) && !reset_mathjax) {
      last_time = curr_time;
      return setTimeout(() => processNextOption(), 1);
   }

   let opts = examples_main[keyid];
   if (!opts) return;

   if (!reset_mathjax) {
      if ((itemid>=0) || (itemid==-2)) {
         if (itemid==-2) itemid = -1; // special workaround for style entry, which is marked as itemid=-2
         if (++itemid>=opts[optid].items.length) itemid = -1;
      }

      if (itemid < 0) { // first check that all items are processed
         if (theOnlyOptionId == optid) {
            keyid = null;
            return processNextOption();
         }
         if (++optid >= opts.length) {
            optid = -1;
            let found = false, next = null;
            for (let key in examples_main) {
               // if (key === "TGeo") continue; // skip already here
               if (found) { next = key; break; }
               if (key == keyid) found = true;
            }

            keyid = next;
            if (theonlykey) keyid = null;
            return processNextOption();
         }
      }
   }

   entry = opts[optid];

   if ((theOnlyOptionId >= 0) && !entry.file && !entry.json && !entry.url) {
      let rid = optid;
      while (--rid >= 0) {
         let sentry = opts[rid];
         if (sentry.file && sentry.item) {
            entry.file = sentry.file; entry.item = sentry.item; break;
         }
      }
   }

   entry_name = "";

   // exclude some entries from the test
   if (entry.notest) return processNextOption();

   if (((entry.latex === "mathjax") || entry.reset_mathjax) && !reset_mathjax)
      return jsroot.require('latex')
                   .then(ltx => ltx.loadMathjax())
                   .then(() => {
         MathJax.startup.defaultReady();
         console.log('Loading MathJax and doing extra reset!!!')
         processNextOption(true);
      });

   let filename = "", itemname = "", jsonname = "", url = "", opt = "", opt2 = "",
       filepath = "http://jsroot.gsi.de/files/";
//       filepath = "https://root.cern.ch/js/files/";

   if (entry.file) {
       filename = entry.file;
       if ((filename.indexOf("http:") < 0) &&
           (filename.indexOf("https:") < 0) &&
           (filename.indexOf("file:") < 0)) filename = filepath + filename;
   }
   if (entry.item)
      itemname = entry.item;

   if (entry.testopt !== undefined)
      opt = entry.testopt;
   else if (entry.opt)
      opt = entry.opt;

   if (entry.json) {
      jsonname = entry.json;
      if ((jsonname.indexOf("http:")<0) && (jsonname.indexOf("https:")<0)) jsonname = filepath + jsonname;
   }
   if (entry.items) {
      if (itemid < 0) {
         if ((itemid==-1) && entry.style) {
            itemid = -2;
            itemname = entry.style; // special case when style should be applied before objects drawing
         } else {
           itemid = 0;
         }
      }
      if (itemid >= 0) {
         itemname = entry.items[itemid];
         if (entry.opts && (itemid < entry.opts.length)) opt = entry.opts[itemid];
      }
   }

   if (entry.r3d) opt2 = (opt ? "," : "") + "r3d_" + entry.r3d;

   if (entry.url)
      url = entry.url.replace(/\$\$\$/g, filepath);
   else if (entry.asurl) {
      url = ((entry.asurl === "browser") ? "?" : "?nobrowser&");
      url += jsonname ? "json=" + jsonname : "file=" + filename + "&item=" + itemname;
      if (keyid === "TTree") {
         if ((opt.indexOf(">>") < 0) && (opt.indexOf("dump") < 0) && (opt.indexOf("testio") < 0))
            opt += ">>dump;num:10";
      }
      url += "&opt=" + opt + opt2;
   }

   // if ((opt=='inspect') || (opt=='count')) return processNextOption();

   if (itemid >= 0)
      entry_name = (entry.name || keyid) + "_" + itemname + (opt ? "_" + opt : "");
   else if ('name' in entry)
      entry_name = entry.name;
   else
      entry_name = opt ? opt : keyid;

   if (theOnlyOption) {
      if (entry_name != theOnlyOption) return processNextOption();
      console.log('Select option', entry);
   }

   ProduceGlobalStyleCopy();
   if (!entry.style && init_style) jsroot.gStyle = jsroot.extend({}, init_style);

   // ensure default options
   if (jsroot.Painter) jsroot.Painter.createRootColors(); // ensure default colors
   jsroot.settings.Latex = 2;
   if (entry.latex) jsroot.settings.Latex = jsroot.constants.Latex.fromString(entry.latex);
   // seedrandom('hello.', { global: true }); // set global random
   jsroot._.id_counter = 1; // used in some custom styles

   if (url.length > 0) {
      testfile = testobj = null;
      return ProcessURL(url);
   } else if (jsonname.length > 0) {
      testfile = testobj = null;
      jsroot.httpRequest(jsonname, 'object').then(obj => {
         testobj = obj;
         ProduceSVG(testobj, opt+opt2);
      });
   } else if (filename.length > 0) {
      jsroot.openFile(filename).then(file => {
         testfile = file;
         return testfile.readObject(itemname);
      }).then(obj => {
         if (itemid==-2) {
            // special handling of style
            // Check that copy of gStyle exists
            ProduceGlobalStyleCopy();
            // first create copy of existing style
            let newstyle = jsroot.extend({}, jsroot.gStyle);
            // then apply changes to the
            jsroot.gStyle = jsroot.extend(newstyle, obj);
            return processNextOption();
         } else {
            testobj = obj;
            ProduceSVG(testobj, opt+opt2);
         }
      });
   } else if (itemname.length > 0) {
      testfile.readObject(itemname).then(obj => {
         testobj = obj;
         ProduceSVG(testobj, opt+opt2);
      });
   } else {
      ProduceSVG(testobj, opt+opt2);
   }
}

// start processing

processNextOption();
<commit_msg>Adjust test to batch display creation<commit_after>let jsroot = require("jsroot"),
    fs = require("fs"),
    xml_formatter = require('xml-formatter');

let examples_main = require("./../jsroot/demo/examples.json");

examples_main.TH1.push({ name: "B_local", file: "file://other/hsimple.root", item: "hpx;1", opt:"B,fill_green", title: "draw histogram as bar chart" });
examples_main.TTree.push({ name: "2d_local", asurl: true, file: "file://other/hsimple.root", item: "ntuple", opt: "px:py", title: "Two-dimensional TTree::Draw" });

console.log(`JSROOT version  ${jsroot.version_id} ${jsroot.version_date}`);

let init_style = null,
    test_mode = "verify", nmatch = 0, ndiff = 0, nnew = 0,
    keyid = 'TH1', theonlykey = false, optid = -1,
    theOnlyOption, theOnlyOptionId = -100, itemid = -1,
    entry, entry_name = "", testfile = null, testobj = null,
    all_diffs = [],
    last_time = new Date().getTime(),
    processNextOption;

if (process.argv && (process.argv.length > 2)) {

   for (let cnt=2;cnt<process.argv.length;++cnt)
      switch (process.argv[cnt]) {
        case "-v":
        case "--verify":  test_mode = "verify"; break;
        case "-c":
        case "--create": test_mode = "create"; break;
        case "-k":
        case "--key":
           keyid = process.argv[++cnt];
           theonlykey = true;
           if (!keyid || !examples_main[keyid])
              return console.log('Key not found', keyid);
           break;
        case "-o":
        case "--opt":
           theOnlyOption = process.argv[++cnt];
           theOnlyOptionId = parseInt(theOnlyOption);
           if (isNaN(theOnlyOptionId) || (theOnlyOptionId<0) || !examples_main[keyid][theOnlyOptionId]) {
              theOnlyOptionId = -100;
           } else {
              console.log('Select option', examples_main[keyid][theOnlyOptionId], 'for key', keyid);
              optid = theOnlyOptionId - 1;
              theOnlyOption = "";
           }
           break;
        case "-m":
        case "--more":
           let examples_more = require("./../jsroot/demo/examples_more.json");

           for (let key in examples_more) {
              if (examples_main[key])
                 examples_main[key].push(...examples_more[key]);
              else
                 examples_main[key] = examples_more[key];
           }
           break;
        case "-i":
        case "--ignore":
            process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;
            break;

        default:
           console.log('Usage: node test.js [options]');
           console.log('   -v | --verify : check stored content against current JSROOT version');
           console.log('   -c | --create : perform checks and overwrite when results differ');
           console.log('   -k | --key keyname : select specific key (class name) like TH1 or TProfile for testing');
           console.log('   -o | --opt id : select specific option id (number or name), only when key is specified');
           console.log('   -m | --more : use more tests');
           console.log('   -i | --ignore : ignore TLS checks');
           return;
      }
}

function ProduceGlobalStyleCopy() {
   // copy style when painter is loaded
   if (!init_style && jsroot.Painter) init_style = jsroot.gStyle;
}

function ProduceFile(content, extension, subid) {
   if (!entry_name) entry_name = keyid;

   entry_name = entry_name.replace(/ /g, '_')
                          .replace(/\+/g,'p').replace(/\>/g,'more')
                          .replace(/\</g,'less').replace(/\|/g,'I')
                          .replace(/\[/g,'L').replace(/\]/g,'J').replace(/\*/g,'star');

   let use_name = entry_name;
   if (subid)
      use_name += "_" + subid;

   if (extension != ".json")
      content = xml_formatter(content, {indentation: ' ', lineSeparator: '\n' });

   try {
      fs.accessSync(keyid, fs.constants.W_OK);
   } catch(err) {
      fs.mkdirSync(keyid);
   }

   let svgname = keyid + "/" + use_name + extension,
       svg0 = null, result = "MATCH";

   try {
     svg0 = fs.readFileSync(svgname, 'utf-8');
     if (svg0 != content) result = "DIFF";
   } catch(e) {
     svg0 = null;
     result = "NEW";
   }

//   // workaround to ignore alice variation, to let enable TGeo testings
// if ((result == "DIFF") && (keyid == "TGeo") && (entry_name == "alice") && (Math.abs(svg0.length - content.length) < 0.01*svg0.length)) {
//      console.log('!! Ignore alice variation for now !!');
//      content = svg0;
//      result = "MATCH";
//   }

   switch (result) {
      case "NEW": nnew++; break;
      case "DIFF": ndiff++; break;
      default: nmatch++;
   }

   let clen = content ? content.length : -1;
   console.log(keyid, use_name, 'result', result, 'len='+clen, (svg0 && result=='DIFF' ? 'rel0='+(clen/svg0.length*100).toFixed(1)+'\%' : ''));

   if (result === "DIFF") all_diffs.push(svgname);

   if ((result === "NEW") || ((test_mode === 'create') && (result!=='MATCH'))) {
      if (clen > 0)
         fs.writeFileSync(svgname, content);
      else if (result !== "NEW")
         fs.unlink(svgname);
   }

   if (subid === undefined) processNextOption();
}

function ProduceSVG(obj, opt) {

   // use only for object reading
   if ((theOnlyOptionId >= 0) && theOnlyOptionId !== optid)
      return processNextOption();

  if (entry.reset_funcs) obj.fFunctions = jsroot.create("TList");

   jsroot.makeSVG({ object: obj, option: opt, width: 1200, height: 800 })
         .then(svg => {
            ProduceFile(svg, ".svg");
            if (entry.reset_funcs) obj.fFunctions = jsroot.create("TList");
         });
}

function ProcessURL(url) {

   let hpainter;

   return jsroot.require('hierarchy').then(() => {

      hpainter = new jsroot.HierarchyPainter("testing", null);

      hpainter.setDisplay('batch');

      return hpainter.createDisplay();
   }).then(() => hpainter.startGUI(null, url)).then(() => {

      let disp = hpainter.getDisplay();
      if (disp.numFrames() == 0) {
         console.log(' Processing url: ', url);
         console.log('   !!! BATCH URL CREATES NO FRAME !!!', keyid, entry_name);
      }
      for (let n = 0; n < disp.numFrames(); ++n) {
         let json = disp.makeJSON(n, 1);
         if (json) ProduceFile(json, ".json", n);
         let svg = json ? "" : disp.makeSVG(n);
         if (svg) ProduceFile(svg, ".svg", n);
      }

      processNextOption();
   });
}

processNextOption = reset_mathjax => {

   if (!keyid) {
      if (all_diffs.length) console.log("ALL DIFFS", all_diffs);
      console.log('No more data to process');
      console.log("SUMMARY: match", nmatch, "diff", ndiff, "new", nnew);
      return;
   }

   // make timeout to avoid deep callstack
   let curr_time = new Date().getTime();
   if ((curr_time - last_time > 10000) && !reset_mathjax) {
      last_time = curr_time;
      return setTimeout(() => processNextOption(), 1);
   }

   let opts = examples_main[keyid];
   if (!opts) return;

   if (!reset_mathjax) {
      if ((itemid>=0) || (itemid==-2)) {
         if (itemid==-2) itemid = -1; // special workaround for style entry, which is marked as itemid=-2
         if (++itemid>=opts[optid].items.length) itemid = -1;
      }

      if (itemid < 0) { // first check that all items are processed
         if (theOnlyOptionId == optid) {
            keyid = null;
            return processNextOption();
         }
         if (++optid >= opts.length) {
            optid = -1;
            let found = false, next = null;
            for (let key in examples_main) {
               // if (key === "TGeo") continue; // skip already here
               if (found) { next = key; break; }
               if (key == keyid) found = true;
            }

            keyid = next;
            if (theonlykey) keyid = null;
            return processNextOption();
         }
      }
   }

   entry = opts[optid];

   if ((theOnlyOptionId >= 0) && !entry.file && !entry.json && !entry.url) {
      let rid = optid;
      while (--rid >= 0) {
         let sentry = opts[rid];
         if (sentry.file && sentry.item) {
            entry.file = sentry.file; entry.item = sentry.item; break;
         }
      }
   }

   entry_name = "";

   // exclude some entries from the test
   if (entry.notest) return processNextOption();

   if (((entry.latex === "mathjax") || entry.reset_mathjax) && !reset_mathjax)
      return jsroot.require('latex')
                   .then(ltx => ltx.loadMathjax())
                   .then(() => {
         MathJax.startup.defaultReady();
         console.log('Loading MathJax and doing extra reset!!!')
         processNextOption(true);
      });

   let filename = "", itemname = "", jsonname = "", url = "", opt = "", opt2 = "",
       filepath = "http://jsroot.gsi.de/files/";
//       filepath = "https://root.cern.ch/js/files/";

   if (entry.file) {
       filename = entry.file;
       if ((filename.indexOf("http:") < 0) &&
           (filename.indexOf("https:") < 0) &&
           (filename.indexOf("file:") < 0)) filename = filepath + filename;
   }
   if (entry.item)
      itemname = entry.item;

   if (entry.testopt !== undefined)
      opt = entry.testopt;
   else if (entry.opt)
      opt = entry.opt;

   if (entry.json) {
      jsonname = entry.json;
      if ((jsonname.indexOf("http:")<0) && (jsonname.indexOf("https:")<0)) jsonname = filepath + jsonname;
   }
   if (entry.items) {
      if (itemid < 0) {
         if ((itemid==-1) && entry.style) {
            itemid = -2;
            itemname = entry.style; // special case when style should be applied before objects drawing
         } else {
           itemid = 0;
         }
      }
      if (itemid >= 0) {
         itemname = entry.items[itemid];
         if (entry.opts && (itemid < entry.opts.length)) opt = entry.opts[itemid];
      }
   }

   if (entry.r3d) opt2 = (opt ? "," : "") + "r3d_" + entry.r3d;

   if (entry.url)
      url = entry.url.replace(/\$\$\$/g, filepath);
   else if (entry.asurl) {
      url = ((entry.asurl === "browser") ? "?" : "?nobrowser&");
      url += jsonname ? "json=" + jsonname : "file=" + filename + "&item=" + itemname;
      if (keyid === "TTree") {
         if ((opt.indexOf(">>") < 0) && (opt.indexOf("dump") < 0) && (opt.indexOf("testio") < 0))
            opt += ">>dump;num:10";
      }
      url += "&opt=" + opt + opt2;
   }

   // if ((opt=='inspect') || (opt=='count')) return processNextOption();

   if (itemid >= 0)
      entry_name = (entry.name || keyid) + "_" + itemname + (opt ? "_" + opt : "");
   else if ('name' in entry)
      entry_name = entry.name;
   else
      entry_name = opt ? opt : keyid;

   if (theOnlyOption) {
      if (entry_name != theOnlyOption) return processNextOption();
      console.log('Select option', entry);
   }

   ProduceGlobalStyleCopy();
   if (!entry.style && init_style) jsroot.gStyle = jsroot.extend({}, init_style);

   // ensure default options
   if (jsroot.Painter) jsroot.Painter.createRootColors(); // ensure default colors
   jsroot.settings.Latex = 2;
   if (entry.latex) jsroot.settings.Latex = jsroot.constants.Latex.fromString(entry.latex);
   // seedrandom('hello.', { global: true }); // set global random
   jsroot._.id_counter = 1; // used in some custom styles

   if (url.length > 0) {
      testfile = testobj = null;
      return ProcessURL(url);
   } else if (jsonname.length > 0) {
      testfile = testobj = null;
      jsroot.httpRequest(jsonname, 'object').then(obj => {
         testobj = obj;
         ProduceSVG(testobj, opt+opt2);
      });
   } else if (filename.length > 0) {
      jsroot.openFile(filename).then(file => {
         testfile = file;
         return testfile.readObject(itemname);
      }).then(obj => {
         if (itemid==-2) {
            // special handling of style
            // Check that copy of gStyle exists
            ProduceGlobalStyleCopy();
            // first create copy of existing style
            let newstyle = jsroot.extend({}, jsroot.gStyle);
            // then apply changes to the
            jsroot.gStyle = jsroot.extend(newstyle, obj);
            return processNextOption();
         } else {
            testobj = obj;
            ProduceSVG(testobj, opt+opt2);
         }
      });
   } else if (itemname.length > 0) {
      testfile.readObject(itemname).then(obj => {
         testobj = obj;
         ProduceSVG(testobj, opt+opt2);
      });
   } else {
      ProduceSVG(testobj, opt+opt2);
   }
}

// start processing

processNextOption();
<|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>🤖(break): 2017-7-6 01:32:02<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>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>🤖(break): 2017-7-6 08:06:52<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>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>🤖(break): 2017-12-4 01:52:59<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>"use strict";

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

const keys = ['--es6']
const [processPath, , marketId = null, marketSymbol = null] = process.argv.filter (x => !keys.includes (x))
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')

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

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, { market: marketId || 'all', symbol: marketSymbol || 'all' }, '\n')

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

let markets = {}
let proxies = [
    '',
    'https://crossorigin.me/',
    'https://cors-anywhere.herokuapp.com/',
    // 'http://cors-proxy.htmldriven.com/?url=',
]

ccxt.markets.forEach (id => {
    markets[id] = new (ccxt)[id] ({
        verbose: true,
    })
})

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

for (let id in config)
    for (let key in config[id])
        markets[id][key] = config[id][key]

markets['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 testMarketSymbolTicker = async (market, symbol) => {
    await sleep (market.rateLimit)
    let ticker = await market.fetchTicker (symbol)
    log (market.id.green, symbol, 'ticker', ticker,
        ticker['datetime'],
        'high: '    + ticker['high'],
        'low: '     + ticker['low'],
        'bid: '     + ticker['bid'],
        'ask: '     + ticker['ask'],
        'volume: '  + ticker['quoteVolume'])

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

    return ticker;
}

let testMarketSymbolOrderbook = async (market, symbol) => {
    await sleep (market.rateLimit)
    let orderbook = await market.fetchOrderBook (symbol)
    log (market.id.green, symbol, 'order book',
        orderbook['datetime'],
        'bid: '       + ((orderbook.bids.length > 0) ? orderbook.bids[0][0] : 'N/A'),
        'bidVolume: ' + ((orderbook.bids.length > 0) ? orderbook.bids[0][1] : 'N/A'),
        'ask: '       + ((orderbook.asks.length > 0) ? orderbook.asks[0][0] : 'N/A'),
        'askVolume: ' + ((orderbook.asks.length > 0) ? 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 (market.id, symbol, 'bids reversed')
        else if (bids[first][0] > bids[last][0])
            log (market.id, symbol, '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 (market.id, symbol, 'asks reversed', asks[first][0], asks[last][0])
        else if (asks[first][0] < asks[last][0])
            log (market.id, symbol, '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!')

    return orderbook
}

let testMarketSymbolTrades = async (market, symbol) => {
    let trades = await market.fetchTrades (symbol)
    log (market.id, symbol, 'trades', Object.values (trades).length)
    return trades
}

let testMarketSymbol = async (market, symbol) => {
    await sleep (market.rateLimit)
    await testMarketSymbolTicker (market, symbol)
    if (market.id == 'coinmarketcap') {
        log (await market.fetchTickers ());
        log (await market.fetchGlobal ());
    } else {
        await testMarketSymbolOrderbook (market, symbol)
        if ([ '_1broker', 'xbtce', 'btcexchange', 'anxpro' ].indexOf (market.id) < 0) {
            await testMarketSymbolTrades (market, symbol)
        }
    }
}

let testMarketBalance = async (market, symbol) => {
    await sleep (market.rateLimit)
    let balance = await market.fetchBalance ()
    log (market.id.green, 'balance', balance)
}

let loadMarket = async market => {
    let products  = await market.loadProducts ()
    log (market.id.green, market.symbols.length, 'symbols', market.symbols.join (', '))
}

let testMarket = async market => {

    let delay = market.rateLimit

    let keys = Object.keys (market.products)

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

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

    // let trades = await market.fetchTrades (Object.keys (market.products)[0])
    // console.log (market.id, trades)

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

    await testMarketBalance (market)

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

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

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

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

}

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

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

let tryAllProxies = async function (market, proxies) {

    let currentProxy = 0
    let maxRetries   = proxies.length

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

        try {

            market.proxy = proxies[currentProxy]

            if ([ 'coinspot' ].indexOf (market.id) < 0) {
                await loadMarket (market)
                await testMarket (market)
                break;
            }

        } catch (e) {

            currentProxy = ++currentProxy % proxies.length
            if (e instanceof ccxt.DDoSProtectionError || e.message.includes ('ECONNRESET')) {
                log.bright.yellow (market.id, '[DDoS Protection Error] ' + e.message)
            } else if (e instanceof ccxt.TimeoutError) {
                log.bright.yellow (market.id, '[Timeout Error] ' + e.message)
            } else if (e instanceof ccxt.AuthenticationError) {
                log.bright.yellow (market.id, '[Authentication Error] ' + e.message)
            } else if (e instanceof ccxt.MarketNotAvailableError) {
                log.bright.yellow (market.id, '[Market Not Available Error] ' + e.message)
            } else if (e instanceof ccxt.EndpointNotAvailableError) {
                log.bright.yellow (market.id, '[Endpoint Not Available Error] ' + e.message)
            } else {
                throw e;
            }
        }

    }
}

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

var test = async function () {

    // printExchangesTable ()

    if (marketId) {

        const market = markets[marketId]

        if (!market)
            throw new Error ('Market `' + marketId + '` not found')

        if (marketSymbol) {

            if (marketSymbol == 'balance')

                await testMarketBalance (market)

            else

                await testMarketSymbol (market, marketSymbol)

        } else {

            await tryAllProxies (market, proxies)
        }

    } else {

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

            log.bright.green ('MARKET:', id)

            const market = markets[id]

            await tryAllProxies (market, proxies)

        }
    }

} ()
<commit_msg>cmc off in test.js temporarily<commit_after>"use strict";

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

const keys = ['--es6']
const [processPath, , marketId = null, marketSymbol = null] = process.argv.filter (x => !keys.includes (x))
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')

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

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, { market: marketId || 'all', symbol: marketSymbol || 'all' }, '\n')

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

let markets = {}
let proxies = [
    '',
    'https://crossorigin.me/',
    'https://cors-anywhere.herokuapp.com/',
    // 'http://cors-proxy.htmldriven.com/?url=',
]

ccxt.markets.forEach (id => {
    markets[id] = new (ccxt)[id] ({
        verbose: true,
    })
})

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

for (let id in config)
    for (let key in config[id])
        markets[id][key] = config[id][key]

markets['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 testMarketSymbolTicker = async (market, symbol) => {
    await sleep (market.rateLimit)
    let ticker = await market.fetchTicker (symbol)
    log (market.id.green, symbol, 'ticker', ticker,
        ticker['datetime'],
        'high: '    + ticker['high'],
        'low: '     + ticker['low'],
        'bid: '     + ticker['bid'],
        'ask: '     + ticker['ask'],
        'volume: '  + ticker['quoteVolume'])

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

    return ticker;
}

let testMarketSymbolOrderbook = async (market, symbol) => {
    await sleep (market.rateLimit)
    let orderbook = await market.fetchOrderBook (symbol)
    log (market.id.green, symbol, 'order book',
        orderbook['datetime'],
        'bid: '       + ((orderbook.bids.length > 0) ? orderbook.bids[0][0] : 'N/A'),
        'bidVolume: ' + ((orderbook.bids.length > 0) ? orderbook.bids[0][1] : 'N/A'),
        'ask: '       + ((orderbook.asks.length > 0) ? orderbook.asks[0][0] : 'N/A'),
        'askVolume: ' + ((orderbook.asks.length > 0) ? 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 (market.id, symbol, 'bids reversed')
        else if (bids[first][0] > bids[last][0])
            log (market.id, symbol, '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 (market.id, symbol, 'asks reversed', asks[first][0], asks[last][0])
        else if (asks[first][0] < asks[last][0])
            log (market.id, symbol, '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!')

    return orderbook
}

let testMarketSymbolTrades = async (market, symbol) => {
    let trades = await market.fetchTrades (symbol)
    log (market.id, symbol, 'trades', Object.values (trades).length)
    return trades
}

let testMarketSymbol = async (market, symbol) => {
    await sleep (market.rateLimit)
    await testMarketSymbolTicker (market, symbol)
    if (market.id == 'coinmarketcap') {
        // log (await market.fetchTickers ());
        log (await market.fetchGlobal ());
    } else {
        await testMarketSymbolOrderbook (market, symbol)
        if ([ '_1broker', 'xbtce', 'btcexchange', 'anxpro' ].indexOf (market.id) < 0) {
            await testMarketSymbolTrades (market, symbol)
        }
    }
}

let testMarketBalance = async (market, symbol) => {
    await sleep (market.rateLimit)
    let balance = await market.fetchBalance ()
    log (market.id.green, 'balance', balance)
}

let loadMarket = async market => {
    let products  = await market.loadProducts ()
    log (market.id.green, market.symbols.length, 'symbols', market.symbols.join (', '))
}

let testMarket = async market => {

    let delay = market.rateLimit

    let keys = Object.keys (market.products)

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

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

    // let trades = await market.fetchTrades (Object.keys (market.products)[0])
    // console.log (market.id, trades)

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

    await testMarketBalance (market)

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

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

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

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

}

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

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

let tryAllProxies = async function (market, proxies) {

    let currentProxy = 0
    let maxRetries   = proxies.length

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

        try {

            market.proxy = proxies[currentProxy]

            if ([ 'coinspot' ].indexOf (market.id) < 0) {
                await loadMarket (market)
                await testMarket (market)
                break;
            }

        } catch (e) {

            currentProxy = ++currentProxy % proxies.length
            if (e instanceof ccxt.DDoSProtectionError || e.message.includes ('ECONNRESET')) {
                log.bright.yellow (market.id, '[DDoS Protection Error] ' + e.message)
            } else if (e instanceof ccxt.TimeoutError) {
                log.bright.yellow (market.id, '[Timeout Error] ' + e.message)
            } else if (e instanceof ccxt.AuthenticationError) {
                log.bright.yellow (market.id, '[Authentication Error] ' + e.message)
            } else if (e instanceof ccxt.MarketNotAvailableError) {
                log.bright.yellow (market.id, '[Market Not Available Error] ' + e.message)
            } else if (e instanceof ccxt.EndpointNotAvailableError) {
                log.bright.yellow (market.id, '[Endpoint Not Available Error] ' + e.message)
            } else {
                throw e;
            }
        }

    }
}

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

var test = async function () {

    // printExchangesTable ()

    if (marketId) {

        const market = markets[marketId]

        if (!market)
            throw new Error ('Market `' + marketId + '` not found')

        if (marketSymbol) {

            if (marketSymbol == 'balance')

                await testMarketBalance (market)

            else

                await testMarketSymbol (market, marketSymbol)

        } else {

            await tryAllProxies (market, proxies)
        }

    } else {

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

            log.bright.green ('MARKET:', id)

            const market = markets[id]

            await tryAllProxies (market, proxies)

        }
    }

} ()
<|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-6 08:50:55<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>import path from 'path';
import test from 'ava';
import readChunk from 'read-chunk';
import fileType from '.';

function check(ext, name) {
	const file = path.join(__dirname, 'fixture', `${(name || 'fixture')}.${ext}`);
	const fileInfo = fileType(readChunk.sync(file, 0, 4 + 4096)) || {};
	return fileInfo.ext;
}

const types = [
	'jpg',
	'png',
	'gif',
	'webp',
	'flif',
	'cr2',
	'tif',
	'bmp',
	'jxr',
	'psd',
	'zip',
	'tar',
	'rar',
	'gz',
	'bz2',
	'7z',
	'dmg',
	'mp4',
	'mid',
	'mkv',
	'webm',
	'mov',
	'avi',
	'wmv',
	'mpg',
	'mp2',
	'mp3',
	'm4a',
	'oga',
	'ogg',
	'ogv',
	'opus',
	'flac',
	'wav',
	'spx',
	'amr',
	'pdf',
	'epub',
	'exe',
	'swf',
	'rtf',
	'wasm',
	'woff',
	'woff2',
	'eot',
	'ttf',
	'otf',
	'ico',
	'flv',
	'ps',
	'xz',
	'sqlite',
	'nes',
	'crx',
	'xpi',
	'cab',
	'deb',
	'ar',
	'rpm',
	'Z',
	'lz',
	'msi',
	'mxf',
	'mts',
	'blend',
	'bpg',
	'docx',
	'pptx',
	'xlsx',
	'3gp',
	'jp2',
	'jpm',
	'jpx',
	'mj2',
	'aif',
	'qcp',
	'odt',
	'ods',
	'odp',
	'xml',
	'mobi',
	'heic',
	'cur',
	'ktx'
];

const names = {
	'3gp': ['fixture', 'fixture2'],
	woff2: ['fixture', 'fixture-otto'],
	woff: ['fixture', 'fixture-otto'],
	eot: ['fixture', 'fixture-0x20001'],
	mov: ['fixture', 'fixture-mjpeg'],
	mp2: ['fixture', 'fixture-mpa', 'fixture-faac-adts'],
	mp3: ['fixture', 'fixture-offset1-id3', 'fixture-offset1', 'fixture-mp2l3', 'fixture-ffe3'],
	mp4: ['fixture-imovie', 'fixture-isom', 'fixture-isomv2', 'fixture-mp4v2',
		'fixture-m4v', 'fixture-dash', 'fixture-aac-adts'],
	tif: ['fixture-big-endian', 'fixture-little-endian'],
	gz: ['fixture.tar'],
	xz: ['fixture.tar'],
	lz: ['fixture.tar'],
	Z: ['fixture.tar'],
	mkv: ['fixture', 'fixture2'],
	mxf: ['fixture'],
	mpg: ['fixture', 'fixture2'],
	heic: ['fixture-mif1', 'fixture-msf1', 'fixture-heic'],
	ape: ['fixture-monkeysaudio']
};

function testFile(t, type, name) {
	t.is(check(type, name), type);
}

for (const type of types) {
	if (Object.prototype.hasOwnProperty.call(names, type)) {
		for (const name of names[type]) {
			test(type, testFile, type, name);
		}
	} else {
		test(type, testFile, type);
	}
}
<commit_msg>Activate Monkey's Audio unit test (#154)<commit_after>import path from 'path';
import test from 'ava';
import readChunk from 'read-chunk';
import fileType from '.';

function check(ext, name) {
	const file = path.join(__dirname, 'fixture', `${(name || 'fixture')}.${ext}`);
	const fileInfo = fileType(readChunk.sync(file, 0, 4 + 4096)) || {};
	return fileInfo.ext;
}

const types = [
	'jpg',
	'png',
	'gif',
	'webp',
	'flif',
	'cr2',
	'tif',
	'bmp',
	'jxr',
	'psd',
	'zip',
	'tar',
	'rar',
	'gz',
	'bz2',
	'7z',
	'dmg',
	'mp4',
	'mid',
	'mkv',
	'webm',
	'mov',
	'avi',
	'wmv',
	'mpg',
	'mp2',
	'mp3',
	'm4a',
	'oga',
	'ogg',
	'ogv',
	'opus',
	'flac',
	'wav',
	'spx',
	'amr',
	'pdf',
	'epub',
	'exe',
	'swf',
	'rtf',
	'wasm',
	'woff',
	'woff2',
	'eot',
	'ttf',
	'otf',
	'ico',
	'flv',
	'ps',
	'xz',
	'sqlite',
	'nes',
	'crx',
	'xpi',
	'cab',
	'deb',
	'ar',
	'rpm',
	'Z',
	'lz',
	'msi',
	'mxf',
	'mts',
	'blend',
	'bpg',
	'docx',
	'pptx',
	'xlsx',
	'3gp',
	'jp2',
	'jpm',
	'jpx',
	'mj2',
	'aif',
	'qcp',
	'odt',
	'ods',
	'odp',
	'xml',
	'mobi',
	'heic',
	'cur',
	'ktx',
	'ape'
];

const names = {
	'3gp': ['fixture', 'fixture2'],
	woff2: ['fixture', 'fixture-otto'],
	woff: ['fixture', 'fixture-otto'],
	eot: ['fixture', 'fixture-0x20001'],
	mov: ['fixture', 'fixture-mjpeg'],
	mp2: ['fixture', 'fixture-mpa', 'fixture-faac-adts'],
	mp3: ['fixture', 'fixture-offset1-id3', 'fixture-offset1', 'fixture-mp2l3', 'fixture-ffe3'],
	mp4: ['fixture-imovie', 'fixture-isom', 'fixture-isomv2', 'fixture-mp4v2',
		'fixture-m4v', 'fixture-dash', 'fixture-aac-adts'],
	tif: ['fixture-big-endian', 'fixture-little-endian'],
	gz: ['fixture.tar'],
	xz: ['fixture.tar'],
	lz: ['fixture.tar'],
	Z: ['fixture.tar'],
	mkv: ['fixture', 'fixture2'],
	mxf: ['fixture'],
	mpg: ['fixture', 'fixture2'],
	heic: ['fixture-mif1', 'fixture-msf1', 'fixture-heic'],
	ape: ['fixture-monkeysaudio']
};

function testFile(t, type, name) {
	t.is(check(type, name), type);
}

for (const type of types) {
	if (Object.prototype.hasOwnProperty.call(names, type)) {
		for (const name of names[type]) {
			test(type, testFile, type, name);
		}
	} else {
		test(type, testFile, type);
	}
}
<|endoftext|>