<commit_before>/* eslint-disable no-console */
import configuration from './configuration'

const logger = {
  debug(...args) {
    if (['debug'].includes(configuration.logLevel)) {
      console.debug(...args)
    }
  },
  log(...args) {
    if (['debug', 'log'].includes(configuration.logLevel)) {
      console.log(...args)
    }
  },
  warn(...args) {
    if (['debug', 'log', 'warn'].includes(configuration.logLevel)) {
      console.warn(...args)
    }
  },
  error(...args) {
    if (['debug', 'log', 'warn', 'error'].includes(configuration.logLevel)) {
      console.error(...args)
    }
  },
}

export default logger
<commit_msg>Make IE11 consumers life (a little bit) easier<commit_after>/* eslint-disable no-console */
import configuration from './configuration'

const logger = {
  debug(...args) {
    if (['debug'].indexOf(configuration.logLevel) !== -1) {
      console.debug(...args)
    }
  },
  log(...args) {
    if (['debug', 'log'].indexOf(configuration.logLevel) !== -1) {
      console.log(...args)
    }
  },
  warn(...args) {
    if (['debug', 'log', 'warn'].indexOf(configuration.logLevel) !== -1) {
      console.warn(...args)
    }
  },
  error(...args) {
    if (['debug', 'log', 'warn', 'error'].indexOf(configuration.logLevel) !== -1) {
      console.error(...args)
    }
  },
}

export default logger
<|endoftext|>


<commit_before>
var _slider = createElement(div);
var getGenerator = function (container, tagName = 'item') {
    if (!container) return;
    if (!container.childNodes.length && container.$generator) return container.$generator;
    var template = document.createElement(tagName);
    var templates = [].concat.apply([], container.childNodes).filter(a => {
        if (a.hasAttribute('insert')) {
            return false;
        }
        return true;
    });
    if (templates.length < container.childNodes.length && templates.length >= 1) {
        var c = document.createComment('lattice');
        c.index = null;
        container.insertBefore(c, templates[0]);
        templates.splice(1, templates.length - 1);
        var paddingCount = [].indexOf.call(container.childNodes, c);
        container.paddingCount = paddingCount;
    }
    appendChild(template, templates);
    container.insertBefore = _slider.insertBefore;
    container.appendChild = _slider.appendChild;
    var scopes = container.$parentScopes || [];
    if (container.$scope) scopes = scopes.concat(container.$scope);
    return container.$generator = function (index, com, element) {
        if (!com) {
            if (!container.src || index >= container.src.length) return;
            com = container.src[index];
        }
        if (!com) return;
        if (!element) {
            var template1 = template.cloneNode(true);
            if (!template1.childNodes.length) {
                element = template1;
            }
            else {
                element = template1.childNodes[1];
                if (template1.childNodes.length > 1) element.with = [].concat.apply([], template1.childNodes).slice(1);
            }
        }
        var parsedSrc = container.$src;
        if (parsedSrc) {
            var { keyName, itemName, indexName } = parsedSrc;
            var newScope = {
                [keyName || '$key']: index,
                [itemName || '$item']: com,
                [indexName || '$index']: index
            };
            var newItem = render(element, newScope, scopes);
            if (element.with) newItem.with = render(element.with, newScope, scopes);
        } else {
            var newScope = container.src[index];
            if (!isObject(newScope)) newScope = {
                get $item() {
                    return container.src[this.$index];
                },
                set $item(v) {
                    container.src[this.$index] = v;
                    this.value = v;
                },
                $key: index,
                $index: index,
                toString() {
                    return this.$item;
                },
                valueOf() {
                    return this.$item;
                }
            }
            var newItem = render(element, newScope, scopes);
            if (element.with) newItem.with = render(newItem.with = element.with, newScope, scopes);
        }
        return newItem;
    };
};
<commit_msg>修复一些问题<commit_after>
var _slider = createElement(div);
var getGenerator = function (container, tagName = 'item') {
    if (!container) return;
    if (!container.childNodes.length && container.$generator) return container.$generator;
    var template = document.createElement(tagName);
    var templates = [].concat.apply([], container.childNodes).filter(a => {
        if (a.hasAttribute('insert')) {
            return false;
        }
        return true;
    });
    if (templates.length < container.childNodes.length && templates.length >= 1) {
        var c = document.createComment('lattice');
        c.index = null;
        container.insertBefore(c, templates[0]);
        templates.splice(1, templates.length - 1);
        var paddingCount = [].indexOf.call(container.childNodes, c);
        container.paddingCount = paddingCount;
    }
    appendChild(template, templates);
    container.insertBefore = _slider.insertBefore;
    container.appendChild = _slider.appendChild;
    var scopes = container.$parentScopes || [];
    if (container.$scope) scopes = scopes.concat(container.$scope);
    return container.$generator = function (index, com, element) {
        if (!com) {
            if (!container.src || index >= container.src.length) return;
            com = container.src[index];
        }
        if (!com) return;
        if (!element) {
            var template1 = template.cloneNode(true);
            if (!template1.childNodes.length) {
                element = template1;
            }
            else {
                element = template1.childNodes[0];
                if (template1.childNodes.length > 1) element.with = [].concat.apply([], template1.childNodes).slice(1);
            }
        }
        var parsedSrc = container.$src;
        if (parsedSrc) {
            var { keyName, itemName, indexName } = parsedSrc;
            var newScope = {
                [keyName || '$key']: index,
                [itemName || '$item']: com,
                [indexName || '$index']: index
            };
            var newItem = render(element, newScope, scopes);
            if (element.with) newItem.with = render(element.with, newScope, scopes);
        } else {
            var newScope = container.src[index];
            if (!isObject(newScope)) newScope = {
                get $item() {
                    return container.src[this.$index];
                },
                set $item(v) {
                    container.src[this.$index] = v;
                    this.value = v;
                },
                $key: index,
                $index: index,
                toString() {
                    return this.$item;
                },
                valueOf() {
                    return this.$item;
                }
            }
            var newItem = render(element, newScope, scopes);
            if (element.with) newItem.with = render(newItem.with = element.with, newScope, scopes);
        }
        return newItem;
    };
};
<|endoftext|>


<commit_before>function _concat(arr1, arr2) {
	/**
	 * https://jsperf.com/array-prototype-push-apply-vs-concat/20
	 */
	let i = arr2.length;
	if (i <= 0) {
		return;
	}

	while (--i) {
		arr1.push(arr2[i]);
	}

	arr1.push(arr2[i]);
}

module.exports = _concat;
<commit_msg>fix: dash concat<commit_after>function _concat(arr1, arr2) {
	/**
	 * https://jsperf.com/array-prototype-push-apply-vs-concat/20
	 */
	const len = arr2.length;

	for (let i = 0; i < len; ++i) {
		arr1.push(arr2[i]);
	}
}

module.exports = _concat;
<|endoftext|>


<commit_before>'use strict';

angular.module('myApp')
    .config(routeConfig);

routeConfig.$inject = ['$stateProvider', '$urlRouterProvider'];

function routeConfig($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/');

    $stateProvider
        .state('map', {
            url: '/',
            templateUrl: '/public/app/map/map.html',
            controller: 'mapCtrl',
        })
        .state('profile', {
            url: '/profile/{id}',
            templateUrl: '/public/app/profile/profile.html',
            controller: 'userProfileCtrl',
            controllerAs: 'vm'
        })
        .state('types_all', {
            url: '/types',
            templateUrl: '/public/app/type/view-types.html',
            controller: 'viewTypesCtrl',
            controllerAs: 'vm'
        })
        .state('types_new', {
            url: '/types/add',
            templateUrl: '/public/app/type/add-type.html',
            controller: 'addTypeCtrl',
            controllerAs: 'vm'
        })
        .state('types_one', {
            url: '/types/:id',
            templateUrl: '/public/app/type/edit-type.html',
            controller: 'editTypeCtrl',
            controllerAs: 'vm'
        })
        .state('places_all', {
            url: '/places',
            templateUrl: '/public/app/place/view-places.html',
            controller: 'viewPlacesCtrl',
            controllerAs: 'vm'
        })
        .state('places_new', {
            url: '/places/add',
            templateUrl: '/public/app/place/add-place.html',
            controller: 'addPlaceCtrl',
            controllerAs: 'vm'
        })
        .state('places_one', {
            url: '/places/:id',
            templateUrl: '/public/app/place/edit-place.html',
            controller: 'editPlaceCtrl',
            controllerAs: 'vm'
        })
}
<commit_msg>Add vm<commit_after>'use strict';

angular.module('myApp')
    .config(routeConfig);

routeConfig.$inject = ['$stateProvider', '$urlRouterProvider'];

function routeConfig($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/');

    $stateProvider
        .state('map', {
            url: '/',
            templateUrl: '/public/app/map/map.html',
            controller: 'mapCtrl',
            controllerAs: 'vm'
        })
        .state('profile', {
            url: '/profile/{id}',
            templateUrl: '/public/app/profile/profile.html',
            controller: 'userProfileCtrl',
            controllerAs: 'vm'
        })
        .state('types_all', {
            url: '/types',
            templateUrl: '/public/app/type/view-types.html',
            controller: 'viewTypesCtrl',
            controllerAs: 'vm'
        })
        .state('types_new', {
            url: '/types/add',
            templateUrl: '/public/app/type/add-type.html',
            controller: 'addTypeCtrl',
            controllerAs: 'vm'
        })
        .state('types_one', {
            url: '/types/:id',
            templateUrl: '/public/app/type/edit-type.html',
            controller: 'editTypeCtrl',
            controllerAs: 'vm'
        })
        .state('places_all', {
            url: '/places',
            templateUrl: '/public/app/place/view-places.html',
            controller: 'viewPlacesCtrl',
            controllerAs: 'vm'
        })
        .state('places_new', {
            url: '/places/add',
            templateUrl: '/public/app/place/add-place.html',
            controller: 'addPlaceCtrl',
            controllerAs: 'vm'
        })
        .state('places_one', {
            url: '/places/:id',
            templateUrl: '/public/app/place/edit-place.html',
            controller: 'editPlaceCtrl',
            controllerAs: 'vm'
        })
}
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var tape = require( 'tape' );
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var NINF = require( '@stdlib/math/constants/float64-ninf' );
var PINF = require( '@stdlib/math/constants/float64-pinf' );
var logpdf = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof logpdf, 'function', 'main export is a function' );
	t.end();
});

tape( 'if provided `NaN` for any parameter, the function returns `NaN`', function test( t ) {
	var y;

	y = logpdf( NaN, 0.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	y = logpdf( 0.0, NaN );
	t.equal( isnan( y ), true, 'returns NaN' );

	t.end();
});

tape( 'the function returns `+Infinity` if provided `x` equal to `mu`', function test( t ) {
	var y;

	y = logpdf( 2.0, 2.0 );
	t.equal( y, PINF, 'returns +Infinity' );

	y = logpdf( 0.0, 0.0 );
	t.equal( y, PINF, 'returns +Infinity' );

	y = logpdf( -3.0, -3.0 );
	t.equal( y, PINF, 'returns +Infinity' );

	t.end();
});

tape( 'the function returns `-Infinity` if provided `x` not equal to `mu`', function test( t ) {
	var y;

	y = logpdf( 2.0, 3.0 );
	t.equal( y, NINF, 'returns -Infinity' );

	y = logpdf( 4.0, 3.0 );
	t.equal( y, NINF, 'returns -Infinity' );

	t.end();
});
<commit_msg>Add test case<commit_after>'use strict';

// MODULES //

var tape = require( 'tape' );
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var NINF = require( '@stdlib/math/constants/float64-ninf' );
var PINF = require( '@stdlib/math/constants/float64-pinf' );
var logpdf = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof logpdf, 'function', 'main export is a function' );
	t.end();
});

tape( 'if provided `NaN` for any parameter, the function returns `NaN`', function test( t ) {
	var y;

	y = logpdf( NaN, 0.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	y = logpdf( 0.0, NaN );
	t.equal( isnan( y ), true, 'returns NaN' );

	y = logpdf( NaN, NaN );
	t.equal( isnan( y ), true, 'returns NaN' );

	t.end();
});

tape( 'the function returns `+Infinity` if provided `x` equal to `mu`', function test( t ) {
	var y;

	y = logpdf( 2.0, 2.0 );
	t.equal( y, PINF, 'returns +Infinity' );

	y = logpdf( 0.0, 0.0 );
	t.equal( y, PINF, 'returns +Infinity' );

	y = logpdf( -3.0, -3.0 );
	t.equal( y, PINF, 'returns +Infinity' );

	t.end();
});

tape( 'the function returns `-Infinity` if provided `x` not equal to `mu`', function test( t ) {
	var y;

	y = logpdf( 2.0, 3.0 );
	t.equal( y, NINF, 'returns -Infinity' );

	y = logpdf( 4.0, 3.0 );
	t.equal( y, NINF, 'returns -Infinity' );

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


<commit_before>Ext.define('Ext.grid.plugin.RowEditingCustom', {
    extend: 'Ext.grid.plugin.RowEditing',
    alias: 'plugin.roweditingCustom',

    hiddenButtons: true,

    initEditorConfig: function () {
        var me = this,
            grid = me.grid,
            view = me.view,
            headerCt = grid.headerCt,
            btns = ['saveBtnText', 'cancelBtnText', 'errorsText', 'dirtyText'],
            b,

            bLen = btns.length,
            cfg = {
                autoCancel: me.autoCancel,
                autoUpdate: me.autoUpdate,
                removeUnmodified: me.removeUnmodified,
                errorSummary: me.errorSummary,
                formAriaLabel: me.formAriaLabel,
                formAriaLabelRowBase: me.formAriaLabelRowBase + (grid.hideHeaders ? -1 : 0),
                fields: headerCt.getGridColumns(),
                hidden: true,
                view: view,
                updateButton: function (valid) { },
                // keep a reference..
                editingPlugin: me
            },
            item;

        /*
            Custom configuration.
        */
        if (me.hiddenButtons) {
            cfg.getFloatingButtons = function () {
                var me = this,
                    btns = me.floatingButtons;

                if (!btns && !me.destroying && !me.destroyed) {
                    me.floatingButtons = btns = Ext.create('Ext.container.Container', {
                        hidden: true,
                        setButtonPosition: function () { },
                    });
                }

                return btns;
            };
        } else {
            for (b = 0; b < bLen; b++) {
                item = btns[b];

                if (Ext.isDefined(me[item])) {
                    cfg[item] = me[item];
                }
            }
        }

        return cfg;
    }
});<commit_msg>Adding action buttons on editable grid<commit_after>Ext.define('Ext.grid.plugin.RowEditingCustom', {
    extend: 'Ext.grid.plugin.RowEditing',
    alias: 'plugin.roweditingCustom',

    /**
     * Property
     * It hides the default action buttons
     * default: true
     */
    hiddenButtons: true,

    /**
     * Property:
     * It adds a button in a extra action column into grid.
     *
     * Accepts: boolean (true show | false hide)| button object (not implemented yet)
     * Default: true
     */
    saveButton: true,

    /**
     * Property:
     * It adds a button in a extra action column into grid.
     *
     * Accepts: boolean (true show | false hide)| button object (not implemented yet)
     * Default: true
     */
    cancelButton: true,

    /**
     * Hides a column on edit
     *
     * Accepts: string (itemId)
     * default: null
     */
    columnHiddenOnEdit: null,

    /**
     * Sets extra buttons on action column
     *
     * Accepts: list of objects
     * default: empty list
     */
    extraButtons: [],

    /**
     * Configure everything
     */
    initEditorConfig: function () {

        /*
         *  Adds the extra action column
         */
        this.addExtraColumn();

        var me = this,
            grid = me.grid,
            view = me.view,
            headerCt = grid.headerCt,
            btns = ['saveBtnText', 'cancelBtnText', 'errorsText', 'dirtyText'],
            b,

            bLen = btns.length,
            cfg = {
                autoCancel: me.autoCancel,
                autoUpdate: me.autoUpdate,
                removeUnmodified: me.removeUnmodified,
                errorSummary: me.errorSummary,
                formAriaLabel: me.formAriaLabel,
                formAriaLabelRowBase: me.formAriaLabelRowBase + (grid.hideHeaders ? -1 : 0),
                fields: headerCt.getGridColumns(),
                hidden: true,
                view: view,
                updateButton: function (valid) { },
                // keep a reference..
                editingPlugin: me
            },
            item;

        /*
         *  Custom configuration.
         */
        if (me.hiddenButtons) {
            cfg.getFloatingButtons = function () {
                var me = this,
                    btns = me.floatingButtons;

                if (!btns && !me.destroying && !me.destroyed) {
                    me.floatingButtons = btns = Ext.create('Ext.container.Container', {
                        hidden: true,
                        setButtonPosition: function () { },
                    });
                }

                return btns;
            };
        } else {
            for (b = 0; b < bLen; b++) {
                item = btns[b];

                if (Ext.isDefined(me[item])) {
                    cfg[item] = me[item];
                }
            }
        }

        return cfg;
    },

    listeners: {
        beforeedit: function (grid, e, eOpts) {
            return e.column.xtype !== 'actioncolumn';
        }
    },

    /**
     * Add the extra action column
     */
    addExtraColumn() {
        var me = this,
            grid = me.grid;

        if (me.cancelButton) {

            if (me.cancelButton === true) {
                me.cancelButton = {
                    iconCls: 'x-fa fa-times',
                    xtype: 'button',
                    editor: true,
                    tooltip: 'Cancel',
                    handler: function (grid, rowIndex, colIndex) {
                        alert('todo!!!');
                    }
                };
            }

            me.extraButtons.push(me.cancelButton);
        }

        if (me.saveButton) {

            if (me.saveButton === true) {
                me.saveButton = {
                    iconCls: 'x-fa fa-check',
                    xtype: 'button',
                    tooltip: 'Save the edited line',
                    handler: function (grid, rowIndex, colIndex) {
                        alert('todo!!!');
                    }
                };
            }

            me.extraButtons.push(me.saveButton);
        }

        if (me.extraButtons) {
            for (index in me.extraButtons) {
                grid.headerCt.insert(grid.columns.length, {
                    xtype: 'actioncolumn',
                    width: 30,
                    align: 'center',
                    editor: me.extraButtons[index],
                    menuDisabled: true,
                    sortable: false,
                    border: false,
                    resizable: false,
                    hideable: false,
                    menuDisabled: true
                });
            }
        }
    }
});<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'

const sizeMap = {
  small: 16,
  medium: 32,
  large: 64
}

const alignMap = {
  top: 'text-top',
  middle: 'middle'
}

const defaultSize = [16, 16]

export default function Octicon(props) {
  const {
    ariaLabel,
    children,
    className = 'octicon',
    icon: Icon,
    size,
    verticalAlign
  } = props

  const child = (typeof Icon === 'function')
    ? <Icon />
    : React.Children.only(children)

  const [width, height] = child.type.size || defaultSize
  const attrs = {
    ariaLabel,
    className,
    height: height,
    role: 'img',
    viewBox: [0, 0, width, height].join(' ')
  }

  if (size in sizeMap) {
    attrs.height = sizeMap[size]
  }

  attrs.width = attrs.height * width / height

  const alignment = alignMap[verticalAlign] || 'text-bottom'

  attrs.style = {
    display: 'inline-block',
    fill: 'currentColor',
    verticalAlign: alignment
  }

  return <svg {...attrs}>{child}</svg>
}

Octicon.propTypes = {
  ariaLabel: PropTypes.string,
  children: PropTypes.element,
  icon: PropTypes.func,
  size: PropTypes.oneOf(Object.keys(sizeMap)),
  verticalAlign: PropTypes.oneOf([
    'middle', 'text-bottom', 'text-top', 'top'
  ])
}

// this exports all of the icon classes as named exports, which can be
// tree-shaken by tools such as webpack, rollup, etc.
export * from './icons'
<commit_msg>linty<commit_after>import React from 'react'
import PropTypes from 'prop-types'

const sizeMap = {
  small: 16,
  medium: 32,
  large: 64
}

const alignMap = {
  top: 'text-top',
  middle: 'middle'
}

const defaultSize = [16, 16]

export default function Octicon(props) {
  const {
    ariaLabel,
    children,
    className = 'octicon',
    icon: Icon,
    size,
    verticalAlign
  } = props

  const child = (typeof Icon === 'function')
    ? <Icon />
    : React.Children.only(children)

  const [width, height] = child.type.size || defaultSize
  const attrs = {
    ariaLabel,
    className,
    height,
    role: 'img',
    viewBox: [0, 0, width, height].join(' ')
  }

  if (size in sizeMap) {
    attrs.height = sizeMap[size]
  }

  attrs.width = attrs.height * width / height

  const alignment = alignMap[verticalAlign] || 'text-bottom'

  attrs.style = {
    display: 'inline-block',
    fill: 'currentColor',
    verticalAlign: alignment
  }

  return <svg {...attrs}>{child}</svg>
}

Octicon.propTypes = {
  ariaLabel: PropTypes.string,
  children: PropTypes.element,
  icon: PropTypes.func,
  size: PropTypes.oneOf(Object.keys(sizeMap)),
  verticalAlign: PropTypes.oneOf([
    'middle', 'text-bottom', 'text-top', 'top'
  ])
}

// this exports all of the icon classes as named exports, which can be
// tree-shaken by tools such as webpack, rollup, etc.
export * from './icons'
<|endoftext|>


<commit_before>"use strict";
const logCleaner = require("./log-cleaner");
const util = require("util");
const process = require("process");
const incomingMessage = require("http").IncomingMessage;

function isString(value) {
  return value && value.toLowerCase;
}

function serialize(results, args) {
  if (!args) {
    return results;
  }
  if (Array.isArray(args)) {
    args.forEach(function (a) {
      serialize(results, a);
    });
    return results;
  }
  if (args.stack) {
    results.push(args.stack.split("\n"));
  } else if (args instanceof incomingMessage) {
    results.push(util.inspect(args.headers, {showHidden: true, depth: 4}) + "\n");
    results.push(util.inspect(args.body, {showHidden: true, depth: 4}) + "\n");
  } else if (Object.keys(args).length > 0) {
    results.push(util.inspect(args, {showHidden: true, depth: 4}) + "\n");
  } else {
    results.push(util.inspect(args) + "\n");
  }
}

function buildMessage(level, msg, args, options) {
  let _msg = msg,
    _args = args;

  if (!isString(msg) && isString(args)) {
    _args = msg;
    _msg = args;
  }

  if (!isString(msg) && !isString(args)) {
    _args = [msg, args];
    _msg = "";
  }

  if (!Array.isArray(_args)) {
    _args = [_args];
  }

  _args = logCleaner.cleanArgs(_args);

  let serialized = serialize([], _args),
    tokens = {
    date: new Date().toISOString(),
    level: level,
    message: logCleaner.cleanUrlRawParameters(_msg),
    serverId: options && options.serverId ? `${options.serverId}#${process.pid}` : "",
    traceId: options && options.traceId ? options.traceId : "",
    data: serialized.length > 0 ?  serialized : ""
  };
  return tokens;
}

class Logger {
  constructor(options) {
    this.options = options;
    this.loggers = [];
    this.level = options && options.level ? options.level : "debug";
    this.levels = {debug: 0, info: 1, error: 2, fatal: 3};
  }

  // For parity with the Stream interface (stream.write)
  write(...args) {
    this.loggers.forEach((logger) => {
      // Delegate the call to the concrete logger classes
      logger.write(...args);
    });
  }

  _log(msg) {
    this.loggers.forEach((logger) => {
      logger.log(msg);
    });
  }

  setLevel(minLevel) {
    this.level = minLevel;
  }

  getLevel() {
    return this.level;
  }

  getLoggers() {
    return this.loggers;
  }

  addLogger(logger) {
    if (logger.error && logger.error.apply) {
      this.loggers.push(logger);
    } else {
      let loggerOptions = this.options.loggers[logger];
      this.loggers.push(require("./providers/" + loggerOptions.provider).create(loggerOptions.options));
    }
  }

  clearLoggers() {
    this.loggers = [];
  }

  // Level ? :-)
  log(level, msg, args) {
    if (this.levels[this.getLevel()] <= this.levels[level]) {
      this._log(buildMessage(level, msg, args, this.options));
    }
  }

  // Level 0
  debug(msg, args) {
    if (this.levels[this.getLevel()] <= 0) {
      this._log(buildMessage("debug", msg, args, this.options));
    }
  }

  // Level 1
  info(msg, args) {
    if (this.levels[this.getLevel()] <= 1) {
      this._log(buildMessage("info", msg, args, this.options));
    }
  }

  // Level 2
  error(msg, args) {
    if (this.levels[this.getLevel()] <= 2) {
      this._log(buildMessage("error", msg, args, this.options));
    }
  }

  // Level 3
  fatal(msg, args) {
    if (this.levels[this.getLevel()] <= 3) {
      this._log(buildMessage("fatal", msg, args, this.options));
    }
  }
}

module.exports = {Logger};
<commit_msg>[HG] expose native log levels as constants<commit_after>"use strict";
const logCleaner = require("./log-cleaner");
const util = require("util");
const process = require("process");
const incomingMessage = require("http").IncomingMessage;

function isString(value) {
  return value && value.toLowerCase;
}

function serialize(results, args) {
  if (!args) {
    return results;
  }
  if (Array.isArray(args)) {
    args.forEach(function (a) {
      serialize(results, a);
    });
    return results;
  }
  if (args.stack) {
    results.push(args.stack.split("\n"));
  } else if (args instanceof incomingMessage) {
    results.push(util.inspect(args.headers, {showHidden: true, depth: 4}) + "\n");
    results.push(util.inspect(args.body, {showHidden: true, depth: 4}) + "\n");
  } else if (Object.keys(args).length > 0) {
    results.push(util.inspect(args, {showHidden: true, depth: 4}) + "\n");
  } else {
    results.push(util.inspect(args) + "\n");
  }
}

function buildMessage(level, msg, args, options) {
  let _msg = msg,
    _args = args;

  if (!isString(msg) && isString(args)) {
    _args = msg;
    _msg = args;
  }

  if (!isString(msg) && !isString(args)) {
    _args = [msg, args];
    _msg = "";
  }

  if (!Array.isArray(_args)) {
    _args = [_args];
  }

  _args = logCleaner.cleanArgs(_args);

  let serialized = serialize([], _args),
    tokens = {
    date: new Date().toISOString(),
    level: level,
    message: logCleaner.cleanUrlRawParameters(_msg),
    serverId: options && options.serverId ? `${options.serverId}#${process.pid}` : "",
    traceId: options && options.traceId ? options.traceId : "",
    data: serialized.length > 0 ?  serialized : ""
  };
  return tokens;
}

class Logger {
  static LogLevel() {
    return {
      DEBUG: "debug",
      INFO: "info",
      ERROR: "error",
      FATAL: "fatal"
    }
  }
  constructor(options) {
    this.options = options;
    this.loggers = [];
    this.level = options && options.level ? options.level : "debug";
    this.levels = {debug: 0, info: 1, error: 2, fatal: 3};
  }

  // For parity with the Stream interface (stream.write)
  write(...args) {
    this.loggers.forEach((logger) => {
      // Delegate the call to the concrete logger classes
      logger.write(...args);
    });
  }

  _log(msg) {
    this.loggers.forEach((logger) => {
      logger.log(msg);
    });
  }

  setLevel(minLevel) {
    this.level = minLevel;
  }

  getLevel() {
    return this.level;
  }

  getLoggers() {
    return this.loggers;
  }

  addLogger(logger) {
    if (logger.error && logger.error.apply) {
      this.loggers.push(logger);
    } else {
      let loggerOptions = this.options.loggers[logger];
      this.loggers.push(require("./providers/" + loggerOptions.provider).create(loggerOptions.options));
    }
  }

  clearLoggers() {
    this.loggers = [];
  }

  // Level ? :-)
  log(level, msg, args) {
    if (this.levels[this.getLevel()] <= this.levels[level]) {
      this._log(buildMessage(level, msg, args, this.options));
    }
  }

  // Level 0
  debug(msg, args) {
    if (this.levels[this.getLevel()] <= 0) {
      this._log(buildMessage("debug", msg, args, this.options));
    }
  }

  // Level 1
  info(msg, args) {
    if (this.levels[this.getLevel()] <= 1) {
      this._log(buildMessage("info", msg, args, this.options));
    }
  }

  // Level 2
  error(msg, args) {
    if (this.levels[this.getLevel()] <= 2) {
      this._log(buildMessage("error", msg, args, this.options));
    }
  }

  // Level 3
  fatal(msg, args) {
    if (this.levels[this.getLevel()] <= 3) {
      this._log(buildMessage("fatal", msg, args, this.options));
    }
  }
}

module.exports = {Logger};
<|endoftext|>


<commit_before>var Function, atomCompileLess, compileFile, fs, getFileContents, less, path;

less = require("less");

fs = require("fs");

path = require("path");

Function = require("loophole").Function;

getFileContents = function(filePath, callback) {
  var content, read;
  content = '';
  return fs.readFile(filePath, 'utf-8', read = function(err, data) {
    if (err) {
      throw err;
    }
    return callback(data);
  });
};

compileFile = function(filepath) {
  var outputCompressed, showSuccessMessage;
  outputCompressed = atom.config.get('atom-compile-less.compressCss');
  showSuccessMessage = atom.config.get('atom-compile-less.showSuccessMessage');
  return getFileContents(filepath, function(content) {
    var parser;
    if (!content) {
      throw err;
    }
    parser = new less.Parser({
      paths: [path.dirname(filepath)]
    });
    return parser.parse(content, (function(_this) {
      return function(err, parsedContent) {
        var cssFilePath, outputCss;
        if (err) {
          throw err;
        }
        outputCss = parsedContent.toCSS({
          compress: outputCompressed
        });
        cssFilePath = filepath.replace(".less", ".css");
        return fs.writeFile(cssFilePath, outputCss, function(err) {
          var fileName, message;
          if (showSuccessMessage) {
            fileName = cssFilePath.split('/');
            fileName = fileName[fileName.length - 1];
            message = 'File ' + fileName + ' compiled! Yeih!';
            return atom.notifications.addSuccess(message);
          }
        });
      };
    })(this));
  });
};

atomCompileLess = function() {
  var currentEditor, currentFilePath, includeMainFile, projectMainLess, projectPath;
  currentEditor = atom.workspace.getActiveTextEditor();
  if (currentEditor) {
    currentFilePath = currentEditor.getPath();
    if (currentFilePath.substr(-4) === "less") {
      projectPath = atom.project.getPaths();
      projectMainLess = atom.project.getPaths() + atom.config.get('atom-compile-less.mainLessFile');
      includeMainFile = atom.config.get('atom-compile-less.compileMainFile');
      compileFile(currentFilePath);
      if (includeMainFile) {
        compileFile(projectMainLess);
      }
      return global.Function = Function;
    }
  }
};

module.exports = {
  activate: (function(_this) {
    atom.config.set('atom-compile-less.compressCss', true);
    atom.config.set('atom-compile-less.mainLessFile', '/main.less');
    atom.config.set('atom-compile-less.compileMainFile', true);
    atom.config.set('atom-compile-less.showSuccessMessage', true);
    return function(state) {
      return atom.workspace.observeTextEditors(function(editor) {
        return editor.onDidSave((function(_this) {
          return function() {
            return atomCompileLess();
          };
        })(this));
      });
    };
  })(this),
  deactivate: function() {},
  serialize: function() {}
};
<commit_msg>fixed config schema<commit_after>var Function, atomCompileLess, compileFile, fs, getFileContents, less, path;

less = require("less");
fs = require("fs");
path = require("path");

Function = require("loophole").Function;

getFileContents = function(filePath, callback) {
  var content, read;
  content = '';
  return fs.readFile(filePath, 'utf-8', read = function(err, data) {
    if (err) {
      throw err;
    }
    return callback(data);
  });
};

compileFile = function(filepath) {
  var outputCompressed, showSuccessMessage;
  outputCompressed = atom.config.get('atom-compile-less.compressCss');
  showSuccessMessage = atom.config.get('atom-compile-less.showSuccessMessage');
  return getFileContents(filepath, function(content) {
    var parser;
    if (!content) {
      throw err;
    }
    parser = new less.Parser({
      paths: [path.dirname(filepath)]
    });
    return parser.parse(content, (function(_this) {
      return function(err, parsedContent) {
        var cssFilePath, outputCss;
        if (err) {
          throw err;
        }
        outputCss = parsedContent.toCSS({
          compress: outputCompressed
        });
        cssFilePath = filepath.replace(".less", ".css");
        return fs.writeFile(cssFilePath, outputCss, function(err) {
          var fileName, message;
          if (showSuccessMessage) {
            fileName = cssFilePath.split('/');
            fileName = fileName[fileName.length - 1];
            message = 'File ' + fileName + ' compiled! Yeih!';
            return atom.notifications.addSuccess(message);
          }
        });
      };
    })(this));
  });
};

atomCompileLess = function() {
  var currentEditor, currentFilePath, includeMainFile, projectMainLess, projectPath;
  currentEditor = atom.workspace.getActiveTextEditor();
  if (currentEditor) {
    currentFilePath = currentEditor.getPath();
    if (currentFilePath.substr(-4) === "less") {
      projectPath = atom.project.getPaths();
      projectMainLess = atom.project.getPaths() + atom.config.get('atom-compile-less.mainLessFile');
      console.log(atom.config.get('atom-compile-less.mainLessFile'));
      includeMainFile = atom.config.get('atom-compile-less.compileMainFile');
      compileFile(currentFilePath);
      if (includeMainFile) {
        compileFile(projectMainLess);
      }
      return global.Function = Function;
    }
  }
};

module.exports = {
  config: {
    compressCss: {
      type: 'boolean',
      default: true
    },
    mainLessFile: {
      type: 'string',
      default: 'main.less'
    },
    compileMainFile: {
      type: 'boolean',
      default: true
    },
    showSuccessMessage: {
      type: 'boolean',
      default: true
    },
  },

  activate: (function(_this) {
    return function(state) {
      return atom.workspace.observeTextEditors(function(editor) {
        return editor.onDidSave((function(_this) {
          return function() {
            return atomCompileLess();
          };
        })(this));
      });
    };
  })(this),
  deactivate: function() {},
  serialize: function() {}
};
<|endoftext|>


<commit_before>'use strict';

var nightwatch_reportviewer = require('../lib/nightwatch-reportviewer.js');

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

exports['awesome'] = {
  setUp: function(done) {
    // setup here
    done();
  },
  'no args': function(test) {
    test.expect(1);
    // tests here
    test.equal(nightwatch_reportviewer.awesome(), 'awesome', 'should be awesome.');
    test.done();
  },
};
<commit_msg>Commented out the default tests.<commit_after>'use strict';

var nightwatch_html_reporter = require('../lib/nightwatch-html-reporter.js');

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

// exports['awesome'] = {
//   setUp: function(done) {
//     // setup here
//     done();
//   },
//   'no args': function(test) {
//     test.expect(1);
//     // tests here
//     test.equal(nightwatch_reportviewer.awesome(), 'awesome', 'should be awesome.');
//     test.done();
//   },
// };
<|endoftext|>


<commit_before>/**
 * based on
 * https://github.com/CreateJS/EaselJS/blob/631cdffb85eff9413dab43b4676f059b4232d291/src/easeljs/geom/Matrix2D.js
 */
const DEG_TO_RAD = Math.PI / 180;

/**
 * Represents an affine transformation matrix, and provides tools for constructing and concatenating matrices.
 *
 * This matrix can be visualized as:
 *
 * 	[ a  c  tx
 * 	  b  d  ty
 * 	  0  0  1  ]
 *
 * Note the locations of b and c.
 *
 * @class Matrix2D
 * @param {Number} [a=1] Specifies the a property for the new matrix.
 * @param {Number} [b=0] Specifies the b property for the new matrix.
 * @param {Number} [c=0] Specifies the c property for the new matrix.
 * @param {Number} [d=1] Specifies the d property for the new matrix.
 * @param {Number} [tx=0] Specifies the tx property for the new matrix.
 * @param {Number} [ty=0] Specifies the ty property for the new matrix.
 * @constructor
 **/
export default class Matrix2D {
    constructor() {
        this.reset();

        // public properties:
        /**
         * Position (0, 0) in a 3x3 affine transformation matrix.
         * @property a
         * @type Number
         **/

        /**
         * Position (0, 1) in a 3x3 affine transformation matrix.
         * @property b
         * @type Number
         **/

        /**
         * Position (1, 0) in a 3x3 affine transformation matrix.
         * @property c
         * @type Number
         **/

        /**
         * Position (1, 1) in a 3x3 affine transformation matrix.
         * @property d
         * @type Number
         **/

        /**
         * Position (2, 0) in a 3x3 affine transformation matrix.
         * @property tx
         * @type Number
         **/

        /**
         * Position (2, 1) in a 3x3 affine transformation matrix.
         * @property ty
         * @type Number
         **/
    }

    /**
     * Reset current matrix to an identity matrix.
     * @method reset
     * @return {Matrix2D} This matrix. Useful for chaining method calls.
     **/
    reset = function() {
        this.a = this.d = 1;
        this.b = this.c = this.tx = this.ty = 0;
        return this;
    };

    /**
     * Returns an array with current matrix values.
     * @method toArray
     * @return {Array} an array with current matrix values.
     **/
    toArray = function() {
        return [this.a, this.b, this.c, this.d, this.tx, this.ty];
    };

    /**
     * Appends the specified matrix properties to this matrix. All parameters are required.
     * This is the equivalent of multiplying `(this matrix) * (specified matrix)`.
     * @method append
     * @param {Number} a
     * @param {Number} b
     * @param {Number} c
     * @param {Number} d
     * @param {Number} tx
     * @param {Number} ty
     * @return {Matrix2D} This matrix. Useful for chaining method calls.
     **/
    append = function(a, b, c, d, tx, ty) {
        const a1 = this.a;
        const b1 = this.b;
        const c1 = this.c;
        const d1 = this.d;
        if (a !== 1 || b !== 0 || c !== 0 || d !== 1) {
            this.a = a1 * a + c1 * b;
            this.b = b1 * a + d1 * b;
            this.c = a1 * c + c1 * d;
            this.d = b1 * c + d1 * d;
        }
        this.tx = a1 * tx + c1 * ty + this.tx;
        this.ty = b1 * tx + d1 * ty + this.ty;
        return this;
    };

    /**
     * Generates matrix properties from the specified display object transform properties, and appends them to this matrix.
     * For example, you can use this to generate a matrix representing the transformations of a display object:
     *
     * 	var mtx = new createjs.Matrix2D();
     * 	mtx.appendTransform(o.x, o.y, o.scaleX, o.scaleY, o.rotation);
     * @method appendTransform
     * @param {Number} x
     * @param {Number} y
     * @param {Number} scaleX
     * @param {Number} scaleY
     * @param {Number} rotation
     * @param {Number} skewX
     * @param {Number} skewY
     * @param {Number} regX Optional.
     * @param {Number} regY Optional.
     * @return {Matrix2D} This matrix. Useful for chaining method calls.
     **/
    appendTransform = function(
        x,
        y,
        scaleX,
        scaleY,
        rotation,
        skewX,
        skewY,
        regX,
        regY
    ) {
        let cos, sin;
        if (rotation % 360) {
            const r = rotation * DEG_TO_RAD;
            cos = Math.cos(r);
            sin = Math.sin(r);
        } else {
            cos = 1;
            sin = 0;
        }

        if (skewX || skewY) {
            // TODO: can this be combined into a single append operation?
            skewX *= DEG_TO_RAD;
            skewY *= DEG_TO_RAD;
            this.append(
                Math.cos(skewY),
                Math.sin(skewY),
                Math.sin(skewX),
                Math.cos(skewX),
                x,
                y
            );
            this.append(
                cos * scaleX,
                sin * scaleX,
                -sin * scaleY,
                cos * scaleY,
                0,
                0
            );
        } else {
            this.append(
                cos * scaleX,
                sin * scaleX,
                -sin * scaleY,
                cos * scaleY,
                x,
                y
            );
        }

        if (regX || regY) {
            // append the registration offset:
            this.tx -= regX * this.a + regY * this.c;
            this.ty -= regX * this.b + regY * this.d;
        }
        return this;
    };
}
<commit_msg>Optimize Matrix2d and fix skew spec conformance<commit_after>/**
 * based on
 * https://github.com/CreateJS/EaselJS/blob/631cdffb85eff9413dab43b4676f059b4232d291/src/easeljs/geom/Matrix2D.js
 */
const DEG_TO_RAD = Math.PI / 180;

/**
 * Represents an affine transformation matrix, and provides tools for constructing and concatenating matrices.
 *
 * This matrix can be visualized as:
 *
 * 	[ a  c  tx
 * 	  b  d  ty
 * 	  0  0  1  ]
 *
 * Note the locations of b and c.
 *
 * @class Matrix2D
 * @param {Number} [a=1] Specifies the a property for the new matrix.
 * @param {Number} [b=0] Specifies the b property for the new matrix.
 * @param {Number} [c=0] Specifies the c property for the new matrix.
 * @param {Number} [d=1] Specifies the d property for the new matrix.
 * @param {Number} [tx=0] Specifies the tx property for the new matrix.
 * @param {Number} [ty=0] Specifies the ty property for the new matrix.
 * @constructor
 **/
export default class Matrix2D {
    constructor() {
        this.reset();

        // public properties:
        /**
         * Position (0, 0) in a 3x3 affine transformation matrix.
         * @property a
         * @type Number
         **/

        /**
         * Position (0, 1) in a 3x3 affine transformation matrix.
         * @property b
         * @type Number
         **/

        /**
         * Position (1, 0) in a 3x3 affine transformation matrix.
         * @property c
         * @type Number
         **/

        /**
         * Position (1, 1) in a 3x3 affine transformation matrix.
         * @property d
         * @type Number
         **/

        /**
         * Position (2, 0) in a 3x3 affine transformation matrix.
         * @property tx
         * @type Number
         **/

        /**
         * Position (2, 1) in a 3x3 affine transformation matrix.
         * @property ty
         * @type Number
         **/
    }

    /**
     * Reset current matrix to an identity matrix.
     * @method reset
     * @return {Matrix2D} This matrix. Useful for chaining method calls.
     **/
    reset = function() {
        this.a = this.d = 1;
        this.b = this.c = this.tx = this.ty = 0;
        this.hasInitialState = true;
        return this;
    };

    /**
     * Returns an array with current matrix values.
     * @method toArray
     * @return {Array} an array with current matrix values.
     **/
    toArray = function() {
        return [this.a, this.b, this.c, this.d, this.tx, this.ty];
    };

    /**
     * Appends the specified matrix properties to this matrix. All parameters are required.
     * This is the equivalent of multiplying `(this matrix) * (specified matrix)`.
     * @method append
     * @param {Number} a
     * @param {Number} b
     * @param {Number} c
     * @param {Number} d
     * @param {Number} tx
     * @param {Number} ty
     * @return {Matrix2D} This matrix. Useful for chaining method calls.
     **/
    append = function(a, b, c, d, tx, ty) {
        if (this.hasInitialState) {
            this.hasInitialState = false;
            this.a = a;
            this.b = b;
            this.c = c;
            this.d = d;
            this.tx = tx;
            this.ty = ty;
            return this;
        }
        const a1 = this.a;
        const b1 = this.b;
        const c1 = this.c;
        const d1 = this.d;
        if (a !== 1 || b !== 0 || c !== 0 || d !== 1) {
            this.a = a1 * a + c1 * b;
            this.b = b1 * a + d1 * b;
            this.c = a1 * c + c1 * d;
            this.d = b1 * c + d1 * d;
        }
        this.tx = a1 * tx + c1 * ty + this.tx;
        this.ty = b1 * tx + d1 * ty + this.ty;
        return this;
    };

    /**
     * Generates matrix properties from the specified display object transform properties, and appends them to this matrix.
     * For example, you can use this to generate a matrix representing the transformations of a display object:
     *
     * 	var mtx = new createjs.Matrix2D();
     * 	mtx.appendTransform(o.x, o.y, o.scaleX, o.scaleY, o.rotation);
     * @method appendTransform
     * @param {Number} x
     * @param {Number} y
     * @param {Number} scaleX
     * @param {Number} scaleY
     * @param {Number} rotation
     * @param {Number} skewX
     * @param {Number} skewY
     * @param {Number} regX Optional.
     * @param {Number} regY Optional.
     * @return {Matrix2D} This matrix. Useful for chaining method calls.
     **/
    appendTransform = function(
        x,
        y,
        scaleX,
        scaleY,
        rotation,
        skewX,
        skewY,
        regX,
        regY,
    ) {
        let cos, sin;
        if (rotation % 360) {
            const r = rotation * DEG_TO_RAD;
            cos = Math.cos(r);
            sin = Math.sin(r);
        } else {
            cos = 1;
            sin = 0;
        }

        const a = cos * scaleX;
        const b = sin * scaleX;
        const c = -sin * scaleY;
        const d = cos * scaleY;

        if (skewX || skewY) {
            const b1 = Math.tan(skewY * DEG_TO_RAD);
            const c1 = Math.tan(skewX * DEG_TO_RAD);
            this.append(a + c1 * b, b1 * a + b, c + c1 * d, b1 * c + d, x, y);
        } else {
            this.append(a, b, c, d, x, y);
        }

        if (regX || regY) {
            // append the registration offset:
            this.tx -= regX * this.a + regY * this.c;
            this.ty -= regX * this.b + regY * this.d;
        }
        return this;
    };
}
<|endoftext|>


<commit_before>/**
 * Extends optimist with support for JSON config file
 *
 * Pass a path to the config file using --config option
 *
 * @see https://github.com/substack/node-optimist
 * @see https://github.com/substack/minimist
 */
var debug = require('debug')('optimist:config'),
	fs = require('fs'),
	optimist = require('optimist');

function parseConfigFile(configFileName) {
	var json,
		configParsed;

	debug('Using "%s" config file', configFileName);

	// check the existance of the config file
	if (!fs.existsSync(configFileName)) {
		throw 'Config file "' + configFileName + '" cannot be found!';
	}

	// parse it
	try {
		json = fs.readFileSync(configFileName).toString();
		configParsed = JSON.parse(json);
	}
	catch(e) {
		debug('Config file parsing failed (%s)', e);
		throw 'Config file parsing failed (' + e + ')';
	}

	debug('Config file parsed: %j', configParsed);
	return configParsed;
}

// extend optimist
var origParse = optimist.parse;

optimist.parse = function(args) {
	var options = origParse(args);

	debug('parse: %j', args);
	debug('options: %j', options);

	// check the config file
	var configFileName = this.configFileParam && options[this.configFileParam],
		configParsed;

	// if --config is not provided, quit
	if (!configFileName) {
		return options;
	}

	configParsed = parseConfigFile(configFileName);

	return options;
}

optimist.setConfigFile = function(configFileParam) {
	this.configFileParam = configFileParam;
	return this.describe(this.configFileParam, 'uses JSON-formatted config file to set parameters').string(this.configFileParam);
}

module.exports = optimist;

/**

module.exports = function(program, argv, configParam) {
	configParam = configParam || 'config';

	// add --config parameter to help
	program.describe(configParam, 'uses JSON-formatted config file to set parameters').string(configParam);

	var options = program.parse(argv),
		defaults = program.parse('');

	// get the config file path
	var configFileName = options[configParam],
		configParsed;

	// if --config is not provided, quit
	if (!configFileName) {
		return options;
	}

	configParsed = parseConfigFile(configFileName);

	// go through each option and replace with value coming from command line option
	Object.keys(options).forEach(function(key) {
		if (options[key] !== defaults[key]) {
			configParsed[key] = options[key];
			debug('%s = %s', key, options[key]);
		}
	});

	// cleanup
	delete configParsed[configParam];

	debug('Defaults: %j', defaults);
	debug('Options: %j', configParsed);
	throw 'foo';
	return configParsed;
};
**/
<commit_msg>Convert nested objects into options<commit_after>/**
 * Extends optimist with support for JSON config file
 *
 * Pass a path to the config file using --config option
 *
 * @see https://github.com/substack/node-optimist
 * @see https://github.com/substack/minimist
 */
var debug = require('debug')('optimist:config'),
	fs = require('fs'),
	optimist = require('optimist');

function parseConfigFile(configFileName) {
	var json,
		configParsed;

	debug('Using "%s" config file', configFileName);

	// check the existance of the config file
	if (!fs.existsSync(configFileName)) {
		throw 'Config file "' + configFileName + '" cannot be found!';
	}

	// parse it
	try {
		json = fs.readFileSync(configFileName).toString();
		configParsed = JSON.parse(json);
	}
	catch(e) {
		debug('Config file parsing failed (%s)', e);
		throw 'Config file parsing failed (' + e + ')';
	}

	// convert nested objects into options
	// {'foo':{'bar': 1}} -> --foo--bar 1
	Object.keys(configParsed).forEach(function(key) {
		var value = configParsed[key];

		if (typeof value === 'object' && !Array.isArray(value)) {
			delete configParsed[key];

			// remove plural suffix
			key = key.replace(/s$/, '');

			debug('Unwrapping --%s-... options...', key);

			Object.keys(value).forEach(function(subKey) {
				configParsed[key + '-' + subKey] = value[subKey];
			});
		}
	});

	debug('Config file parsed: %j', configParsed);
	return configParsed;
}

// extend optimist
var origParse = optimist.parse;

optimist.parse = function(args) {
	var options = origParse(args);

	debug('parse: %j', args);
	debug('options: %j', options);

	// check the config file
	var configFileName = this.configFileParam && options[this.configFileParam],
		configParsed;

	// if --config is not provided, quit
	if (!configFileName) {
		return options;
	}

	configParsed = parseConfigFile(configFileName);

	// apply the rest of the options provided via command line
	Object.keys(configParsed).forEach(function(key) {
		options[key] = configParsed[key];
	});

	// cleanup
	delete options[this.configFileParam];
	return options;
}

optimist.setConfigFile = function(configFileParam) {
	this.configFileParam = configFileParam;
	return this.describe(this.configFileParam, 'uses JSON-formatted config file to set parameters').string(this.configFileParam);
}

module.exports = optimist;

/**

module.exports = function(program, argv, configParam) {
	configParam = configParam || 'config';

	// add --config parameter to help
	program.describe(configParam, 'uses JSON-formatted config file to set parameters').string(configParam);

	var options = program.parse(argv),
		defaults = program.parse('');

	// get the config file path
	var configFileName = options[configParam],
		configParsed;

	// if --config is not provided, quit
	if (!configFileName) {
		return options;
	}

	configParsed = parseConfigFile(configFileName);

	// go through each option and replace with value coming from command line option
	Object.keys(options).forEach(function(key) {
		if (options[key] !== defaults[key]) {
			configParsed[key] = options[key];
			debug('%s = %s', key, options[key]);
		}
	});

	// cleanup
	delete configParsed[configParam];

	debug('Defaults: %j', defaults);
	debug('Options: %j', configParsed);
	throw 'foo';
	return configParsed;
};
**/
<|endoftext|>


<commit_before>const Base64Util = require('../../util/base64-util');

/**
 * Adapter class
 */
class ScratchLinkDeviceAdapter {
    constructor (scratchLinkSocket, {service, commandChar, responseChar}) {
        this.scratchLinkSocket = scratchLinkSocket;

        this._service = service;
        this._commandChar = commandChar;
        this._responseChar = responseChar;
        this._onResponse = this._onResponse.bind(this);
        this._deviceOnResponse = null;
    }

    get godirectAdapter () {
        return true;
    }

    writeCommand (commandBuffer) {
        const data = Base64Util.uint8ArrayToBase64(commandBuffer);

        return this.scratchLinkSocket
            .write(this._service, this._commandChar, data, 'base64', true);
    }

    setup ({onResponse}) {
        this._deviceOnResponse = onResponse;
        return this.scratchLinkSocket
            .startNotifications(this._service, this._responseChar, this._onResponse);

        // TODO:
        // How do we find out from scratch link if communication closes?
    }

    _onResponse (base64) {
        const array = Base64Util.base64ToUint8Array(base64);
        const response = new DataView(array.buffer);
        return this._deviceOnResponse(response);
    }
}

module.exports = ScratchLinkDeviceAdapter;
<commit_msg>Removing withResponse flag since it is not needed and was causing a crash on Windows.<commit_after>const Base64Util = require('../../util/base64-util');

/**
 * Adapter class
 */
class ScratchLinkDeviceAdapter {
    constructor (scratchLinkSocket, {service, commandChar, responseChar}) {
        this.scratchLinkSocket = scratchLinkSocket;

        this._service = service;
        this._commandChar = commandChar;
        this._responseChar = responseChar;
        this._onResponse = this._onResponse.bind(this);
        this._deviceOnResponse = null;
    }

    get godirectAdapter () {
        return true;
    }

    writeCommand (commandBuffer) {
        const data = Base64Util.uint8ArrayToBase64(commandBuffer);

        return this.scratchLinkSocket
            .write(this._service, this._commandChar, data, 'base64');
    }

    setup ({onResponse}) {
        this._deviceOnResponse = onResponse;
        return this.scratchLinkSocket
            .startNotifications(this._service, this._responseChar, this._onResponse);

        // TODO:
        // How do we find out from scratch link if communication closes?
    }

    _onResponse (base64) {
        const array = Base64Util.base64ToUint8Array(base64);
        const response = new DataView(array.buffer);
        return this._deviceOnResponse(response);
    }
}

module.exports = ScratchLinkDeviceAdapter;
<|endoftext|>


<commit_before>'use strict';

// Rename this file to local.js for having a local configuration variables that
// will not get commited and pushed to remote repositories.
// Use it for your API keys, passwords, etc.

/* For example:

module.exports = {
  db: {
    uri: 'mongodb://localhost/local-dev',
    options: {
      user: '',
      pass: ''
    }
  },
  facebook: {
    clientID: process.env.FACEBOOK_ID || 'APP_ID',
    clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
    callbackURL: '/auth/facebook/callback'
  }
};
*/
<commit_msg>local.example.js still has old fb auth callback<commit_after>'use strict';

// Rename this file to local.js for having a local configuration variables that
// will not get commited and pushed to remote repositories.
// Use it for your API keys, passwords, etc.

/* For example:

module.exports = {
  db: {
    uri: 'mongodb://localhost/local-dev',
    options: {
      user: '',
      pass: ''
    }
  },
  facebook: {
    clientID: process.env.FACEBOOK_ID || 'APP_ID',
    clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
    callbackURL: '/api/auth/facebook/callback'
  }
};
*/
<|endoftext|>


<commit_before>/**
 * Extends optimist with support for JSON/YAML config file
 *
 * Pass a path to the config file using --config option
 *
 * @see https://github.com/substack/node-optimist
 * @see https://github.com/substack/minimist
 */
var debug = require('debug')('optimist:config'),
	fs = require('fs'),
	optimist = require('optimist'),
	yaml = require('js-yaml');

function parseConfigFile(configFileName) {
	var raw,
		configMode,
		configParsed;

	debug('using "%s" config file', configFileName);

	// check the existance of the config file
	if (!fs.existsSync(configFileName)) {
		throw 'Config file "' + configFileName + '" cannot be found!';
	}

	// JSON or YAML?
	configMode = /\.yaml$/.test(configFileName) ? 'YAML' : 'JSON';

	// parse it
	try {
		raw = fs.readFileSync(configFileName).toString();

		switch(configMode) {
			case 'YAML':
				configParsed = yaml.safeLoad(raw);
				break;

			case 'JSON':
				configParsed = JSON.parse(raw);
				break;
		}
	}
	catch(e) {
		debug('%s config file parsing failed (%s)', configMode, e);
		throw configMode + '%s config file parsing failed (' + e + ')';
	}

	// convert nested objects into options
	// {'foo':{'bar': 1}} -> --foo--bar 1
	Object.keys(configParsed).forEach(function(key) {
		var value = configParsed[key];

		if (typeof value === 'object' && !Array.isArray(value)) {
			delete configParsed[key];

			// remove plural suffix
			key = key.replace(/s$/, '');

			debug('unwrapping --%s-* options...', key);

			Object.keys(value).forEach(function(subKey) {
				configParsed[key + '-' + subKey] = value[subKey];
			});
		}
	});

	debug('%s config file parsed: %j', configMode, configParsed);
	return configParsed;
}

// extend optimist
var origParse = optimist.parse;

optimist.parse = function(args) {
	var options = origParse(args);
	debug('parse: %j', args);

	// check the config file
	var configFileName = this.configFileParam && options[this.configFileParam],
		configParsed;

	// if --config is not provided, quit
	if (!configFileName) {
		debug('options: %j', options);
		return options;
	}

	configParsed = parseConfigFile(configFileName);

	// apply the rest of the options provided via command line
	Object.keys(configParsed).forEach(function(key) {
		// check if given option was not provided via command line
		if (args.indexOf('--' + key) > -1) {
			debug('--%s option provided via command line, will skip the value from config file', key);
			return;
		}

		options[key] = configParsed[key];
	});

	// cleanup
	delete options[this.configFileParam];

	debug('options: %j', options);
	return options;
};

optimist.setConfigFile = function(configFileParam) {
	this.configFileParam = configFileParam;
	return this.describe(this.configFileParam, 'uses JSON-formatted config file to set parameters').string(this.configFileParam);
};

module.exports = optimist;
<commit_msg>Update README and --help<commit_after>/**
 * Extends optimist with support for JSON/YAML config file
 *
 * Pass a path to the config file using --config option
 *
 * @see https://github.com/substack/node-optimist
 * @see https://github.com/substack/minimist
 */
var debug = require('debug')('optimist:config'),
	fs = require('fs'),
	optimist = require('optimist'),
	yaml = require('js-yaml');

function parseConfigFile(configFileName) {
	var raw,
		configMode,
		configParsed;

	debug('using "%s" config file', configFileName);

	// check the existance of the config file
	if (!fs.existsSync(configFileName)) {
		throw 'Config file "' + configFileName + '" cannot be found!';
	}

	// JSON or YAML?
	configMode = /\.yaml$/.test(configFileName) ? 'YAML' : 'JSON';

	// parse it
	try {
		raw = fs.readFileSync(configFileName).toString();

		switch(configMode) {
			case 'YAML':
				configParsed = yaml.safeLoad(raw);
				break;

			case 'JSON':
				configParsed = JSON.parse(raw);
				break;
		}
	}
	catch(e) {
		debug('%s config file parsing failed (%s)', configMode, e);
		throw configMode + '%s config file parsing failed (' + e + ')';
	}

	// convert nested objects into options
	// {'foo':{'bar': 1}} -> --foo--bar 1
	Object.keys(configParsed).forEach(function(key) {
		var value = configParsed[key];

		if (typeof value === 'object' && !Array.isArray(value)) {
			delete configParsed[key];

			// remove plural suffix
			key = key.replace(/s$/, '');

			debug('unwrapping --%s-* options...', key);

			Object.keys(value).forEach(function(subKey) {
				configParsed[key + '-' + subKey] = value[subKey];
			});
		}
	});

	debug('%s config file parsed: %j', configMode, configParsed);
	return configParsed;
}

// extend optimist
var origParse = optimist.parse;

optimist.parse = function(args) {
	var options = origParse(args);
	debug('parse: %j', args);

	// check the config file
	var configFileName = this.configFileParam && options[this.configFileParam],
		configParsed;

	// if --config is not provided, quit
	if (!configFileName) {
		debug('options: %j', options);
		return options;
	}

	configParsed = parseConfigFile(configFileName);

	// apply the rest of the options provided via command line
	Object.keys(configParsed).forEach(function(key) {
		// check if given option was not provided via command line
		if (args.indexOf('--' + key) > -1) {
			debug('--%s option provided via command line, will skip the value from config file', key);
			return;
		}

		options[key] = configParsed[key];
	});

	// cleanup
	delete options[this.configFileParam];

	debug('options: %j', options);
	return options;
};

optimist.setConfigFile = function(configFileParam) {
	this.configFileParam = configFileParam;
	return this.describe(this.configFileParam, 'uses JSON or YAML-formatted config file to set parameters').string(this.configFileParam);
};

module.exports = optimist;
<|endoftext|>


<commit_before>/**
 * @author Massimiliano Izzo
 * @description main tool for migration
 */
var connections = require('../config/connections.js');
var BluebirdPromise = require('bluebird');

function Migrator(mysqlConn, pgConn) {

    if (!mysqlConn) mysqlConn = 'mysqlLocal';
    if (!pgConn) pgConn = 'postgresqlLocal';

    console.log(connections[mysqlConn]);
    console.log(connections[pgConn]);

    this.knexMysql = require('knex')(connections[mysqlConn]);
    // this.knexMysql.select('ID_PRJ').from('PROJECT').then(console.log).catch(console.log);
    this.knexPg = require('knex')(connections[pgConn]);
    // this.knexPg.select('name').from('data_type').then(console.log).catch(console.log);
}

Migrator.prototype = {

    /**
     * @name migrateProjects
     * @description tool to migrate all the projects
     */
    migrateProjects: function() {

        var knexPg = this.knexPg;

        return this.knexMysql.select('ID_PRJ', 'NAME_PROJECT', 'DESCR_PROJECT').from('PROJECT')
        .orderBy('ID_PRJ')

        .then(function(rows) {
            console.log(rows);
            return BluebirdPromise.each(rows, function(record) {
                console.log(record);
                return knexPg.returning('id').insert({
                    'name': record.NAME_PROJECT,
                    'description': record.DESCR_PROJECT,
                    'created_at': new Date(),
                    'updated_at': new Date()
                }).into('project');
            }, {concurrency: 1});
        });

    },

    /**
     * @name migrateSubject
     * @description tool to migrate a signle subject together with all its data(?) in the database
     * @param{Integer} mysqlId - the ID of the subject in MySQL
     */
    migrateSubject: function(mysqlId) {

        var knexPg = this.knexPg;

        return this.knexMysql.select('NAME', 'SURNAME', 'BIRTH_DATE', 'ID_SEX', 'CODE', 'ID_PRJ', 'INSERT_DATE', 'DATE_LAST_UPDATE').from('PERSONAL_DATA')
        .leftJoin('PATIENT', 'PERSONAL_DATA.ID_PRS_DATA', 'PATIENT.ID_PRS_DATA')
        .where('PERSONAL_DATA.ID_PRS_DATA','=',mysqlId)

        .then(function(rows) {
            var record = rows[0];
            return knexPg.transaction(function(trx) {

                // insert Personal Details
                return knexPg.returning('id').insert({
                    'given_name': record.NAME,
                    'surname': record.SURNAME,
                    'birth_date': record.BIRTH_DATE,
                    'created_at': record.INSERT_DATE,
                    'updated_at': record.DATE_LAST_UPDATE
                }).into('personal_details').transacting(trx)

                // insert Subject
                .then(function(ids) {
                    var idPersonalData = ids[0];
                    return knexPg.returning('id').insert({
                        'code': record.CODE,
                        'sex': record.ID_SEX,
                        'metadata': {},
                        'created_at': record.INSERT_DATE,
                        'updated_at': record.DATE_LAST_UPDATE
                    }).into('subject').transacting(trx);
                })

                // insert project-subject association
                .then(function(ids) {
                    var idSubject = ids[0];
                    return knexPg.insert({'project_subjects': idProject, 'subject_projects': idSubject})
                    .into('project_subjects__subject_projects').transacting(trx);
                });

            });
        });
    }

};

module.exports = Migrator;
<commit_msg>fixed ambiguity error #3<commit_after>/**
 * @author Massimiliano Izzo
 * @description main tool for migration
 */
var connections = require('../config/connections.js');
var BluebirdPromise = require('bluebird');

function Migrator(mysqlConn, pgConn) {

    if (!mysqlConn) mysqlConn = 'mysqlLocal';
    if (!pgConn) pgConn = 'postgresqlLocal';

    console.log(connections[mysqlConn]);
    console.log(connections[pgConn]);

    this.knexMysql = require('knex')(connections[mysqlConn]);
    // this.knexMysql.select('ID_PRJ').from('PROJECT').then(console.log).catch(console.log);
    this.knexPg = require('knex')(connections[pgConn]);
    // this.knexPg.select('name').from('data_type').then(console.log).catch(console.log);
}

Migrator.prototype = {

    /**
     * @name migrateProjects
     * @description tool to migrate all the projects
     */
    migrateProjects: function() {

        var knexPg = this.knexPg;

        return this.knexMysql.select('ID_PRJ', 'NAME_PROJECT', 'DESCR_PROJECT').from('PROJECT')
        .orderBy('ID_PRJ')

        .then(function(rows) {
            console.log(rows);
            return BluebirdPromise.each(rows, function(record) {
                console.log(record);
                return knexPg.returning('id').insert({
                    'name': record.NAME_PROJECT,
                    'description': record.DESCR_PROJECT,
                    'created_at': new Date(),
                    'updated_at': new Date()
                }).into('project');
            }, {concurrency: 1});
        });

    },

    /**
     * @name migrateSubject
     * @description tool to migrate a signle subject together with all its data(?) in the database
     * @param{Integer} mysqlId - the ID of the subject in MySQL
     */
    migrateSubject: function(mysqlId) {

        var knexPg = this.knexPg;

        return this.knexMysql.select('NAME', 'SURNAME', 'BIRTH_DATE', 'ID_SEX', 'CODE', 'ID_PRJ', 'INSERT_DATE', 'DATE_LAST_UPDATE').from('PERSONAL_DATA')
        .leftJoin('PATIENT', 'PERSONAL_DATA.ID_PRS_DATA', 'PATIENT.ID_PRS_DATA')
        .where('PERSONAL_DATA.ID_PRS_DATA','=',mysqlId)

        .then(function(rows) {
            var record = rows[0];
            return knexPg.transaction(function(trx) {

                // insert Personal Details
                return knexPg.returning('id').insert({
                    'given_name': record.NAME,
                    'surname': record.SURNAME,
                    'birth_date': record.BIRTH_DATE,
                    'created_at': record.INSERT_DATE,
                    'updated_at': record.DATE_LAST_UPDATE
                }).into('personal_details').transacting(trx)

                // insert Subject
                .then(function(ids) {
                    var idPersonalData = ids[0];
                    return knexPg.returning('id').insert({
                        'code': record.CODE,
                        'sex': record.ID_SEX,
                        'metadata': {},
                        'created_at': record.INSERT_DATE,
                        'updated_at': record.DATE_LAST_UPDATE
                    }).into('subject').transacting(trx);
                })

                // insert project-subject association
                .then(function(ids) {
                    var idSubject = ids[0];
                    return knexPg.insert({'project_subjects': record.ID_PRJ, 'subject_projects': idSubject})
                    .into('project_subjects__subject_projects').transacting(trx);
                });

            });
        });
    }

};

module.exports = Migrator;
<|endoftext|>


<commit_before>/**
 * server.js - http server for bcoin
 * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
 * https://github.com/indutny/bcoin
 */

var EventEmitter = require('events').EventEmitter;
var bcoin = require('../../bcoin');
var HTTPServer = require('./http');
var utils = require('../utils');
var assert = utils.assert;

/**
 * NodeServer
 */

function NodeServer(node, options) {
  if (!options)
    options = {};

  this.options = options;
  this.node = node;
  this.walletdb = node.walletdb;
  this.pool = node.pool;
  this.loaded = false;

  this.server = new HTTPServer(options);
  this.io = null;

  this._init();
}

utils.inherits(NodeServer, EventEmitter);

NodeServer.prototype._init = function _init() {
  var self = this;

  this.use(function(req, res, next, send) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Credentials', 'true');
    res.setHeader(
      'Access-Control-Allow-Methods',
      'GET,HEAD,PUT,PATCH,POST,DELETE');

    if (req.method === 'OPTIONS') {
      res.statusCode = 200;
      return res.end();
    }

    next();
  });

  this.use(function(req, res, next, send) {
    var params = utils.merge({}, req.query, req.body, req.params);
    var options = {};

    if (params.id) {
      assert(params.id !== '!all');
      options.id = params.id;
    }

    if (params.hash) {
      if (utils.isInt(params.hash))
        options.height = params.hash >>> 0;
      else
        options.hash = utils.revHex(params.hash);
    }

    if (params.index != null)
      options.index = params.index >>> 0;

    if (params.height != null)
      options.height = params.height >>> 0;

    if (params.start != null)
      options.start = params.start >>> 0;

    if (params.end != null)
      options.end = params.end >>> 0;

    if (params.limit != null)
      options.limit = params.limit >>> 0;

    if (params.changeDepth)
      options.changeDepth = params.changeDepth >>> 0;

    if (params.receiveDepth)
      options.receiveDepth = params.receiveDepth >>> 0;

    if (params.address) {
      params.addresses = params.address;
      options.address = params.address;
    }

    if (params.value)
      options.value = utils.satoshi(params.value);

    if (params.addresses) {
      if (typeof params.addresses === 'string')
        options.addresses = params.addresses.split(',');
      else
        options.addresses = params.addresses;
    }

    if (params.tx) {
      try {
        options.tx = bcoin.tx.fromRaw(params.tx, 'hex');
      } catch (e) {
        return next(e);
      }
    }

    if (params.now)
      options.now = params.now >>> 0;

    if (params.age)
      options.age = params.age >>> 0;

    if (params.passphrase)
      options.passphrase = params.passphrase;

    if (params.bin)
      options.bin = true;

    req.options = options;

    next();
  });

  this.get('/', function(req, res, next, send) {
    send(200, {
      version: constants.userAgent,
      network: self.node.network.type
    });
  });

  // UTXO by address
  this.get('/coin/address/:address', function(req, res, next, send) {
    self.node.getCoinsByAddress(req.options.addresses, function(err, coins) {
      if (err)
        return next(err);

      if (!coins.length)
        return send(404);

      send(200, coins.map(function(coin) {
        return coin.toJSON();
      }));
    });
  });

  // UTXO by id
  this.get('/coin/:hash/:index', function(req, res, next, send) {
    self.node.getCoin(req.options.hash, req.options.index, function(err, coin) {
      if (err)
        return next(err);

      if (!coin)
        return send(404);

      send(200, coin.toJSON());
    });
  });

  // Bulk read UTXOs
  this.post('/coin/address', function(req, res, next, send) {
    self.node.getCoinsByAddress(req.body.addresses, function(err, coins) {
      if (err)
        return next(err);

      if (!coins.length)
        return send(404);

      send(200, coins.map(function(coin) {
        return coin.toJSON();
      }));
    });
  });

  // TX by hash
  this.get('/tx/:hash', function(req, res, next, send) {
    self.node.getTX(req.options.hash, function(err, tx) {
      if (err)
        return next(err);

      if (!tx)
        return send(404);

      send(200, tx.toJSON());
    });
  });

  // TX by address
  this.get('/tx/address/:address', function(req, res, next, send) {
    self.node.getTXByAddress(req.options.addresses, function(err, txs) {
      if (err)
        return next(err);

      if (!txs.length)
        return send(404);

      send(200, txs.map(function(tx) {
        return tx.toJSON();
      }));
    });
  });

  // Bulk read TXs
  this.post('/tx/address', function(req, res, next, send) {
    self.node.getTXByAddress(req.body.addresses, function(err, txs) {
      if (err)
        return next(err);

      if (!txs.length)
        return send(404);

      send(200, txs.map(function(tx) {
        return tx.toJSON();
      }));
    });
  });

  // Block by hash/height
  this.get('/block/:hash', function(req, res, next, send) {
    var hash = req.options.hash || req.options.height;
    self.node.getFullBlock(hash, function(err, block) {
      if (err)
        return next(err);

      if (!block)
        return send(404);

      send(200, block.toJSON());
    });
  });

  // Get wallet
  this.get('/wallet/:id', function(req, res, next, send) {
    self.walletdb.getJSON(req.options.id, function(err, json) {
      if (err)
        return next(err);

      if (!json)
        return send(404);

      send(200, json);
    });
  });

  // Create/get wallet
  this.post('/wallet/:id', function(req, res, next, send) {
    self.walletdb.create(req.options, function(err, wallet) {
      var json;

      if (err)
        return next(err);

      if (!wallet)
        return send(404);

      json = wallet.toJSON();
      wallet.destroy();

      send(200, json);
    });
  });

  // Send TX
  this.post('/wallet/:id/send', function(req, res, next, send) {
    var id = req.options.id;
    var passphrase = req.options.passphrase;
    self.walletdb.get(id, passphrase, function(err, wallet) {
      if (err)
        return next(err);

      if (!wallet)
        return send(404);

      wallet.createTX({
        address: req.options.address,
        value: req.options.value
      }, function(err, tx) {
        wallet.destroy();

        if (err)
          return next(err);

        self.pool.sendTX(tx, function(err) {
          if (err)
            return next(err);

          send(200, tx.toJSON());
        });
      });
    });
  });

  // Zap Wallet TXs
  this.post('/wallet/:id/zap', function(req, res, next, send) {
    var id = req.options.id;
    var now = req.options.now;
    var age = req.options.age;

    self.walletdb.zapWallet(id, now, age, function(err, wallet) {
      if (err)
        return next(err);

      send(200, {
        success: true
      });
    });
  });

  // Update wallet / sync address depth
  this.put('/wallet/:id', function(req, res, next, send) {
    var id = req.options.id;
    var receive = req.options.receiveDepth;
    var change = req.options.changeDepth;

    self.walletdb.setDepth(id, receive, change, function(err) {
      if (err)
        return next(err);

      send(200, {
        success: true
      });
    });
  });

  // Wallet Balance
  this.get('/wallet/:id/balance', function(req, res, next, send) {
    self.walletdb.getBalance(req.options.id, function(err, balance) {
      if (err)
        return next(err);

      if (!balance)
        return send(404);

      send(200, {
        confirmed: utils.btc(balance.confirmed),
        unconfirmed: utils.btc(balance.unconfirmed)
      });
    });
  });

  // Wallet UTXOs
  this.get('/wallet/:id/coin', function(req, res, next, send) {
    self.walletdb.getCoins(req.options.id, function(err, coins) {
      if (err)
        return next(err);

      if (!coins.length)
        return send(404);

      send(200, coins.map(function(coin) {
        return coin.toJSON();
      }));
    });
  });

  // Wallet TX
  this.get('/wallet/:id/coin/:hash/:index', function(req, res, next, send) {
    var hash = req.options.hash;
    var index = req.options.index;
    self.walletdb.getCoin(hash, index, function(err, coin) {
      if (err)
        return next(err);

      if (!coin)
        return send(404);

      send(200, coin.toJSON());
    });
  });

  // Wallet TXs
  this.get('/wallet/:id/tx/all', function(req, res, next, send) {
    self.walletdb.getAll(req.options.id, function(err, txs) {
      if (err)
        return next(err);

      if (!txs.length)
        return send(404);

      send(200, txs.map(function(tx) {
        return tx.toJSON();
      }));
    });
  });

  // Wallet Pending TXs
  this.get('/wallet/:id/tx/pending', function(req, res, next, send) {
    self.walletdb.getPending(req.options.id, function(err, txs) {
      if (err)
        return next(err);

      if (!txs.length)
        return send(404);

      send(200, txs.map(function(tx) {
        return tx.toJSON();
      }));
    });
  });

  // Wallet TXs within time range
  this.get('/wallet/:id/tx/range', function(req, res, next, send) {
    self.walletdb.getRange(req.options.id, req.options, function(err, txs) {
      if (err)
        return next(err);

      if (!txs.length)
        return send(404);

      send(200, txs.map(function(tx) {
        return tx.toJSON();
      }));
    });
  });

  // Wallet TXs within time range
  this.get('/wallet/:id/tx/last', function(req, res, next, send) {
    var id = req.options.id;
    var limit = req.options.limit;
    self.walletdb.getRange(id, limit, function(err, txs) {
      if (err)
        return next(err);

      if (!txs.length)
        return send(404);

      send(200, txs.map(function(tx) {
        return tx.toJSON();
      }));
    });
  });

  // Wallet TX
  this.get('/wallet/:id/tx/:hash', function(req, res, next, send) {
    self.walletdb.getTX(req.options.hash, function(err, tx) {
      if (err)
        return next(err);

      if (!tx)
        return send(404);

      send(200, tx.toJSON());
    });
  });

  // Broadcast TX
  this.post('/broadcast', function(req, res, next, send) {
    self.pool.sendTX(tx, function(err) {
      if (err)
        return callback(err);

      send(200, {
        success: true
      });
    });
  });

  this.server.on('error', function(err) {
    self.emit('error', err);
  });

  this._initIO();

  if (this.options.port != null)
    this.listen(this.options.port, this.options.host);
};

NodeServer.prototype.open = function open(callback) {
  if (this.loaded)
    return utils.nextTick(callback);

  this.once('open', callback);
};

NodeServer.prototype.close =
NodeServer.prototype.destroy = function destroy(callback) {
  this.server.close(callback);
};

NodeServer.prototype._initIO = function _initIO() {
  var self = this;

  if (!this.server.io)
    return;

  this.server.on('websocket', function(socket) {
    socket.on('error', function(err) {
      self.emit('error', err);
    });
    self.emit('websocket', socket);
  });

  this.walletdb.on('tx', function(tx, map) {
    tx = tx.toJSON();
    map.all.forEach(function(id) {
      self.server.io.to(id).emit('tx', tx);
    });
    self.server.io.to('!all').emit('tx', tx, map);
  });

  this.walletdb.on('confirmed', function(tx, map) {
    tx = tx.toJSON();
    map.all.forEach(function(id) {
      self.server.io.to(id).emit('confirmed', tx);
    });
    self.server.io.to('!all').emit('confirmed', tx, map);
  });

  this.walletdb.on('updated', function(tx, map) {
    tx = tx.toJSON();
    map.all.forEach(function(id) {
      self.server.io.to(id).emit('updated', tx);
    });
    self.server.io.to('!all').emit('updated', tx, map);
  });

  this.walletdb.on('balance', function(balance, id) {
    var json = {
      confirmed: utils.btc(balance.confirmed),
      unconfirmed: utils.btc(balance.unconfirmed)
    };
    self.server.io.to(id).emit('balance', json);
    self.server.io.to('!all').emit('balance', json, id);
  });

  this.walletdb.on('balances', function(balances) {
    var json = {};
    Object.keys(balances).forEach(function(id) {
      json[id] = {
        confirmed: utils.btc(balances[id].confirmed),
        unconfirmed: utils.btc(balances[id].unconfirmed)
      };
    });
    self.server.io.to('!all').emit('balances', json);
  });
};

NodeServer.prototype.use = function use(path, callback) {
  return this.server.use(path, callback);
};

NodeServer.prototype.get = function get(path, callback) {
  return this.server.get(path, callback);
};

NodeServer.prototype.post = function post(path, callback) {
  return this.server.post(path, callback);
};

NodeServer.prototype.put = function put(path, callback) {
  return this.server.put(path, callback);
};

NodeServer.prototype.del = function del(path, callback) {
  return this.server.del(path, callback);
};

NodeServer.prototype.listen = function listen(port, host, callback) {
  var self = this;
  return this.server.listen(port, host, function(err) {
    if (err) {
      if (callback)
        return callback(err);
      return self.emit('error', err);
    }

    self.loaded = true;
    self.emit('open');

    if (callback)
      callback();
  });
};

/**
 * Expose
 */

module.exports = NodeServer;
<commit_msg>http.<commit_after>/**
 * server.js - http server for bcoin
 * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
 * https://github.com/indutny/bcoin
 */

var EventEmitter = require('events').EventEmitter;
var bcoin = require('../../bcoin');
var HTTPServer = require('./http');
var utils = require('../utils');
var assert = utils.assert;

/**
 * NodeServer
 */

function NodeServer(node, options) {
  if (!options)
    options = {};

  this.options = options;
  this.node = node;
  this.walletdb = node.walletdb;
  this.pool = node.pool;
  this.loaded = false;

  this.server = new HTTPServer(options);
  this.io = null;

  this._init();
}

utils.inherits(NodeServer, EventEmitter);

NodeServer.prototype._init = function _init() {
  var self = this;

  this.use(function(req, res, next, send) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Credentials', 'true');
    res.setHeader(
      'Access-Control-Allow-Methods',
      'GET,HEAD,PUT,PATCH,POST,DELETE');

    if (req.method === 'OPTIONS') {
      res.statusCode = 200;
      return res.end();
    }

    next();
  });

  this.use(function(req, res, next, send) {
    var params = utils.merge({}, req.query, req.body, req.params);
    var options = {};

    if (params.id) {
      assert(params.id !== '!all');
      options.id = params.id;
    }

    if (params.hash) {
      if (utils.isInt(params.hash))
        options.height = params.hash >>> 0;
      else
        options.hash = utils.revHex(params.hash);
    }

    if (params.index != null)
      options.index = params.index >>> 0;

    if (params.height != null)
      options.height = params.height >>> 0;

    if (params.start != null)
      options.start = params.start >>> 0;

    if (params.end != null)
      options.end = params.end >>> 0;

    if (params.limit != null)
      options.limit = params.limit >>> 0;

    if (params.changeDepth)
      options.changeDepth = params.changeDepth >>> 0;

    if (params.receiveDepth)
      options.receiveDepth = params.receiveDepth >>> 0;

    if (params.address) {
      params.addresses = params.address;
      options.address = params.address;
    }

    if (params.value)
      options.value = utils.satoshi(params.value);

    if (params.addresses) {
      if (typeof params.addresses === 'string')
        options.addresses = params.addresses.split(',');
      else
        options.addresses = params.addresses;
    }

    if (params.tx) {
      try {
        options.tx = bcoin.tx.fromRaw(params.tx, 'hex');
      } catch (e) {
        return next(e);
      }
    }

    if (params.now)
      options.now = params.now >>> 0;

    if (params.age)
      options.age = params.age >>> 0;

    if (params.passphrase)
      options.passphrase = params.passphrase;

    if (params.bin)
      options.bin = true;

    req.options = options;

    next();
  });

  this.get('/', function(req, res, next, send) {
    send(200, {
      version: constants.userAgent,
      network: self.node.network.type
    });
  });

  // UTXO by address
  this.get('/coin/address/:address', function(req, res, next, send) {
    self.node.getCoinsByAddress(req.options.addresses, function(err, coins) {
      if (err)
        return next(err);

      if (!coins.length)
        return send(404);

      send(200, coins.map(function(coin) {
        return coin.toJSON();
      }));
    });
  });

  // UTXO by id
  this.get('/coin/:hash/:index', function(req, res, next, send) {
    self.node.getCoin(req.options.hash, req.options.index, function(err, coin) {
      if (err)
        return next(err);

      if (!coin)
        return send(404);

      send(200, coin.toJSON());
    });
  });

  // Bulk read UTXOs
  this.post('/coin/address', function(req, res, next, send) {
    self.node.getCoinsByAddress(req.body.addresses, function(err, coins) {
      if (err)
        return next(err);

      if (!coins.length)
        return send(404);

      send(200, coins.map(function(coin) {
        return coin.toJSON();
      }));
    });
  });

  // TX by hash
  this.get('/tx/:hash', function(req, res, next, send) {
    self.node.getTX(req.options.hash, function(err, tx) {
      if (err)
        return next(err);

      if (!tx)
        return send(404);

      send(200, tx.toJSON());
    });
  });

  // TX by address
  this.get('/tx/address/:address', function(req, res, next, send) {
    self.node.getTXByAddress(req.options.addresses, function(err, txs) {
      if (err)
        return next(err);

      if (!txs.length)
        return send(404);

      send(200, txs.map(function(tx) {
        return tx.toJSON();
      }));
    });
  });

  // Bulk read TXs
  this.post('/tx/address', function(req, res, next, send) {
    self.node.getTXByAddress(req.body.addresses, function(err, txs) {
      if (err)
        return next(err);

      if (!txs.length)
        return send(404);

      send(200, txs.map(function(tx) {
        return tx.toJSON();
      }));
    });
  });

  // Block by hash/height
  this.get('/block/:hash', function(req, res, next, send) {
    var hash = req.options.hash || req.options.height;
    self.node.getFullBlock(hash, function(err, block) {
      if (err)
        return next(err);

      if (!block)
        return send(404);

      send(200, block.toJSON());
    });
  });

  // Get wallet
  this.get('/wallet/:id', function(req, res, next, send) {
    self.walletdb.getJSON(req.options.id, function(err, json) {
      if (err)
        return next(err);

      if (!json)
        return send(404);

      send(200, json);
    });
  });

  // Create/get wallet
  this.post('/wallet/:id', function(req, res, next, send) {
    self.walletdb.create(req.options, function(err, wallet) {
      var json;

      if (err)
        return next(err);

      if (!wallet)
        return send(404);

      json = wallet.toJSON();
      wallet.destroy();

      send(200, json);
    });
  });

  // Send TX
  this.post('/wallet/:id/send', function(req, res, next, send) {
    var id = req.options.id;
    var passphrase = req.options.passphrase;
    self.walletdb.get(id, passphrase, function(err, wallet) {
      if (err)
        return next(err);

      if (!wallet)
        return send(404);

      wallet.createTX({
        address: req.options.address,
        value: req.options.value
      }, function(err, tx) {
        wallet.destroy();

        if (err)
          return next(err);

        self.pool.sendTX(tx, function(err) {
          if (err)
            return next(err);

          send(200, tx.toJSON());
        });
      });
    });
  });

  // Zap Wallet TXs
  this.post('/wallet/:id/zap', function(req, res, next, send) {
    var id = req.options.id;
    var now = req.options.now;
    var age = req.options.age;

    self.walletdb.zapWallet(id, now, age, function(err, wallet) {
      if (err)
        return next(err);

      send(200, {
        success: true
      });
    });
  });

  // Update wallet / sync address depth
  this.put('/wallet/:id', function(req, res, next, send) {
    var id = req.options.id;
    var receive = req.options.receiveDepth;
    var change = req.options.changeDepth;

    self.walletdb.setDepth(id, receive, change, function(err) {
      if (err)
        return next(err);

      send(200, {
        success: true
      });
    });
  });

  // Wallet Balance
  this.get('/wallet/:id/balance', function(req, res, next, send) {
    self.walletdb.getBalance(req.options.id, function(err, balance) {
      if (err)
        return next(err);

      if (!balance)
        return send(404);

      send(200, {
        confirmed: utils.btc(balance.confirmed),
        unconfirmed: utils.btc(balance.unconfirmed)
      });
    });
  });

  // Wallet UTXOs
  this.get('/wallet/:id/coin', function(req, res, next, send) {
    self.walletdb.getCoins(req.options.id, function(err, coins) {
      if (err)
        return next(err);

      if (!coins.length)
        return send(404);

      send(200, coins.map(function(coin) {
        return coin.toJSON();
      }));
    });
  });

  // Wallet TX
  this.get('/wallet/:id/coin/:hash/:index', function(req, res, next, send) {
    var hash = req.options.hash;
    var index = req.options.index;
    self.walletdb.getCoin(hash, index, function(err, coin) {
      if (err)
        return next(err);

      if (!coin)
        return send(404);

      send(200, coin.toJSON());
    });
  });

  // Wallet TXs
  this.get('/wallet/:id/tx/all', function(req, res, next, send) {
    self.walletdb.getAll(req.options.id, function(err, txs) {
      if (err)
        return next(err);

      if (!txs.length)
        return send(404);

      send(200, txs.map(function(tx) {
        return tx.toJSON();
      }));
    });
  });

  // Wallet Pending TXs
  this.get('/wallet/:id/tx/pending', function(req, res, next, send) {
    self.walletdb.getPending(req.options.id, function(err, txs) {
      if (err)
        return next(err);

      if (!txs.length)
        return send(404);

      send(200, txs.map(function(tx) {
        return tx.toJSON();
      }));
    });
  });

  // Wallet TXs within time range
  this.get('/wallet/:id/tx/range', function(req, res, next, send) {
    self.walletdb.getRange(req.options.id, req.options, function(err, txs) {
      if (err)
        return next(err);

      if (!txs.length)
        return send(404);

      send(200, txs.map(function(tx) {
        return tx.toJSON();
      }));
    });
  });

  // Wallet TXs within time range
  this.get('/wallet/:id/tx/last', function(req, res, next, send) {
    var id = req.options.id;
    var limit = req.options.limit;
    self.walletdb.getRange(id, limit, function(err, txs) {
      if (err)
        return next(err);

      if (!txs.length)
        return send(404);

      send(200, txs.map(function(tx) {
        return tx.toJSON();
      }));
    });
  });

  // Wallet TX
  this.get('/wallet/:id/tx/:hash', function(req, res, next, send) {
    self.walletdb.getTX(req.options.hash, function(err, tx) {
      if (err)
        return next(err);

      if (!tx)
        return send(404);

      send(200, tx.toJSON());
    });
  });

  // Broadcast TX
  this.post('/broadcast', function(req, res, next, send) {
    self.pool.sendTX(tx, function(err) {
      if (err)
        return callback(err);

      send(200, {
        success: true
      });
    });
  });

  // Mempool snapshot
  this.get('/mempool', function(req, res, next, send) {
    self.node.mempool.getAll(function(err, txs) {
      if (err)
        return callback(err);

      if (!txs.length)
        return send(404);

      send(200, txs.map(function(tx) {
        return tx.toJSON();
      }));
    });
  });

  this.server.on('error', function(err) {
    self.emit('error', err);
  });

  this._initIO();

  if (this.options.port != null)
    this.listen(this.options.port, this.options.host);
};

NodeServer.prototype.open = function open(callback) {
  if (this.loaded)
    return utils.nextTick(callback);

  this.once('open', callback);
};

NodeServer.prototype.close =
NodeServer.prototype.destroy = function destroy(callback) {
  this.server.close(callback);
};

NodeServer.prototype._initIO = function _initIO() {
  var self = this;

  if (!this.server.io)
    return;

  this.server.on('websocket', function(socket) {
    socket.on('error', function(err) {
      self.emit('error', err);
    });
    self.emit('websocket', socket);
  });

  this.walletdb.on('tx', function(tx, map) {
    tx = tx.toJSON();
    map.all.forEach(function(id) {
      self.server.io.to(id).emit('tx', tx);
    });
    self.server.io.to('!all').emit('tx', tx, map);
  });

  this.walletdb.on('confirmed', function(tx, map) {
    tx = tx.toJSON();
    map.all.forEach(function(id) {
      self.server.io.to(id).emit('confirmed', tx);
    });
    self.server.io.to('!all').emit('confirmed', tx, map);
  });

  this.walletdb.on('updated', function(tx, map) {
    tx = tx.toJSON();
    map.all.forEach(function(id) {
      self.server.io.to(id).emit('updated', tx);
    });
    self.server.io.to('!all').emit('updated', tx, map);
  });

  this.walletdb.on('balance', function(balance, id) {
    var json = {
      confirmed: utils.btc(balance.confirmed),
      unconfirmed: utils.btc(balance.unconfirmed)
    };
    self.server.io.to(id).emit('balance', json);
    self.server.io.to('!all').emit('balance', json, id);
  });

  this.walletdb.on('balances', function(balances) {
    var json = {};
    Object.keys(balances).forEach(function(id) {
      json[id] = {
        confirmed: utils.btc(balances[id].confirmed),
        unconfirmed: utils.btc(balances[id].unconfirmed)
      };
    });
    self.server.io.to('!all').emit('balances', json);
  });
};

NodeServer.prototype.use = function use(path, callback) {
  return this.server.use(path, callback);
};

NodeServer.prototype.get = function get(path, callback) {
  return this.server.get(path, callback);
};

NodeServer.prototype.post = function post(path, callback) {
  return this.server.post(path, callback);
};

NodeServer.prototype.put = function put(path, callback) {
  return this.server.put(path, callback);
};

NodeServer.prototype.del = function del(path, callback) {
  return this.server.del(path, callback);
};

NodeServer.prototype.listen = function listen(port, host, callback) {
  var self = this;
  return this.server.listen(port, host, function(err) {
    if (err) {
      if (callback)
        return callback(err);
      return self.emit('error', err);
    }

    self.loaded = true;
    self.emit('open');

    if (callback)
      callback();
  });
};

/**
 * Expose
 */

module.exports = NodeServer;
<|endoftext|>