<commit_before>// James, I've put comments with your name on parts of code that I have questions for.
// Some of the logic issues I have involve where the betting functions need to be stored. Their own prototype? On the playerOne
// instance but not on the Dealer instance? etc ...
/*
  @james-huston my initial thought on the betting would be to have it as something seperate that way the player logic could all
  be shared between the player/dealer. You might consider a game "controller" class like your game UI that you attach the dealer
  and any players to. when the UI needs to do something like place a bet it asks the game controller to handle it and the game
  controller to make a bet for that player or something like that.
*/
// I created a GameUI constructor b/c it seems weird to not have those similar items stored somewhere
// even if that may change down the line. What do I do with all of the eventListeners and stuff? Can that code go
// down at the bottom of the page just sort of loose and unassociated with a prototype.
/*
  @james-huston I would attach all of the event listeners to your gameui prototype
*/

// Overall, I feel confident with how and why my code needs to be structured this way. I understand why and how the code I've writtien
// works. I just know that the decision-making and organization are skills that will come with time.

// constructor
function Player() {
	this.cards = [];
	this.score = 0;
	this.wager = 0;
}

Player.prototype.receiveCard = function(card){
	this.card.push(card);
};

// constructor
function PlayerUI(name){
	this.name = name;
  	this.cardDom = undefined;
  	this.scoreDom = undefined;
}

// setCardDom method
// 		James, why does this need to be a method?
//		Why can't it just be assigned like a variable?
/*
  @james-huston the reason to do this is so you have a chance to validate it and make sure that it is actually
  a dom element you can manipulate. remember you don't have jquery doing all of it's "magical" silent checking
  on elements when you try to modify them so you need to make sure you have a valid element that you can work
  with whatever way you plan to work with it. Maybe not 100% relevent for your project but in shared/reusable
  code it would be a good thing to be safe with.
*/
PlayerUI.prototype.setCardDom = function(element){
  	this.cardDom = element;
};

PlayerUI.prototype.setScoreDom = function(element){
  	this.scoreDom = element;
};

// constructor
function GameUI(){
	this.dealButton = document.getElementById('deal-button');
	this.hitButton = document.getElementById('hit-me');
	this.stayButton = document.getElementById('stay');
	this.resetButton = document.getElementById('reset');
}

// constructor
function Card(definedCard) {
	// this ensures that if we're not passed an object, we throw an error
	if (definedCard !== undefined && 'object' !== typeof definedCard) {
		throw new Error('');
	}

	this.suit = definedCard.suit;
	this.symbol = definedCard.symbol;
	this.color = definedCard.color;
	this.face = definedCard.face;
	this.name = definedCard.name;
	this.value = definedCard.value;
}

// constructor
function Deck(){
	this.suits = {
		0: {
			'suit': 'diamonds',
			'symbol': '♦',
			'color': 'red'
		},

		1: {
			'suit': 'hearts',
			'symbol': '♥',
			'color': 'red'
		},

		2: {
			'suit': 'clubs',
			'symbol': '♣',
			'color': 'black'
		},

		3: {
			'suit': 'spades',
			'symbol': '♠',
			'color': 'black'
		}
	}; // close suits

	this.cards = {
		1: {
			'name': 'ace',
			'face': 'A',
			'value': 1
		},

		2: {
			'name': 'two',
			'face': '2',
			'value': 2
		},

		3: {
			'name': 'three',
			'face': 3,
			'value': 3
		},

		4: {
			'name': 'four',
			'face': '4',
			'value': 4
		},

		5: {
			'name': 'five',
			'face': '5',
			'value': 5
		},

		6: {
			'name': 'six',
			'face': '6',
			'value': 6
		},

		7: {
			'name': 'seven',
			'face': '7',
			'value': 7
		},

		8: {
			'name': 'eight',
			'face': '8',
			'value': 8
		},

		9: {
			'name': 'nine',
			'face': '9',
			'value': 9
		},

		10: {
			'name': 'ten',
			'face': '10',
			'value': 10
		},

		11: {
			'name': 'jack',
			'face': 'J',
			'value': 10
		},

		12: {
			'name': 'queen',
			'face': 'Q',
			'value': 10
		},

		13: {
			'name': 'king',
			'face': 'K',
			'value': 10
		},

		14: {
			'name': 'ace',
			'face': 'A',
			'value': 11
		}
	}; // close cards
}

// James, I'm starting to combine methods under one prototype. I saw this syntax and it makes sense to me. It also
// kind of answers my question about the use of "constructor: 'constructorName' " as a syntax
/*
  @james-huston this if fine if you are more comfortable with it and working in your own project/setting your
  own coding standards. Just make sure you are comfortable with other styles so you recognize them and can
  work with other code comfortably and you are good.
*/
Deck.prototype = {
	constructor: Deck,
	dealRandomCard: function(){
		var suitType = Math.floor(Math.random() * 4);
		var cardNumber = Math.floor(Math.random() * 13) + 1;

		var randomCard = new Card({
			suit: this.suits[suitType].suit,
			symbol: this.suits[suitType].symbol,
			color: this.suits[suitType].color,
			face: this.cards[cardNumber].face,
			name: this.cards[cardNumber].name,
			value: this.cards[cardNumber].value
		});

		// console.log(randomCard);
		return randomCard;
	},
	dealCards: function(user, number){
		for (var i = 0; i < number; i++) {
			this.dealRandomCard(user);
			// James, I'm in the process of making this logic work.
			// this doesn't return correctly ... yet
		}
	}
};

/*
  @james-huston so these things right now are kinda disparent "things" that just happen. These would be things
  handled by your game controller constructor if you had one.
*/
var playerOne = new Player();
var playerRender = new PlayerUI('John');

var gameDealer = new Player();
var dealerRender = new PlayerUI('Dealer');

var myDeck = new Deck();

myDeck.dealRandomCard();
myDeck.dealCards(Player, 2);
<commit_msg>put vars up top<commit_after>// James, I've put comments with your name on parts of code that I have questions for.
// Some of the logic issues I have involve where the betting functions need to be stored. Their own prototype? On the playerOne
// instance but not on the Dealer instance? etc ...
/*
  @james-huston my initial thought on the betting would be to have it as something seperate that way the player logic could all
  be shared between the player/dealer. You might consider a game "controller" class like your game UI that you attach the dealer
  and any players to. when the UI needs to do something like place a bet it asks the game controller to handle it and the game
  controller to make a bet for that player or something like that.
*/
// I created a GameUI constructor b/c it seems weird to not have those similar items stored somewhere
// even if that may change down the line. What do I do with all of the eventListeners and stuff? Can that code go
// down at the bottom of the page just sort of loose and unassociated with a prototype.
/*
  @james-huston I would attach all of the event listeners to your gameui prototype
*/

// Overall, I feel confident with how and why my code needs to be structured this way. I understand why and how the code I've writtien
// works. I just know that the decision-making and organization are skills that will come with time.

// setCardDom method
// 		James, why does this need to be a method?
//		Why can't it just be assigned like a variable?
/*
  @james-huston the reason to do this is so you have a chance to validate it and make sure that it is actually
  a dom element you can manipulate. remember you don't have jquery doing all of it's "magical" silent checking
  on elements when you try to modify them so you need to make sure you have a valid element that you can work
  with whatever way you plan to work with it. Maybe not 100% relevent for your project but in shared/reusable
  code it would be a good thing to be safe with.
*/

// James, I'm starting to combine methods under one prototype. I saw this syntax and it makes sense to me. It also
// kind of answers my question about the use of "constructor: 'constructorName' " as a syntax
/*
  @james-huston this if fine if you are more comfortable with it and working in your own project/setting your
  own coding standards. Just make sure you are comfortable with other styles so you recognize them and can
  work with other code comfortably and you are good.
*/
/*
  @james-huston so these things right now are kinda disparent "things" that just happen. These would be things
  handled by your game controller constructor if you had one.
*/

// create Player 1
var playerOne = new Player();
var playerRender = new PlayerUI('John');

// create Dealer instance
var gameDealer = new Player();
var dealerRender = new PlayerUI('Dealer');

// create Deck instance
var myDeck = new Deck();

// constructor
function Player() {
	this.cards = [];
	this.score = 0;
	this.wager = 0;
}

Player.prototype.receiveCard = function(card){
	this.card.push(card);
};

// constructor
function PlayerUI(name){
	this.name = name;
  	this.cardDom = undefined;
  	this.scoreDom = undefined;
}

PlayerUI.prototype.setCardDom = function(element){
  	this.cardDom = element;
};

PlayerUI.prototype.setScoreDom = function(element){
  	this.scoreDom = element;
};

function GameController() {

}

// constructor
function GameUI(){
	this.dealButton = document.getElementById('deal-button');
	this.hitButton = document.getElementById('hit-me');
	this.stayButton = document.getElementById('stay');
	this.resetButton = document.getElementById('reset');
}

// constructor
function Card(definedCard) {
	// this ensures that if we're not passed an object, we throw an error
	if (definedCard !== undefined && 'object' !== typeof definedCard) {
		throw new Error('');
	}

	this.suit = definedCard.suit;
	this.symbol = definedCard.symbol;
	this.color = definedCard.color;
	this.face = definedCard.face;
	this.name = definedCard.name;
	this.value = definedCard.value;
}

// constructor
function Deck(){
	this.suits = {
		0: {
			'suit': 'diamonds',
			'symbol': '♦',
			'color': 'red'
		},

		1: {
			'suit': 'hearts',
			'symbol': '♥',
			'color': 'red'
		},

		2: {
			'suit': 'clubs',
			'symbol': '♣',
			'color': 'black'
		},

		3: {
			'suit': 'spades',
			'symbol': '♠',
			'color': 'black'
		}
	}; // close suits

	this.cards = {
		1: {
			'name': 'ace',
			'face': 'A',
			'value': 1
		},

		2: {
			'name': 'two',
			'face': '2',
			'value': 2
		},

		3: {
			'name': 'three',
			'face': 3,
			'value': 3
		},

		4: {
			'name': 'four',
			'face': '4',
			'value': 4
		},

		5: {
			'name': 'five',
			'face': '5',
			'value': 5
		},

		6: {
			'name': 'six',
			'face': '6',
			'value': 6
		},

		7: {
			'name': 'seven',
			'face': '7',
			'value': 7
		},

		8: {
			'name': 'eight',
			'face': '8',
			'value': 8
		},

		9: {
			'name': 'nine',
			'face': '9',
			'value': 9
		},

		10: {
			'name': 'ten',
			'face': '10',
			'value': 10
		},

		11: {
			'name': 'jack',
			'face': 'J',
			'value': 10
		},

		12: {
			'name': 'queen',
			'face': 'Q',
			'value': 10
		},

		13: {
			'name': 'king',
			'face': 'K',
			'value': 10
		},

		14: {
			'name': 'ace',
			'face': 'A',
			'value': 11
		}
	}; // close cards
}

Deck.prototype = {
	constructor: Deck,
	dealRandomCard: function(){
		var suitType = Math.floor(Math.random() * 4);
		var cardNumber = Math.floor(Math.random() * 13) + 1;

		var randomCard = new Card({
			suit: this.suits[suitType].suit,
			symbol: this.suits[suitType].symbol,
			color: this.suits[suitType].color,
			face: this.cards[cardNumber].face,
			name: this.cards[cardNumber].name,
			value: this.cards[cardNumber].value
		});

		// console.log(randomCard);
		return randomCard;
	},
	dealCards: function(user, number){
		for (var i = 0; i < number; i++) {
			this.dealRandomCard(user);
			// James, I'm in the process of making this logic work.
			// this doesn't return correctly ... yet
		}
	}
};

myDeck.dealRandomCard();
myDeck.dealCards(Player, 2);<|endoftext|>


<commit_before>import config from "config"

// This is the key to this one file:
config.BIDDER_POSITION_MAX_BID_AMOUNT_CENTS_LIMIT = 400000

import { runQuery } from "schema/v2/test/utils"

describe("SaleArtwork type", () => {
  const saleArtwork = {
    id: "ed-ruscha-pearl-dust-combination-from-insects-portfolio",
    sale_id: "los-angeles-modern-auctions-march-2015",
    highest_bid: {
      cancelled: false,
      amount_cents: 325000,
      display_amount_dollars: "€3,250",
    },
    bidder_positions_count: 7,
    highest_bid_amount_cents: 325000,
    display_highest_bid_amount_dollars: "€3,250",
    minimum_next_bid_cents: 351000,
    display_minimum_next_bid_dollars: "€3,510",
    opening_bid_cents: 180000,
    display_opening_bid_dollars: "€1,800",
    low_estimate_cents: 200000,
    display_low_estimate_dollars: "€2,000",
    high_estimate_cents: 300000,
    display_high_estimate_dollars: "€3,000",
    reserve_status: "reserve_met",
    currency: "EUR",
    symbol: "€",
  }

  const execute = async (
    query,
    gravityResponse = saleArtwork,
    context = {}
  ) => {
    return await runQuery(query, {
      saleArtworkRootLoader: () => Promise.resolve(gravityResponse),
      ...context,
    })
  }

  describe("bid_increments", () => {
    describe("with a max amount set", () => {
      it("does not return increments above the max allowed", async () => {
        const query = `
          {
            sale_artwork(id: "54c7ed2a7261692bfa910200") {
              bid_increments
            }
          }
        `

        const context = {
          saleLoader: () => {
            return Promise.resolve({
              increment_strategy: "default",
            })
          },
          incrementsLoader: sale => {
            return Promise.resolve([
              {
                key: sale.increment_strategy,
                increments: [
                  {
                    from: 0,
                    to: 399999,
                    amount: 5000,
                  },
                  {
                    from: 400000,
                    to: 1000000,
                    amount: 10000,
                  },
                ],
              },
            ])
          },
        }

        const data = await execute(query, saleArtwork, context)
        expect(data.sale_artwork.bid_increments.slice(0, 20)).toEqual([
          351000,
          355000,
          360000,
          365000,
          370000,
          375000,
          380000,
          385000,
          390000,
          395000,
          400000,
        ])
      })
    })
  })
})
<commit_msg>Fix v2 sale_artwork_max_bid_env test<commit_after>import config from "config"

// This is the key to this one file:
config.BIDDER_POSITION_MAX_BID_AMOUNT_CENTS_LIMIT = 400000

import { runQuery } from "schema/v2/test/utils"

describe("SaleArtwork type", () => {
  const saleArtwork = {
    id: "ed-ruscha-pearl-dust-combination-from-insects-portfolio",
    sale_id: "los-angeles-modern-auctions-march-2015",
    highest_bid: {
      cancelled: false,
      amount_cents: 325000,
      display_amount_dollars: "€3,250",
    },
    bidder_positions_count: 7,
    highest_bid_amount_cents: 325000,
    display_highest_bid_amount_dollars: "€3,250",
    minimum_next_bid_cents: 351000,
    display_minimum_next_bid_dollars: "€3,510",
    opening_bid_cents: 180000,
    display_opening_bid_dollars: "€1,800",
    low_estimate_cents: 200000,
    display_low_estimate_dollars: "€2,000",
    high_estimate_cents: 300000,
    display_high_estimate_dollars: "€3,000",
    reserve_status: "reserve_met",
    currency: "EUR",
    symbol: "€",
  }

  const execute = async (
    query,
    gravityResponse = saleArtwork,
    context = {}
  ) => {
    return await runQuery(query, {
      saleArtworkRootLoader: () => Promise.resolve(gravityResponse),
      ...context,
    })
  }

  describe("increments", () => {
    describe("with a max amount set", () => {
      it("does not return increments above the max allowed", async () => {
        const query = `
          {
            saleArtwork(id: "54c7ed2a7261692bfa910200") {
              increments {
                cents
              }
            }
          }
        `

        const context = {
          saleLoader: () => {
            return Promise.resolve({
              increment_strategy: "default",
            })
          },
          incrementsLoader: sale => {
            return Promise.resolve([
              {
                key: sale.increment_strategy,
                increments: [
                  {
                    from: 0,
                    to: 399999,
                    amount: 5000,
                  },
                  {
                    from: 400000,
                    to: 1000000,
                    amount: 10000,
                  },
                ],
              },
            ])
          },
        }

        const data = await execute(query, saleArtwork, context)
        expect(
          data.saleArtwork.increments.slice(0, 20).map(i => i.cents)
        ).toEqual([
          351000,
          355000,
          360000,
          365000,
          370000,
          375000,
          380000,
          385000,
          390000,
          395000,
          400000,
        ])
      })
    })
  })
})
<|endoftext|>


<commit_before>"use strict";
var scene, StaticScene, TruckFollowScene;
(function() {
    var svg;
    var svgNS;

    StaticScene = function () {
        this.center = new Point(0, 0);
        this.viewportCenter = new Point(0, 0);
    }
    StaticScene.prototype.initialize = function() {
        svg = document.getElementById('field');
        svgNS = svg.getAttribute('xmlns');
    }
    StaticScene.prototype.adjustViewport = function() {
        //http://stackoverflow.com/a/15459233/3140
        var e = window, a = 'inner';
        if (!( 'innerWidth' in window )) {
            a = 'client';
            e = document.documentElement || document.body;
        }
        var w = e[a+'Width'];
        var h = e[a+'Height'];

        updateAttribute(svg, 'width', w);
        updateAttribute(svg, 'height', h);

        this.viewportCenter = new Point(w/2, h/2);
    }
    StaticScene.prototype.draw = function(bodies) {
        var scene = this;
        if(!svg) scene.initialize();

        scene.adjustViewport();
        scene.drawGround();
        bodies.forEach(function(body) {
            scene.drawBody(body);
        });
    }
    StaticScene.prototype.drawGround = function() {
    }
    StaticScene.prototype.transform = function(point) {
        return this.viewportCenter.add(point).subtract(this.center);
    }
    StaticScene.prototype.drawBody = function(obj) {
        if(!('rect' in obj)) obj.rect = createRect(obj.style);
        var rect = obj.rect;
        var body = obj.body;
        var transformBody = this.transform(body.center);

        updateAttribute(rect, 'x', transformBody.x);
        updateAttribute(rect, 'y', transformBody.y);
        updateAttribute(rect, 'rx', 4);
        updateAttribute(rect, 'ry', 4);
        updateAttribute(rect, 'width', body.size.x);
        updateAttribute(rect, 'height', body.size.y);
    }

    TruckFollowScene = function (truck) {
        StaticScene.call(this);
        this.truck = truck;
    }
    TruckFollowScene.prototype = Object.create(StaticScene.prototype);
    TruckFollowScene.prototype.constructor = TruckFollowScene;

    TruckFollowScene.prototype.draw = function(bodies) {
        this.center = this.truck.center;
        StaticScene.prototype.draw.call(this, bodies);
    }

    function createRect(style) {
        var rect = document.createElementNS(svgNS, "rect");
        rect.setAttribute('style', style);
        svg.appendChild(rect);

        return rect;
    }
    function updateAttribute(el, attrName, val) {
        if(el.getAttribute(attrName) != val) {
            el.setAttribute(attrName, val);
        }
    }
})();
<commit_msg>Very simple ground animation: short black rect<commit_after>"use strict";
var scene, StaticScene, TruckFollowScene;
(function() {
    var svg;
    var svgNS;

    StaticScene = function () {
        this.center = new Point(0, 0);
        this.viewportCenter = new Point(0, 0);
    }
    StaticScene.prototype.initialize = function() {
        svg = document.getElementById('field');
        svgNS = svg.getAttribute('xmlns');
    }
    StaticScene.prototype.adjustViewport = function() {
        //http://stackoverflow.com/a/15459233/3140
        var e = window, a = 'inner';
        if (!( 'innerWidth' in window )) {
            a = 'client';
            e = document.documentElement || document.body;
        }
        var w = e[a+'Width'];
        var h = e[a+'Height'];

        updateAttribute(svg, 'width', w);
        updateAttribute(svg, 'height', h);

        this.viewportCenter = new Point(w/2, h/2);
    }
    StaticScene.prototype.draw = function(bodies) {
        var scene = this;
        if(!svg) scene.initialize();

        scene.adjustViewport();
        scene.drawGround();
        bodies.forEach(function(body) {
            scene.drawBody(body);
        });
    }

    StaticScene.prototype.getGroundRect = function() {
        return this.groundRect = this.groundRect || createRect('fill:black;');
    }
    StaticScene.prototype.getGroundBody = function() {
        return this.groundBody = this.groundBody || new Body(
            new Point(0, 0), // center
            new Size(1000, 100), // size
            1, // weight
            new Vector(0, 0), // velocity
            new Vector(0, 0) // orientation
        );
    }

    StaticScene.prototype.drawGround = function() {
        this.updateRect(this.getGroundRect(), this.getGroundBody());
    }
    StaticScene.prototype.transform = function(point) {
        return this.viewportCenter.add(point).subtract(this.center);
    }
    StaticScene.prototype.drawBody = function(obj) {
        if(!('rect' in obj)) obj.rect = createRect(obj.style);
        this.updateRect(obj.rect, obj.body);
    }
    StaticScene.prototype.updateRect = function(rect, body) {
        var transformBody = this.transform(body.center);

        updateAttribute(rect, 'x', transformBody.x);
        updateAttribute(rect, 'y', transformBody.y);
        updateAttribute(rect, 'rx', 4);
        updateAttribute(rect, 'ry', 4);
        updateAttribute(rect, 'width', body.size.x);
        updateAttribute(rect, 'height', body.size.y);
    }

    TruckFollowScene = function (truck) {
        StaticScene.call(this);
        this.truck = truck;
    }
    TruckFollowScene.prototype = Object.create(StaticScene.prototype);
    TruckFollowScene.prototype.constructor = TruckFollowScene;

    TruckFollowScene.prototype.draw = function(bodies) {
        this.center = this.truck.center;
        StaticScene.prototype.draw.call(this, bodies);
    }

    function createRect(style) {
        var rect = document.createElementNS(svgNS, "rect");
        rect.setAttribute('style', style);
        svg.appendChild(rect);

        return rect;
    }
    function updateAttribute(el, attrName, val) {
        if(el.getAttribute(attrName) != val) {
            el.setAttribute(attrName, val);
        }
    }
})();
<|endoftext|>


<commit_before>// Copyright 2013-2021, University of Colorado Boulder

/*
 * @author Jonathan Olson <jonathan.olson@colorado.edu>
 */

( function() {

  window.assertions = window.assertions || {};
  window.assertions.assertFunction = window.assertions.assertFunction || function( predicate, ...messages ) {
    if ( !predicate ) {

      // don't treat falsey as a message.
      messages = messages.filter( message => !!messages );

      // Log the stack trace to IE.  Just creating an Error is not enough, it has to be caught to get a stack.
      if ( window.navigator && window.navigator.appName === 'Microsoft Internet Explorer' ) {
        messages.push( `stack=\n${new Error().stack}` );
      }

      // Add "Assertion Failed" to the front of the message list
      const assertPrefix = messages.length > 0 ? 'Assertion failed: ' : 'Assertion failed';
      console && console.log && console.log( assertPrefix, ...messages );
      if ( window.phet && phet.chipper && phet.chipper.queryParameters && phet.chipper.queryParameters.debugger ) {
        debugger; // eslint-disable-line no-debugger
      }
      throw new Error( assertPrefix + messages.join( '\n ' ) );
    }
  };

  window.assert = window.assert || null;
  window.assertSlow = window.assertSlow || null;

  window.assertions.enableAssert = function() {
    window.assert = window.assertions.assertFunction;
    window.console && window.console.log && window.console.log( 'enabling assert' );
  };
  window.assertions.disableAssert = function() {
    window.assert = null;
    window.console && window.console.log && window.console.log( 'disabling assert' );
  };

  window.assertions.enableAssertSlow = function() {
    window.assertSlow = window.assertions.assertFunction;
    window.console && window.console.log && window.console.log( 'enabling assertSlow' );
  };
  window.assertions.disableAssertSlow = function() {
    window.assertSlow = null;
    window.console && window.console.log && window.console.log( 'disabling assertSlow' );
  };
} )();
<commit_msg>update copyright dates from daily grunt work<commit_after>// Copyright 2013-2022, University of Colorado Boulder

/*
 * @author Jonathan Olson <jonathan.olson@colorado.edu>
 */

( function() {

  window.assertions = window.assertions || {};
  window.assertions.assertFunction = window.assertions.assertFunction || function( predicate, ...messages ) {
    if ( !predicate ) {

      // don't treat falsey as a message.
      messages = messages.filter( message => !!messages );

      // Log the stack trace to IE.  Just creating an Error is not enough, it has to be caught to get a stack.
      if ( window.navigator && window.navigator.appName === 'Microsoft Internet Explorer' ) {
        messages.push( `stack=\n${new Error().stack}` );
      }

      // Add "Assertion Failed" to the front of the message list
      const assertPrefix = messages.length > 0 ? 'Assertion failed: ' : 'Assertion failed';
      console && console.log && console.log( assertPrefix, ...messages );
      if ( window.phet && phet.chipper && phet.chipper.queryParameters && phet.chipper.queryParameters.debugger ) {
        debugger; // eslint-disable-line no-debugger
      }
      throw new Error( assertPrefix + messages.join( '\n ' ) );
    }
  };

  window.assert = window.assert || null;
  window.assertSlow = window.assertSlow || null;

  window.assertions.enableAssert = function() {
    window.assert = window.assertions.assertFunction;
    window.console && window.console.log && window.console.log( 'enabling assert' );
  };
  window.assertions.disableAssert = function() {
    window.assert = null;
    window.console && window.console.log && window.console.log( 'disabling assert' );
  };

  window.assertions.enableAssertSlow = function() {
    window.assertSlow = window.assertions.assertFunction;
    window.console && window.console.log && window.console.log( 'enabling assertSlow' );
  };
  window.assertions.disableAssertSlow = function() {
    window.assertSlow = null;
    window.console && window.console.log && window.console.log( 'disabling assertSlow' );
  };
} )();
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2017 Roman Lakhtadyr
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

// @flow
import type { Track, Album } from "../types";

export default [
  "albumData", "SyncKeeper", "$scope", "$location", "$route",
  function (albumData: Album, SyncKeeper: *, $scope: *, $location: *, $route: *) {
    const syncKeeper = SyncKeeper($scope);

    $scope.album = albumData;
    $scope.tracks = albumData.tracks;
    $scope.tracks_selected = ([]: Array<Track>);

    syncKeeper
      .songs($scope.tracks)
      .songs($scope.tracks_selected);

    //$scope.$watch("tracks", () => $route.reload(), true);
  }
];
<commit_msg>Clean<commit_after>/*
 * Copyright (c) 2017 Roman Lakhtadyr
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

// @flow
import type { Track, Album } from "../types";

export default ["albumData", "SyncKeeper", "$scope", (albumData: Album, SyncKeeper: *, $scope: *) => {
  const syncKeeper = SyncKeeper($scope);

  $scope.album = albumData;
  $scope.tracks = albumData.tracks;
  $scope.tracks_selected = ([]: Array<Track>);

  syncKeeper
    .songs($scope.tracks)
    .songs($scope.tracks_selected);
}];
<|endoftext|>


<commit_before>$(function(){
  // I'M SO SORRY I KNOW THIS IS BAD
  // I AM LITERALLY JUST TURNING HTML BACK INTO MARKDOWN
  // SO REVEAL CAN PARSE IT AND TURN IT BACK INTO HTML
  // WHICH IS JUST TERRIBLE BUT YOU KNOW
  // SOMETIMES YOU GOTTA JUST GO WITH IT
  var el = $('script[type="text/template"]');
  var html = el.html();
  var mdstr = md(html);
  el.html(mdstr);

  Reveal.initialize({
    transition: 'none',
    dependencies: [
      // Interpret Markdown in <section> elements
      { src: '{{ site.baseurl }}/public/js/plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
      { src: '{{ site.baseurl }}/public/js/plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },

      // Syntax highlight for <code> elements
      { src: '{{ site.baseurl }}/public/js/plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }
    ]
  });
});
<commit_msg>front matter matters<commit_after>---
---
$(function(){
  // I'M SO SORRY I KNOW THIS IS BAD
  // I AM LITERALLY JUST TURNING HTML BACK INTO MARKDOWN
  // SO REVEAL CAN PARSE IT AND TURN IT BACK INTO HTML
  // WHICH IS JUST TERRIBLE BUT YOU KNOW
  // SOMETIMES YOU GOTTA JUST GO WITH IT
  var el = $('script[type="text/template"]');
  var html = el.html();
  var mdstr = md(html);
  el.html(mdstr);

  Reveal.initialize({
    transition: 'none',
    dependencies: [
      // Interpret Markdown in <section> elements
      { src: '{{ site.baseurl }}/public/js/plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
      { src: '{{ site.baseurl }}/public/js/plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },

      // Syntax highlight for <code> elements
      { src: '{{ site.baseurl }}/public/js/plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }
    ]
  });
});
<|endoftext|>


<commit_before>import angular from 'angular';
import _ from 'underscore';

angular.module('dimApp')
  .factory('dimDestinyTrackerService', DestinyTrackerService);

class gunTransformer {
  translateToDtrGun(gun) {
    return {
      referenceId: gun.hash,
      roll: this.getDtrRoll(gun)
    };
  }

  getRollAndPerks(gun) {
    return {
      roll: this.getDtrRoll(gun),
      selectedPerks: this.getDtrPerks(gun),
      referenceId: gun.hash,
      instanceId: gun.id,
    };
  }

  getDtrPerks(gun) {
    if (!gun.talentGrid) {
      return null;
    }

    return gun.talentGrid.dtrPerks;
  }

  getDtrRoll(gun) {
    if (!gun.talentGrid) {
      return null;
    }

    return gun.talentGrid.dtrRoll;
  }
}

class gunListBuilder {
  constructor() {
    this._gunTransformer = new gunTransformer();
  }

  getNewItems(allItems) {
    return _.where(allItems, { isNew: true });
  }

  getAllItems(stores) {
    var allItems = [];

    stores.forEach(function(store) {
      allItems = allItems.concat(store.items);
    });

    return allItems;
  }

  getGuns(stores) {
    var allItems = this.getAllItems(stores);

    var allGuns = _.filter(allItems,
                        function(item) {
                          if (!item.primStat) {
                            return false;
                          }

                          return (item.primStat.statHash === 368428387);
                        });

    var newGuns = this.getNewItems(allGuns);

    if (newGuns.length > 0) {
      return newGuns;
    }

    return allGuns;
  }

  getWeaponList(stores) {
    var guns = this.getGuns(stores);

    var list = [];
    var self = this;

    guns.forEach(function(gun) {
      var dtrGun = self._gunTransformer.translateToDtrGun(gun);

      if (!self.isKnownGun(list, dtrGun)) {
        list.push(dtrGun);
      }
    });

    return list;
  }

  isKnownGun(list, dtrGun) {
    return _.contains(list, dtrGun);
  }
}

class trackerErrorHandler {
  constructor($q,
              $translate) {
    this.$q = $q;
    this.$translate = $translate;
  }

  handleErrors(response) {
    if (response.status !== 200) {
      return this.$q.reject(new Error(this.$translate.instant('DtrReview.ServiceCallError')));
    }

    return response;
  }

  handleSubmitErrors(response) {
    if (response.status !== 204) {
      return this.$q.reject(new Error(this.$translate.instant('DtrReview.ServiceSubmitError')));
    }

    return response;
  }
}

class bulkFetcher {
  constructor($q, $http, trackerErrorHandler) {
    this.$q = $q;
    this.$http = $http;
    this._gunListBuilder = new gunListBuilder();
    this._trackerErrorHandler = trackerErrorHandler;
  }

  getBulkWeaponDataPromise(gunList) {
    return {
      method: 'POST',
      url: 'https://reviews-api.destinytracker.net/api/weaponChecker/fetch',
      data: gunList,
      dataType: 'json'
    };
  }

  getBulkFetchPromise(stores) {
    if (stores.stores.length === 0) {
      return this.$q.resolve();
    }

    var weaponList = this._gunListBuilder.getWeaponList(stores.stores);

    var promise = this.$q
              .when(this.getBulkWeaponDataPromise(weaponList))
              .then(this.$http)
              .then(this._trackerErrorHandler.handleErrors, this._trackerErrorHandler.handleErrors)
              .then((response) => { return response.data; });

    return promise;
  }

  bulkFetch(stores) {
    this.getBulkFetchPromise(stores)
      .then((bulkRankings) => this.attachRankings(bulkRankings,
                                                  stores.stores));
  }

  attachRankings(bulkRankings,
                          stores) {
    if ((!bulkRankings) ||
        (!bulkRankings.length)) {
      return;
    }

    bulkRankings.forEach(function(bulkRanking) {
      stores.forEach(function(store) {
        store.items.forEach(function(storeItem) {
          if (storeItem.hash === Number(bulkRanking.referenceId)) {
            storeItem.dtrRating = bulkRanking.rating;
          }
        });
      });
    });
  }
}

class reviewsFetcher {
  constructor($q, $http, trackerErrorHandler) {
    this.$q = $q;
    this.$http = $http;
    this._gunTransformer = new gunTransformer();
    this._trackerErrorHandler = trackerErrorHandler;
  }

  getItemReviewsCall(item) {
    return {
      method: 'POST',
      url: 'https://reviews-api.destinytracker.net/api/weaponChecker/reviews',
      data: item,
      dataType: 'json'
    };
  }

  getItemReviewsPromise(item) {
    var postWeapon = this._gunTransformer.getRollAndPerks(item);

    var promise = this.$q
              .when(this.getItemReviewsCall(postWeapon))
              .then(this.$http)
              .then(this._trackerErrorHandler.handleErrors, this._trackerErrorHandler.handleErrors)
              .then((response) => { return response.data; });

    return promise;
  }

  getUserReview(reviewData) {
    return _.findWhere(reviewData.reviews, { isReviewer: true });
  }

  attachReviews(item,
                reviewData) {
    var userReview = this.getUserReview(reviewData);

    if (userReview) {
      item.userRating = userReview.rating;
      item.userReview = userReview.review;
    }
  }

  getItemReviews(item) {
    this.getItemReviewsPromise(item)
      .then((data) => this.attachReviews(item,
                                         data));
  }
}

class reviewSubmitter {
  constructor($q, $http, dimPlatformService, trackerErrorHandler) {
    this.$q = $q;
    this.$http = $http;
    this._gunTransformer = new gunTransformer();
    this._trackerErrorHandler = trackerErrorHandler;
    this._dimPlatformService = dimPlatformService;
  }

  getReviewer() {
    var membershipInfo = this._dimPlatformService.getActive();

    return {
      membershipId: membershipInfo.membershipId,
      type: membershipInfo.type,
      displayName: membershipInfo.id
    };
  }

  toRatingAndReview(userReview) {
    return {
      rating: userReview.rating,
      review: userReview.review
    };
  }

  submitItemReviewCall(itemReview) {
    return {
      method: 'POST',
      url: 'https://reviews-api.destinytracker.net/api/weaponChecker/reviews/submit',
      data: itemReview,
      dataType: 'json'
    };
  }

  submitReviewPromise(item, userReview) {
    var rollAndPerks = this._gunTransformer.getRollAndPerks(item);
    var reviewer = this.getReviewer();
    var review = this.toRatingAndReview(userReview);

    var rating = Object.assign(rollAndPerks, review);
    rating.reviewer = reviewer;

    var promise = this.$q
              .when(this.submitItemReviewCall(rating))
              .then(this.$http)
              .then(this._trackerErrorHandler.handleSubmitErrors, this._trackerErrorHandler.handleSubmitErrors);

    return promise;
  }

  submitReview(item, userReview) {
    this.submitReviewPromise(item, userReview);
  }
}

function DestinyTrackerService($q,
                               $http,
                               $rootScope,
                               dimPlatformService,
                               dimSettingsService,
                               $translate,
                               dimFeatureFlags) {
  var _trackerErrorHandler = new trackerErrorHandler($q, $translate);
  var _bulkFetcher = new bulkFetcher($q, $http, _trackerErrorHandler);
  var _reviewsFetcher = new reviewsFetcher($q, $http, _trackerErrorHandler);
  var _reviewSubmitter = new reviewSubmitter($q, $http, dimPlatformService, _trackerErrorHandler);
  var _postEnabled = dimFeatureFlags.sendingWeaponDataEnabled;

  function _userHasNotOkayedPostingIds() {
    return (!dimSettingsService.allowIdPostToDtr);
  }

  $rootScope.$on('item-clicked', function(event, item) {
    if ((!_postEnabled) ||
        (_userHasNotOkayedPostingIds())) {
      return;
    }

    _reviewsFetcher.getItemReviews(item);
  });

  $rootScope.$on('dim-stores-updated', function(event, stores) {
    if (!_postEnabled) {
      return;
    }

    _bulkFetcher.bulkFetch(stores);
  });

  $rootScope.$on('review-submitted', function(event, item, userReview) {
    if ((!_postEnabled) ||
        (_userHasNotOkayedPostingIds())) {
      return;
    }

    _reviewSubmitter.submitReview(item, userReview);
  });

  return {
    init: function() {}
  };
}<commit_msg>Apparently loading tracker is a thing.<commit_after>import angular from 'angular';
import _ from 'underscore';

angular.module('dimApp')
  .factory('dimDestinyTrackerService', DestinyTrackerService);

class gunTransformer {
  translateToDtrGun(gun) {
    return {
      referenceId: gun.hash,
      roll: this.getDtrRoll(gun)
    };
  }

  getRollAndPerks(gun) {
    return {
      roll: this.getDtrRoll(gun),
      selectedPerks: this.getDtrPerks(gun),
      referenceId: gun.hash,
      instanceId: gun.id,
    };
  }

  getDtrPerks(gun) {
    if (!gun.talentGrid) {
      return null;
    }

    return gun.talentGrid.dtrPerks;
  }

  getDtrRoll(gun) {
    if (!gun.talentGrid) {
      return null;
    }

    return gun.talentGrid.dtrRoll;
  }
}

class gunListBuilder {
  constructor() {
    this._gunTransformer = new gunTransformer();
  }

  getNewItems(allItems) {
    return _.where(allItems, { isNew: true });
  }

  getAllItems(stores) {
    var allItems = [];

    stores.forEach(function(store) {
      allItems = allItems.concat(store.items);
    });

    return allItems;
  }

  getGuns(stores) {
    var allItems = this.getAllItems(stores);

    var allGuns = _.filter(allItems,
                        function(item) {
                          if (!item.primStat) {
                            return false;
                          }

                          return (item.primStat.statHash === 368428387);
                        });

    var newGuns = this.getNewItems(allGuns);

    if (newGuns.length > 0) {
      return newGuns;
    }

    return allGuns;
  }

  getWeaponList(stores) {
    var guns = this.getGuns(stores);

    var list = [];
    var self = this;

    guns.forEach(function(gun) {
      var dtrGun = self._gunTransformer.translateToDtrGun(gun);

      if (!self.isKnownGun(list, dtrGun)) {
        list.push(dtrGun);
      }
    });

    return list;
  }

  isKnownGun(list, dtrGun) {
    return _.contains(list, dtrGun);
  }
}

class trackerErrorHandler {
  constructor($q,
              $translate) {
    this.$q = $q;
    this.$translate = $translate;
  }

  handleErrors(response) {
    if (response.status !== 200) {
      return this.$q.reject(new Error(this.$translate.instant('DtrReview.ServiceCallError')));
    }

    return response;
  }

  handleSubmitErrors(response) {
    if (response.status !== 204) {
      return this.$q.reject(new Error(this.$translate.instant('DtrReview.ServiceSubmitError')));
    }

    return response;
  }
}

class bulkFetcher {
  constructor($q, $http, trackerErrorHandler, loadingTracker) {
    this.$q = $q;
    this.$http = $http;
    this._gunListBuilder = new gunListBuilder();
    this._trackerErrorHandler = trackerErrorHandler;
    this._loadingTracker = loadingTracker;
  }

  getBulkWeaponDataPromise(gunList) {
    return {
      method: 'POST',
      url: 'https://reviews-api.destinytracker.net/api/weaponChecker/fetch',
      data: gunList,
      dataType: 'json'
    };
  }

  getBulkFetchPromise(stores) {
    if (stores.stores.length === 0) {
      return this.$q.resolve();
    }

    var weaponList = this._gunListBuilder.getWeaponList(stores.stores);

    var promise = this.$q
              .when(this.getBulkWeaponDataPromise(weaponList))
              .then(this.$http)
              .then(this._trackerErrorHandler.handleErrors, this._trackerErrorHandler.handleErrors)
              .then((response) => { return response.data; });

    this._loadingTracker.addPromise(promise);

    return promise;
  }

  bulkFetch(stores) {
    this.getBulkFetchPromise(stores)
      .then((bulkRankings) => this.attachRankings(bulkRankings,
                                                  stores.stores));
  }

  attachRankings(bulkRankings,
                          stores) {
    if ((!bulkRankings) ||
        (!bulkRankings.length)) {
      return;
    }

    bulkRankings.forEach(function(bulkRanking) {
      stores.forEach(function(store) {
        store.items.forEach(function(storeItem) {
          if (storeItem.hash === Number(bulkRanking.referenceId)) {
            storeItem.dtrRating = bulkRanking.rating;
          }
        });
      });
    });
  }
}

class reviewsFetcher {
  constructor($q, $http, trackerErrorHandler, loadingTracker) {
    this.$q = $q;
    this.$http = $http;
    this._gunTransformer = new gunTransformer();
    this._trackerErrorHandler = trackerErrorHandler;
    this._loadingTracker = loadingTracker;
  }

  getItemReviewsCall(item) {
    return {
      method: 'POST',
      url: 'https://reviews-api.destinytracker.net/api/weaponChecker/reviews',
      data: item,
      dataType: 'json'
    };
  }

  getItemReviewsPromise(item) {
    var postWeapon = this._gunTransformer.getRollAndPerks(item);

    var promise = this.$q
              .when(this.getItemReviewsCall(postWeapon))
              .then(this.$http)
              .then(this._trackerErrorHandler.handleErrors, this._trackerErrorHandler.handleErrors)
              .then((response) => { return response.data; });

    this._loadingTracker.addPromise(promise);

    return promise;
  }

  getUserReview(reviewData) {
    return _.findWhere(reviewData.reviews, { isReviewer: true });
  }

  attachReviews(item,
                reviewData) {
    var userReview = this.getUserReview(reviewData);

    if (userReview) {
      item.userRating = userReview.rating;
      item.userReview = userReview.review;
    }
  }

  getItemReviews(item) {
    this.getItemReviewsPromise(item)
      .then((data) => this.attachReviews(item,
                                         data));
  }
}

class reviewSubmitter {
  constructor($q, $http, dimPlatformService, trackerErrorHandler, loadingTracker) {
    this.$q = $q;
    this.$http = $http;
    this._gunTransformer = new gunTransformer();
    this._trackerErrorHandler = trackerErrorHandler;
    this._dimPlatformService = dimPlatformService;
    this._loadingTracker = loadingTracker;
  }

  getReviewer() {
    var membershipInfo = this._dimPlatformService.getActive();

    return {
      membershipId: membershipInfo.membershipId,
      type: membershipInfo.type,
      displayName: membershipInfo.id
    };
  }

  toRatingAndReview(userReview) {
    return {
      rating: userReview.rating,
      review: userReview.review
    };
  }

  submitItemReviewCall(itemReview) {
    return {
      method: 'POST',
      url: 'https://reviews-api.destinytracker.net/api/weaponChecker/reviews/submit',
      data: itemReview,
      dataType: 'json'
    };
  }

  submitReviewPromise(item, userReview) {
    var rollAndPerks = this._gunTransformer.getRollAndPerks(item);
    var reviewer = this.getReviewer();
    var review = this.toRatingAndReview(userReview);

    var rating = Object.assign(rollAndPerks, review);
    rating.reviewer = reviewer;

    var promise = this.$q
              .when(this.submitItemReviewCall(rating))
              .then(this.$http)
              .then(this._trackerErrorHandler.handleSubmitErrors, this._trackerErrorHandler.handleSubmitErrors);

    this._loadingTracker.addPromise(promise);

    return promise;
  }

  submitReview(item, userReview) {
    this.submitReviewPromise(item, userReview);
  }
}

function DestinyTrackerService($q,
                               $http,
                               $rootScope,
                               dimPlatformService,
                               dimSettingsService,
                               $translate,
                               dimFeatureFlags,
                               loadingTracker) {
  var _trackerErrorHandler = new trackerErrorHandler($q, $translate);
  var _bulkFetcher = new bulkFetcher($q, $http, _trackerErrorHandler, loadingTracker);
  var _reviewsFetcher = new reviewsFetcher($q, $http, _trackerErrorHandler, loadingTracker);
  var _reviewSubmitter = new reviewSubmitter($q, $http, dimPlatformService, _trackerErrorHandler, loadingTracker);
  var _postEnabled = dimFeatureFlags.sendingWeaponDataEnabled;

  function _userHasNotOkayedPostingIds() {
    return (!dimSettingsService.allowIdPostToDtr);
  }

  $rootScope.$on('item-clicked', function(event, item) {
    if ((!_postEnabled) ||
        (_userHasNotOkayedPostingIds())) {
      return;
    }

    _reviewsFetcher.getItemReviews(item);
  });

  $rootScope.$on('dim-stores-updated', function(event, stores) {
    if (!_postEnabled) {
      return;
    }

    _bulkFetcher.bulkFetch(stores);
  });

  $rootScope.$on('review-submitted', function(event, item, userReview) {
    if ((!_postEnabled) ||
        (_userHasNotOkayedPostingIds())) {
      return;
    }

    _reviewSubmitter.submitReview(item, userReview);
  });

  return {
    init: function() {}
  };
}<|endoftext|>


<commit_before>$(document).ready(function () {
    setTimeout(function () {
        $.ajax({
            url: "https://api.spiget.org/v2/status?spiget___ua=SpigetStats&pretty=false&callback=?",
            dataType: "jsonp",
            success: function (r) {
                resources = r.stats.resources;
                authors = r.stats.authors;

                animateValue("#stat_resources", resources, 1500);
                setTimeout(function () {
                    animateValue("#stat_authors", authors, 1500);
                }, 250);
            }
        });
        // Make the loading delay less noticeable
        animateValue("#stat_daily_requests", 200000, 10000);
        $.ajax({
            url: "https://api.spiget.org/v2/metrics/requests/30?spiget___ua=SpigetStats&pretty=false&simple=true",
            dataType: "json",
            success: function (r) {
                total = 0;
                count = 0;

                $.each(r, function (key, value) {
                    if (value.total > 0) {
                        total += value.total;

                        count += 1;
                    }
                });

                avg = (total > 0 && count > 0) ? total / count : 0;
                rounded = Math.round(avg);

                $("#stat_daily_requests").stop();
                animateValue("#stat_daily_requests", rounded, 1500);
            }
        });
        $.ajax({
            url: "https://api.spiget.org/v2/resources/recentUpdates?spiget___ua=SpigetStats&size=16&pretty=false&callback=?",
            dataType: "jsonp",
            success: function (r) {
                var counter = 0;
                $.each(r, function (index, resource) {
                    if (isArray(resource))
                        return;
                    counter += 1;
                    $("#new-resources").append(//
                        "
" + //
                        "	" + resource.name + "" + //
                        "	" + //
                        "
");

                    if (resource.updateDate === resource.releaseDate) {
                        $("#new_res_extra_" + resource.id).attr("title", "New Resource");
                        $("#new_res_extra_" + resource.id).append(" ");
                    }
                });

                /*
                $(".new-res-author").each(function () {
                    $this = $(this);
                    var id = $this.attr("id");
                    var resId = id.replace("new_res_author_", "");
                    var url = "https://api.spiget.org/v2/resources/" + resId + "/author?callback=?";
                    $.ajax({
                        url: url,
                        dataType: "jsonp",
                        success: function (a) {
                            elem = $("#" + id);
                            elem.attr("href", "https://api.spiget.org/v2/authors/" + a.id + "/go");
                            elem.text(a.username);
                        }
                    });
                });
                */

                if (counter === 0) {
                    $("#new-resources").append(//
                        "
" + //
                        "	No new resources since the last update" + //
                        "
");
                }
            }
        });
        $.ajax({
            url: "https://api.spiget.org/v2/authors/recentUpdates?spiget___ua=SpigetStats&size=16&pretty=false&callback=?",
            dataType: "jsonp",
            success: function (r) {
                var counter = 0;
                $.each(r, function (index, author) {
                    if (isArray(author))
                        return;
                    counter += 1;
                    $("#new-authors").append(//
                        "
" + //
                        "	" + author.name + "" + //
                        "
");
                });
                if (counter === 0) {
                    $("#new-authors").append(//
                        "
" + //
                        "	No new authors since the last update" + //
                        "
");
                }
            }
        });
    }, 500);

    var scrollIndex = 1;
    setInterval(function () {
        if ($("#hidden_test").is(":visible") > 0) {
            $(".scroll-stat").each(function () {
                $this = $(this);
                if (!$this.is(":visible")) {
                    $this.fadeIn();
                }
            });
            return;
        }
        if (scrollIndex >= $(".scroll-stat").length) {
            scrollIndex = 0;
        }
        console.info(scrollIndex);
        $current = $(".scroll-stat").eq(scrollIndex++);

        console.log($current);

        $(".scroll-stat").each(function () {
            $this = $(this);
            if ($this.is(":visible")) {
                $this.fadeOut(500);
            }
        });
        $current.fadeIn(500);

    }, 3500);
});

//http://codepen.io/shivasurya/pen/FatiB/
function animateValue($element, value, duration) {
    $element = $($element);
    if ($element.prop("counter") === undefined) {
        $element.prop("counter", 0);
    }
    $element.animate({
        counter: value
    }, {
        duration: duration,
        easing: "swing",
        step: function (now) {
            $element.text(numeral(Math.ceil(now)).format("0,0"));
        }
    });
}

function isArray(what) {
    return Object.prototype.toString.call(what) === '[object Array]';
}
<commit_msg>increase start value<commit_after>$(document).ready(function () {
    setTimeout(function () {
        $.ajax({
            url: "https://api.spiget.org/v2/status?spiget___ua=SpigetStats&pretty=false&callback=?",
            dataType: "jsonp",
            success: function (r) {
                resources = r.stats.resources;
                authors = r.stats.authors;

                animateValue("#stat_resources", resources, 1500);
                setTimeout(function () {
                    animateValue("#stat_authors", authors, 1500);
                }, 250);
            }
        });
        // Make the loading delay less noticeable
        animateValue("#stat_daily_requests", 275000, 10000);
        $.ajax({
            url: "https://api.spiget.org/v2/metrics/requests/30?spiget___ua=SpigetStats&pretty=false&simple=true",
            dataType: "json",
            success: function (r) {
                total = 0;
                count = 0;

                $.each(r, function (key, value) {
                    if (value.total > 0) {
                        total += value.total;

                        count += 1;
                    }
                });

                avg = (total > 0 && count > 0) ? total / count : 0;
                rounded = Math.round(avg);

                $("#stat_daily_requests").stop();
                animateValue("#stat_daily_requests", rounded, 1500);
            }
        });
        $.ajax({
            url: "https://api.spiget.org/v2/resources/recentUpdates?spiget___ua=SpigetStats&size=16&pretty=false&callback=?",
            dataType: "jsonp",
            success: function (r) {
                var counter = 0;
                $.each(r, function (index, resource) {
                    if (isArray(resource))
                        return;
                    counter += 1;
                    $("#new-resources").append(//
                        "
" + //
                        "	" + resource.name + "" + //
                        "	" + //
                        "
");

                    if (resource.updateDate === resource.releaseDate) {
                        $("#new_res_extra_" + resource.id).attr("title", "New Resource");
                        $("#new_res_extra_" + resource.id).append(" ");
                    }
                });

                /*
                $(".new-res-author").each(function () {
                    $this = $(this);
                    var id = $this.attr("id");
                    var resId = id.replace("new_res_author_", "");
                    var url = "https://api.spiget.org/v2/resources/" + resId + "/author?callback=?";
                    $.ajax({
                        url: url,
                        dataType: "jsonp",
                        success: function (a) {
                            elem = $("#" + id);
                            elem.attr("href", "https://api.spiget.org/v2/authors/" + a.id + "/go");
                            elem.text(a.username);
                        }
                    });
                });
                */

                if (counter === 0) {
                    $("#new-resources").append(//
                        "
" + //
                        "	No new resources since the last update" + //
                        "
");
                }
            }
        });
        $.ajax({
            url: "https://api.spiget.org/v2/authors/recentUpdates?spiget___ua=SpigetStats&size=16&pretty=false&callback=?",
            dataType: "jsonp",
            success: function (r) {
                var counter = 0;
                $.each(r, function (index, author) {
                    if (isArray(author))
                        return;
                    counter += 1;
                    $("#new-authors").append(//
                        "
" + //
                        "	" + author.name + "" + //
                        "
");
                });
                if (counter === 0) {
                    $("#new-authors").append(//
                        "
" + //
                        "	No new authors since the last update" + //
                        "
");
                }
            }
        });
    }, 500);

    var scrollIndex = 1;
    setInterval(function () {
        if ($("#hidden_test").is(":visible") > 0) {
            $(".scroll-stat").each(function () {
                $this = $(this);
                if (!$this.is(":visible")) {
                    $this.fadeIn();
                }
            });
            return;
        }
        if (scrollIndex >= $(".scroll-stat").length) {
            scrollIndex = 0;
        }
        console.info(scrollIndex);
        $current = $(".scroll-stat").eq(scrollIndex++);

        console.log($current);

        $(".scroll-stat").each(function () {
            $this = $(this);
            if ($this.is(":visible")) {
                $this.fadeOut(500);
            }
        });
        $current.fadeIn(500);

    }, 3500);
});

//http://codepen.io/shivasurya/pen/FatiB/
function animateValue($element, value, duration) {
    $element = $($element);
    if ($element.prop("counter") === undefined) {
        $element.prop("counter", 0);
    }
    $element.animate({
        counter: value
    }, {
        duration: duration,
        easing: "swing",
        step: function (now) {
            $element.text(numeral(Math.ceil(now)).format("0,0"));
        }
    });
}

function isArray(what) {
    return Object.prototype.toString.call(what) === '[object Array]';
}
<|endoftext|>


<commit_before>function Bridge () {

	function browserIsAndroid(){
		return navigator.userAgent.match(/Android/i);
	}

	function browserIsRapid(){
		return (typeof ___androidExists !== "undefined");
	}

	function browserSupportsPhoneGap(){
		return (typeof device !== "undefined" &&
				typeof device.phonegap !== "undefined");
	}

	function recommendUserSwitchesToRapid(){
		if(confirm("Do you want to run this website with the PhoneBridge browser?")) {
			switchThisURLToRapid();
		}
	}

	function switchThisURLToRapid(){
		changeURLTo("bridge://" + document.URL);
	}

	function changeURLTo(newUrl){
            location.replace(newUrl);
	}

//=========================================
//client Android Switch to Rapid
//=========================================

	this.android = {};

    this.android.recommendNative = function () {
		if (browserIsAndroid() && !browserIsRapid()){
			recommendUserSwitchesToRapid();
        }
    };

    this.android.requireNative = function () {
		if (browserIsAndroid() && !browserIsRapid()){
			switchThisURLToRapid();
        }
    };

//=========================================
//Accelerometer wrapper
//=========================================
//API:
//	bridge.accelerometer.getCurrentAcceleration(onSuccess, onError)
//	bridge.accelerometer.watchAcceleration(onSuccess, onError)
//=========================================
	this.accelerometer = {};

	function browserSupportsWebkitAccelerometer(){
		return true; //TODO: I don't know how to actually check this
	}

	if (browserIsRapid()){
		this.accelerometer.getCurrentAcceleration = navigator.accelerometer.getCurentAcceleration;
		this.accelerometer.watchAcceleration = navigator.accelerometer.watchAcceleration;
	}
	else if (browserSupportsPhoneGap()){
		this.accelerometer.getCurrentAcceleration = navigator.accelerometer.getCurentAcceleration;
		this.accelerometer.watchAcceleration = navigator.accelerometer.watchAcceleration;
	}
	else if (browserSupportsWebkitAccelerometer()){

		var fnsWatchingAccelerometerOnSuccess = {};
		var nextIDForFnsWatchingAccelerometerOnSuccess = 0;
		var fnsWatchingAccelerometerOnError = {};
		var nextIDForFnsWatchingAccelerometerOnFail = 0;

		var lastEvent = null;

		window.ondevicemotion = function(event){
			lastEvent = event;
			for (fnId in fnsWatchingAccelerometerOnSuccess) {
				fnsWatchingAccelerometerOnSuccess[fnId](event);
			}
		}
		this.accelerometer.getCurrentAcceleration = function(onSuccess, onError){
			if (typeof lastEvent !== null){
				onSuccess(lastEvent);
			}
			else {
				onError();
			}
		}
		this.accelerometer.watchAcceleration = function(onSuccess, onError){
			fnsWatchingAccelerometerOnSuccess[nextIDForFnsWatchingAccelerometerOnSuccess] = onSuccess
			nextIDForFnsWatchingAccelerometerOnSuccess += 1;
			fnsWatchingAccelerometerOnError[nextIDForFnsWatchingAccelerometerOnError] = onError
			nextIDForFnsWatchingAccelerometerOnSuccess += 1;
		}
	}
	else {
		console.log("Device does not accept accelerometer!");
	}
	//accelerometer.getCurrentAcceleration =
	//accelerometer.watchAcceleration =

//=========================================
//Geolocation wrapper
//=========================================
//API:
//	bridge.geolocation.getCurrentAcceleration(onSuccess, onError)
//	bridge.geolocation.watchAcceleration(onSuccess, onError)
//=========================================
    this.geolocation = {};

	function browserSupportsWebkitGeolocation(){
		return true; //TODO: I don't know how to actually check this
	}

    //TODO: Support all the options
	if (browserIsRapid()){

	}
	else if (browserSupportsPhoneGap()){
	}

	else if (browserSupportsWebkitGeolocation()){

    }
	else {
		console.log("Device does not accept geolocation!");
	}
	//accelerometer.getCurrentAcceleration =
	//accelerometer.watchAcceleration =

}

var bridge = new Bridge();

<commit_msg>readded geo location<commit_after>function Bridge () {

	function browserIsAndroid(){
		return navigator.userAgent.match(/Android/i);
	}

	function browserIsRapid(){
		return (typeof ___androidExists !== "undefined");
	}

	function browserSupportsPhoneGap(){
		return (typeof device !== "undefined" &&
				typeof device.phonegap !== "undefined");
	}

	function recommendUserSwitchesToRapid(){
		if(confirm("Do you want to run this website with the PhoneBridge browser?")) {
			switchThisURLToRapid();
		}
	}

	function switchThisURLToRapid(){
		changeURLTo("bridge://" + document.URL);
	}

	function changeURLTo(newUrl){
            location.replace(newUrl);
	}

//=========================================
//client Android Switch to Rapid
//=========================================

	this.android = {};

    this.android.recommendNative = function () {
		if (browserIsAndroid() && !browserIsRapid()){
			recommendUserSwitchesToRapid();
        }
    };

    this.android.requireNative = function () {
		if (browserIsAndroid() && !browserIsRapid()){
			switchThisURLToRapid();
        }
    };

//=========================================
//Accelerometer wrapper
//=========================================
//API:
//	bridge.accelerometer.getCurrentAcceleration(onSuccess, onError)
//	bridge.accelerometer.watchAcceleration(onSuccess, onError)
//=========================================
	this.accelerometer = {};

	function browserSupportsWebkitAccelerometer(){
		return true; //TODO: I don't know how to actually check this
	}

	if (browserIsRapid()){
		this.accelerometer.getCurrentAcceleration = navigator.accelerometer.getCurentAcceleration;
		this.accelerometer.watchAcceleration = navigator.accelerometer.watchAcceleration;
	}
	else if (browserSupportsPhoneGap()){
		this.accelerometer.getCurrentAcceleration = navigator.accelerometer.getCurentAcceleration;
		this.accelerometer.watchAcceleration = navigator.accelerometer.watchAcceleration;
	}
	else if (browserSupportsWebkitAccelerometer()){

		var fnsWatchingAccelerometerOnSuccess = {};
		var nextIDForFnsWatchingAccelerometerOnSuccess = 0;
		var fnsWatchingAccelerometerOnError = {};
		var nextIDForFnsWatchingAccelerometerOnFail = 0;

		var lastEvent = null;

		window.ondevicemotion = function(event){
			lastEvent = event;
			for (fnId in fnsWatchingAccelerometerOnSuccess) {
				fnsWatchingAccelerometerOnSuccess[fnId](event);
			}
		}
		this.accelerometer.getCurrentAcceleration = function(onSuccess, onError){
			if (typeof lastEvent !== null){
				onSuccess(lastEvent);
			}
			else {
				onError();
			}
		}
		this.accelerometer.watchAcceleration = function(onSuccess, onError){
			fnsWatchingAccelerometerOnSuccess[nextIDForFnsWatchingAccelerometerOnSuccess] = onSuccess
			nextIDForFnsWatchingAccelerometerOnSuccess += 1;
			fnsWatchingAccelerometerOnError[nextIDForFnsWatchingAccelerometerOnError] = onError
			nextIDForFnsWatchingAccelerometerOnSuccess += 1;
		}
	}
	else {
		console.log("Device does not accept accelerometer!");
	}
	//accelerometer.getCurrentAcceleration =
	//accelerometer.watchAcceleration =

//=========================================
//Geolocation wrapper
//=========================================
//API:
//	bridge.geolocation.getCurrentPosition(onSuccess, onError)
//	bridge.geolocation.watchAcceleration(onSuccess, onError)
//=========================================
    this.geolocation = {};

	function browserSupportsWebkitGeolocation(){
		return true; //TODO: I don't know how to actually check this
	}

    //TODO: Support all the options
	if (browserIsRapid()){
		this.geolocation.getCurrentPosition = navigator.geolocation.getCurrentPosition;
	}
	else if (browserSupportsPhoneGap()){
		this.geolocation.getCurrentPosition = navigator.geolocation.getCurrentPosition;
	}

	else if (browserSupportsWebkitGeolocation()){
		this.geolocation.getCurrentPosition = navigator.geolocation.getCurrentPosition;

    }
	else {
		console.log("Device does not accept geolocation!");
	}
	//accelerometer.getCurrentAcceleration =
	//accelerometer.watchAcceleration =

}

var bridge = new Bridge();

<|endoftext|>


<commit_before>'use strict';

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

const Exchange = require ('./base/Exchange');
const { ExchangeError } = require ('./base/errors');

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

module.exports = class bxinth extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'bxinth',
            'name': 'BX.in.th',
            'countries': [ 'TH' ], // Thailand
            'rateLimit': 1500,
            'has': {
                'CORS': false,
                'fetchTickers': true,
                'fetchOpenOrders': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766412-567b1eb4-5ed7-11e7-94a8-ff6a3884f6c5.jpg',
                'api': 'https://bx.in.th/api',
                'www': 'https://bx.in.th',
                'doc': 'https://bx.in.th/info/api',
            },
            'api': {
                'public': {
                    'get': [
                        '', // ticker
                        'options',
                        'optionbook',
                        'orderbook',
                        'pairing',
                        'trade',
                        'tradehistory',
                    ],
                },
                'private': {
                    'post': [
                        'balance',
                        'biller',
                        'billgroup',
                        'billpay',
                        'cancel',
                        'deposit',
                        'getorders',
                        'history',
                        'option-issue',
                        'option-bid',
                        'option-sell',
                        'option-myissue',
                        'option-mybid',
                        'option-myoptions',
                        'option-exercise',
                        'option-cancel',
                        'option-history',
                        'order',
                        'withdrawal',
                        'withdrawal-history',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'taker': 0.25 / 100,
                    'maker': 0.25 / 100,
                },
            },
            'commonCurrencies': {
                'DAS': 'DASH',
                'DOG': 'DOGE',
            },
        });
    }

    async fetchMarkets () {
        let markets = await this.publicGetPairing ();
        let keys = Object.keys (markets);
        let result = [];
        for (let p = 0; p < keys.length; p++) {
            let market = markets[keys[p]];
            let id = market['pairing_id'].toString ();
            let baseId = market['secondary_currency'];
            let quoteId = market['primary_currency'];
            let active = market['active'];
            base = this.commonCurrencyCode (baseId);
            quote = this.commonCurrencyCode (quoteId);
            let symbol = base + '/' + quote;
            result.push ({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'baseId': baseId,
                'quoteId': quoteId,
                'active': active,
                'info': market,
            });
        }
        return result;
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let response = await this.privatePostBalance ();
        let balance = response['balance'];
        let result = { 'info': balance };
        let currencies = Object.keys (balance);
        for (let c = 0; c < currencies.length; c++) {
            let currency = currencies[c];
            let code = this.commonCurrencyCode (currency);
            let account = {
                'free': parseFloat (balance[currency]['available']),
                'used': 0.0,
                'total': parseFloat (balance[currency]['total']),
            };
            account['used'] = account['total'] - account['free'];
            result[code] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let orderbook = await this.publicGetOrderbook (this.extend ({
            'pairing': this.marketId (symbol),
        }, 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_price');
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': undefined,
            'low': undefined,
            'bid': parseFloat (ticker['orderbook']['bids']['highbid']),
            'bidVolume': undefined,
            'ask': parseFloat (ticker['orderbook']['asks']['highbid']),
            'askVolume': undefined,
            'vwap': undefined,
            'open': undefined,
            'close': last,
            'last': last,
            'previousClose': undefined,
            'change': this.safeFloat (ticker, 'change'),
            'percentage': undefined,
            'average': undefined,
            'baseVolume': this.safeFloat (ticker, 'volume_24hours'),
            'quoteVolume': undefined,
            'info': ticker,
        };
    }

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

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let tickers = await this.publicGet (this.extend ({
            'pairing': market['id'],
        }, params));
        let id = market['id'].toString ();
        let ticker = tickers[id];
        return this.parseTicker (ticker, market);
    }

    parseTrade (trade, market) {
        let timestamp = this.parse8601 (trade['trade_date'] + '+07:00'); // Thailand UTC+7 offset
        return {
            'id': trade['trade_id'],
            'info': trade,
            'order': trade['order_id'],
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'type': undefined,
            'side': trade['trade_type'],
            'price': this.safeFloat (trade, 'rate'),
            'amount': this.safeFloat (trade, 'amount'),
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetTrade (this.extend ({
            'pairing': market['id'],
        }, params));
        return this.parseTrades (response['trades'], market, since, limit);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let response = await this.privatePostOrder (this.extend ({
            'pairing': this.marketId (symbol),
            'type': side,
            'amount': amount,
            'rate': price,
        }, params));
        return {
            'info': response,
            'id': response['order_id'].toString (),
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        let pairing = undefined; // TODO fixme
        return await this.privatePostCancel ({
            'order_id': id,
            'pairing': pairing,
        });
    }

    async parseOrder (order, market = undefined) {
        let side = this.safeString (order, 'order_type');
        let symbol = undefined;
        if (typeof market === 'undefined') {
            let marketId = this.safeString (order, 'pairing_id');
            if (typeof marketId !== 'undefined')
                if (marketId in this.markets_by_id)
                    market = this.markets_by_id[marketId];
        }
        if (typeof market !== 'undefined')
            symbol = market['symbol'];
        let timestamp = this.parse8601 (order['date']);
        let price = this.safeFloat (order, 'rate');
        let amount = this.safeFloat (order, 'amount');
        return {
            'info': order,
            'id': order['order_id'],
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'type': 'limit',
            'side': side,
            'price': price,
            'amount': amount,
        };
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let request = {};
        let market = undefined;
        if (typeof symbol !== 'undefined') {
            market = this.market (symbol);
            request['pairing'] = market['id'];
        }
        let response = this.privatePostGetorders (this.extend (request, params));
        let orders = this.parseOrders (response['orders'], market, since, limit);
        return this.filterBySymbol (orders, symbol);
    }

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

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        if (api === 'public')
            return response;
        if ('success' in response)
            if (response['success'])
                return response;
        throw new ExchangeError (this.id + ' ' + this.json (response));
    }
};
<commit_msg>minor typos<commit_after>'use strict';

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

const Exchange = require ('./base/Exchange');
const { ExchangeError } = require ('./base/errors');

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

module.exports = class bxinth extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'bxinth',
            'name': 'BX.in.th',
            'countries': [ 'TH' ], // Thailand
            'rateLimit': 1500,
            'has': {
                'CORS': false,
                'fetchTickers': true,
                'fetchOpenOrders': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766412-567b1eb4-5ed7-11e7-94a8-ff6a3884f6c5.jpg',
                'api': 'https://bx.in.th/api',
                'www': 'https://bx.in.th',
                'doc': 'https://bx.in.th/info/api',
            },
            'api': {
                'public': {
                    'get': [
                        '', // ticker
                        'options',
                        'optionbook',
                        'orderbook',
                        'pairing',
                        'trade',
                        'tradehistory',
                    ],
                },
                'private': {
                    'post': [
                        'balance',
                        'biller',
                        'billgroup',
                        'billpay',
                        'cancel',
                        'deposit',
                        'getorders',
                        'history',
                        'option-issue',
                        'option-bid',
                        'option-sell',
                        'option-myissue',
                        'option-mybid',
                        'option-myoptions',
                        'option-exercise',
                        'option-cancel',
                        'option-history',
                        'order',
                        'withdrawal',
                        'withdrawal-history',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'taker': 0.25 / 100,
                    'maker': 0.25 / 100,
                },
            },
            'commonCurrencies': {
                'DAS': 'DASH',
                'DOG': 'DOGE',
            },
        });
    }

    async fetchMarkets () {
        let markets = await this.publicGetPairing ();
        let keys = Object.keys (markets);
        let result = [];
        for (let p = 0; p < keys.length; p++) {
            let market = markets[keys[p]];
            let id = market['pairing_id'].toString ();
            let baseId = market['secondary_currency'];
            let quoteId = market['primary_currency'];
            let active = market['active'];
            let base = this.commonCurrencyCode (baseId);
            let quote = this.commonCurrencyCode (quoteId);
            let symbol = base + '/' + quote;
            result.push ({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'baseId': baseId,
                'quoteId': quoteId,
                'active': active,
                'info': market,
            });
        }
        return result;
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let response = await this.privatePostBalance ();
        let balance = response['balance'];
        let result = { 'info': balance };
        let currencies = Object.keys (balance);
        for (let c = 0; c < currencies.length; c++) {
            let currency = currencies[c];
            let code = this.commonCurrencyCode (currency);
            let account = {
                'free': parseFloat (balance[currency]['available']),
                'used': 0.0,
                'total': parseFloat (balance[currency]['total']),
            };
            account['used'] = account['total'] - account['free'];
            result[code] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let orderbook = await this.publicGetOrderbook (this.extend ({
            'pairing': this.marketId (symbol),
        }, 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_price');
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': undefined,
            'low': undefined,
            'bid': parseFloat (ticker['orderbook']['bids']['highbid']),
            'bidVolume': undefined,
            'ask': parseFloat (ticker['orderbook']['asks']['highbid']),
            'askVolume': undefined,
            'vwap': undefined,
            'open': undefined,
            'close': last,
            'last': last,
            'previousClose': undefined,
            'change': this.safeFloat (ticker, 'change'),
            'percentage': undefined,
            'average': undefined,
            'baseVolume': this.safeFloat (ticker, 'volume_24hours'),
            'quoteVolume': undefined,
            'info': ticker,
        };
    }

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

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let tickers = await this.publicGet (this.extend ({
            'pairing': market['id'],
        }, params));
        let id = market['id'].toString ();
        let ticker = tickers[id];
        return this.parseTicker (ticker, market);
    }

    parseTrade (trade, market) {
        let timestamp = this.parse8601 (trade['trade_date'] + '+07:00'); // Thailand UTC+7 offset
        return {
            'id': trade['trade_id'],
            'info': trade,
            'order': trade['order_id'],
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'type': undefined,
            'side': trade['trade_type'],
            'price': this.safeFloat (trade, 'rate'),
            'amount': this.safeFloat (trade, 'amount'),
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetTrade (this.extend ({
            'pairing': market['id'],
        }, params));
        return this.parseTrades (response['trades'], market, since, limit);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let response = await this.privatePostOrder (this.extend ({
            'pairing': this.marketId (symbol),
            'type': side,
            'amount': amount,
            'rate': price,
        }, params));
        return {
            'info': response,
            'id': response['order_id'].toString (),
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        let pairing = undefined; // TODO fixme
        return await this.privatePostCancel ({
            'order_id': id,
            'pairing': pairing,
        });
    }

    async parseOrder (order, market = undefined) {
        let side = this.safeString (order, 'order_type');
        let symbol = undefined;
        if (typeof market === 'undefined') {
            let marketId = this.safeString (order, 'pairing_id');
            if (typeof marketId !== 'undefined')
                if (marketId in this.markets_by_id)
                    market = this.markets_by_id[marketId];
        }
        if (typeof market !== 'undefined')
            symbol = market['symbol'];
        let timestamp = this.parse8601 (order['date']);
        let price = this.safeFloat (order, 'rate');
        let amount = this.safeFloat (order, 'amount');
        return {
            'info': order,
            'id': order['order_id'],
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'type': 'limit',
            'side': side,
            'price': price,
            'amount': amount,
        };
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let request = {};
        let market = undefined;
        if (typeof symbol !== 'undefined') {
            market = this.market (symbol);
            request['pairing'] = market['id'];
        }
        let response = this.privatePostGetorders (this.extend (request, params));
        let orders = this.parseOrders (response['orders'], market, since, limit);
        return this.filterBySymbol (orders, symbol);
    }

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

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        if (api === 'public')
            return response;
        if ('success' in response)
            if (response['success'])
                return response;
        throw new ExchangeError (this.id + ' ' + this.json (response));
    }
};
<|endoftext|>


<commit_before>var byejob = {

	KEY_CURRENT_DAY: "byejob.current.day",
	KEY_ENTRY_1: "byejob.entry1",
	KEY_ENTRY_2: "byejob.entry2",
	KEY_LEAVE_1: "byejob.leave1",

	jEntry1: null,
	jEntry2: null,
	jLeave1: null,

	init : function() {
		this.loadJqueryObjects();
		this.loadEvents();
		this.loadCurrentDay();
	},

	loadCurrentDay: function(){
		var self = this;
		var currentDay = self.getKeyLocalSession(self.KEY_CURRENT_DAY);

		if (currentDay) {
			if(currentDay == new Date().getDay()) {
				self.loadTimes();
			} else {
				self.reseteTimes();
			}
		} else {
			self.saveCurrentDay();
		}
	},

	loadTimes: function(){
		var entry1 = this.getKeyLocalSession(this.KEY_ENTRY_1);
		if(entry1){
			this.jEntry1.val(this.getTimeString(entry1));
		}

		var entry2 = this.getKeyLocalSession(this.KEY_ENTRY_2);
		if(entry2){
			this.jEntry2.val(this.getTimeString(entry2));
		}

		var leave1 = this.getKeyLocalSession(this.getTimeString(this.KEY_LEAVE_1));
		if(leave1){
			this.jLeave1.val(leave1);
		}
	},

	getTimeString: function(date){
		var time = new Date();
		time.setTime(date);
		return time.getHours() + ":" + time.getMinutes();
	},

	reseteTimes: function(){
		localStorage.removeItem(this.KEY_ENTRY_1);
		this.jEntry1.val("");

		localStorage.removeItem(this.KEY_ENTRY_2);
		this.jEntry2.val("");

		localStorage.removeItem(this.KEY_LEAVE_1);
		this.jLeave1.val("");

		this.saveCurrentDay();
	},

	saveCurrentDay: function(){
		this.saveKeyLocalSession(this.KEY_CURRENT_DAY, new Date().getDay());
	},

	saveTime: function(event){
		var self = this;
		var jEntry = $(event.target);
		var time = jEntry.val().trim();

		if(time.length > 0){
			var value = self.getTime(time).getTime();
			var data = jEntry.data('entry');
			if (data) {
				if (data == 1) {
					self.saveKeyLocalSession(self.KEY_ENTRY_1, value);
				} else if(data == 2) {
					self.saveKeyLocalSession(self.KEY_ENTRY_2, value);
				}
			} else {
				var data = jEntry.data('leave');
				if (data && data == 1) {
					self.saveKeyLocalSession(self.KEY_LEAVE_1, value);
				}
			}
		}
	},

	saveKeyLocalSession: function(key, value){
		localStorage.setItem(key, value);
	},

	getKeyLocalSession: function(key){
		return localStorage.getItem(key);
	},

	getTime: function(time){
		var timeArray = time.split(":");
		var date = new Date();
		date.setHours(timeArray[0]);
		date.setMinutes(timeArray[1]);
		date.setSeconds(0);
		date.setMilliseconds(0);
		return date;
	},

	loadJqueryObjects: function(){
		this.jEntry1 = $('#entry_1');
		this.jEntry2 = $('#entry_2');
		this.jLeave1 = $('#leave_1');
	},

	loadEvents: function(){
		var self = this;
		self.jEntry1.on('blur', function(event){
			self.saveTime(event);
		});

		self.jEntry2.on('blur', function(event){
			self.saveTime(event);
		});

		self.jLeave1.on('blur', function(event){
			self.saveTime(event);
		});
	},

	loadJsFiles: function(){
		var self = this;
		setTimeout(function(){
			self.loadJsFile("../js/jquery-2.1.1.min.js", function(){
				self.init();
			});
		}, 1000);
	},

	loadJsFile: function(filename, callback){
		var fileref=document.createElement('script');
		fileref.setAttribute("type","text/javascript");
		fileref.setAttribute("src", filename);
		fileref.onload = callback;
		document.getElementsByTagName("head")[0].appendChild(fileref);
	}
};

document.addEventListener('DOMContentLoaded', function() {
	byejob.loadJsFiles();
});<commit_msg>Atualizando save e load de batidas<commit_after>var byejob = {

	KEY_CURRENT_DAY: "byejob.current.day",
	KEY_ENTRY_1: "byejob.entry1",
	KEY_ENTRY_2: "byejob.entry2",
	KEY_LEAVE_1: "byejob.leave1",

	jEntry1: null,
	jEntry2: null,
	jLeave1: null,

	init : function() {
		this.loadJqueryObjects();
		this.loadEvents();
		this.loadCurrentDay();
	},

	loadCurrentDay: function(){
		var self = this;
		var currentDay = self.getKeyLocalSession(self.KEY_CURRENT_DAY);

		if (currentDay) {
			if(currentDay == new Date().getDay()) {
				self.loadTimes();
			} else {
				self.reseteTimes();
			}
		} else {
			self.saveCurrentDay();
		}
	},

	loadTimes: function(){
		var entry1 = this.getKeyLocalSession(this.KEY_ENTRY_1);
		if(entry1){
			this.jEntry1.val(this.getTimeString(entry1));
		}

		var entry2 = this.getKeyLocalSession(this.KEY_ENTRY_2);
		if(entry2){
			this.jEntry2.val(this.getTimeString(entry2));
		}

		var leave1 = this.getKeyLocalSession(this.KEY_LEAVE_1);
		if(leave1){
			this.jLeave1.val(this.getTimeString(leave1));
		}
	},

	getTimeString: function(date){
		var time = new Date();
		time.setTime(date);
		var hours = time.getHours();
		var minutes = time.getMinutes();
		return (hours > 10 ? hours : '0' + hours) + ":" + (minutes > 10 ? minutes : '0' + minutes);
	},

	reseteTimes: function(){
		localStorage.removeItem(this.KEY_ENTRY_1);
		this.jEntry1.val("");

		localStorage.removeItem(this.KEY_ENTRY_2);
		this.jEntry2.val("");

		localStorage.removeItem(this.KEY_LEAVE_1);
		this.jLeave1.val("");

		this.saveCurrentDay();
	},

	saveCurrentDay: function(){
		this.saveKeyLocalSession(this.KEY_CURRENT_DAY, new Date().getDay());
	},

	saveTime: function(event){
		var self = this;
		var jEntry = $(event.target);
		var time = jEntry.val().trim();

		if(time.length > 0){
			var value = self.getTime(time).getTime();
			var data = jEntry.data('entry');
			if (data) {
				if (data == 1) {
					self.saveKeyLocalSession(self.KEY_ENTRY_1, value);
				} else if(data == 2) {
					self.saveKeyLocalSession(self.KEY_ENTRY_2, value);
				}
			} else {
				var data = jEntry.data('leave');
				if (data && data == 1) {
					self.saveKeyLocalSession(self.KEY_LEAVE_1, value);
				}
			}
		}
	},

	saveKeyLocalSession: function(key, value){
		localStorage.setItem(key, value);
	},

	getKeyLocalSession: function(key){
		return localStorage.getItem(key);
	},

	getTime: function(time){
		var timeArray = time.split(":");
		var date = new Date();
		date.setHours(timeArray[0]);
		date.setMinutes(timeArray[1]);
		date.setSeconds(0);
		date.setMilliseconds(0);
		return date;
	},

	loadJqueryObjects: function(){
		this.jEntry1 = $('#entry_1');
		this.jEntry2 = $('#entry_2');
		this.jLeave1 = $('#leave_1');
	},

	loadEvents: function(){
		var self = this;
		self.jEntry1.on('blur', function(event){
			self.saveTime(event);
		});

		self.jEntry2.on('blur', function(event){
			self.saveTime(event);
		});

		self.jLeave1.on('blur', function(event){
			self.saveTime(event);
		});
	},

	loadJsFiles: function(){
		var self = this;
		setTimeout(function(){
			self.loadJsFile("../js/jquery-2.1.1.min.js", function(){
				self.init();
			});
		}, 1000);
	},

	loadJsFile: function(filename, callback){
		var fileref=document.createElement('script');
		fileref.setAttribute("type","text/javascript");
		fileref.setAttribute("src", filename);
		fileref.onload = callback;
		document.getElementsByTagName("head")[0].appendChild(fileref);
	}
};

document.addEventListener('DOMContentLoaded', function() {
	byejob.loadJsFiles();
});<|endoftext|>


<commit_before>TrelloPowerUp.initialize({
  'board-buttons': function(t, options){
    return [{
    icon: './images/button-pic.jpg',
    text: 'My Button',
    callback: function(t){
      var elem = document.getElementById("header");
      elem.parentNode.removeChild(elem);
    }}];
  }
});
<commit_msg>test alert<commit_after>TrelloPowerUp.initialize({
  'board-buttons': function(t, options){
    return [{
    icon: './images/button-pic.jpg',
    text: 'My Button',
    callback: function(t){
      alert("Hello world");
    }}];
  }
});
<|endoftext|>