<commit_before>var EventEmitter = require('eventemitter2').EventEmitter2,
    util = require('util'),
    Discovery = require('./Discovery'),
    axon = require('axon'),
    Subscriber = require('./Subscriber'),
    Requester = require('./Requester');

var Sockend = function(io, advertisement, discoveryOptions) {
    EventEmitter.call(this, {
        wildcard: true, // should the event emitter use wildcards.
        delimiter: '::', // the delimiter used to segment namespaces, defaults to `.`.
        newListener: false, // if you want to emit the newListener event set to true.
        maxListeners: 2000 // the max number of listeners that can be assigned to an event, defaults to 10.
    });

    advertisement = advertisement || {};
    advertisement.axon_type = 'sockend';
    this.advertisement = advertisement;

    var that = this,
        d = Discovery(advertisement, discoveryOptions);

    var namespaces = {};

    d.on('added', function(obj) {
        if (obj.advertisement.axon_type != 'rep') return;
        if (obj.advertisement.key != advertisement.key) return;

        var namespace = obj.advertisement.namespace,
            normalizedNamespace =  namespace || '';

        if (namespaces['/' + normalizedNamespace]) return;

        namespaces['/' + normalizedNamespace] = true;
        obj.namespace = namespace;

        var requester = new Requester({
            name: 'sockendReq',
            namespace: namespace,
            key: that.advertisement.key
        }, discoveryOptions);
        obj.requester = requester;

        obj.requesterSocketHandler = function(socket) {
            obj.advertisement.respondsTo.forEach(function(topic) {
                socket.on(topic, function(data, cb) {
                    if (arguments.length == 1 && typeof data == 'function') {
                        cb = data;
                        data = {};
                    }

                    var req = {
                        type: topic,
                        data: data
                    };

                    requester.send(req, cb);
                });
            });
        };

        requester.on('ready', function() {
            var server = io.sockets;
            if (namespace) server = io.of('/' + namespace);
            server.on('connection', obj.requesterSocketHandler);
        });
    });

    d.on('added', function(obj) {
        if (obj.advertisement.axon_type != 'pub-emitter') return;
        if (obj.advertisement.key != advertisement.key) return;

        var subscriber = new Subscriber({
            name: 'sockendSub',
            namespace: obj.advertisement.namespace,
            key: that.advertisement.key
        }, discoveryOptions);

        obj.subscriber = subscriber;

        subscriber.on('**', function(data) {
            if (this.event == 'added' || this.event == 'removed') return;

            var topic = this.event.split('::'),
                namespace = '';

            if (topic.length > 1) {
                namespace += '/' + topic[0];
                topic = topic.slice(1)
            }

            topic = topic.join('');

            io.of(namespace).emit(topic, data);
        });

        subscriber.on('removed', function() {
            subscriber.close();
        });
    });
};
util.inherits(Sockend, EventEmitter);

module.exports = Sockend;
<commit_msg>Implement request transformators for Sockend that allows the implementer to modify requests.<commit_after>var EventEmitter = require('eventemitter2').EventEmitter2,
    util = require('util'),
    Discovery = require('./Discovery'),
    axon = require('axon'),
    Subscriber = require('./Subscriber'),
    Requester = require('./Requester');

var Sockend = function(io, advertisement, discoveryOptions) {
    EventEmitter.call(this, {
        wildcard: true, // should the event emitter use wildcards.
        delimiter: '::', // the delimiter used to segment namespaces, defaults to `.`.
        newListener: false, // if you want to emit the newListener event set to true.
        maxListeners: 2000 // the max number of listeners that can be assigned to an event, defaults to 10.
    });

    advertisement = advertisement || {};
    advertisement.axon_type = 'sockend';
    this.advertisement = advertisement;
    this.requesterTransformators = [];

    var that = this,
        d = Discovery(advertisement, discoveryOptions);

    var namespaces = {};

    d.on('added', function(obj) {
        if (obj.advertisement.axon_type != 'rep') return;
        if (obj.advertisement.key != advertisement.key) return;

        var namespace = obj.advertisement.namespace,
            normalizedNamespace =  namespace || '';

        if (namespaces['/' + normalizedNamespace]) return;

        namespaces['/' + normalizedNamespace] = true;
        obj.namespace = namespace;

        var requester = new Requester({
            name: 'sockendReq',
            namespace: namespace,
            key: that.advertisement.key
        }, discoveryOptions);
        obj.requester = requester;

        obj.requesterSocketHandler = function(socket) {
            obj.advertisement.respondsTo.forEach(function(topic) {
                socket.on(topic, function(data, cb) {
                    if (arguments.length == 1 && typeof data == 'function') {
                        cb = data;
                        data = {};
                    }

                    var req = {
                        type: topic,
                        data: data
                    };

                    that.requesterTransformators.forEach(function(transFn) {
                        transFn(req, socket);
                    });

                    requester.send(req, cb);
                });
            });
        };

        requester.on('ready', function() {
            var server = io.sockets;
            if (namespace) server = io.of('/' + namespace);
            server.on('connection', obj.requesterSocketHandler);
        });
    });

    d.on('added', function(obj) {
        if (obj.advertisement.axon_type != 'pub-emitter') return;
        if (obj.advertisement.key != advertisement.key) return;

        var subscriber = new Subscriber({
            name: 'sockendSub',
            namespace: obj.advertisement.namespace,
            key: that.advertisement.key
        }, discoveryOptions);

        obj.subscriber = subscriber;

        subscriber.on('**', function(data) {
            if (this.event == 'added' || this.event == 'removed') return;

            var topic = this.event.split('::'),
                namespace = '';

            if (topic.length > 1) {
                namespace += '/' + topic[0];
                topic = topic.slice(1)
            }

            topic = topic.join('');

            io.of(namespace).emit(topic, data);
        });

        subscriber.on('removed', function() {
            subscriber.close();
        });
    });
};
util.inherits(Sockend, EventEmitter);

module.exports = Sockend;
<|endoftext|>


<commit_before>var NAME = "Crazy Penguins";
var indetifier = require('./indetifier');
global.map = global.map || [];

module.exports = {

  VERSION: "0.2.2",

  bet_request: function (game_state, bet) {
    var highCards = ['10', 'J', 'Q', 'K', 'A'];
    var highCardsForLessPeople = ['7', '8', '9', '10', 'J', 'Q', 'K', 'A'];

    var smallCardsForPair = ['2', '3', '4', '5'];
    var betTreshold = 0.2; //prcentages of player money, see isBetNotBig() function
    var playersTreshold = 2;
    var allInStep = 0.25;
    var smallPairBetMultiplier = 0.7;
    var player = game_state.players[game_state.in_action];

    function getMinBetForKeepPlaying() {
      //return game_state.players.reduce(function (p, n) { return n.bet > p ? n.bet : p }, 0);
      return game_state.current_buy_in;
    }

    function getGameBetRound() {
      var round = map[game_state.game_id];
      if (round != undefined) {
        round++;
      } else {
        map = [];
        round = 0;
      }

      map[game_state.game_id] = round;

      return round;
    }

    function isCardNotEmpty() {
      return player.hole_cards[0] && player.hole_cards[1];
    }

    function isPairCards() {
      return player.hole_cards[0].rank == player.hole_cards[1].rank;
    }

    function isCardPresent(array) {
      return array.some(function (cardsElement) {
        return player.hole_cards[0].rank == cardsElement || player.hole_cards[1].rank == cardsElement;
      });
    }

    function isHighCardPresent() {
      return isCardPresent(highCards);
    }

    function isHighCardForLessPeoplePresent() {
      return isCardPresent(highCardsForLessPeople);
    }

    function isSmallCardPresent() {
      return smallCardsForPair.some(function (cardsElement) {
        return player.hole_cards[0].rank == cardsElement || player.hole_cards[1].rank == cardsElement;
      });
      // return false;
    }

    function isPostFlop() {
      return game_state.community_cards.length > 0;
    }

    function isAnyPlaybleCombination() {
      indetifier.setCards(player.hole_cards, game_state.community_cards);
      return (indetifier.isPair() && isHighCardPresent()) || indetifier.isTriple() || indetifier.isTwoPairs() || indetifier.isKare() || indetifier.isFullHouse();
    }

    var minBet = getMinBetForKeepPlaying();

    function isBetNotBig() {
      return minBet < player.stack * betTreshold;
    }

    function getActivePlayersCount() {
      return game_state.players.filter(function (p) { return p.status == "active" }).length;
    }

    function manyPlayersCanPlay() {
      return getActivePlayersCount() > playersTreshold;
      // return true;
    }

    function getAllIn() {
      // bet(player.stack);
      bet(Math.round(minBet + (player.stack * allInStep)));
    }

    if (isCardNotEmpty() && isAnyPlaybleCombination()) {
      //All in!
      getAllIn();
    } else if (!manyPlayersCanPlay()) {
      if (isCardNotEmpty() && (indetifier.isPair() && isHighCardForLessPeoplePresent())) {
        //All in!
        getAllIn();
      } else if (/*isBetNotBig() &&*/ isCardNotEmpty() && isHighCardPresent()) {
        bet(minBet/* + game_state.minimum_raise*/);
      } else {
        bet(0);
      }
    } else {
      bet(0);
    }
  },

  showdown: function (game_state) {

  }
};
<commit_msg>asdasfsdfs<commit_after>var NAME = "Crazy Penguins";
var indetifier = require('./indetifier');
global.map = global.map || [];

module.exports = {

  VERSION: "0.2.2",

  bet_request: function (game_state, bet) {
    var highCards = ['10', 'J', 'Q', 'K', 'A'];
    var highCardsForLessPeople = ['7', '8', '9', '10', 'J', 'Q', 'K', 'A'];

    var smallCardsForPair = ['2', '3', '4', '5'];
    var betTreshold = 0.2; //prcentages of player money, see isBetNotBig() function
    var playersTreshold = 2;
    var allInStep = 0.25;
    var smallPairBetMultiplier = 0.7;
    var player = game_state.players[game_state.in_action];

    function getMinBetForKeepPlaying() {
      //return game_state.players.reduce(function (p, n) { return n.bet > p ? n.bet : p }, 0);
      return game_state.current_buy_in || 0;
    }

    function getGameBetRound() {
      var round = map[game_state.game_id];
      if (round != undefined) {
        round++;
      } else {
        map = [];
        round = 0;
      }

      map[game_state.game_id] = round;

      return round;
    }

    function isCardNotEmpty() {
      return player.hole_cards[0] && player.hole_cards[1];
    }

    function isPairCards() {
      return player.hole_cards[0].rank == player.hole_cards[1].rank;
    }

    function isCardPresent(array) {
      return array.some(function (cardsElement) {
        return player.hole_cards[0].rank == cardsElement || player.hole_cards[1].rank == cardsElement;
      });
    }

    function isHighCardPresent() {
      return isCardPresent(highCards);
    }

    function isHighCardForLessPeoplePresent() {
      return isCardPresent(highCardsForLessPeople);
    }

    function isSmallCardPresent() {
      return smallCardsForPair.some(function (cardsElement) {
        return player.hole_cards[0].rank == cardsElement || player.hole_cards[1].rank == cardsElement;
      });
      // return false;
    }

    function isPostFlop() {
      return game_state.community_cards.length > 0;
    }

    function isAnyPlaybleCombination() {
      indetifier.setCards(player.hole_cards, game_state.community_cards);
      return (indetifier.isPair() && isHighCardPresent()) || indetifier.isTriple() || indetifier.isTwoPairs() || indetifier.isKare() || indetifier.isFullHouse();
    }

    var minBet = getMinBetForKeepPlaying();

    function isBetNotBig() {
      return minBet < player.stack * betTreshold;
    }

    function getActivePlayersCount() {
      return game_state.players.filter(function (p) { return p.status == "active" }).length;
    }

    function manyPlayersCanPlay() {
      return getActivePlayersCount() > playersTreshold;
      // return true;
    }

    function getAllIn() {
      // bet(player.stack);
      bet(Math.round(minBet + (player.stack * allInStep)));
    }

    if (isCardNotEmpty() && isAnyPlaybleCombination()) {
      //All in!
      getAllIn();
    } else if (!manyPlayersCanPlay()) {
      if (isCardNotEmpty() && (indetifier.isPair() && isHighCardForLessPeoplePresent())) {
        //All in!
        getAllIn();
      } else if (/*isBetNotBig() &&*/ isCardNotEmpty() && isHighCardPresent()) {
        bet(minBet/* + game_state.minimum_raise*/);
      } else {
        bet(0);
      }
    } else {
      bet(0);
    }
  },

  showdown: function (game_state) {

  }
};
<|endoftext|>


<commit_before>define(function(require) {
  var $ = require('jquery');
  var rtp = require('rtp/ui-module');
  require('rtp/controllers/map-page');
  require('rtp/controllers/login-page');

  rtp.config(function($routeProvider) {
    $routeProvider.when('/login', {
      templateUrl: 'login.html',
      controller: 'LoginPageController'
    });
    // /logout has no view, it redirects back to the main page.
    $routeProvider.otherwise({
      templateUrl: 'map.html',
      controller: 'MapPageController'
    });
  });
  rtp.controller('MainController', function() {
    console.log('MainController loaded');
  });

  angular.bootstrap($('body')[0], ['rtp']);
});
<commit_msg>Enabling html5 mode for routes.<commit_after>define(function(require) {
  var $ = require('jquery');
  var rtp = require('rtp/ui-module');
  require('rtp/controllers/map-page');
  require('rtp/controllers/login-page');

  rtp.config(function($routeProvider, $locationProvider) {
    $locationProvider.html5Mode(true);
    $routeProvider.when('/login', {
      templateUrl: 'login.html',
      controller: 'LoginPageController'
    });
    // /logout has no view, it redirects back to the main page.
    $routeProvider.otherwise({
      templateUrl: 'map.html',
      controller: 'MapPageController'
    });
  });
  rtp.controller('MainController', function() {
    console.log('MainController loaded');
  });

  angular.bootstrap($('body')[0], ['rtp']);
});
<|endoftext|>


<commit_before>/* Copyright 2017 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const globalScope = require('./global_scope');

// Skip compatibility checks for the extensions and if we already ran
// this module.
if ((typeof PDFJSDev === 'undefined' ||
     !PDFJSDev.test('FIREFOX || MOZCENTRAL')) &&
    !globalScope._pdfjsCompatibilityChecked) {

globalScope._pdfjsCompatibilityChecked = true;

const isNodeJS = require('./is_node');

const hasDOM = typeof window === 'object' && typeof document === 'object';

// Support: Node.js
(function checkNodeBtoa() {
  if (globalScope.btoa || !isNodeJS()) {
    return;
  }
  globalScope.btoa = function(chars) {
    // eslint-disable-next-line no-undef
    return Buffer.from(chars, 'binary').toString('base64');
  };
})();

// Support: Node.js
(function checkNodeAtob() {
  if (globalScope.atob || !isNodeJS()) {
    return;
  }
  globalScope.atob = function(input) {
    // eslint-disable-next-line no-undef
    return Buffer.from(input, 'base64').toString('binary');
  };
})();

// Provides support for ChildNode.remove in legacy browsers.
// Support: IE.
(function checkChildNodeRemove() {
  if (!hasDOM) {
    return;
  }
  if (typeof Element.prototype.remove !== 'undefined') {
    return;
  }
  Element.prototype.remove = function () {
    if (this.parentNode) {
      // eslint-disable-next-line mozilla/avoid-removeChild
      this.parentNode.removeChild(this);
    }
  };
})();

// Provides support for DOMTokenList.prototype.{add, remove}, with more than
// one parameter, in legacy browsers.
// Support: IE
(function checkDOMTokenListAddRemove() {
  if (!hasDOM || isNodeJS()) {
    return;
  }
  const div = document.createElement('div');
  div.classList.add('testOne', 'testTwo');

  if (div.classList.contains('testOne') === true &&
      div.classList.contains('testTwo') === true) {
    return;
  }
  const OriginalDOMTokenListAdd = DOMTokenList.prototype.add;
  const OriginalDOMTokenListRemove = DOMTokenList.prototype.remove;

  DOMTokenList.prototype.add = function(...tokens) {
    for (let token of tokens) {
      OriginalDOMTokenListAdd.call(this, token);
    }
  };
  DOMTokenList.prototype.remove = function(...tokens) {
    for (let token of tokens) {
      OriginalDOMTokenListRemove.call(this, token);
    }
  };
})();

// Provides support for DOMTokenList.prototype.toggle, with the optional
// "force" parameter, in legacy browsers.
// Support: IE
(function checkDOMTokenListToggle() {
  if (!hasDOM || isNodeJS()) {
    return;
  }
  const div = document.createElement('div');
  if (div.classList.toggle('test', 0) === false) {
    return;
  }

  DOMTokenList.prototype.toggle = function(token) {
    let force = (arguments.length > 1 ? !!arguments[1] : !this.contains(token));
    return (this[force ? 'add' : 'remove'](token), force);
  };
})();

// Provides support for String.prototype.startsWith in legacy browsers.
// Support: IE, Chrome<41
(function checkStringStartsWith() {
  if (String.prototype.startsWith) {
    return;
  }
  require('core-js/es/string/starts-with');
})();

// Provides support for String.prototype.endsWith in legacy browsers.
// Support: IE, Chrome<41
(function checkStringEndsWith() {
  if (String.prototype.endsWith) {
    return;
  }
  require('core-js/es/string/ends-with');
})();

// Provides support for String.prototype.includes in legacy browsers.
// Support: IE, Chrome<41
(function checkStringIncludes() {
  if (String.prototype.includes) {
    return;
  }
  require('core-js/es/string/includes');
})();

// Provides support for Array.prototype.includes in legacy browsers.
// Support: IE, Chrome<47
(function checkArrayIncludes() {
  if (Array.prototype.includes) {
    return;
  }
  require('core-js/es/array/includes');
})();

// Provides support for Array.from in legacy browsers.
// Support: IE
(function checkArrayFrom() {
  if (Array.from) {
    return;
  }
  require('core-js/es/array/from');
})();

// Provides support for Object.assign in legacy browsers.
// Support: IE
(function checkObjectAssign() {
  if (Object.assign) {
    return;
  }
  require('core-js/es/object/assign');
})();

// Provides support for Math.log2 in legacy browsers.
// Support: IE, Chrome<38
(function checkMathLog2() {
  if (Math.log2) {
    return;
  }
  Math.log2 = require('core-js/es/math/log2');
})();

// Provides support for Number.isNaN in legacy browsers.
// Support: IE.
(function checkNumberIsNaN() {
  if (Number.isNaN) {
    return;
  }
  Number.isNaN = require('core-js/es/number/is-nan');
})();

// Provides support for Number.isInteger in legacy browsers.
// Support: IE, Chrome<34
(function checkNumberIsInteger() {
  if (Number.isInteger) {
    return;
  }
  Number.isInteger = require('core-js/es/number/is-integer');
})();

// Support: IE, Safari<11, Chrome<63
(function checkPromise() {
  if (typeof PDFJSDev !== 'undefined' && PDFJSDev.test('IMAGE_DECODERS')) {
    // The current image decoders are synchronous, hence `Promise` shouldn't
    // need to be polyfilled for the IMAGE_DECODERS build target.
    return;
  }
  if (globalScope.Promise && (globalScope.Promise.prototype &&
                              globalScope.Promise.prototype.finally)) {
    return;
  }
  globalScope.Promise = require('core-js/es/promise/index');
})();

// Support: IE
(function checkURL() {
  if (typeof PDFJSDev !== 'undefined' && PDFJSDev.test('IMAGE_DECODERS')) {
    // The current image decoders don't use the `URL` constructor, so it
    // doesn't need to be polyfilled for the IMAGE_DECODERS build target.
    return;
  }
  if (typeof PDFJSDev !== 'undefined' && !PDFJSDev.test('GENERIC')) {
    // The `URL` constructor is assumed to be available in the extension builds.
    return;
  }
  globalScope.URL = require('core-js/web/url');
})();

// Support: IE<11, Safari<8, Chrome<36
(function checkWeakMap() {
  if (globalScope.WeakMap) {
    return;
  }
  globalScope.WeakMap = require('core-js/es/weak-map/index');
})();

// Support: IE11
(function checkWeakSet() {
  if (globalScope.WeakSet) {
    return;
  }
  globalScope.WeakSet = require('core-js/es/weak-set/index');
})();

// Provides support for String.codePointAt in legacy browsers.
// Support: IE11.
(function checkStringCodePointAt() {
  if (String.prototype.codePointAt) {
    return;
  }
  require('core-js/es/string/code-point-at');
})();

// Provides support for String.fromCodePoint in legacy browsers.
// Support: IE11.
(function checkStringFromCodePoint() {
  if (String.fromCodePoint) {
    return;
  }
  String.fromCodePoint = require('core-js/es/string/from-code-point');
})();

// Support: IE
(function checkSymbol() {
  if (globalScope.Symbol) {
    return;
  }
  require('core-js/es/symbol/index');
})();

// Provides support for String.prototype.padStart in legacy browsers.
// Support: IE, Chrome<57
(function checkStringPadStart() {
  if (String.prototype.padStart) {
    return;
  }
  require('core-js/es/string/pad-start');
})();

// Provides support for String.prototype.padEnd in legacy browsers.
// Support: IE, Chrome<57
(function checkStringPadEnd() {
  if (String.prototype.padEnd) {
    return;
  }
  require('core-js/es/string/pad-end');
})();

// Provides support for Object.values in legacy browsers.
// Support: IE, Chrome<54
(function checkObjectValues() {
  if (Object.values) {
    return;
  }
  Object.values = require('core-js/es/object/values');
})();

}
<commit_msg>Update `src/shared/compatibility.js` to only run with `SKIP_BABEL = false` set<commit_after>/* Copyright 2017 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* eslint no-var: error */

const globalScope = require('./global_scope');

// Skip compatibility checks for modern builds and if we already ran the module.
if ((typeof PDFJSDev === 'undefined' || !PDFJSDev.test('SKIP_BABEL')) &&
    !globalScope._pdfjsCompatibilityChecked) {

globalScope._pdfjsCompatibilityChecked = true;

const isNodeJS = require('./is_node');

const hasDOM = typeof window === 'object' && typeof document === 'object';

// Support: Node.js
(function checkNodeBtoa() {
  if (globalScope.btoa || !isNodeJS()) {
    return;
  }
  globalScope.btoa = function(chars) {
    // eslint-disable-next-line no-undef
    return Buffer.from(chars, 'binary').toString('base64');
  };
})();

// Support: Node.js
(function checkNodeAtob() {
  if (globalScope.atob || !isNodeJS()) {
    return;
  }
  globalScope.atob = function(input) {
    // eslint-disable-next-line no-undef
    return Buffer.from(input, 'base64').toString('binary');
  };
})();

// Provides support for ChildNode.remove in legacy browsers.
// Support: IE.
(function checkChildNodeRemove() {
  if (!hasDOM) {
    return;
  }
  if (typeof Element.prototype.remove !== 'undefined') {
    return;
  }
  Element.prototype.remove = function () {
    if (this.parentNode) {
      // eslint-disable-next-line mozilla/avoid-removeChild
      this.parentNode.removeChild(this);
    }
  };
})();

// Provides support for DOMTokenList.prototype.{add, remove}, with more than
// one parameter, in legacy browsers.
// Support: IE
(function checkDOMTokenListAddRemove() {
  if (!hasDOM || isNodeJS()) {
    return;
  }
  const div = document.createElement('div');
  div.classList.add('testOne', 'testTwo');

  if (div.classList.contains('testOne') === true &&
      div.classList.contains('testTwo') === true) {
    return;
  }
  const OriginalDOMTokenListAdd = DOMTokenList.prototype.add;
  const OriginalDOMTokenListRemove = DOMTokenList.prototype.remove;

  DOMTokenList.prototype.add = function(...tokens) {
    for (let token of tokens) {
      OriginalDOMTokenListAdd.call(this, token);
    }
  };
  DOMTokenList.prototype.remove = function(...tokens) {
    for (let token of tokens) {
      OriginalDOMTokenListRemove.call(this, token);
    }
  };
})();

// Provides support for DOMTokenList.prototype.toggle, with the optional
// "force" parameter, in legacy browsers.
// Support: IE
(function checkDOMTokenListToggle() {
  if (!hasDOM || isNodeJS()) {
    return;
  }
  const div = document.createElement('div');
  if (div.classList.toggle('test', 0) === false) {
    return;
  }

  DOMTokenList.prototype.toggle = function(token) {
    let force = (arguments.length > 1 ? !!arguments[1] : !this.contains(token));
    return (this[force ? 'add' : 'remove'](token), force);
  };
})();

// Provides support for String.prototype.startsWith in legacy browsers.
// Support: IE, Chrome<41
(function checkStringStartsWith() {
  if (String.prototype.startsWith) {
    return;
  }
  require('core-js/es/string/starts-with');
})();

// Provides support for String.prototype.endsWith in legacy browsers.
// Support: IE, Chrome<41
(function checkStringEndsWith() {
  if (String.prototype.endsWith) {
    return;
  }
  require('core-js/es/string/ends-with');
})();

// Provides support for String.prototype.includes in legacy browsers.
// Support: IE, Chrome<41
(function checkStringIncludes() {
  if (String.prototype.includes) {
    return;
  }
  require('core-js/es/string/includes');
})();

// Provides support for Array.prototype.includes in legacy browsers.
// Support: IE, Chrome<47
(function checkArrayIncludes() {
  if (Array.prototype.includes) {
    return;
  }
  require('core-js/es/array/includes');
})();

// Provides support for Array.from in legacy browsers.
// Support: IE
(function checkArrayFrom() {
  if (Array.from) {
    return;
  }
  require('core-js/es/array/from');
})();

// Provides support for Object.assign in legacy browsers.
// Support: IE
(function checkObjectAssign() {
  if (Object.assign) {
    return;
  }
  require('core-js/es/object/assign');
})();

// Provides support for Math.log2 in legacy browsers.
// Support: IE, Chrome<38
(function checkMathLog2() {
  if (Math.log2) {
    return;
  }
  Math.log2 = require('core-js/es/math/log2');
})();

// Provides support for Number.isNaN in legacy browsers.
// Support: IE.
(function checkNumberIsNaN() {
  if (Number.isNaN) {
    return;
  }
  Number.isNaN = require('core-js/es/number/is-nan');
})();

// Provides support for Number.isInteger in legacy browsers.
// Support: IE, Chrome<34
(function checkNumberIsInteger() {
  if (Number.isInteger) {
    return;
  }
  Number.isInteger = require('core-js/es/number/is-integer');
})();

// Support: IE, Safari<11, Chrome<63
(function checkPromise() {
  if (typeof PDFJSDev !== 'undefined' && PDFJSDev.test('IMAGE_DECODERS')) {
    // The current image decoders are synchronous, hence `Promise` shouldn't
    // need to be polyfilled for the IMAGE_DECODERS build target.
    return;
  }
  if (globalScope.Promise && (globalScope.Promise.prototype &&
                              globalScope.Promise.prototype.finally)) {
    return;
  }
  globalScope.Promise = require('core-js/es/promise/index');
})();

// Support: IE
(function checkURL() {
  if (typeof PDFJSDev !== 'undefined' && PDFJSDev.test('IMAGE_DECODERS')) {
    // The current image decoders don't use the `URL` constructor, so it
    // doesn't need to be polyfilled for the IMAGE_DECODERS build target.
    return;
  }
  if (typeof PDFJSDev !== 'undefined' && !PDFJSDev.test('GENERIC')) {
    // The `URL` constructor is assumed to be available in the extension builds.
    return;
  }
  globalScope.URL = require('core-js/web/url');
})();

// Support: IE<11, Safari<8, Chrome<36
(function checkWeakMap() {
  if (globalScope.WeakMap) {
    return;
  }
  globalScope.WeakMap = require('core-js/es/weak-map/index');
})();

// Support: IE11
(function checkWeakSet() {
  if (globalScope.WeakSet) {
    return;
  }
  globalScope.WeakSet = require('core-js/es/weak-set/index');
})();

// Provides support for String.codePointAt in legacy browsers.
// Support: IE11.
(function checkStringCodePointAt() {
  if (String.prototype.codePointAt) {
    return;
  }
  require('core-js/es/string/code-point-at');
})();

// Provides support for String.fromCodePoint in legacy browsers.
// Support: IE11.
(function checkStringFromCodePoint() {
  if (String.fromCodePoint) {
    return;
  }
  String.fromCodePoint = require('core-js/es/string/from-code-point');
})();

// Support: IE
(function checkSymbol() {
  if (globalScope.Symbol) {
    return;
  }
  require('core-js/es/symbol/index');
})();

// Provides support for String.prototype.padStart in legacy browsers.
// Support: IE, Chrome<57
(function checkStringPadStart() {
  if (String.prototype.padStart) {
    return;
  }
  require('core-js/es/string/pad-start');
})();

// Provides support for String.prototype.padEnd in legacy browsers.
// Support: IE, Chrome<57
(function checkStringPadEnd() {
  if (String.prototype.padEnd) {
    return;
  }
  require('core-js/es/string/pad-end');
})();

// Provides support for Object.values in legacy browsers.
// Support: IE, Chrome<54
(function checkObjectValues() {
  if (Object.values) {
    return;
  }
  Object.values = require('core-js/es/object/values');
})();

}
<|endoftext|>


<commit_before>module.exports = {

    VERSION: "0.0.11",

    bet_request: function (game_state, bet) {
        var myBet        = 0,
            myIndex      = game_state.in_action,
            currentBuyIn = game_state.current_buy_in,
            myCurrentBet = game_state.players[myIndex].bet,
            myCards      = game_state.players[myIndex].hole_cards,
            myStack      = game_state.players[myIndex].stack,
            tableCards   = game_state.community_cards,
            allCards     = myCards.concat(tableCards),
            minimumRaise = game_state.minimum_raise,
            decision,
            multiplier   = 1,
            callBet      = this.getRaiseAmount(currentBuyIn, myCurrentBet, minimumRaise),
            raiseBet     = this.getCallAmount(currentBuyIn, myCurrentBet);

        if (tableCards.length) {
            if (this.checkIsStreetFlash(allCards)) {
                decision = this.ACTIONS.ALL_IN;
            } else if (this.checkIsCare(allCards)) {
                decision = this.ACTIONS.ALL_IN;
            } else if (this.checkIsFullHouse(allCards)) {
                decision = this.ACTIONS.ALL_IN;
            } else if (this.checkIsFlash(allCards)) {
                decision = this.ACTIONS.RAISE;
            } else if (this.checkIsStreet(allCards)) {
                decision = this.ACTIONS.RAISE;
            } else if (this.checkIsSet(allCards)) {
                if (callBet < 200) {
                    decision = this.ACTIONS.CALL;
                } else {
                    decision = this.ACTIONS.FOLD;
                }
            } else if (this.checkIsTwoPair(allCards)) {
                if (callBet < 100) {
                    decision = this.ACTIONS.CALL;
                } else {
                    decision = this.ACTIONS.FOLD;
                }
            } else if (this.checkIsPair(allCards)) {
                if (callBet < 50) {
                    decision = this.ACTIONS.CALL;
                } else {
                    decision = this.ACTIONS.FOLD;
                }
            } else {
                decision = this.ACTIONS.FOLD;
            }
        } else {
            //starting (no flop)
            var card1 = myCards[0],
                card2 = myCards[1];

            decision = this.ACTIONS.FOLD;

            if (card1.rank === card2.rank) {
                decision = this.ACTIONS.RAISE;
            } else if (this.HIGH_RANKS.indexOf(card1.rank) > -1 && this.HIGH_RANKS.indexOf(card2.rank) > -1) {
                decision = this.ACTIONS.RAISE;
            } else if (card1.suit == card2.suit) {
                decision = this.ACTIONS.CALL;
            }

            if (decision == this.ACTIONS.FOLD && callBet < 50) {
                decision = this.ACTIONS.CALL;
            }

            if (callBet > 400) {
                decision = this.ACTIONS.FOLD;
            }

            if (card1.rank === card2.rank && this.HIGH_RANKS.indexOf(card1.rank)) {
                decision = this.ACTIONS.CALL;
            }
        }

        if (decision == this.ACTIONS.RAISE) {
            myBet = callBet;
        } else if (decision == this.ACTIONS.CALL) {
            myBet = raiseBet;
        } else if (decision == this.ACTIONS.ALL_IN) {
            myBet = Math.round(myStack / 3);
        }

        console.log('======================================================================');
        console.log('my cards: ' + JSON.stringify(myCards));
        console.log('table cards: ' + JSON.stringify(tableCards));
        console.log('my stack: ' + myStack);
        console.log('decision: ' + decision);
        console.log('my bet: ' + myBet);
        console.log('======================================================================');

        bet(myBet);
    },

    // decisionMaker: function (game_state, myIndex, currentBuyIn, myCurrentBet, minimumRaise) {
    //     var myBet = 0,
    //         decision = this.checkCombination(game_state, myIndex);
    //
    //     if (decision == this.ACTIONS.RAISE) {
    //         myBet = this.getRaiseAmount(currentBuyIn, myCurrentBet);
    //     } else if (decision == this.ACTIONS.CALL) {
    //         myBet = this.getCallAmount(currentBuyIn, myCurrentBet, minimumRaise);
    //     }
    //
    //     return myBet;
    // },

    checkCombination: function (myCards) {
        var card1    = myCards[0],
            card2    = myCards[1],
            decision = this.ACTIONS.FOLD;

        if (card1.rank === card2.rank) {
            decision = this.ACTIONS.RAISE;
        } else if (this.HIGH_RANKS.indexOf(card1.rank) > -1 && this.HIGH_RANKS.indexOf(card2.rank) > -1) {
            decision = this.ACTIONS.RAISE;
        } else if (card1.suit == card2.suit) {
            decision = this.ACTIONS.CALL;
        }

        return decision;
    },

    getCallAmount: function (currentBuyIn, myCurrentBet) {
        var myBet = 0;

        myBet = currentBuyIn - myCurrentBet;

        return myBet;
    },

    getRaiseAmount: function (currentBuyIn, myCurrentBet, minimumRaise) {
        var myBet = 0;

        myBet = currentBuyIn - myCurrentBet + minimumRaise;

        return myBet;
    },

    checkIsFlash: function (incomingCards) {
        var spades = 0;
        var diamonds = 0;
        var hearts = 0;
        var clubs = 0;

        if (incomingCards.length <= 4) {
            return false;
        }

        for (var i = 0; i < incomingCards.length; i++) {
            var incomingCardItem = incomingCards[i];

            if (incomingCardItem.suit == this.SUITS.SPADES) {
                spades++;
            }
            if (incomingCardItem.suit == this.SUITS.DIAMONDS) {
                diamonds++;
            }
            if (incomingCardItem.suit == this.SUITS.HEARTS) {
                hearts++;
            }
            if (incomingCardItem.suit == this.SUITS.CLUBS) {
                clubs++;
            }
            if (spades == 5 || diamonds == 5 || hearts == 5 || clubs == 5) {
                return true;

            }
        }
        return false;
    },

    checkIsPair: function (incomingCards) {

        var pair = [];

        for (var i = 0; i < incomingCards.length; i++) {

            var incomingCard = incomingCards[i];

            if (!pair[incomingCard.rank]) pair[incomingCard.rank] = 0;

            pair[incomingCard.rank] = pair[incomingCard.rank] + 1;

        }

        for (var j in pair) {
            if (pair[j] >= 2) {
                return true;
            }
        }

        return false;

    },

    checkIsTwoPair: function (incomingCards) {

        var pair = [];

        for (var i = 0; i < incomingCards.length; i++) {

            var incomingCard = incomingCards[i];

            if (!pair[incomingCard.rank]) pair[incomingCard.rank] = 0;

            pair[incomingCard.rank] = pair[incomingCard.rank] + 1;

        }
        var countPair = 0;

        for (var j in pair) {
            if (pair[j] >= 2) {
                countPair++;

            }
            if (countPair == 2) {

                return true;
            }
        }

        return false;

    },

    checkIsSet: function (incomingCards) {

        var pair = [];

        for (var i = 0; i < incomingCards.length; i++) {

            var incomingCard = incomingCards[i];

            if (!pair[incomingCard.rank]) pair[incomingCard.rank] = 0;

            pair[incomingCard.rank] = pair[incomingCard.rank] + 1;

        }

        for (var j in pair) {
            if (pair[j] >= 3) {
                return true;
            }
        }

        return false;

    },

    checkIsStreet: function (incomingCards) {
        var arrRanks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"];

        var street = [];

        var tempStreet = [];

        if (incomingCards.length < 5) {
            return false;
        }
        for (var z = 0; z < arrRanks.length; z++) {
            street[arrRanks[z]] = 0;
        }

        for (var i = 0; i < incomingCards.length; i++) {

            var incomingCard = incomingCards[i];

            if (!street[incomingCard.rank]) street[incomingCard.rank] = 0;

            street[incomingCard.rank] = street[incomingCard.rank] + 1;

        }
        var countStreet = 0;
        for (var key in street) {

            if (street[key] != 0) {
                countStreet++
            }
            if (countStreet == 5) {
                return true;
            }
            if (street[key] == 0) {
                countStreet = 0;
            }
        }

        return false;

    },

    checkIsFullHouse: function (incomingCards) {
        var fullHouse = [];

        for (var i = 0; i < incomingCards.length; i++) {

            var incomingCard = incomingCards[i];

            if (!fullHouse[incomingCard.rank]) fullHouse[incomingCard.rank] = 0;

            fullHouse[incomingCard.rank] = fullHouse[incomingCard.rank] + 1;

        }
        var pair = false;
        var set = false;

        for (var j in fullHouse) {
            if (fullHouse[j] == 3) {
                set = true;
            }
            if (fullHouse[j] == 2) {
                pair = true;
            }
            if (pair && set) {
                return true;
            }
        }

        return false;
    },

    checkIsCare: function (incomingCards) {
        var checkCare = 0;
        var arrCombination = [];

        if (incomingCards.length < 4) {
            return false;
        }

        for (var i = 0; i < incomingCards.length; i++) {
            var incomingCardItem = incomingCards[i];

            if (!arrCombination[incomingCardItem.rank]) {
                arrCombination[incomingCardItem.rank] = 0;
            }

            arrCombination[incomingCardItem.rank] = arrCombination[incomingCardItem.rank] + 1;
        }

        for (var k in arrCombination) {
            if (arrCombination.hasOwnProperty(k)) {
                if (arrCombination[k] == 4) {
                    return true;
                }
            }
        }

        return false;
    },

    checkIsStreetFlash: function (incomingCards) {
        var spades = 0;
        var diamonds = 0;
        var hearts = 0;
        var clubs = 0;

        if (incomingCards.length <= 4) {
            return false
        }

        for (var i = 0; i < incomingCards.length; i++) {
            console.log(incomingCards[i]);
            var incomingCardItem = incomingCards[i];
            if (incomingCardItem.suit == 'spades') {
                spades++;
            }
            if (incomingCardItem.suit == 'diamonds') {
                diamonds++;
            }
            if (incomingCardItem.suit == 'hearts') {
                hearts++;
            }
            if (incomingCardItem.suit == 'clubs') {
                clubs++;
            }
            if (spades == 5 || diamonds == 5 || hearts == 5 || clubs == 5) {
                var arrRanks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"];

                var street = [];

                var tempStreet = [];

                if (incomingCards.length < 5) {
                    return false;
                }
                for (var z = 0; z < arrRanks.length; z++) {
                    street[arrRanks[z]] = 0;
                }

                for (var y = 0; y < incomingCards.length; y++) {

                    var incomingCard = incomingCards[y];

                    if (!street[incomingCard.rank]) street[incomingCard.rank] = 0;

                    street[incomingCard.rank] = street[incomingCard.rank] + 1;

                }
                var countStreet = 0;
                for (var key in street) {

                    if (street[key] != 0) {
                        countStreet++
                    }
                    if (countStreet == 5) {
                        return true;
                    }
                    if (street[key] == 0) {
                        countStreet = 0;
                    }
                }

            } else {
                return false;
            }
        }
        return false;
    },

    showdown: function (game_state) {

    },

    ACTIONS: {
        FOLD: 'fold',
        RAISE: 'raise',
        CALL: 'call',
        ALL_IN: 'allIn'
    },

    ALL_RANKS: ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"],

    HIGH_RANKS: ["A", "10", "J", "Q", "K"],

    // SUITS: ['spades', 'diamonds', 'hearts', 'clubs']

    SUITS: {
        SPADES: 'spades',
        DIAMONDS: 'diamonds',
        HEARTS: 'hearts',
        CLUBS: 'clubs'
    }
};
<commit_msg>improve<commit_after>module.exports = {

    VERSION: "0.0.12",

    bet_request: function (game_state, bet) {
        var myBet        = 0,
            myIndex      = game_state.in_action,
            currentBuyIn = game_state.current_buy_in,
            myCurrentBet = game_state.players[myIndex].bet,
            myCards      = game_state.players[myIndex].hole_cards,
            myStack      = game_state.players[myIndex].stack,
            tableCards   = game_state.community_cards,
            allCards     = myCards.concat(tableCards),
            minimumRaise = game_state.minimum_raise,
            decision,
            multiplier   = 1,
            callBet      = this.getRaiseAmount(currentBuyIn, myCurrentBet, minimumRaise),
            raiseBet     = this.getCallAmount(currentBuyIn, myCurrentBet);

        if (tableCards.length) {
            if (this.checkIsStreetFlash(allCards)) {
                decision = this.ACTIONS.ALL_IN;
            } else if (this.checkIsCare(allCards)) {
                decision = this.ACTIONS.ALL_IN;
            } else if (this.checkIsFullHouse(allCards)) {
                decision = this.ACTIONS.ALL_IN;
            } else if (this.checkIsFlash(allCards)) {
                decision = this.ACTIONS.RAISE;
            } else if (this.checkIsStreet(allCards)) {
                decision = this.ACTIONS.RAISE;
            } else if (this.checkIsSet(allCards)) {
                if (callBet < 200) {
                    decision = this.ACTIONS.CALL;
                } else {
                    decision = this.ACTIONS.FOLD;
                }
            } else if (this.checkIsTwoPair(allCards)) {
                if (callBet < 100) {
                    decision = this.ACTIONS.CALL;
                } else {
                    decision = this.ACTIONS.FOLD;
                }
            } else if (this.checkIsPair(allCards)) {
                if (callBet < 50) {
                    decision = this.ACTIONS.CALL;
                } else {
                    decision = this.ACTIONS.FOLD;
                }
            } else {
                decision = this.ACTIONS.FOLD;
            }
        } else {
            //starting (no flop)
            var card1 = myCards[0],
                card2 = myCards[1];

            decision = this.ACTIONS.FOLD;

            if (card1.rank === card2.rank) {
                decision = this.ACTIONS.RAISE;
            } else if (this.HIGH_RANKS.indexOf(card1.rank) > -1 && this.HIGH_RANKS.indexOf(card2.rank) > -1) {
                decision = this.ACTIONS.RAISE;
            } else if (card1.suit == card2.suit) {
                decision = this.ACTIONS.CALL;
            }

            if (decision == this.ACTIONS.FOLD && callBet < 30) {
                decision = this.ACTIONS.CALL;
            }

            if (card1.rank === card2.rank && this.VERY_HIGH_RANKS.indexOf(card1.rank)) {
                decision = this.ACTIONS.RAISE;
            }
        }

        if (decision == this.ACTIONS.RAISE) {
            myBet = callBet;
        } else if (decision == this.ACTIONS.CALL) {
            myBet = raiseBet;
        } else if (decision == this.ACTIONS.ALL_IN) {
            myBet = Math.round(myStack / 3);
        }

        console.log('======================================================================');
        console.log('my cards: ' + JSON.stringify(myCards));
        console.log('table cards: ' + JSON.stringify(tableCards));
        console.log('my stack: ' + myStack);
        console.log('decision: ' + decision);
        console.log('my bet: ' + myBet);
        console.log('======================================================================');

        bet(myBet);
    },

    // decisionMaker: function (game_state, myIndex, currentBuyIn, myCurrentBet, minimumRaise) {
    //     var myBet = 0,
    //         decision = this.checkCombination(game_state, myIndex);
    //
    //     if (decision == this.ACTIONS.RAISE) {
    //         myBet = this.getRaiseAmount(currentBuyIn, myCurrentBet);
    //     } else if (decision == this.ACTIONS.CALL) {
    //         myBet = this.getCallAmount(currentBuyIn, myCurrentBet, minimumRaise);
    //     }
    //
    //     return myBet;
    // },

    checkCombination: function (myCards) {
        var card1    = myCards[0],
            card2    = myCards[1],
            decision = this.ACTIONS.FOLD;

        if (card1.rank === card2.rank) {
            decision = this.ACTIONS.RAISE;
        } else if (this.HIGH_RANKS.indexOf(card1.rank) > -1 && this.HIGH_RANKS.indexOf(card2.rank) > -1) {
            decision = this.ACTIONS.RAISE;
        } else if (card1.suit == card2.suit) {
            decision = this.ACTIONS.CALL;
        }

        return decision;
    },

    getCallAmount: function (currentBuyIn, myCurrentBet) {
        var myBet = 0;

        myBet = currentBuyIn - myCurrentBet;

        return myBet;
    },

    getRaiseAmount: function (currentBuyIn, myCurrentBet, minimumRaise) {
        var myBet = 0;

        myBet = currentBuyIn - myCurrentBet + minimumRaise;

        return myBet;
    },

    checkIsFlash: function (incomingCards) {
        var spades = 0;
        var diamonds = 0;
        var hearts = 0;
        var clubs = 0;

        if (incomingCards.length <= 4) {
            return false;
        }

        for (var i = 0; i < incomingCards.length; i++) {
            var incomingCardItem = incomingCards[i];

            if (incomingCardItem.suit == this.SUITS.SPADES) {
                spades++;
            }
            if (incomingCardItem.suit == this.SUITS.DIAMONDS) {
                diamonds++;
            }
            if (incomingCardItem.suit == this.SUITS.HEARTS) {
                hearts++;
            }
            if (incomingCardItem.suit == this.SUITS.CLUBS) {
                clubs++;
            }
            if (spades == 5 || diamonds == 5 || hearts == 5 || clubs == 5) {
                return true;

            }
        }
        return false;
    },

    checkIsPair: function (incomingCards) {

        var pair = [];

        for (var i = 0; i < incomingCards.length; i++) {

            var incomingCard = incomingCards[i];

            if (!pair[incomingCard.rank]) pair[incomingCard.rank] = 0;

            pair[incomingCard.rank] = pair[incomingCard.rank] + 1;

        }

        for (var j in pair) {
            if (pair[j] >= 2) {
                return true;
            }
        }

        return false;

    },

    checkIsTwoPair: function (incomingCards) {

        var pair = [];

        for (var i = 0; i < incomingCards.length; i++) {

            var incomingCard = incomingCards[i];

            if (!pair[incomingCard.rank]) pair[incomingCard.rank] = 0;

            pair[incomingCard.rank] = pair[incomingCard.rank] + 1;

        }
        var countPair = 0;

        for (var j in pair) {
            if (pair[j] >= 2) {
                countPair++;

            }
            if (countPair == 2) {

                return true;
            }
        }

        return false;

    },

    checkIsSet: function (incomingCards) {

        var pair = [];

        for (var i = 0; i < incomingCards.length; i++) {

            var incomingCard = incomingCards[i];

            if (!pair[incomingCard.rank]) pair[incomingCard.rank] = 0;

            pair[incomingCard.rank] = pair[incomingCard.rank] + 1;

        }

        for (var j in pair) {
            if (pair[j] >= 3) {
                return true;
            }
        }

        return false;

    },

    checkIsStreet: function (incomingCards) {
        var arrRanks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"];

        var street = [];

        var tempStreet = [];

        if (incomingCards.length < 5) {
            return false;
        }
        for (var z = 0; z < arrRanks.length; z++) {
            street[arrRanks[z]] = 0;
        }

        for (var i = 0; i < incomingCards.length; i++) {

            var incomingCard = incomingCards[i];

            if (!street[incomingCard.rank]) street[incomingCard.rank] = 0;

            street[incomingCard.rank] = street[incomingCard.rank] + 1;

        }
        var countStreet = 0;
        for (var key in street) {

            if (street[key] != 0) {
                countStreet++
            }
            if (countStreet == 5) {
                return true;
            }
            if (street[key] == 0) {
                countStreet = 0;
            }
        }

        return false;

    },

    checkIsFullHouse: function (incomingCards) {
        var fullHouse = [];

        for (var i = 0; i < incomingCards.length; i++) {

            var incomingCard = incomingCards[i];

            if (!fullHouse[incomingCard.rank]) fullHouse[incomingCard.rank] = 0;

            fullHouse[incomingCard.rank] = fullHouse[incomingCard.rank] + 1;

        }
        var pair = false;
        var set = false;

        for (var j in fullHouse) {
            if (fullHouse[j] == 3) {
                set = true;
            }
            if (fullHouse[j] == 2) {
                pair = true;
            }
            if (pair && set) {
                return true;
            }
        }

        return false;
    },

    checkIsCare: function (incomingCards) {
        var checkCare = 0;
        var arrCombination = [];

        if (incomingCards.length < 4) {
            return false;
        }

        for (var i = 0; i < incomingCards.length; i++) {
            var incomingCardItem = incomingCards[i];

            if (!arrCombination[incomingCardItem.rank]) {
                arrCombination[incomingCardItem.rank] = 0;
            }

            arrCombination[incomingCardItem.rank] = arrCombination[incomingCardItem.rank] + 1;
        }

        for (var k in arrCombination) {
            if (arrCombination.hasOwnProperty(k)) {
                if (arrCombination[k] == 4) {
                    return true;
                }
            }
        }

        return false;
    },

    checkIsStreetFlash: function (incomingCards) {
        var spades = 0;
        var diamonds = 0;
        var hearts = 0;
        var clubs = 0;

        if (incomingCards.length <= 4) {
            return false
        }

        for (var i = 0; i < incomingCards.length; i++) {
            console.log(incomingCards[i]);
            var incomingCardItem = incomingCards[i];
            if (incomingCardItem.suit == 'spades') {
                spades++;
            }
            if (incomingCardItem.suit == 'diamonds') {
                diamonds++;
            }
            if (incomingCardItem.suit == 'hearts') {
                hearts++;
            }
            if (incomingCardItem.suit == 'clubs') {
                clubs++;
            }
            if (spades == 5 || diamonds == 5 || hearts == 5 || clubs == 5) {
                var arrRanks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"];

                var street = [];

                var tempStreet = [];

                if (incomingCards.length < 5) {
                    return false;
                }
                for (var z = 0; z < arrRanks.length; z++) {
                    street[arrRanks[z]] = 0;
                }

                for (var y = 0; y < incomingCards.length; y++) {

                    var incomingCard = incomingCards[y];

                    if (!street[incomingCard.rank]) street[incomingCard.rank] = 0;

                    street[incomingCard.rank] = street[incomingCard.rank] + 1;

                }
                var countStreet = 0;
                for (var key in street) {

                    if (street[key] != 0) {
                        countStreet++
                    }
                    if (countStreet == 5) {
                        return true;
                    }
                    if (street[key] == 0) {
                        countStreet = 0;
                    }
                }

            } else {
                return false;
            }
        }
        return false;
    },

    showdown: function (game_state) {

    },

    ACTIONS: {
        FOLD: 'fold',
        RAISE: 'raise',
        CALL: 'call',
        ALL_IN: 'allIn'
    },

    ALL_RANKS: ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"],

    HIGH_RANKS: ["A", "10", "J", "Q", "K"],

    VERY_HIGH_RANKS: ["A", "Q", "K"],

    // SUITS: ['spades', 'diamonds', 'hearts', 'clubs']

    SUITS: {
        SPADES: 'spades',
        DIAMONDS: 'diamonds',
        HEARTS: 'hearts',
        CLUBS: 'clubs'
    }
};
<|endoftext|>


<commit_before>/**
* Creational patterns to create UI Components
* @private
* @static
* @name factory
* @param {object} [obj] Configuration Object
* @returns {object}
*/
(function () {
	function checkInstance() {
		/*var instance;

		instances[this.name] = instances[this.name] || [];

		if (typeof this.$el !== 'undefined') {
			$.each(instances[this.name], function (i, el) {
				if (el.el === this.el) {
					instance = el;
					return false;
				}
			});
		}

		if (typeof instance === 'object') {
			return instance;
		}

		instances[this.name].push(this);
		*/
	}

	function init($el, options) {
		if (typeof options === 'undefined') {
			if (typeof $el === 'undefined') {
				this.options = util.clone(this.defaults);

			} else if ($el instanceof $) {
				this.$el = $el;
				this.el = $el[0];
				this.options = util.clone(this.defaults);

			} else if (typeof $el === 'object') {
				this.options = util.extend($el, util.clone(this.defaults));
			}

		} else if ($el instanceof $ && typeof options === 'object') {
			this.$el = $el;
			this.el = $el[0];
			this.options = util.extend(options, util.clone(this.defaults));

		} else {
			throw new window.Error('Expected 2 parameters or less');
		}

		//return checkInstance.call(this);
	}

	function toCapitalCase(name) {
		return name[0].toUpperCase() + name.substr(1);
	}

	function createPlugin(klass) {
		var name = klass.prototype.name;

		/*$.fn[name] = function (options) {
			$.each(this, function (i, el) {
				widgets.push(new ch[toCapitalCase(name)]($(el), options));
			});

			//return ((widgets.length > 1) ? widgets : widgets[0]);
		};*/

		$[name] = function ($el, options) {
			var widget = new klass($el, options);
			instances[this.name].push(widget);

			return widget;
		};

		$.fn.[name] = function (options) {
			var widgets = [];
			// ACA esta toda la papa: http://docs.jquery.com/Plugins/Authoring
			// Aca tenemos ordenar los parametros del plugin para meterlos dentro un ub objecto.
			// Si es un string, un numbero, una funcion, o ambos (num, str), (str), (fn)

			// El el siempre viene porque esto se utiliza con selector SIEMPRE!

			// Here!

			$.each(this, function (i, el) {

				widgets.push(new klass($(el), options));
			})
		};
	}

	function factory(klass) {
		klass.prototype.constructor = klass;
		klass.prototype.init = init;

		// tiene que crear $.widget y $('').widget();
		createPlugin(klass);

		exports[klass.name] = klass;
	}

	exports.factory = factory;
}());

(function () {
	function EventEmitter() {
		var pepe = 'privado';
		this.on = function () {
			console.log(pepe + this.name);
		}
	};

	exports.EventEmitter = EventEmitter;
}());

(function () {

	function Widget(el, options) {
		// aca adentro se tienen que definir los this.el y this.options y tiene que chequear si exisite la instancia
		// en el factory tiene que preparar los parametros que recibe el plugin de jquery y transformarlo en (el, options)
		/*var instance = this.init(el, options);
		if (typeof instance === 'object') {
			console.log('Ya existe!');
			return instance;
		}*/

		this.init(el, options)

		//this.create();

		// Lo que expongo
		/*return {
			'name': this.name,
			'on': this.on,
			'uid': this.uid,
			'getId': this.getId
		};*/

		return this;
	}

	Widget.prototype = {};
	Widget.prototype.name = 'widget';
	Widget.prototype.getId = function () {
		console.log(this.uid);
	};

	Widget.prototype.defaults = {
		'open': false
	};

	// -----------------------------
	//util.require(Widget, [ch.EventEmitter]);

	/*Widget.prototype.init = function ($el, options) {
		if (typeof options === 'undefined') {
			if (typeof $el === 'undefined') {
				this.options = util.clone(this.defaults);

			} else if ($el instanceof $) {
				this.$el = $el;
				this.el = $el[0];
				this.options = util.clone(this.defaults);

			} else if (typeof $el === 'object') {
				this.options = util.extend($el, util.clone(this.defaults));
			}

		} else if ($el instanceof $ && typeof options === 'object') {
			this.$el = $el;
			this.el = $el[0];
			this.options = util.extend(options, util.clone(this.defaults));

		} else {
			throw new window.Error('Expected 2 parameters or less');
		}

		return this.checkInstance();
	};*/

	exports.factory(Widget);
}());

/*(function () {
	function A() {
		this.init();
	};

	inherits(A, ch.Widget);

	A.prototype.name = 'A';

	A.prototype.init = function () {
		this.uid = (i+=1);
	};

	exports.A = A;
}());*/

/*
if (arguments.length === 0) {
	this.options = ch.util.clone(this.defaults);

} else {

	switch (typeof options) {
	case 'object':
		this.options = ch.util.extend(options, ch.util.clone(this.defaults));
		break;

	case 'string':
		this.options = ch.util.extend({'message': options}, ch.util.clone(this.defaults));
		break;

	case 'undefined':
		this.options = ch.util.clone(this.defaults);
		break;
	}

	switch (typeof el) {
	case 'object':
		if (el instanceof $) {
			this.el = el;
		} else {
			this.options = ch.util.extend(el, ch.util.clone(this.defaults));
		}
		break;

	case 'string':
		this.options = ch.util.extend({'message': el}, ch.util.clone(this.defaults));
		break;

	case 'number':
		this.options = ch.util.extend({'num': el}, ch.util.clone(this.defaults));
		break;

	case 'function':
		this.options = ch.util.extend({'fn': el}, ch.util.clone(this.defaults));
		break;
	}
}

*/<commit_msg>Updated method factory(): now it creates jQuery plugins and methods<commit_after>/**
* Creational patterns to create UI Components
* @private
* @static
* @name factory
* @param {object} [obj] Configuration Object
* @returns {object}
*/
(function () {

	function init($el, options) {
		if (typeof options === 'undefined') {
			if (typeof $el === 'undefined') {
				this.options = util.clone(this.defaults);

			} else if ($el instanceof $) {
				this.$el = $el;
				this.el = $el[0];
				this.options = util.clone(this.defaults);

			} else if (typeof $el === 'object') {
				this.options = util.extend($el, util.clone(this.defaults));
			}

		} else if ($el instanceof $ && typeof options === 'object') {
			this.$el = $el;
			this.el = $el[0];
			this.options = util.extend(options, util.clone(this.defaults));

		} else {
			throw new window.Error('Expected 2 parameters or less');
		}

	}

	/*function toCapitalCase(name) {
		return name[0].toUpperCase() + name.substr(1);
	}*/

	function createPlugin(klass) {
		var name = klass.prototype.name,
			widget,
			map = {
				'string': 'message',
				'number': 'num',
				'function': 'fn'
			};

		// $.widget(options);
		$[name] = function (options) {
			widget = new klass(options);
			instances[name].push(widget);

			return widget;
		};

		// $(el).widget(options);
		$.fn[name] = function (options) {
			var widgets = [],
				message = arguments[1],
				type = typeof options;

			if (type !== 'undefined' && type !== 'object') {
				var parameter = options;
				options = {};
				options[map[type]] = parameter;

				// Could come a messages as a second argument
				if (typeof message === 'string') {
					options.message = message;
				}
			}

			// http://docs.jquery.com/Plugins/Authoring
			// Aca tenemos ordenar los parametros del plugin para meterlos dentro un ub objecto
			// Si es un string, un numbero, una funcion, o ambos (num, str), (str), (fn)
			// El $el siempre viene porque esto se utiliza con selector SIEMPRE!

			$.each(this, function (i, el) {
				var $el = $(el),
					data = $el.data(name);

				if (!data) {
					widget = new klass($el, options);
					$el.data(name, widget);

					instances[name].push(widget);

				} else {
					widget = data;
				}

				widgets.push(widget);
			});

			return ((widgets.length > 1) ? widgets : widget[0]);
		};
	}

	function factory(klass) {
		var name = klass.name.toLowerCase();

		klass.prototype.constructor = klass;
		klass.prototype.init = init;

		// Gets or creates the klass's instances map
		instances[name] = instances[name] || [];

		// tiene que crear $.widget y $('').widget();
		createPlugin(klass);

		exports[klass.name] = klass;
	}

	exports.factory = factory;
}());

(function () {
	function EventEmitter() {
		var pepe = 'privado';
		this.on = function () {
			console.log(pepe + this.name);
		}
	};

	exports.EventEmitter = EventEmitter;
}());

(function () {

	function Widget(el, options) {
		// aca adentro se tienen que definir los this.el y this.options y tiene que chequear si exisite la instancia
		// en el factory tiene que preparar los parametros que recibe el plugin de jquery y transformarlo en (el, options)
		/*var instance = this.init(el, options);
		if (typeof instance === 'object') {
			console.log('Ya existe!');
			return instance;
		}*/

		this.init(el, options)

		//this.create();

		// Lo que expongo
		/*return {
			'name': this.name,
			'on': this.on,
			'uid': this.uid,
			'getId': this.getId
		};*/

		return this;
	}

	Widget.prototype = {};
	Widget.prototype.name = 'widget';
	Widget.prototype.getId = function () {
		console.log(this.uid);
	};

	Widget.prototype.defaults = {
		'open': false
	};

	// -----------------------------
	//util.require(Widget, [ch.EventEmitter]);

	/*Widget.prototype.init = function ($el, options) {
		if (typeof options === 'undefined') {
			if (typeof $el === 'undefined') {
				this.options = util.clone(this.defaults);

			} else if ($el instanceof $) {
				this.$el = $el;
				this.el = $el[0];
				this.options = util.clone(this.defaults);

			} else if (typeof $el === 'object') {
				this.options = util.extend($el, util.clone(this.defaults));
			}

		} else if ($el instanceof $ && typeof options === 'object') {
			this.$el = $el;
			this.el = $el[0];
			this.options = util.extend(options, util.clone(this.defaults));

		} else {
			throw new window.Error('Expected 2 parameters or less');
		}

		return this.checkInstance();
	};*/

	exports.factory(Widget);
}());

/*(function () {
	function A() {
		this.init();
	};

	inherits(A, ch.Widget);

	A.prototype.name = 'A';

	A.prototype.init = function () {
		this.uid = (i+=1);
	};

	exports.A = A;
}());*/

/*
if (arguments.length === 0) {
	this.options = ch.util.clone(this.defaults);

} else {

	switch (typeof options) {
	case 'object':
		this.options = ch.util.extend(options, ch.util.clone(this.defaults));
		break;

	case 'string':
		this.options = ch.util.extend({'message': options}, ch.util.clone(this.defaults));
		break;

	case 'undefined':
		this.options = ch.util.clone(this.defaults);
		break;
	}

	switch (typeof el) {
	case 'object':
		if (el instanceof $) {
			this.el = el;
		} else {
			this.options = ch.util.extend(el, ch.util.clone(this.defaults));
		}
		break;

	case 'string':
		this.options = ch.util.extend({'message': el}, ch.util.clone(this.defaults));
		break;

	case 'number':
		this.options = ch.util.extend({'num': el}, ch.util.clone(this.defaults));
		break;

	case 'function':
		this.options = ch.util.extend({'fn': el}, ch.util.clone(this.defaults));
		break;
	}
}

*/<|endoftext|>


<commit_before>var http = require('http'),
    url = require('url'),
    request = require('request'),
    sensor = {'temperature': '',
              'humidity': '',
               'lamp': ''};

// Get all the sensors every 4 seconds
setInterval(function() {
    // Get the Temperature value
    request('http://localhost:8094/cxf/temp/devices/sensor/temperature', function (error, res, body) {
        if (!error && res.statusCode == 200) {
            sensor['temperature'] = body;
            console.log('Temperature Updated');
        }
    });

    // Get the Humidity value
    request('http://localhost:8094/cxf/humidity/devices/sensor/humidity', function (error, res, body) {
        if (!error && res.statusCode == 200) {
            sensor['humidity'] = body;
            console.log('Humidity Updated');
        }
    });

    // Get the Lamp status
    request('http://localhost:8094/cxf/lamp/devices/actuator/lamp', function (error, res, body) {
        if (!error && res.statusCode == 200) {
            sensor['lamp'] = body;
            console.log('Lamp Updated');
        }
    });
}, 4000);

http.createServer(function(req, res) {
    var path = url.parse(req.url).pathname,
        data = '{"Error":true}';

    switch(path){
        case '/sensor/temperature':
            data = sensor['temperature'];
            break;
        case '/sensor/humidity':
            data = sensor['humidity'];
            break;
        case '/actuator/lamp':
            data = sensor['lamp'];
            break;
    }

    console.log('Get JSON requisition of length ' + data.length + ' bytes');
    res.writeHead(200, {
        'Content-Type': 'application/json',
        'Content-Length': data.length,
        'access-control-allow-headers': 'Content-Type',
        'access-control-allow-methods': 'GET, POST, DELETE, PUT',
        'access-control-allow-origin': '*'
    });
    res.write(data, 'utf8');

    return res.end();

}).listen(8050);
console.log('Running Server on port 8050');<commit_msg>Teste de sistema de Callback internos<commit_after>var http = require('http'),
    url = require('url'),
    request = require('request'),
    sensor = {'temperature': '',
              'humidity': '',
               'lamp': ''};

// Get all the sensors every 4 seconds
setInterval(function() {
    // Get the Temperature value
    request('http://localhost:8094/cxf/temp/devices/sensor/temperature', function (error, res, body) {
        if (!error && res.statusCode == 200) {
            sensor['temperature'] = body;
            console.log('Temperature Updated');
        }
        humi();
    });

    // Get the Humidity value
    function humi(){request('http://localhost:8094/cxf/humidity/devices/sensor/humidity', function (error, res, body) {
        if (!error && res.statusCode == 200) {
            sensor['humidity'] = body;
            console.log('Humidity Updated');
        }
        lamp();
    });}

    // Get the Lamp status
    function lamp(){request('http://localhost:8094/cxf/lamp/devices/actuator/lamp', function (error, res, body) {
        if (!error && res.statusCode == 200) {
            sensor['lamp'] = body;
            console.log('Lamp Updated');
        }
    });}
}, 4000);

http.createServer(function(req, res) {
    var path = url.parse(req.url).pathname,
        data = '{"Error":true}';

    switch(path){
        case '/sensor/temperature':
            data = sensor['temperature'];
            break;
        case '/sensor/humidity':
            data = sensor['humidity'];
            break;
        case '/actuator/lamp':
            data = sensor['lamp'];
            break;
    }

    console.log('Get JSON requisition of length ' + data.length + ' bytes');
    res.writeHead(200, {
        'Content-Type': 'application/json',
        'Content-Length': data.length,
        'access-control-allow-headers': 'Content-Type',
        'access-control-allow-methods': 'GET, POST, DELETE, PUT',
        'access-control-allow-origin': '*'
    });
    res.write(data, 'utf8');

    return res.end();

}).listen(8050);
console.log('Running Server on port 8050');<|endoftext|>


<commit_before>/*
waitMe - 1.06 [06.02.15]
Author: vadimsva
Github: https://github.com/vadimsva/waitMe
*/
(function(g){g.fn.waitMe=function(h){return this.each(function(){var f=g(this),u,n,b,p=!1,l="background-color",k="",m="",q,c,d,e,r,t={init:function(){e=g.extend({effect:"bounce",text:"",bg:"rgba(255,255,255,0.7)",color:"#000",sizeW:"",sizeH:""},h);r=(new Date).getMilliseconds();q=g('

');var a="width:"+e.sizeW+";height:"+e.sizeH;switch(e.effect){case "none":b=0;break;case "bounce":b=3;c="";d=a;break;case "rotateplane":b=1;c="";d=a;break;case "stretch":b=
5;c="";d=a;break;case "orbit":b=2;c=a;d="";break;case "roundBounce":b=12;c=a;d="";break;case "win8":b=5;p=!0;d=c=a;break;case "win8_linear":b=5;p=!0;c=a;d="";break;case "ios":b=12;c=a;d="";break;case "facebook":b=3;c="";d=a;break;case "rotation":b=1;l="border-color";c="";d=a;break;case "timer":b=2;k="border-color:"+e.color;c=a;d="";break;case "pulse":b=1;l="border-color";c="";d=a;break;case "progressBar":b=1;c="";d=a;break;case "bouncePulse":b=3,c="",d=a}""==e.sizeW&&""==e.sizeH&&(c=d="");""!=c&&
""!=k&&(k=";"+k);if(0<b){n=g('

');for(a=1;a<=b;++a)m=p?m+('

'):m+('

');n=g('
'+m+"
")}e.text&&(u=g('
'+e.text+"
"));f.find("> .waitMe")&&f.find("> .waitMe").remove();
waitMeDivObj=g('

');waitMeDivObj.append(n,u);q.append(waitMeDivObj);"HTML"==f[0].tagName&&(f=g("body"));f.addClass("waitMe_container").attr("data-waitme_id",r).append(q);f.find("> .waitMe").css({background:e.bg});f.find(".waitMe_content").css({marginTop:-f.find(".waitMe_content").outerHeight()/2+"px"})},hide:function(){var a=f.attr("data-waitme_id");f.removeClass("waitMe_container").removeAttr("data-waitme_id");f.find('.waitMe[data-waitme_id="'+a+'"]').remove()}};
if(t[h])return t[h].apply(this,Array.prototype.slice.call(arguments,1));if("object"===typeof h||!h)return t.init.apply(this,arguments);g.event.special.destroyed={remove:function(a){a.handler&&a.handler()}}})}})(jQuery);
<commit_msg>11.02.15<commit_after>/*
waitMe - 1.07 [11.02.15]
Author: vadimsva
Github: https://github.com/vadimsva/waitMe
*/
(function(g){g.fn.waitMe=function(h){return this.each(function(){var f=g(this),u,n,c,p=!1,m="background-color",k="",l="",q,d,b,e,r,t={init:function(){e=g.extend({effect:"bounce",text:"",bg:"rgba(255,255,255,0.7)",color:"#000",sizeW:"",sizeH:"",source:""},h);r=(new Date).getMilliseconds();q=g('

');var a="width:"+e.sizeW+";height:"+e.sizeH;switch(e.effect){case "none":c=0;break;case "bounce":c=3;d="";b=a;break;case "rotateplane":c=1;d="";b=a;break;case "stretch":c=
5;d="";b=a;break;case "orbit":c=2;d=a;b="";break;case "roundBounce":c=12;d=a;b="";break;case "win8":c=5;p=!0;b=d=a;break;case "win8_linear":c=5;p=!0;d=a;b="";break;case "ios":c=12;d=a;b="";break;case "facebook":c=3;d="";b=a;break;case "rotation":c=1;m="border-color";d="";b=a;break;case "timer":c=2;k="border-color:"+e.color;d=a;b="";break;case "pulse":c=1;m="border-color";d="";b=a;break;case "progressBar":c=1;d="";b=a;break;case "bouncePulse":c=3;d="";b=a;break;case "img":c=1,d="",b=a}""==e.sizeW&&
""==e.sizeH&&(d=b="");""!=d&&""!=k&&(k=";"+k);if(0<c){n=g('

');if("img"==e.effect)l='';else for(a=1;a<=c;++a)l=p?l+('

'):l+('

');n=g('
'+l+"
")}e.text&&(u=g('
'+e.text+"
"));f.find("> .waitMe")&&f.find("> .waitMe").remove();waitMeDivObj=g('

');waitMeDivObj.append(n,u);q.append(waitMeDivObj);"HTML"==f[0].tagName&&(f=g("body"));f.addClass("waitMe_container").attr("data-waitme_id",r).append(q);f.find("> .waitMe").css({background:e.bg});f.find(".waitMe_content").css({marginTop:-f.find(".waitMe_content").outerHeight()/2+"px"})},hide:function(){var a=f.attr("data-waitme_id");f.removeClass("waitMe_container").removeAttr("data-waitme_id");
f.find('.waitMe[data-waitme_id="'+a+'"]').remove()}};if(t[h])return t[h].apply(this,Array.prototype.slice.call(arguments,1));if("object"===typeof h||!h)return t.init.apply(this,arguments);g.event.special.destroyed={remove:function(a){a.handler&&a.handler()}}})}})(jQuery);
<|endoftext|>


<commit_before>const uuid = require('uuid');
const async = require('async');
const Hapi = require('hapi');
const kvstore = require('./kvstore');
const config = require('./config');
const util = require('./util');

var internalError = Hapi.Error.internal;
var badRequest = Hapi.Error.badRequest;
var notFound = Hapi.Error.notFound;

var kv = kvstore.connect(config.get('kvstore'));

/* user account model
 *
 * user should have account id
 *
 * <email>/userid = <userId>
 *
 * <userId>/meta = {
 *  params: <user params>
 *  passwordVerifier: <password verifier>
 *  kA: <kA key>
 *  kBWrapped: <wrapped kB key>
 * }
 *
 * */

exports.create = function(data, cb) {
  // generate user id
  var userId = util.getUserId();
  var metaKey = userId + '/user';
  var kA;

  async.waterfall([
    // ensure that an account doesn't already exist for the email
    function(cb) {
      kv.get(data.email + '/uid', function (err, doc) {
        if (doc) return cb(badRequest('AccountExistsForEmail'));
        cb(null);
      });
    },
    // link email to userid
    function(cb) {
      kv.set(data.email + '/uid', userId, cb);
    },
    // get new class A key
    util.getKA,
    // create user account
    function(key, cb) {
      kA = key;
      kv.set(metaKey, {
        params: data.params,
        verifier: data.verifier,
        kA: key,
        kB: data.kB
      }, cb);
    }
  ], cb);
};

// Initialize the SRP process
exports.startLogin = function(email, cb) {
  async.waterfall([
    // get uid
    exports.getId.bind(null, email),
    // create a temporary session document
    function (uid, cb) {
      // get sessionID
      var sid = util.getSessionId();

      // eventually will store SRP state
      // and expiration time
      kv.set(sid + '/session', {
        uid: uid
      }, function (err) {
        // return sessionID
        cb(err, { sessionId: sid });
      });
    }
  ], cb);
};

// Finish the SRP process and return account info
exports.finishLogin = function(sessionId, verifier, cb) {
  var sessKey = sessionId + '/session';
  var uid, user, accountToken;

  async.waterfall([
    // get session doc
    function(cb) {
      kv.get(sessKey, function(err, session) {
        if (err) return cb(err);
        if (!session) return cb(notFound('UnknownSession'));
        cb(null, session.value);
      });
    },
    // get user info
    function(session, cb) {
      uid = session.uid;
      exports.getUser(session.uid, cb);
    },

    // check password
    function(result, cb) {
      user = result;
      if (user.verifier !== verifier) {
        return cb(badRequest('IncorrectPassword'));
      }
      cb(null);
    },

    // create accountToken
    util.getAccountToken,

    // create temporary account token doc
    function(token, cb) {
      accountToken = token;
      kv.set(token + '/accountToken', { uid: uid }, cb);
    },
    // delete session doc
    function(cb) {
      kv.delete(sessKey, cb);
    },
    // return info
    function(cb) {
      cb({
        accountToken: accountToken,
        kA: user.kA,
        kB: user.kB,
      });
    }
  ], cb);
};

// This method returns the userId currently associated with an email address.
exports.getId = function(email, cb) {
  kv.get(email + '/uid', function(err, result) {
    if (err) return cb(internalError(err));
    if (!result) return cb(notFound('UnknownUser'));
    cb(null, result.value);
  });
};

// get meta data associated with a user
exports.getUser = function(userId, cb) {
  kv.get(userId + '/user', function(err, doc) {
    if (err) return cb(internalError(err));
    if (!doc) return cb(notFound('UnknownUser'));
    cb(null, doc.value);
  });
};

<commit_msg>fix comments<commit_after>const uuid = require('uuid');
const async = require('async');
const Hapi = require('hapi');
const kvstore = require('./kvstore');
const config = require('./config');
const util = require('./util');

var internalError = Hapi.Error.internal;
var badRequest = Hapi.Error.badRequest;
var notFound = Hapi.Error.notFound;

var kv = kvstore.connect(config.get('kvstore'));

/* user account model
 *
 * <email>/uid = <userId>
 *
 * <userId>/user = {
 *  params: <user params>
 *  verifier: <password verifier>
 *  kA: <kA key>
 *  kB: <wrapped kB key>
 * }
 *
 * <sessionId>/session = {
 *  uid: <userId>
 * }
 *
 * <accountToken>/account = {
 *  uid: <userId>
 * }
 *
 * */

exports.create = function(data, cb) {
  // generate user id
  var userId = util.getUserId();
  var userKey = userId + '/user';

  async.waterfall([
    // ensure that an account doesn't already exist for the email
    function(cb) {
      kv.get(data.email + '/uid', function (err, doc) {
        if (doc) return cb(badRequest('AccountExistsForEmail'));
        cb(null);
      });
    },
    // link email to userid
    function(cb) {
      kv.set(data.email + '/uid', userId, cb);
    },
    // get new class A key
    util.getKA,
    // create user account
    function(key, cb) {
      kv.set(userKey, {
        params: data.params,
        verifier: data.verifier,
        kA: key,
        kB: data.kB
      }, cb);
    }
  ], cb);
};

// Initialize the SRP process
exports.startLogin = function(email, cb) {
  async.waterfall([
    // get uid
    exports.getId.bind(null, email),
    // create a temporary session document
    function (uid, cb) {
      // get sessionID
      var sid = util.getSessionId();

      // eventually will store SRP state
      // and expiration time
      kv.set(sid + '/session', {
        uid: uid
      }, function (err) {
        // return sessionID
        cb(err, { sessionId: sid });
      });
    }
  ], cb);
};

// Finish the SRP process and return account info
exports.finishLogin = function(sessionId, verifier, cb) {
  var sessKey = sessionId + '/session';
  var uid, user, accountToken;

  async.waterfall([
    // get session doc
    function(cb) {
      kv.get(sessKey, function(err, session) {
        if (err) return cb(err);
        if (!session) return cb(notFound('UnknownSession'));
        cb(null, session.value);
      });
    },
    // get user info
    function(session, cb) {
      uid = session.uid;
      exports.getUser(session.uid, cb);
    },

    // check password
    function(result, cb) {
      user = result;
      if (user.verifier !== verifier) {
        return cb(badRequest('IncorrectPassword'));
      }
      cb(null);
    },

    // create accountToken
    util.getAccountToken,

    // create temporary account token doc
    function(token, cb) {
      accountToken = token;
      kv.set(token + '/accountToken', { uid: uid }, cb);
    },
    // delete session doc
    function(cb) {
      kv.delete(sessKey, cb);
    },
    // return info
    function(cb) {
      cb({
        accountToken: accountToken,
        kA: user.kA,
        kB: user.kB,
      });
    }
  ], cb);
};

// This method returns the userId currently associated with an email address.
exports.getId = function(email, cb) {
  kv.get(email + '/uid', function(err, result) {
    if (err) return cb(internalError(err));
    if (!result) return cb(notFound('UnknownUser'));
    cb(null, result.value);
  });
};

// get meta data associated with a user
exports.getUser = function(userId, cb) {
  kv.get(userId + '/user', function(err, doc) {
    if (err) return cb(internalError(err));
    if (!doc) return cb(notFound('UnknownUser'));
    cb(null, doc.value);
  });
};

<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
// Load bower components
//= require es5-shim/es5-shim.js
//= require lodash/lodash.js
//= require jquery-ujs/src/rails.js
//= require jquery-bootpag/lib/jquery.bootpag.js
//= require d3/d3.js
//= require queue-async/queue.js
//
// Load common d3 helper functions
//= require bar_chart
//= require donut_chart
//= require d3_helpers

<commit_msg>include fitvids.js in default.js<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
// Load bower components
//= require es5-shim/es5-shim.js
//= require lodash/lodash.js
//= require jquery-ujs/src/rails.js
//= require jquery-bootpag/lib/jquery.bootpag.js
//= require d3/d3.js
//= require queue-async/queue.js
//= require fitvids/jquery.fitvids.js
//
// Load common d3 helper functions
//= require bar_chart
//= require donut_chart
//= require d3_helpers

<|endoftext|>


<commit_before>import React from 'react';

import { Sparklines, SparklinesLine, SparklinesReferenceLine, SparklinesSpots } from 'react-sparklines';

import numeral from 'numeral';
import utils from '../utils';

// sub components
import Direction from './cp-parts/cp-direction';
import Sizer from './cp-parts/cp-sizer';
import Pricer from './cp-parts/cp-pricer';

/**
 * @class CurrencyPairs
 * @extends {React.Component}
 */
class CurrencyPair extends React.Component {

  static propTypes = {
    id: React.PropTypes.number,
    pair: React.PropTypes.string,
    buy: React.PropTypes.number,
    sell: React.PropTypes.number,
    // spread: React.PropTypes.string,
    precision: React.PropTypes.number,
    pip: React.PropTypes.number,
    onExecute: React.PropTypes.func,
    state: React.PropTypes.string,
    response: React.PropTypes.object
  }

  /**
   * @constructs CurrencyPair
   * @param {Object=} props
   * @param {Object=} context
   */
  constructor(props, context){
    super(props, context);
    this.state = {
      size: 0,
      chart: false,
      info: false,
      tearoff: false,
      state: 'listening',
      historic: []
    };

    this._checkStaleConnection = this._checkStaleConnection.bind(this);
  }

  componentWillMount(){
    const size     = utils.getConvertedSize(this.props.size),
          historic = this.props.mid ? [this.props.mid] : [];

    this.setState({
      size,
      historic,
      state: this.props.state
    });
  }

  _checkStaleConnection(){
    const diff = Date.now() - this.lastUpdated;
    if (diff > STALE_TIMEOUT){
      this.setState({
        state: 'stale',
        message: 'Pricing has become unavailable, no data received for over 4 seconds'
      });
    }
  }

  componentWillReceiveProps(props, state){
    const historic = this.state.historic;

    props.mid && historic.push(props.mid);

    // 30 max historic prices
    historic.length > 30 && (historic.shift());

    const payload = {
      historic,
      state: state.state ? state.state : props.state || 'listening'
    };

    if (!this.state.info && props.response != null){
      this.setState({
        info: true
      });
    }
    else if (props.response && props.response.message === null){
      delete this.lastResponse;
      this.setState({
        info: false
      });
    }

    this.setState(payload);
  }

  shouldComponentUpdate(props, state){
    //refuse props updates while we have a summary or error message info div shown until this.setState()
    if ((props.buy != this.props.buy || props.sell != this.props.sell) || props.state !== this.state.state){
      return true;
    }
    else {
      return state.chart !== this.state.chart || state.state !== this.state.state || this.state.info != state.info;
    }
  }

  /**
   * Explodes a price into big, pip, 10th.
   * @param {Number} price
   * @returns {{bigFigures: string, pip: string, pipFraction: string}}
   */
  parsePrice(price:number){
    const { precision, pip } = this.props,
          priceString = price ? price.toFixed(precision) : '',
          fractions   = priceString.split('.')[1];

    return priceString ? {
      bigFigures: Math.floor(price) + '.' + fractions.substring(0, pip - 2),
      pip: fractions.substring(pip - 2, pip),
      pipFraction: fractions.substring(pip, pip + 1)
    } : {
      bigFigures: '',
      pip: '-',
      pipFraction: ''
    };
  }

  /**
   * Formats spread
   * @param sell
   * @param buy
   * @returns {string}
   */
  getSpread(sell:number, buy:number){
    const { pip, precision } = this.props;
    return sell != null ? ((sell - buy) * Math.pow(10, pip)).toFixed(precision - pip) : '';
  }

  /**
   * Determine the change as up or down on a tick.
   * @returns {string}
   */
  getDirection(mid){
    const historic = this.state.historic,
          len      = historic.length - 2;

    return (historic.length > 1) ?
      historic[len] < mid ? 'up' :
        historic[len] > mid ?
          'down' :
          '-'
      : '-';
  }

  /**
   * Calls back the passed fn with the direction and size
   * @param {String} direction
   */
  execute(direction){
    // attempt to capture price we request against.
    if (this.props.onExecute && this.state.size !== 0){
      let s = Number(this.state.size);
      isNaN(s) || this.props.onExecute({
        direction: direction,
        amount: s,
        rate: this.props[direction].toFixed(this.props.precision),
        pair: this.props.pair,
        valueDate: this.SPOTDATE,
        trader: 'SJP'
      });
      this.setState({
        state: 'executing'
      });
    }
    else {
      console.error('To execute spot trade, you need onExecute({Payload}) callback and a valid size');
    }
  }

  /**
   * Click handler for the 'Done'
   * @param {HTMLEvent} e
   */
  onDismissLastResponse(e){
    e && e.preventDefault();
    this.setState({
      info: false
    });
    delete this.lastResponse;
  }

  /**
   * Parses an ACK response string, saves element into instance until user action
   * @param {Object} response
   * @returns {ReactDOM.Element}
   */
  renderMessage(response){
    if (!response)
      return false;

    if (response.message){
      return this.lastResponse = (

          {response.message}

      );
    }

    const action = response.direction === 'sell' ? 'Sold' : 'Bought',
          amount = numeral(response.amount).format('0,000,000[.]00');

    // we will cache last response to diverge from state until user dismisses it.
    return this.lastResponse = (

        {action} {response.pair.substr(0, 3)} {amount}

        vs {response.pair.substr(3, 3)}
        at {response.rate}

        {response.valueDate}

        Trade ID {response.id}
         this.onDismissLastResponse(e)}>{response.status}

    );
  }

	/**
   * When a execution fails to confirm, show a warning.
   * @returns {HTMLElement}
   */
  getNoResponseMessage(){
    return
Error: No response was received from the server, the execution status is unknown. Please contact your sales rep. this.setState({state: 'listening'})}>Done
;
  }

  /**
   * @param {DOMEvent=} e
   */
  toggleTearoff(e:DOMEvent){
    e && e.preventDefault();
    this.setState({tearoff: !this.state.tearoff});
  }

  render(){
    const { historic, size, state, info, chart } = this.state,
          { buy, sell, mid, pair, response } = this.props;

    const parsedBuy  = this.parsePrice(buy),
          parsedSell = this.parsePrice(sell);

    const execute   = this.execute.bind(this),
          title     = pair.substr(0, 3) + ' / ' + pair.substr(3, 3);

    // any ACK or failed messages will come via state.info / last response
    let message = info ? (this.lastResponse || this.renderMessage(response)) : false;

    // if execution has gone down, state will be `blocked`.
    state === 'blocked' && (message = this.getNoResponseMessage());

    return

         this.setState({chart: !this.state.chart})}/> {title}

      {message}

        <Pricer direction='buy' onExecute={execute} price={this.parsePrice(buy)}/>
        <Direction direction={this.getDirection(mid)} spread={this.getSpread(sell, buy)}/>
        <Pricer direction='sell' onExecute={execute} price={this.parsePrice(sell)}/>

      <Sizer className={message ? 'sizer disabled' : 'sizer'} size={size} onChange={(size) => this.setState({size})} pair={pair}/>

      {chart ?
        <Sparklines data={historic.slice()} width={326} height={24} margin={0}>
          <SparklinesLine />
          <SparklinesSpots />
          <SparklinesReferenceLine type='mean'/>
        </Sparklines> :

}

;
  }
}

export default CurrencyPair;
<commit_msg>cleanup for readibility<commit_after>import React from 'react';

import { Sparklines, SparklinesLine, SparklinesReferenceLine, SparklinesSpots } from 'react-sparklines';

import numeral from 'numeral';
import utils from '../utils';

// sub components
import Direction from './cp-parts/cp-direction';
import Sizer from './cp-parts/cp-sizer';
import Pricer from './cp-parts/cp-pricer';

/**
 * @class CurrencyPairs
 * @extends {React.Component}
 */
class CurrencyPair extends React.Component {

  static propTypes = {
    id: React.PropTypes.number,
    pair: React.PropTypes.string,
    buy: React.PropTypes.number,
    sell: React.PropTypes.number,
    // spread: React.PropTypes.string,
    precision: React.PropTypes.number,
    pip: React.PropTypes.number,
    onExecute: React.PropTypes.func,
    state: React.PropTypes.string,
    response: React.PropTypes.object
  }

  /**
   * @constructs CurrencyPair
   * @param {Object=} props
   * @param {Object=} context
   */
  constructor(props, context){
    super(props, context);
    this.state = {
      size: 0,
      chart: false,
      info: false,
      tearoff: false,
      state: 'listening',
      historic: []
    };

    this._checkStaleConnection = this._checkStaleConnection.bind(this);
  }

  componentWillMount(){
    const size     = utils.getConvertedSize(this.props.size),
          historic = this.props.mid ? [this.props.mid] : [];

    this.setState({
      size,
      historic,
      state: this.props.state
    });
  }

  _checkStaleConnection(){
    const diff = Date.now() - this.lastUpdated;
    if (diff > STALE_TIMEOUT){
      this.setState({
        state: 'stale',
        message: 'Pricing has become unavailable, no data received for over 4 seconds'
      });
    }
  }

  componentWillReceiveProps(props, state){
    const historic = this.state.historic;

    props.mid && historic.push(props.mid);

    // 30 max historic prices
    historic.length > 30 && (historic.shift());

    const payload = {
      historic,
      state: state.state ? state.state : props.state || 'listening'
    };

    if (!this.state.info && props.response != null){
      this.setState({
        info: true
      });
    }
    else if (props.response && props.response.message === null){
      delete this.lastResponse;
      this.setState({
        info: false
      });
    }

    this.setState(payload);
  }

  shouldComponentUpdate(props, state){
    //refuse props updates while we have a summary or error message info div shown until this.setState()
    if ((props.buy != this.props.buy || props.sell != this.props.sell) || props.state !== this.state.state){
      return true;
    }
    else {
      return state.chart !== this.state.chart || state.state !== this.state.state || this.state.info != state.info;
    }
  }

  /**
   * Explodes a price into big, pip, 10th.
   * @param {Number} price
   * @returns {{bigFigures: string, pip: string, pipFraction: string}}
   */
  parsePrice(price:number){
    const { precision, pip } = this.props,
          priceString = price ? price.toFixed(precision) : '',
          fractions   = priceString.split('.')[1];

    return priceString ? {
      bigFigures: Math.floor(price) + '.' + fractions.substring(0, pip - 2),
      pip: fractions.substring(pip - 2, pip),
      pipFraction: fractions.substring(pip, pip + 1)
    } : {
      bigFigures: '',
      pip: '-',
      pipFraction: ''
    };
  }

  /**
   * Formats spread
   * @param sell
   * @param buy
   * @returns {string}
   */
  getSpread(sell:number, buy:number){
    const { pip, precision } = this.props;
    return sell != null ? ((sell - buy) * Math.pow(10, pip)).toFixed(precision - pip) : '';
  }

  /**
   * Determine the change as up or down on a tick.
   * @returns {string}
   */
  getDirection(mid){
    const historic = this.state.historic,
          len      = historic.length - 2;

    return (historic.length > 1) ?
      historic[len] < mid ? 'up' :
        historic[len] > mid ?
          'down' :
          '-'
      : '-';
  }

  /**
   * Calls back the passed fn with the direction and size
   * @param {String} direction
   */
  execute(direction){
    // attempt to capture price we request against.
    if (this.props.onExecute && this.state.size !== 0){
      let s = Number(this.state.size);
      isNaN(s) || this.props.onExecute({
        direction: direction,
        amount: s,
        rate: this.props[direction].toFixed(this.props.precision),
        pair: this.props.pair,
        valueDate: this.SPOTDATE,
        trader: 'SJP'
      });
      this.setState({
        state: 'executing'
      });
    }
    else {
      console.error('To execute spot trade, you need onExecute({Payload}) callback and a valid size');
    }
  }

  /**
   * Click handler for the 'Done'
   * @param {HTMLEvent} e
   */
  onDismissLastResponse(e){
    e && e.preventDefault();
    this.setState({
      info: false
    });
    delete this.lastResponse;
  }

  /**
   * Parses an ACK response string, saves element into instance until user action
   * @param {Object} response
   * @returns {ReactDOM.Element}
   */
  renderMessage(response){
    if (!response)
      return false;

    if (response.message){
      return this.lastResponse = (

          {response.message}

      );
    }

    const action = response.direction === 'sell' ? 'Sold' : 'Bought',
          amount = numeral(response.amount).format('0,000,000[.]00');

    // we will cache last response to diverge from state until user dismisses it.
    return this.lastResponse = (

        {action} {response.pair.substr(0, 3)} {amount}

        vs {response.pair.substr(3, 3)}
        at {response.rate}

        {response.valueDate}

        Trade ID {response.id}
         this.onDismissLastResponse(e)}>{response.status}

    );
  }

	/**
   * When a execution fails to confirm, show a warning.
   * @returns {HTMLElement}
   */
  getNoResponseMessage(){
    return
Error: No response was received from the server, the execution status is unknown. Please contact your sales rep. this.setState({state: 'listening'})}>Done
;
  }

  /**
   * @param {DOMEvent=} e
   */
  toggleTearoff(e:DOMEvent){
    e && e.preventDefault();
    this.setState({tearoff: !this.state.tearoff});
  }

  render(){
    const { historic, size, state, info, chart } = this.state,
          { buy, sell, mid, pair, response } = this.props;

    const parsedBuy  = this.parsePrice(buy),
          parsedSell = this.parsePrice(sell);

    const execute   = this.execute.bind(this),
          title     = pair.substr(0, 3) + ' / ' + pair.substr(3, 3);

    // any ACK or failed messages will come via state.info / last response
    let message = info ? (this.lastResponse || this.renderMessage(response)) : false;

    // if execution has gone down, state will be `blocked`.
    state === 'blocked' && (message = this.getNoResponseMessage());

    return

         this.setState({chart: !this.state.chart})}/>
        {title}

      {message}

        <Pricer direction='buy' onExecute={execute} price={this.parsePrice(buy)}/>
        <Direction direction={this.getDirection(mid)} spread={this.getSpread(sell, buy)}/>
        <Pricer direction='sell' onExecute={execute} price={this.parsePrice(sell)}/>

      <Sizer className={message ? 'sizer disabled' : 'sizer'} size={size} onChange={(size) => this.setState({size})} pair={pair}/>

      {chart ?
        <Sparklines data={historic.slice()} width={326} height={24} margin={0}>
          <SparklinesLine />
          <SparklinesSpots />
          <SparklinesReferenceLine type='mean'/>
        </Sparklines> :

}

;
  }
}

export default CurrencyPair;
<|endoftext|>