<commit_before>"use strict";
/*global alert: true, ODSA, console */

(function ($) {
  var av;
  var tree;
  var leftAlign = 250;
  var topAlign = 0;
  var nodeGap = 25;
  var nodeHeight = 33;
  var nodeWidth = 45;
  var labelShift = 10;
  var labelSet;

  function runit() {
    av = new JSAV($(".avcontainer"));
	labelSet = new Array();
    MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
	$(".avcontainer").on("jsav-message", function() {
      // invoke MathJax to do conversion again
      MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
    });

	//Slide 1
	av.umsg("Let's see how we can guess the closed form solution of the recurrence $T(n) = T(n-1) + 1$");
	av.displayInit();

	//Slide 2
	av.umsg("For a problem of size $n$, we have $1$ unit of work plus the amount of work required for one subproblem of size $n-1$");
	av.umsg("
 $T(n) = 1 + T(n-1)$", {"preserve": true});
	labelSet.push(av.label("Amount of Work", {"top": topAlign - 10 , "left": leftAlign + 200}));
	labelSet.push(av.label("----------------------------------", {"top": topAlign + 0.5 * nodeHeight, "left": leftAlign + nodeWidth + labelShift}));
	labelSet.push(av.label("1", {"top": topAlign + 0.5 * nodeHeight , "left": leftAlign + nodeWidth + labelShift * 20}));
	tree = av.ds.tree({left: leftAlign, top: topAlign, nodegap: nodeGap});
	var root = tree.newNode("$n$");
    tree.root(root);
	var nMinusOne = tree.newNode("$n-1$");
	root.addChild(nMinusOne);
	tree.layout();
	av.step();

	//Slide 3
	av.umsg("For a problem of size $n-1$, we have $1$ unit of work plus the amount of work required for one subproblem of size $n-2$");
	av.umsg("
 $T(n) = 1 + (1 + T(n-2))$", {"preserve": true});
	labelSet.push(av.label("----------------------------------", {"top": topAlign + 2 * nodeHeight + nodeGap , "left": leftAlign + nodeWidth + labelShift}));
	labelSet.push(av.label("1", {"top": topAlign + 2 * nodeHeight + nodeGap , "left": leftAlign + nodeWidth + labelShift * 20}));
	var nMinusTwo = tree.newNode("$n-2$");
	nMinusOne.addChild(nMinusTwo);
	tree.layout();
	av.step();

	//Slide 4
	av.umsg("For a problem of size $n-2$, we have $1$ unit of work plus the amount of work required for one subproblem of size $n-3$");
	av.umsg("
 $T(n) = 1 + (1 + (1 + T(n-3)))$", {"preserve": true});
	labelSet.push(av.label("----------------------------------", {"top": topAlign + 3.5 * nodeHeight + 2 * nodeGap , "left": leftAlign + nodeWidth + labelShift}));
	labelSet.push(av.label("1", {"top": topAlign + 3.5 * nodeHeight + 2 * nodeGap , "left": leftAlign + nodeWidth + labelShift * 20}));
	var nMinusThree = tree.newNode("$n-3$");
	nMinusTwo.addChild(nMinusThree);
	tree.layout();
	av.step();

	//Slide 5
	av.umsg("For a problem of size $n-3$, we have $1$ unit of work plus the amount of work required for one subproblem of size $n-4$");
	av.umsg("
 $T(n) = 1 + (1 + (1 + (1 + T(n-4)))$", {"preserve": true});
	labelSet.push(av.label("----------------------------------", {"top": topAlign + 5 * nodeHeight + 3 * nodeGap , "left": leftAlign + nodeWidth + labelShift}));
	labelSet.push(av.label("1", {"top": topAlign + 5 * nodeHeight + 3 * nodeGap , "left": leftAlign + nodeWidth + labelShift * 20}));
	var nMinusFour = tree.newNode("$n-4$");
	nMinusThree.addChild(nMinusFour);
	tree.layout();
	av.step();

	//Slide 6
	av.umsg("This pattern will continue till we reach a subproblem of size $1$");
	av.umsg("
 $T(n) = 1 + (1 + (1 + (1 + (1 + (...))))$", {"preserve": true});
	labelSet.push(av.label("----------------------------------", {"top": topAlign + 8.5 * nodeHeight + 4 * nodeGap , "left": leftAlign + nodeWidth + labelShift}));
	labelSet.push(av.label("1", {"top": topAlign + 8.5 * nodeHeight + 4 * nodeGap , "left": leftAlign + nodeWidth + labelShift * 20}));
	var one = tree.newNode("$1$");
	nMinusFour.addChild(one);
	var edge = one.edgeToParent();
	edge.addClass("dashed");
	tree.layout();
	av.step();

	//Slide 7
	av.umsg("Thus, the closed form solution of $T(n) = T(n-1) + 1$ can be modeled by the summation $\\displaystyle\\sum_{i=1}^{n}1$");
	av.step();

	//Slide 8
	av.umsg("Finally, we have the closed form solution of $T(n) = T(n-1) + 1$ evaluates to $n$");
	av.step();

	//Slide 9
	av.umsg("Similarily, we can guess the closed form solution of the recurrence $T(n) = T(n-1) + n$");
	$.each(labelSet, function(index, value){
	  value.hide();
	});
	tree.hide();
	av.step();

	//Slide 10
	labelSet = new Array();
	av.umsg("For a problem of size $n$, we have $n$ units of work plus the amount of work required for one subproblem of size $n-1$");
	av.umsg("
 $T(n) = n + T(n-1)$", {"preserve": true});
	labelSet.push(av.label("Amount of Work", {"top": topAlign - 10 , "left": leftAlign + 200}));
	labelSet.push(av.label("----------------------------------", {"top": topAlign + 0.5 * nodeHeight, "left": leftAlign + nodeWidth + labelShift}));
	labelSet.push(av.label("$n$", {"top": topAlign + 0.5 * nodeHeight , "left": leftAlign + nodeWidth + labelShift * 20}));
	tree = av.ds.tree({left: leftAlign, top: topAlign, nodegap: nodeGap});
	var root = tree.newNode("$n$");
    tree.root(root);
	var nMinusOne = tree.newNode("$n-1$");
	root.addChild(nMinusOne);
	tree.layout();
	av.step();

	//Slide 11
	av.umsg("For a problem of size $n-1$, we have $n-1$ units of work plus the amount of work required for one subproblem of size $n-2$");
	av.umsg("
 $T(n) = n + (n-1 + T(n-2))$", {"preserve": true});
	labelSet.push(av.label("----------------------------------", {"top": topAlign + 2 * nodeHeight + nodeGap , "left": leftAlign + nodeWidth + labelShift}));
	labelSet.push(av.label("$n-1$", {"top": topAlign + 2 * nodeHeight + nodeGap , "left": leftAlign + nodeWidth + labelShift * 20}));
	var nMinusTwo = tree.newNode("$n-2$");
	nMinusOne.addChild(nMinusTwo);
	tree.layout();
	av.step();

	//Slide 12
	av.umsg("For each problem of size $n-2$, we have $n-2$ units of work plus the amount of work required for one subproblem of size $n-3$");
	av.umsg("
 $T(n) = n + (n-1 + (n-2 + T(n-3)))$", {"preserve": true});
	labelSet.push(av.label("----------------------------------", {"top": topAlign + 3.5 * nodeHeight + 2 * nodeGap , "left": leftAlign + nodeWidth + labelShift}));
	labelSet.push(av.label("$n-2$", {"top": topAlign + 3.5 * nodeHeight + 2 * nodeGap , "left": leftAlign + nodeWidth + labelShift * 20}));
	var nMinusThree = tree.newNode("$n-3$");
	nMinusTwo.addChild(nMinusThree);
	tree.layout();
	av.step();

	//Slide 13
	av.umsg("For a problem of size $n-3$, we have $n-3$ units of work plus the amount of work required for one subproblem of size $n-4$");
	av.umsg("
 $T(n) = n + (n-1 + (n-2 + (n-3 + T(n-4)))$", {"preserve": true});
	labelSet.push(av.label("----------------------------------", {"top": topAlign + 5 * nodeHeight + 3 * nodeGap , "left": leftAlign + nodeWidth + labelShift}));
	labelSet.push(av.label("$n-3$", {"top": topAlign + 5 * nodeHeight + 3 * nodeGap , "left": leftAlign + nodeWidth + labelShift * 20}));
	var nMinusFour = tree.newNode("$n-4$");
	nMinusThree.addChild(nMinusFour);
	tree.layout();
	av.step();

	//Slide 14
	av.umsg("This pattern will continue till we reach a subproblem of size $1$");
	av.umsg("
 $T(n) = n + (n-1 + (n-2 + (n-3 + (n-4 + (...))))$", {"preserve": true});
	labelSet.push(av.label("----------------------------------", {"top": topAlign + 8.5 * nodeHeight + 4 * nodeGap , "left": leftAlign + nodeWidth + labelShift}));
	labelSet.push(av.label("$1$", {"top": topAlign + 8.5 * nodeHeight + 4 * nodeGap , "left": leftAlign + nodeWidth + labelShift * 20}));
	var one = tree.newNode("$1$");
	nMinusFour.addChild(one);
	var edge = one.edgeToParent();
	edge.addClass("dashed");
	tree.layout();
	av.step();

	//Slide 15
	av.umsg("Thus, the closed form solution of $T(n) = T(n-1) + 1$ can be modeled by the summation $\\displaystyle\\sum_{i=1}^{n}i$");
	av.step();

	//Slide 16
	av.umsg("Since we already now that $\\displaystyle\\sum_{i=1}^{n}i = \\frac{n(n+1)}{2}$, we have the closed form solution of $T(n) = T(n-1) + n$ evaluates to $ \\frac{n(n+1)}{2} $");
	av.step();

	av.recorded();
}
  function about() {
    var mystring = "Linear Recurrences\nWritten by Mohammed Fawzi and Cliff Shaffer\nCreated as part of the OpenDSA hypertextbook project.\nFor more information, see http://algoviz.org/OpenDSA\nWritten during February, 2014\nJSAV library version " + JSAV.version();
    alert(mystring);
  }

  // Connect action callbacks to the HTML entities
  $('#about').click(about);
  $('#runit').click(runit);
  $('#reset').click(ODSA.AV.reset);
}(jQuery));
<commit_msg>Delete LinearRecurrences.js<commit_after><|endoftext|>


<commit_before>/**
 * @license
 * Copyright (c) 2017 Google Inc. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * Code distributed by Google as part of this project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */

const Entity = require("./entity.js");
const assert = require('assert');
const Type = require('./type.js');

class Schema {
  constructor(model) {
    this._model = model;
    this.name = model.name;
    this.parents = model.parents.map(parent => new Schema(parent));
    this._normative = {};
    this._optional = {};
    assert(model.sections);
    for (var section of model.sections) {
      var into = section.sectionType == 'normative' ? this._normative : this._optional;
      for (var field in section.fields) {
        // TODO normalize field types here?
        into[field] = section.fields[field];
      }
    }
  }

  toLiteral() {
    return this._model;
  }

  get type() {
    return Type.newEntity(this.toLiteral());
  }

  get normative() {
    var normative = {};
    for (var parent of this.parents)
      Object.assign(normative, parent.normative);
    Object.assign(normative, this._normative);
    return normative;
  }

  get optional() {
    var optional = {};
    for (var parent of this.parents)
      Object.assign(optional, parent.optional);
    Object.assign(optional, this._optional);
    return optional;
  }

  entityClass() {
    let schema = this;
    const className = this.name;
    var properties = Object.keys(this.normative).concat(Object.keys(this.optional));
    var classJunk = ['toJSON', 'prototype', 'toString'];

    var clazz = class extends Entity {
      constructor(data) {
        var p = new Proxy(data, {
          get: (target, name) => {
            if (classJunk.includes(name))
              return undefined;
            if (name.constructor == Symbol)
              return undefined;
            if (!properties.includes(name))
              throw new Error(`Can't access field ${name} not in schema ${className}`);
            return target[name];
          },
          set: (target, name, value) => {
            if (!properties.includes(name)) {
              throw new Error(`Can't write field ${name} not in schema ${className}`);
            }
            target[name] = value;
            return true;
          }
        });
        super();
        this.rawData = p;
      }

      dataClone() {
        var clone = {};
        properties.forEach(prop => clone[prop] = this.rawData[prop]);
        return clone;
      }

      static get key() {
        return {
          tag: 'entity',
          schema: schema.toLiteral(),
        };
      }
    }

    Object.defineProperty(clazz, 'type', {value: this.type});
    Object.defineProperty(clazz, 'name', {value: this.name});
    for (let property in this.normative) {
      // TODO: type checking, make a distinction between normative
      // and optional properties.
      // TODO: add query / getter functions for user properties
      Object.defineProperty(clazz.prototype, property, {
        get: function() {
          return this.rawData[property];
        },
        set: function(v) {
          this.rawData[property] = v;
        }
      });
    }
    for (let property in this.optional) {
      Object.defineProperty(clazz.prototype, property, {
        get: function() {
          return this.rawData[property];
        },
        set: function(v) {
          this.rawData[property] = v;
        }
      });
    }
    return clazz;
  }

  toString() {
    let results = [];
    results.push(`schema ${this.name}`.concat(this.parent ? ` extends ${this.parent.name}` : ''));

    let propertiesToString = (properties, keyword) => {
      if (Object.keys(properties).length > 0) {
        results.push(`  ${keyword}`);
        Object.keys(properties).forEach(name => {
          let schemaType = Array.isArray(properties[name]) && properties[name].length > 1 ? `(${properties[name].join(' or ')})` : properties[name];
          results.push(`    ${schemaType} ${name}`);
        });
      }
    }

    propertiesToString(this.normative, 'normative');
    propertiesToString(this.optional, 'optional');
    return results.join('\n');
  }
}

module.exports = Schema;
<commit_msg>Support schemas without parents<commit_after>/**
 * @license
 * Copyright (c) 2017 Google Inc. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * Code distributed by Google as part of this project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */

const Entity = require("./entity.js");
const assert = require('assert');
const Type = require('./type.js');

class Schema {
  constructor(model) {
    this._model = model;
    this.name = model.name;
    this.parents = (model.parents || []).map(parent => new Schema(parent));
    this._normative = {};
    this._optional = {};
    assert(model.sections);
    for (var section of model.sections) {
      var into = section.sectionType == 'normative' ? this._normative : this._optional;
      for (var field in section.fields) {
        // TODO normalize field types here?
        into[field] = section.fields[field];
      }
    }
  }

  toLiteral() {
    return this._model;
  }

  get type() {
    return Type.newEntity(this.toLiteral());
  }

  get normative() {
    var normative = {};
    for (var parent of this.parents)
      Object.assign(normative, parent.normative);
    Object.assign(normative, this._normative);
    return normative;
  }

  get optional() {
    var optional = {};
    for (var parent of this.parents)
      Object.assign(optional, parent.optional);
    Object.assign(optional, this._optional);
    return optional;
  }

  entityClass() {
    let schema = this;
    const className = this.name;
    var properties = Object.keys(this.normative).concat(Object.keys(this.optional));
    var classJunk = ['toJSON', 'prototype', 'toString'];

    var clazz = class extends Entity {
      constructor(data) {
        var p = new Proxy(data, {
          get: (target, name) => {
            if (classJunk.includes(name))
              return undefined;
            if (name.constructor == Symbol)
              return undefined;
            if (!properties.includes(name))
              throw new Error(`Can't access field ${name} not in schema ${className}`);
            return target[name];
          },
          set: (target, name, value) => {
            if (!properties.includes(name)) {
              throw new Error(`Can't write field ${name} not in schema ${className}`);
            }
            target[name] = value;
            return true;
          }
        });
        super();
        this.rawData = p;
      }

      dataClone() {
        var clone = {};
        properties.forEach(prop => clone[prop] = this.rawData[prop]);
        return clone;
      }

      static get key() {
        return {
          tag: 'entity',
          schema: schema.toLiteral(),
        };
      }
    }

    Object.defineProperty(clazz, 'type', {value: this.type});
    Object.defineProperty(clazz, 'name', {value: this.name});
    for (let property in this.normative) {
      // TODO: type checking, make a distinction between normative
      // and optional properties.
      // TODO: add query / getter functions for user properties
      Object.defineProperty(clazz.prototype, property, {
        get: function() {
          return this.rawData[property];
        },
        set: function(v) {
          this.rawData[property] = v;
        }
      });
    }
    for (let property in this.optional) {
      Object.defineProperty(clazz.prototype, property, {
        get: function() {
          return this.rawData[property];
        },
        set: function(v) {
          this.rawData[property] = v;
        }
      });
    }
    return clazz;
  }

  toString() {
    let results = [];
    results.push(`schema ${this.name}`.concat(this.parent ? ` extends ${this.parent.name}` : ''));

    let propertiesToString = (properties, keyword) => {
      if (Object.keys(properties).length > 0) {
        results.push(`  ${keyword}`);
        Object.keys(properties).forEach(name => {
          let schemaType = Array.isArray(properties[name]) && properties[name].length > 1 ? `(${properties[name].join(' or ')})` : properties[name];
          results.push(`    ${schemaType} ${name}`);
        });
      }
    }

    propertiesToString(this.normative, 'normative');
    propertiesToString(this.optional, 'optional');
    return results.join('\n');
  }
}

module.exports = Schema;
<|endoftext|>


<commit_before>// Copyright 2016, University of Colorado Boulder

/**
 * PhET-iO wrapper type for phet's ObservableArray type.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Andrew Adare (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var assertInstanceOf = require( 'PHET_IO/assertions/assertInstanceOf' );
  var phetioInherit = require( 'PHET_IO/phetioInherit' );
  var phetioNamespace = require( 'PHET_IO/phetioNamespace' );
  var TObject = require( 'PHET_IO/types/TObject' );
  var toEventOnEmit = require( 'PHET_IO/events/toEventOnEmit' );

  /**
   * Parametric wrapper type constructor.  Given an element type, this function returns an ObservbleArray wrapper type.
   * @param {TObject} elementType - wrapper type of the DerivedProperty
   * @constructor
   */
  function TObservableArray( elementType ) {
    assert && assert( typeof( elementType ) === 'function', 'element type should be defined' );

    /**
     * This type constructor is parameterized based on the instance of Events.
     * @param observableArray
     * @param {string} phetioID - the full unique tandem name for the instance
     * @constructor
     */
    var TObservableArrayImpl = function TObservableArrayImpl( observableArray, phetioID ) {
      TObject.call( this, observableArray, phetioID );
      assertInstanceOf( observableArray, phet.axon.ObservableArray );

      /**
       * @param item
       * @returns {{item: Object}} - returns the stateObject of child item
       */
      var itemToStateObject = function( item ) {

        assert && assert( !!elementType.toStateObject, elementType.typeName + '.toStateObject is undefined' );

        return { item: elementType.toStateObject( item ) };
      };
      toEventOnEmit( observableArray.startedCallbacksForItemAddedEmitter, observableArray.endedCallbacksForItemAddedEmitter, 'model', phetioID, TObservableArray( elementType ), 'itemAdded', itemToStateObject );
      toEventOnEmit( observableArray.startedCallbacksForItemRemovedEmitter, observableArray.endedCallbacksForItemRemovedEmitter, 'model', phetioID, TObservableArray( elementType ), 'itemRemoved', itemToStateObject );
    };
    return phetioInherit( TObject, 'TObservableArray', TObservableArrayImpl, {}, {
      documentation: 'An array that sends notifications when its values have changed.',
      elementType: elementType,
      events: [ 'itemAdded', 'itemRemoved' ]
    } );
  }

  phetioNamespace.register( 'TObservableArray', TObservableArray );

  return TObservableArray;
} );

<commit_msg>Added phetioID in TObservableArray messages, and removed unused methods on TParticle, see https://github.com/phetsims/phet-io/issues/44<commit_after>// Copyright 2016, University of Colorado Boulder

/**
 * PhET-iO wrapper type for phet's ObservableArray type.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Andrew Adare (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var assertInstanceOf = require( 'PHET_IO/assertions/assertInstanceOf' );
  var phetioInherit = require( 'PHET_IO/phetioInherit' );
  var phetioNamespace = require( 'PHET_IO/phetioNamespace' );
  var TObject = require( 'PHET_IO/types/TObject' );
  var toEventOnEmit = require( 'PHET_IO/events/toEventOnEmit' );

  /**
   * Parametric wrapper type constructor.  Given an element type, this function returns an ObservbleArray wrapper type.
   * @param {TObject} elementType - wrapper type of the DerivedProperty
   * @constructor
   */
  function TObservableArray( elementType ) {
    assert && assert( typeof( elementType ) === 'function', 'element type should be defined' );

    /**
     * This type constructor is parameterized based on the instance of Events.
     * @param observableArray
     * @param {string} phetioID - the full unique tandem name for the instance
     * @constructor
     */
    var TObservableArrayImpl = function TObservableArrayImpl( observableArray, phetioID ) {
      TObject.call( this, observableArray, phetioID );
      assertInstanceOf( observableArray, phet.axon.ObservableArray );

      /**
       * @param item
       * @returns {Object} - returns the stateObject of child item
       */
      var formatForDataStream = function( item ) {

        // Supply phetioID if it is available
        var result = { phetioID: item.phetioID };

        // Supply state if it is available
        if ( elementType.toStateObject ) {
          result.state = elementType.toStateObject( item );
        }
        return result;
      };
      toEventOnEmit( observableArray.startedCallbacksForItemAddedEmitter, observableArray.endedCallbacksForItemAddedEmitter, 'model', phetioID, TObservableArray( elementType ), 'itemAdded', formatForDataStream );
      toEventOnEmit( observableArray.startedCallbacksForItemRemovedEmitter, observableArray.endedCallbacksForItemRemovedEmitter, 'model', phetioID, TObservableArray( elementType ), 'itemRemoved', formatForDataStream );
    };
    return phetioInherit( TObject, 'TObservableArray', TObservableArrayImpl, {}, {
      documentation: 'An array that sends notifications when its values have changed.',
      elementType: elementType,
      events: [ 'itemAdded', 'itemRemoved' ]
    } );
  }

  phetioNamespace.register( 'TObservableArray', TObservableArray );

  return TObservableArray;
} );

<|endoftext|>


<commit_before>'use strict';

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

const Exchange = require ('./base/Exchange');
const { ExchangeError, InsufficientFunds, InvalidOrder, AuthenticationError, PermissionDenied, InvalidNonce, OrderNotFound, DDoSProtection } = require ('./base/errors');

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

module.exports = class btcbox extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'btcbox',
            'name': 'BtcBox',
            'countries': [ 'JP' ],
            'rateLimit': 1000,
            'version': 'v1',
            'has': {
                'CORS': false,
                'fetchOrder': true,
                'fetchOrders': true,
                'fetchOpenOrders': true,
                'fetchTickers': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/31275803-4df755a8-aaa1-11e7-9abb-11ec2fad9f2d.jpg',
                'api': 'https://www.btcbox.co.jp/api',
                'www': 'https://www.btcbox.co.jp/',
                'doc': 'https://www.btcbox.co.jp/help/asm',
            },
            'api': {
                'public': {
                    'get': [
                        'depth',
                        'orders',
                        'ticker',
                        'allticker',
                    ],
                },
                'private': {
                    'post': [
                        'balance',
                        'trade_add',
                        'trade_cancel',
                        'trade_list',
                        'trade_view',
                        'wallet',
                    ],
                },
            },
            'markets': {
                'BTC/JPY': { 'id': 'BTC/JPY', 'symbol': 'BTC/JPY', 'base': 'BTC', 'quote': 'JPY' },
            },
            'exceptions': {
                '104': AuthenticationError,
                '105': PermissionDenied,
                '106': InvalidNonce,
                '107': InvalidOrder, // price should be an integer
                '200': InsufficientFunds,
                '201': InvalidOrder, // amount too small
                '202': InvalidOrder, // price should be [0 : 1000000]
                '203': OrderNotFound,
                '401': OrderNotFound, // cancel canceled, closed or non-existent order
                '402': DDoSProtection,
            },
        });
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let balances = await this.privatePostBalance ();
        let result = { 'info': balances };
        let currencies = Object.keys (this.currencies);
        for (let i = 0; i < currencies.length; i++) {
            let currency = currencies[i];
            let lowercase = currency.toLowerCase ();
            if (lowercase === 'dash')
                lowercase = 'drk';
            let account = this.account ();
            let free = lowercase + '_balance';
            let used = lowercase + '_lock';
            if (free in balances)
                account['free'] = parseFloat (balances[free]);
            if (used in balances)
                account['used'] = parseFloat (balances[used]);
            account['total'] = this.sum (account['free'], account['used']);
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let request = {};
        let numSymbols = this.symbols.length;
        if (numSymbols > 1)
            request['coin'] = market['id'];
        let orderbook = await this.publicGetDepth (this.extend (request, params));
        return this.parseOrderBook (orderbook);
    }

    parseTicker (ticker, market = undefined) {
        let timestamp = this.milliseconds ();
        let symbol = undefined;
        if (market)
            symbol = market['symbol'];
        let last = this.safeFloat (ticker, 'last');
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': this.safeFloat (ticker, 'high'),
            'low': this.safeFloat (ticker, 'low'),
            'bid': this.safeFloat (ticker, 'buy'),
            'bidVolume': undefined,
            'ask': this.safeFloat (ticker, 'sell'),
            'askVolume': undefined,
            'vwap': undefined,
            'open': undefined,
            'close': last,
            'last': last,
            'previousClose': undefined,
            'change': undefined,
            'percentage': undefined,
            'average': undefined,
            'baseVolume': this.safeFloat (ticker, 'vol'),
            'quoteVolume': this.safeFloat (ticker, 'volume'),
            'info': ticker,
        };
    }

    async fetchTickers (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        let tickers = await this.publicGetAllticker (params);
        let ids = Object.keys (tickers);
        let result = {};
        for (let i = 0; i < ids.length; i++) {
            let id = ids[i];
            let market = this.markets_by_id[id];
            let symbol = market['symbol'];
            let ticker = tickers[id];
            result[symbol] = this.parseTicker (ticker, market);
        }
        return result;
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let request = {};
        let numSymbols = this.symbols.length;
        if (numSymbols > 1)
            request['coin'] = market['id'];
        let ticker = await this.publicGetTicker (this.extend (request, params));
        return this.parseTicker (ticker, market);
    }

    parseTrade (trade, market) {
        let timestamp = parseInt (trade['date']) * 1000; // GMT time
        return {
            'info': trade,
            'id': trade['tid'],
            'order': undefined,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'type': undefined,
            'side': trade['type'],
            'price': trade['price'],
            'amount': trade['amount'],
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let request = {};
        let numSymbols = this.symbols.length;
        if (numSymbols > 1)
            request['coin'] = market['id'];
        let response = await this.publicGetOrders (this.extend (request, params));
        return this.parseTrades (response, market, since, limit);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let request = {
            'amount': amount,
            'price': price,
            'type': side,
        };
        let numSymbols = this.symbols.length;
        if (numSymbols > 1)
            request['coin'] = market['id'];
        let response = await this.privatePostTradeAdd (this.extend (request, params));
        return {
            'info': response,
            'id': response['id'],
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        return await this.privatePostTradeCancel (this.extend ({
            'id': id,
        }, params));
    }

    parseOrder (order) {
        // {"id":11,"datetime":"2014-10-21 10:47:20","type":"sell","price":42000,"amount_original":1.2,"amount_outstanding":1.2,"status":"closed","trades":[]}
        const id = this.safeString (order, 'id');
        const timestamp = this.parse8601 (order['datetime'] + '+09:00'); // Tokyo time
        const amount = this.safeFloat (order, 'amount_original');
        const remaining = this.safeFloat (order, 'amount_outstanding');
        let filled = undefined;
        if (typeof amount !== 'undefined')
            if (typeof remaining !== 'undefined')
                filled = amount - remaining;
        const price = this.safeFloat (order, 'price');
        let cost = undefined;
        if (typeof price !== 'undefined')
            if (typeof filled !== 'undefined')
                cost = filled * price;
        // status is set by fetchOrder method only
        const statuses = {
            // TODO: complete list
            'part': 'open', // partially or not at all executed
            'all': 'closed', // fully executed
            'cancelled': 'canceled',
            'closed': 'closed', // never encountered, seems to be bug in the doc
        };
        let status = undefined;
        if (order['status'] in statuses)
            status = statuses[order['status']];
        // fetchOrders do not return status, use heuristic
        if (typeof status === 'undefined')
            if (typeof remaining !== 'undefined' && remaining === 0)
                status = 'closed';
        let trades = undefined; // todo: this.parseTrades (order['trades']);
        return {
            'id': id,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'lastTradeTimestamp': undefined,
            'amount': amount,
            'remaining': remaining,
            'filled': filled,
            'side': order['type'],
            'type': undefined,
            'status': status,
            'symbol': 'BTC/JPY',
            'price': price,
            'cost': cost,
            'trades': trades,
            'fee': undefined,
            'info': order,
        };
    }

    async fetchOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        let response = await this.privatePostTradeView (this.extend ({
            'id': id,
        }, params));
        return this.parseOrder (response);
    }

    async fetchOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let response = await this.privatePostTradeList (this.extend ({
            'type': 'all', // 'open' or 'all'
        }, params));
        // status (open/closed/canceled) is undefined
        return this.parseOrders (response);
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let response = await this.privatePostTradeList (this.extend ({
            'type': 'open', // 'open' or 'all'
        }, params));
        const orders = this.parseOrders (response);
        // btcbox does not return status, but we know it's 'open' as we queried for open orders
        for (let i = 0; i < orders.length; i++) {
            const order = orders[i];
            order['status'] = 'open';
        }
        return orders;
    }

    nonce () {
        return this.milliseconds ();
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'] + '/' + this.version + '/' + path;
        if (api === 'public') {
            if (Object.keys (params).length)
                url += '?' + this.urlencode (params);
        } else {
            this.checkRequiredCredentials ();
            let nonce = this.nonce ().toString ();
            let query = this.extend ({
                'key': this.apiKey,
                'nonce': nonce,
            }, params);
            let request = this.urlencode (query);
            let secret = this.hash (this.encode (this.secret));
            query['signature'] = this.hmac (this.encode (request), this.encode (secret));
            body = this.urlencode (query);
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    handleErrors (httpCode, reason, url, method, headers, body) {
        // typical error response: {"result":false,"code":"401"}
        if (httpCode >= 400)
            return; // resort to defaultErrorHandler
        if (body[0] !== '{')
            return; // not json, resort to defaultErrorHandler
        const response = JSON.parse (body);
        const result = this.safeValue (response, 'result');
        if (typeof result === 'undefined' || result === true)
            return; // either public API (no error codes expected) or success
        const errorCode = this.safeValue (response, 'code');
        const feedback = this.id + ' ' + this.json (response);
        const exceptions = this.exceptions;
        if (errorCode in exceptions)
            throw new exceptions[errorCode] (feedback);
        throw new ExchangeError (feedback); // unknown message
    }
};
<commit_msg>remove fetchTickers and update fetchTiker<commit_after>'use strict';

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

const Exchange = require ('./base/Exchange');
const { ExchangeError, InsufficientFunds, InvalidOrder, AuthenticationError, PermissionDenied, InvalidNonce, OrderNotFound, DDoSProtection } = require ('./base/errors');

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

module.exports = class btcbox extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'btcbox',
            'name': 'BtcBox',
            'countries': [ 'JP' ],
            'rateLimit': 1000,
            'version': 'v1',
            'has': {
                'CORS': false,
                'fetchOrder': true,
                'fetchOrders': true,
                'fetchOpenOrders': true,
                'fetchTickers': false,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/31275803-4df755a8-aaa1-11e7-9abb-11ec2fad9f2d.jpg',
                'api': 'https://www.btcbox.co.jp/api',
                'www': 'https://www.btcbox.co.jp/',
                'doc': 'https://www.btcbox.co.jp/help/asm',
            },
            'api': {
                'public': {
                    'get': [
                        'depth',
                        'orders',
                        'ticker',
                    ],
                },
                'private': {
                    'post': [
                        'balance',
                        'trade_add',
                        'trade_cancel',
                        'trade_list',
                        'trade_view',
                        'wallet',
                    ],
                },
            },
            'markets': {
                'BTC/JPY': { 'id': 'BTC/JPY', 'symbol': 'BTC/JPY', 'base': 'BTC', 'quote': 'JPY' },
                'ETH/JPY': { 'id': 'ETH/JPY', 'symbol': 'ETH/JPY', 'base': 'ETH', 'quote': 'JPY' },
                'LTC/JPY': { 'id': 'LTC/JPY', 'symbol': 'LTC/JPY', 'base': 'LTC', 'quote': 'JPY' },
                'BCH/JPY': { 'id': 'BCH/JPY', 'symbol': 'BCH/JPY', 'base': 'BCH', 'quote': 'JPY' },
            },
            'exceptions': {
                '104': AuthenticationError,
                '105': PermissionDenied,
                '106': InvalidNonce,
                '107': InvalidOrder, // price should be an integer
                '200': InsufficientFunds,
                '201': InvalidOrder, // amount too small
                '202': InvalidOrder, // price should be [0 : 1000000]
                '203': OrderNotFound,
                '401': OrderNotFound, // cancel canceled, closed or non-existent order
                '402': DDoSProtection,
            },
        });
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let balances = await this.privatePostBalance ();
        let result = { 'info': balances };
        let currencies = Object.keys (this.currencies);
        for (let i = 0; i < currencies.length; i++) {
            let currency = currencies[i];
            let lowercase = currency.toLowerCase ();
            if (lowercase === 'dash')
                lowercase = 'drk';
            let account = this.account ();
            let free = lowercase + '_balance';
            let used = lowercase + '_lock';
            if (free in balances)
                account['free'] = parseFloat (balances[free]);
            if (used in balances)
                account['used'] = parseFloat (balances[used]);
            account['total'] = this.sum (account['free'], account['used']);
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let request = {};
        let numSymbols = this.symbols.length;
        if (numSymbols > 1)
            request['coin'] = market['id'];
        let orderbook = await this.publicGetDepth (this.extend (request, params));
        return this.parseOrderBook (orderbook);
    }

    parseTicker (ticker, market = undefined) {
        let timestamp = this.milliseconds ();
        let symbol = undefined;
        if (market)
            symbol = market['symbol'];
        let last = this.safeFloat (ticker, 'last');
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': this.safeFloat (ticker, 'high'),
            'low': this.safeFloat (ticker, 'low'),
            'bid': this.safeFloat (ticker, 'buy'),
            'bidVolume': undefined,
            'ask': this.safeFloat (ticker, 'sell'),
            'askVolume': undefined,
            'vwap': undefined,
            'open': undefined,
            'close': last,
            'last': last,
            'previousClose': undefined,
            'change': undefined,
            'percentage': undefined,
            'average': undefined,
            'baseVolume': this.safeFloat (ticker, 'vol'),
            'quoteVolume': this.safeFloat (ticker, 'volume'),
            'info': ticker,
        };
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let request = {};
        let numSymbols = this.symbols.length;
        if (numSymbols > 1)
            request['coin'] = market['base'].toLowerCase ();
        let ticker = await this.publicGetTicker (this.extend (request, params));
        return this.parseTicker (ticker, market);
    }

    parseTrade (trade, market) {
        let timestamp = parseInt (trade['date']) * 1000; // GMT time
        return {
            'info': trade,
            'id': trade['tid'],
            'order': undefined,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'type': undefined,
            'side': trade['type'],
            'price': trade['price'],
            'amount': trade['amount'],
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let request = {};
        let numSymbols = this.symbols.length;
        if (numSymbols > 1)
            request['coin'] = market['id'];
        let response = await this.publicGetOrders (this.extend (request, params));
        return this.parseTrades (response, market, since, limit);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let request = {
            'amount': amount,
            'price': price,
            'type': side,
        };
        let numSymbols = this.symbols.length;
        if (numSymbols > 1)
            request['coin'] = market['id'];
        let response = await this.privatePostTradeAdd (this.extend (request, params));
        return {
            'info': response,
            'id': response['id'],
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        return await this.privatePostTradeCancel (this.extend ({
            'id': id,
        }, params));
    }

    parseOrder (order) {
        // {"id":11,"datetime":"2014-10-21 10:47:20","type":"sell","price":42000,"amount_original":1.2,"amount_outstanding":1.2,"status":"closed","trades":[]}
        const id = this.safeString (order, 'id');
        const timestamp = this.parse8601 (order['datetime'] + '+09:00'); // Tokyo time
        const amount = this.safeFloat (order, 'amount_original');
        const remaining = this.safeFloat (order, 'amount_outstanding');
        let filled = undefined;
        if (typeof amount !== 'undefined')
            if (typeof remaining !== 'undefined')
                filled = amount - remaining;
        const price = this.safeFloat (order, 'price');
        let cost = undefined;
        if (typeof price !== 'undefined')
            if (typeof filled !== 'undefined')
                cost = filled * price;
        // status is set by fetchOrder method only
        const statuses = {
            // TODO: complete list
            'part': 'open', // partially or not at all executed
            'all': 'closed', // fully executed
            'cancelled': 'canceled',
            'closed': 'closed', // never encountered, seems to be bug in the doc
        };
        let status = undefined;
        if (order['status'] in statuses)
            status = statuses[order['status']];
        // fetchOrders do not return status, use heuristic
        if (typeof status === 'undefined')
            if (typeof remaining !== 'undefined' && remaining === 0)
                status = 'closed';
        let trades = undefined; // todo: this.parseTrades (order['trades']);
        return {
            'id': id,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'lastTradeTimestamp': undefined,
            'amount': amount,
            'remaining': remaining,
            'filled': filled,
            'side': order['type'],
            'type': undefined,
            'status': status,
            'symbol': 'BTC/JPY',
            'price': price,
            'cost': cost,
            'trades': trades,
            'fee': undefined,
            'info': order,
        };
    }

    async fetchOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        let response = await this.privatePostTradeView (this.extend ({
            'id': id,
        }, params));
        return this.parseOrder (response);
    }

    async fetchOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let response = await this.privatePostTradeList (this.extend ({
            'type': 'all', // 'open' or 'all'
        }, params));
        // status (open/closed/canceled) is undefined
        return this.parseOrders (response);
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let response = await this.privatePostTradeList (this.extend ({
            'type': 'open', // 'open' or 'all'
        }, params));
        const orders = this.parseOrders (response);
        // btcbox does not return status, but we know it's 'open' as we queried for open orders
        for (let i = 0; i < orders.length; i++) {
            const order = orders[i];
            order['status'] = 'open';
        }
        return orders;
    }

    nonce () {
        return this.milliseconds ();
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'] + '/' + this.version + '/' + path;
        if (api === 'public') {
            if (Object.keys (params).length)
                url += '?' + this.urlencode (params);
        } else {
            this.checkRequiredCredentials ();
            let nonce = this.nonce ().toString ();
            let query = this.extend ({
                'key': this.apiKey,
                'nonce': nonce,
            }, params);
            let request = this.urlencode (query);
            let secret = this.hash (this.encode (this.secret));
            query['signature'] = this.hmac (this.encode (request), this.encode (secret));
            body = this.urlencode (query);
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    handleErrors (httpCode, reason, url, method, headers, body) {
        // typical error response: {"result":false,"code":"401"}
        if (httpCode >= 400)
            return; // resort to defaultErrorHandler
        if (body[0] !== '{')
            return; // not json, resort to defaultErrorHandler
        const response = JSON.parse (body);
        const result = this.safeValue (response, 'result');
        if (typeof result === 'undefined' || result === true)
            return; // either public API (no error codes expected) or success
        const errorCode = this.safeValue (response, 'code');
        const feedback = this.id + ' ' + this.json (response);
        const exceptions = this.exceptions;
        if (errorCode in exceptions)
            throw new exceptions[errorCode] (feedback);
        throw new ExchangeError (feedback); // unknown message
    }
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

/**
 * Video Schema
 */
var VideoSchema = new Schema({
    created: {
        type: Date,
        default: Date.now
    },
    title: {
        type: String,
        default: '',
        trim: true
    },
    url: {
        type: String,
        default: '',
        trim: true
    },
    live: {
        type: Boolean,
        default: false
    },
    user: {
        type: Schema.ObjectId,
        ref: 'user'
//    },
//    event: {
//        type: Schema.ObjectId,
//        ref: 'Event'
    }
});

/**
 * Validations
 */
VideoSchema.path('title').validate(function(title) {
    return title.length;
}, 'Title cannot be blank');

VideoSchema.path('url').validate(function(url) {
    return url.length;
}, 'Url cannot be blank');

/**
 * Statics
 */
VideoSchema.statics.load = function(id, cb) {
    this.findOne({
        _id: id
    }).populate('user', 'name username').exec(cb);
};

mongoose.model('Video', VideoSchema);
<commit_msg>schema fix<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

/**
 * Video Schema
 */
var VideoSchema = new Schema({
    created: {
        type: Date,
        default: Date.now
    },
    title: {
        type: String,
        default: '',
        trim: true
    },
    url: {
        type: String,
        default: '',
        trim: true
    },
    live: {
        type: Boolean,
        default: false
    },
    user: {
        type: Schema.ObjectId,
        ref: 'User'
//    },
//    event: {
//        type: Schema.ObjectId,
//        ref: 'Event'
    }
});

/**
 * Validations
 */
VideoSchema.path('title').validate(function(title) {
    return title.length;
}, 'Title cannot be blank');

VideoSchema.path('url').validate(function(url) {
    return url.length;
}, 'Url cannot be blank');

/**
 * Statics
 */
VideoSchema.statics.load = function(id, cb) {
    this.findOne({
        _id: id
    }).populate('user', 'name username').exec(cb);
};

mongoose.model('Video', VideoSchema);
<|endoftext|>


<commit_before>// This file is not used in production.
/* eslint-disable import/no-extraneous-dependencies */

const path = require('path');
const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const baseConfig = require('./webpack.base');

module.exports = webpackMerge(baseConfig, {
    entry: [
        'react-hot-loader/patch',
        './doc/index.js'
    ],

    output: {
        publicPath: '/'
    },

    module: {
        rules: [
            {
                test: /\.jsx?$/,
                include: [
                    path.resolve(__dirname, '../src'),
                    path.resolve(__dirname, '../doc')
                ],
                enforce: 'pre',
                loader: 'eslint-loader',
                options: {
                    /**
                     * Report every eslint error as a warning.
                     *
                     * This prevents Webpack dev-server from blocking HMR updates only because
                     * eslint fails. `create-react-app` also chooses to use only warnings,
                     * since `eslint-loader` has already make warnings “very visible”.
                     *
                     * Ref: https://git.io/vyu8d
                     */
                    emitWarning: true
                }
            },
        ]
    },

    devtool: 'inline-source-map',

    devServer: {
        compress: true,
        contentBase: false,
        hotOnly: true,
        port: 3100,
        publicPath: '/',
        stats: {
            assets: false,
            children: false,
            chunkModules: false,
            hash: false,
            version: false
        },
        watchOptions: {
            ignored: /node_modules/
        }
    },

    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NamedModulesPlugin(),
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: './demo/index.html',
            hash: false,
            minify: {
                collapseWhitespace: true
            }
        })
    ]
});
<commit_msg>[webpack] Rename demo entry<commit_after>// This file is not used in production.
/* eslint-disable import/no-extraneous-dependencies */

const path = require('path');
const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const baseConfig = require('./webpack.base');

module.exports = webpackMerge(baseConfig, {
    entry: [
        'react-hot-loader/patch',
        './demo/index.js'
    ],

    output: {
        filename: 'gypcrete-demo.js',
        publicPath: '/'
    },

    module: {
        rules: [
            {
                test: /\.jsx?$/,
                include: [
                    path.resolve(__dirname, '../src'),
                    path.resolve(__dirname, '../demo')
                ],
                enforce: 'pre',
                loader: 'eslint-loader',
                options: {
                    /**
                     * Report every eslint error as a warning.
                     *
                     * This prevents Webpack dev-server from blocking HMR updates only because
                     * eslint fails. `create-react-app` also chooses to use only warnings,
                     * since `eslint-loader` has already make warnings “very visible”.
                     *
                     * Ref: https://git.io/vyu8d
                     */
                    emitWarning: true
                }
            },
            {
                test: /\.jsx?$/,
                include: [
                    path.resolve(__dirname, '../demo')
                ],
                use: ['babel-loader']
            }
        ]
    },

    devtool: 'source-map',

    devServer: {
        compress: true,
        contentBase: false,
        hotOnly: true,
        port: 3100,
        publicPath: '/',
        stats: {
            assets: false,
            children: false,
            chunkModules: false,
            hash: false,
            version: false
        },
        watchOptions: {
            ignored: /node_modules/
        }
    },

    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NamedModulesPlugin(),
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: './demo/index.html',
            hash: false,
            minify: {
                collapseWhitespace: true
            }
        })
    ]
});
<|endoftext|>


<commit_before>import './oauth_config.js';
export * from './apollo_server.js';
import './intl_polyfill.js';
import './site.js';

import './connectors/mongo.js';

export * from './connectors.js';
export * from './query.js';
export * from './meteor_patch.js';
export * from '../modules/index.js';
export * from './mutators.js';
export * from './render_context.js';
export * from './inject_data.js';
<commit_msg>reexport utils on server<commit_after>import './oauth_config.js';
export * from './apollo_server.js';
import './intl_polyfill.js';
import './site.js';

import './connectors/mongo.js';

export * from './connectors.js';
export * from './query.js';
export * from './meteor_patch.js';
export * from '../modules/index.js';
export * from './mutators.js';
export * from './render_context.js';
export * from './inject_data.js';
export * from './utils.js';
<|endoftext|>


<commit_before>var webpack = require('webpack');
var webpackMerge = require('webpack-merge');
const TerserJSPlugin = require("terser-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const RemoveStrictPlugin = require('remove-strict-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');

const ENV = process.env.NODE_ENV = process.env.ENV = 'production';

function createConfig(target){
  filenameInsert = target === 'var' ? '.' : '.' + target + '.';
  return webpackMerge(commonConfig, {
    mode: 'production',
    output: {
      path: helpers.root('dist'),
      publicPath: '/dist/',
      filename: '[name]' + filenameInsert + 'js',
      chunkFilename: '[id]' + filenameInsert + 'chunk.js',
      libraryTarget:target
        // 'amd' // e2e n, import y
        // 'var' // e2e y, import n
        // 'assign' // e2e n, import n
        // 'global'  // e2e y, import
    },

    optimization:{
      // Enabling splitChunks seems to stop the global JSONEditor object being set
      /*
      splitChunks:{
        chunks:'all'
      },
      */
      minimize:true
    },

    plugins: [
      // new CleanWebpackPlugin({ // Clean all but dev subdirectory before building
      //   cleanOnceBeforeBuildPatterns: ['**/*',
      //    // '!dev/**/*'      // doesn't work
      //    '!dev/**'      // works
      //   ],
      // }),
      new RemoveStrictPlugin(),           // I have put this in to avoid IE throwing error Assignment to read-only properties is not allowed in strict mode
      // This doesn't seem to actually be minimising the CSS!
      new OptimizeCSSAssetsPlugin({
        cssProcessor: require('cssnano'),
        cssProcessorPluginOptions: {
          preset: ['default', { discardComments: { removeAll: true } }],
        }/*,
        canPrint: true*/
      }),
      new webpack.NoEmitOnErrorsPlugin(),
      new MiniCssExtractPlugin({
        // Options similar to the same options in webpackOptions.output
        // all options are optional
        filename: '[name].[hash].css',
        chunkFilename: '[id].css',
        ignoreOrder: false, // Enable to remove warnings about conflicting order
      }),
      new webpack.DefinePlugin({
        'process.env': {
          'ENV': JSON.stringify(ENV)
        }
      })
    ],

    devServer: {
      contentBase: helpers.root('.'),
      historyApiFallback: true,
      stats: 'minimal',
      port:8080
    }

  });
}

module.exports = [
  createConfig('var'),
  createConfig('amd')
];<commit_msg>removed comments<commit_after>var webpack = require('webpack');
var webpackMerge = require('webpack-merge');
const TerserJSPlugin = require("terser-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const RemoveStrictPlugin = require('remove-strict-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');

const ENV = process.env.NODE_ENV = process.env.ENV = 'production';

function createConfig(target){
  filenameInsert = target === 'var' ? '.' : '.' + target + '.';
  return webpackMerge(commonConfig, {
    mode: 'production',
    output: {
      path: helpers.root('dist'),
      publicPath: '/dist/',
      filename: '[name]' + filenameInsert + 'js',
      chunkFilename: '[id]' + filenameInsert + 'chunk.js',
      libraryTarget:target
    },

    optimization:{
      minimize:true
    },

    plugins: [
      new RemoveStrictPlugin(),           // I have put this in to avoid IE throwing error Assignment to read-only properties is not allowed in strict mode
      // This doesn't seem to actually be minimising the CSS!
      new OptimizeCSSAssetsPlugin({
        cssProcessor: require('cssnano'),
        cssProcessorPluginOptions: {
          preset: ['default', { discardComments: { removeAll: true } }],
        }
      }),
      new webpack.NoEmitOnErrorsPlugin(),
      new MiniCssExtractPlugin({
        // Options similar to the same options in webpackOptions.output
        // all options are optional
        filename: '[name].[hash].css',
        chunkFilename: '[id].css',
        ignoreOrder: false, // Enable to remove warnings about conflicting order
      }),
      new webpack.DefinePlugin({
        'process.env': {
          'ENV': JSON.stringify(ENV)
        }
      })
    ],

    devServer: {
      contentBase: helpers.root('.'),
      historyApiFallback: true,
      stats: 'minimal',
      port:8080
    }

  });
}

module.exports = [
  createConfig('var'),
  createConfig('amd')
];<|endoftext|>


<commit_before>function detectUserAgent() {
  var match = navigator.userAgent.match(/(firefox|safari|chrome|opera|msie)/i);
  if (match) {
    $('body').addClass(match[0].toLowerCase());
  }
  return true;
}

function romanize (num) {
	if (!+num)
		return false;
	var	digits = String(+num).split(""),
		key = ["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM",
		       "","X","XX","XXX","XL","L","LX","LXX","LXXX","XC",
		       "","I","II","III","IV","V","VI","VII","VIII","IX"],
		roman = "",
		i = 3;
	while (i--)
		roman = (key[+digits.pop() + (i * 10)] || "") + roman;
	return Array(+digits.join("") + 1).join("M") + roman;
}

function toc(refs) {
  toc = $('div.toc li');
  $.each(toc, function(i, v) {
    element = toc.slice(i, i+1);
    link = element.children('a');
    tag = link.attr('href').slice(1);
    text = link.text();
    width = link.innerWidth();
    page_number = refs[tag];
    element.prepend('
 ' + page_number + '
');
    pn = element.children('div.toc_page_number').first();
    while (width + pn.innerWidth() < element.innerWidth()) {
      pn.prepend('.');
    }
    pn[0].removeChild(pn[0].firstChild);
  });
}

function typeset(tag) {
  var $nodes = $(tag).children('[class!="not-rendered"]');
  var $old_nodes = $nodes;

  var aux_pages = 1;
  var pages = 0;

  var page_name;

  var toc_refs = {};

  var body = $(tag);
  body.prepend('

');
  var last_page = $('#page-0');

  function form_page() {
    if (pages != 0) {
      page_name = pages;
    }
    else {
      page_name = romanize(aux_pages).toLowerCase();
    }

    $('

').insertAfter(last_page);

    var page = $('#page-' + page_name);
    last_page = page;

    var pageBreak = false;

    var padder;
    var pad_strategy;

    var page_height = page.height() - 10;

    var curY = 0;
    while($nodes.length > 0) {
      var node = $nodes.first();
      if (node.is('script')) {
        $nodes = $nodes.slice(1);
        continue;
      }

      if (curY > 0 && node.is('h1')) {
        // End the page
        pageBreak = true;
      }

      var new_node = node.clone();
      page.append(new_node);

      obj_height = new_node.outerHeight(true);
      if (pageBreak || curY + obj_height > page_height) {
        new_node.remove();

        if (node.is('p') && !pageBreak) {
          p = node.clone();
          p.empty();
          p.addClass('split');
          page.append(p);
          p = page.children("p.split");

          // Break up the paragraph
          var $contents = node.contents();
          var $words = new Array();
          for (var i = 0; i < $contents.length; i++) {
            if ($contents[i].nodeType == 3) {
              jQuery.each($contents[i].nodeValue.split(' '), function() {
                $words[$words.length] = this;
              });
            }
            else {
              var ntag = $contents[i].nodeName;
              var text = $contents[i].firstChild.nodeValue;

              jQuery.each(text.split(' '), function() {
                $words[$words.length] = "<" + ntag + ">" + this + "</" + ntag + ">";
              });
            }
          }

          for(var i = 0; i < $words.length; i++) {
            var word = $words[i];
            p.append(' ');
            p.append(word);
            obj_height = p.outerHeight(true);
            if (curY + obj_height > page_height) {
              // Remove word
              p[0].removeChild(p[0].lastChild);
              p[0].removeChild(p[0].lastChild);

              // Reform rest of paragraph
              node.empty();
              for ( ; i < $words.length; i++) {
                node.addClass('split-next');
                node.append(' ');
                node.append($words[i]);
              }
              break;
            }
          }

          obj_height = p.outerHeight(true);
          curY = (p.position().top - page.position().top) + obj_height;
        }

        // Space to play with
        var diff_height = page_height - curY;

        var $ps = page.children('p + p');
        var $divs = page.children('div');
        var $hs = page.children('h2');

        if (($divs.length + $hs.length) > 0) {
          var num_things = $ps.length + (2 * $divs.length) + (3 * $hs.length);

          var padding = diff_height / num_things;
          $ps.css('margin-top',      '+=' + padding);
          $divs.css('margin-top',    '+=' + padding);
          $divs.css('margin-bottom', '+=' + padding);
          $hs.css('margin-top',      '+=' + 3*padding);

          curY = page_height;
          diff_height = 0;
        }

        // Append footer
        page.append("
" + page_name + "
");
        page.children("div.footer").css("margin-top", "+=" + diff_height);

        if (pageBreak && pages == 0) { pages = 1; return; }
        break;
      }

      // Node Added
      if (node.attr('id')) {
        toc_refs[node.attr('id')] = page_name;
      }

      curY = (new_node.position().top - page.position().top) + obj_height;

      if (node.is('h2') || node.is('h3')) {
        padder = new_node;
        pad_strategy = "push_down";
      }
      else if (node.is('div') || node.is('blockquote')) {
        padder = new_node;
        pad_strategy = "float";
      }

      node.remove();
      $nodes = $nodes.slice(1);
    }

    if (pages > 0) {
      pages++;
    }
    else {
      aux_pages++;
    }
  }

  while ($nodes.length > 0) {
    form_page();
  }

  // Do table of contents
  toc(toc_refs);
  return true;
}

$(window).bind('load', function() {
  detectUserAgent();
  typeset('body');
});
<commit_msg>Fixes typesetter where it tries to pad on a pagebreak.<commit_after>function detectUserAgent() {
  var match = navigator.userAgent.match(/(firefox|safari|chrome|opera|msie)/i);
  if (match) {
    $('body').addClass(match[0].toLowerCase());
  }
  return true;
}

function romanize (num) {
	if (!+num)
		return false;
	var	digits = String(+num).split(""),
		key = ["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM",
		       "","X","XX","XXX","XL","L","LX","LXX","LXXX","XC",
		       "","I","II","III","IV","V","VI","VII","VIII","IX"],
		roman = "",
		i = 3;
	while (i--)
		roman = (key[+digits.pop() + (i * 10)] || "") + roman;
	return Array(+digits.join("") + 1).join("M") + roman;
}

function toc(refs) {
  toc = $('div.toc li');
  $.each(toc, function(i, v) {
    element = toc.slice(i, i+1);
    link = element.children('a');
    tag = link.attr('href').slice(1);
    text = link.text();
    width = link.innerWidth();
    page_number = refs[tag];
    element.prepend('
 ' + page_number + '
');
    pn = element.children('div.toc_page_number').first();
    while (width + pn.innerWidth() < element.innerWidth()) {
      pn.prepend('.');
    }
    pn[0].removeChild(pn[0].firstChild);
  });
}

function typeset(tag) {
  var $nodes = $(tag).children('[class!="not-rendered"]');
  var $old_nodes = $nodes;

  var aux_pages = 1;
  var pages = 0;

  var page_name;

  var toc_refs = {};

  var body = $(tag);
  body.prepend('

');
  var last_page = $('#page-0');

  function form_page() {
    if (pages != 0) {
      page_name = pages;
    }
    else {
      page_name = romanize(aux_pages).toLowerCase();
    }

    $('

').insertAfter(last_page);

    var page = $('#page-' + page_name);
    last_page = page;

    var pageBreak = false;

    var padder;
    var pad_strategy;

    var page_height = page.height() - 10;

    var curY = 0;
    while($nodes.length > 0) {
      var node = $nodes.first();
      if (node.is('script')) {
        $nodes = $nodes.slice(1);
        continue;
      }

      if (curY > 0 && node.is('h1')) {
        // End the page
        pageBreak = true;
      }

      var new_node = node.clone();
      page.append(new_node);

      obj_height = new_node.outerHeight(true);
      if (pageBreak || curY + obj_height > page_height) {
        new_node.remove();

        if (node.is('p') && !pageBreak) {
          p = node.clone();
          p.empty();
          p.addClass('split');
          page.append(p);
          p = page.children("p.split");

          // Break up the paragraph
          var $contents = node.contents();
          var $words = new Array();
          for (var i = 0; i < $contents.length; i++) {
            if ($contents[i].nodeType == 3) {
              jQuery.each($contents[i].nodeValue.split(' '), function() {
                $words[$words.length] = this;
              });
            }
            else {
              var ntag = $contents[i].nodeName;
              var text = $contents[i].firstChild.nodeValue;

              jQuery.each(text.split(' '), function() {
                $words[$words.length] = "<" + ntag + ">" + this + "</" + ntag + ">";
              });
            }
          }

          for(var i = 0; i < $words.length; i++) {
            var word = $words[i];
            p.append(' ');
            p.append(word);
            obj_height = p.outerHeight(true);
            if (curY + obj_height > page_height) {
              // Remove word
              p[0].removeChild(p[0].lastChild);
              p[0].removeChild(p[0].lastChild);

              // Reform rest of paragraph
              node.empty();
              for ( ; i < $words.length; i++) {
                node.addClass('split-next');
                node.append(' ');
                node.append($words[i]);
              }
              break;
            }
          }

          obj_height = p.outerHeight(true);
          curY = (p.position().top - page.position().top) + obj_height;
        }

        // Space to play with
        var diff_height = page_height - curY;

        var $ps = page.children('p + p');
        var $divs = page.children('div');
        var $hs = page.children('h2');

        if (!pageBreak && ($divs.length + $hs.length) > 0) {
          var num_things = $ps.length + (2 * $divs.length) + (3 * $hs.length);

          var padding = diff_height / num_things;
          $ps.css('margin-top',      '+=' + padding);
          $divs.css('margin-top',    '+=' + padding);
          $divs.css('margin-bottom', '+=' + padding);
          $hs.css('margin-top',      '+=' + 3*padding);

          curY = page_height;
          diff_height = 0;
        }

        // Append footer
        page.append("
" + page_name + "
");
        page.children("div.footer").css("margin-top", "+=" + diff_height);

        if (pageBreak && pages == 0) { pages = 1; return; }
        break;
      }

      // Node Added
      if (node.attr('id')) {
        toc_refs[node.attr('id')] = page_name;
      }

      curY = (new_node.position().top - page.position().top) + obj_height;

      if (node.is('h2') || node.is('h3')) {
        padder = new_node;
        pad_strategy = "push_down";
      }
      else if (node.is('div') || node.is('blockquote')) {
        padder = new_node;
        pad_strategy = "float";
      }

      node.remove();
      $nodes = $nodes.slice(1);
    }

    if (pages > 0) {
      pages++;
    }
    else {
      aux_pages++;
    }
  }

  while ($nodes.length > 0) {
    form_page();
  }

  // Do table of contents
  toc(toc_refs);
  return true;
}

$(window).bind('load', function() {
  detectUserAgent();
  typeset('body');
});
<|endoftext|>


<commit_before>define(['jquery', 'base/js/dialog'], function ($, dialog) {
    var api = "/spark/api/v1";

    var show_running_jobs = function() {
        var element = $('<div/>');

        $.getJSON(api + '/applications').done(function(data) {
            data.forEach(function(e, i) {
                var application_div = $('<div/>');
                application_div.append($('<h5/>').text(e.name + ': ' + e.id));
                var application_table = $('<table/>').addClass('table table-hover');

                var header_row = $('<tr/>');
                header_row.append($('<th/>').text('Job ID'));
                header_row.append($('<th/>').text('Job Name'));
                header_row.append($('<th/>').text('Progress'));
                application_table.append(header_row);

                $.getJSON(api + '/applications/' + e.id + '/jobs').done(function (jobs) {
                    jobs.forEach(function(e, i) {
                        var row = $('<tr/>');
                        row.append($('<td/>').text(e.jobId));
                        row.append($('<td/>').text(e.name));

                        var status_class;
                        switch(e.status) {
                            case 'SUCCEEDED':
                                status_class = 'progress-bar-success';
                                break;
                            case 'RUNNING':
                                status_class = 'progress-bar-info';
                                break;
                            case 'FAILED':
                                status_class = 'progress-bar-danger';
                                break;
                            case 'UNKNOWN':
                                status_class = 'progress-bar-warning';
                                break;
                        }

                        // progress defined in percent
                        var progress = e.numCompletedTasks / e.numTasks * 100;

                        var progress_bar_div = $('<div/>').addClass('progress').css({'min-width': '100px', 'margin-bottom': 0});
                        var progress_bar = $('<div/>')
                            .addClass('progress-bar ' + status_class)
                            .attr('role', 'progressbar')
                            .attr('aria-valuenow', progress)
                            .attr('aria-valuemin', 0)
                            .attr('aria-valuemax', 100)
                            .css('width', progress + '%')
                            .text(e.numCompletedTasks + ' out of ' + e.numTasks + ' tasks');
                        progress_bar_div.append(progress_bar);
                        row.append($('<td/>').append(progress_bar_div));

                        application_table.append(row);
                    });
                });
                application_div.append(application_table);
                element.append(application_div);
            });
        });

        var modal = dialog.modal({
            title: "Running Spark Jobs",
            body: element,
            buttons: {
                "Close": {}
            }
        });
        modal.addClass("modal_stretch");
    };

    var load_ipython_extension = function () {
        Jupyter.keyboard_manager.command_shortcuts.add_shortcut('Alt-S', show_running_jobs);
        Jupyter.toolbar.add_buttons_group([{
            'label':    'show running Spark jobs',
            'icon':     'fa-tasks',
            'callback': show_running_jobs,
            'id':       'show_running_jobs'
        }]);
    };

    return {
        load_ipython_extension: load_ipython_extension
    };
});<commit_msg>ui is added to code cell when executed<commit_after>define([
    'jquery',
    'base/js/dialog',
    'base/js/events',
    'notebook/js/codecell'
    ], function ($, dialog, events, codecell) {
    var api = "/spark/api/v1";
    var CodeCell = codecell.CodeCell;

    var show_running_jobs = function() {
        var element = $('<div/>');

        $.getJSON(api + '/applications').done(function(data) {
            data.forEach(function(e, i) {
                var application_div = $('<div/>');
                application_div.append($('<h5/>').text(e.name + ': ' + e.id));
                var application_table = $('<table/>').addClass('table table-hover');

                var header_row = $('<tr/>');
                header_row.append($('<th/>').text('Job ID'));
                header_row.append($('<th/>').text('Job Name'));
                header_row.append($('<th/>').text('Progress'));
                application_table.append(header_row);

                $.getJSON(api + '/applications/' + e.id + '/jobs').done(function (jobs) {
                    jobs.forEach(function(e, i) {
                        var row = $('<tr/>');
                        row.append($('<td/>').text(e.jobId));
                        row.append($('<td/>').text(e.name));

                        var status_class;
                        switch(e.status) {
                            case 'SUCCEEDED':
                                status_class = 'progress-bar-success';
                                break;
                            case 'RUNNING':
                                status_class = 'progress-bar-info';
                                break;
                            case 'FAILED':
                                status_class = 'progress-bar-danger';
                                break;
                            case 'UNKNOWN':
                                status_class = 'progress-bar-warning';
                                break;
                        }

                        // progress defined in percent
                        var progress = e.numCompletedTasks / e.numTasks * 100;

                        var progress_bar_div = $('<div/>').addClass('progress').css({'min-width': '100px', 'margin-bottom': 0});
                        var progress_bar = $('<div/>')
                            .addClass('progress-bar ' + status_class)
                            .attr('role', 'progressbar')
                            .attr('aria-valuenow', progress)
                            .attr('aria-valuemin', 0)
                            .attr('aria-valuemax', 100)
                            .css('width', progress + '%')
                            .text(e.numCompletedTasks + ' out of ' + e.numTasks + ' tasks');
                        progress_bar_div.append(progress_bar);
                        row.append($('<td/>').append(progress_bar_div));

                        application_table.append(row);
                    });
                });
                application_div.append(application_table);
                element.append(application_div);
            });
        });

        var modal = dialog.modal({
            title: "Running Spark Jobs",
            body: element,
            buttons: {
                "Close": {}
            }
        });
        modal.addClass("modal_stretch");
    };

    var spark_progress_bar = function(event, data) {
        var cell = data.cell;
        if (is_spark_cell(cell)) {
            add_progress_bar(cell);
        }
    }

    var add_progress_bar = function(cell) {
        var progress_bar_div = cell.element.find('.progress_bar');
        if (progress_bar_div.length < 1) {
            var input_area = cell.element.find('.input_area');

            progress_bar_div = $('<div/>')
                .addClass('progress_bar')
                .appendTo(input_area);
        }
        var msg = "Progress bar goes here";
        progress_bar_div.text(msg);
    }

    var is_spark_cell = function(cell) {
        // TODO: Find a way to detect if cell is actually running Spark
        return (cell instanceof CodeCell)
    }

    var load_ipython_extension = function () {

        events.on('execute.CodeCell', spark_progress_bar);

        Jupyter.keyboard_manager.command_shortcuts.add_shortcut('Alt-S', show_running_jobs);
        Jupyter.toolbar.add_buttons_group([{
            'label':    'show running Spark jobs',
            'icon':     'fa-tasks',
            'callback': show_running_jobs,
            'id':       'show_running_jobs'
        }]);
    };

    return {
        load_ipython_extension: load_ipython_extension
    };
});<|endoftext|>