<commit_before>(function() {
  'use strict';

  angular.module('dimApp').directive('dimCompare', Compare);

  Compare.$inject = [];

  function Compare() {
    return {
      controller: CompareCtrl,
      controllerAs: 'vm',
      bindToController: true,
      scope: {},
      template: `

             1" class="dim-button" ng-click="vm.compareSimilar('archetype')" translate="{{ vm.compare.location.inWeapons ? 'Compare.Archetype' : 'Compare.Splits'}}" translate-values="{ quantity:  vm.archeTypes.length }">
             1" class="dim-button" ng-click="vm.compareSimilar()" translate="Compare.All" translate-values="{ type: vm.compare.typeName, quantity: vm.similarTypes.length}">
            Compare.Close

              <dim-item-tag ng-if="vm.featureFlags.tagsEnabled" item="item"></dim-item-tag>

                ({{::stat.qualityPercentage.range}})

              <dim-talent-grid ng-if="item.talentGrid" talent-grid="item.talentGrid"></dim-talent-grid>

      `
    };
  }

  CompareCtrl.$inject = ['$scope', 'toaster', 'dimCompareService', 'dimItemService', 'dimFeatureFlags', '$translate'];

  function CompareCtrl($scope, toaster, dimCompareService, dimItemService, dimFeatureFlags, $translate) {
    var vm = this;
    vm.featureFlags = dimFeatureFlags;
    vm.show = dimCompareService.dialogOpen;

    vm.comparisons = [];
    vm.statRanges = {};

    $scope.$on('dim-store-item-compare', function(event, args) {
      vm.show = true;
      dimCompareService.dialogOpen = true;

      vm.add(args);
    });

    vm.cancel = function cancel() {
      vm.comparisons = [];
      vm.statRanges = {};
      vm.similarTypes = [];
      vm.archeTypes = [];
      vm.highlight = null;
      vm.sortedHash = null;
      vm.show = false;
      dimCompareService.dialogOpen = false;
    };

    vm.compareSimilar = function(type) {
      vm.comparisons = _.union(vm.comparisons, type === 'archetype' ? vm.archeTypes : vm.similarTypes);
    };

    vm.sort = function(statHash) {
      vm.sortedHash = statHash;
      vm.comparisons = _.sortBy(_.sortBy(_.sortBy(vm.comparisons, 'index'), 'name').reverse(), function(item) {
        return _.findWhere(item.stats, { statHash: statHash }).value;
      }).reverse();
    };

    vm.add = function add(args) {
      if (!args.item.talentGrid || !args.item.equipment) {
        return;
      }

      if (vm.comparisons.length && vm.comparisons[0].typeName && args.item.typeName !== vm.comparisons[0].typeName) {
        if (vm.comparisons[0].classType && args.item.classType !== vm.comparisons[0].classType) {
          toaster.pop('warning', args.item.name, $translate.instant(Compare.Error.Class, vm.comparisons[0].classType));
          return;
        }
        toaster.pop('warning', args.item.name, $translate.instant(Compare.Error.Archetype, vm.comparisons[0].typeName));
        return;
      }

      if (args.dupes) {
        vm.compare = args.item;
        vm.similarTypes = _.where(dimItemService.getItems(), { typeName: vm.compare.typeName });
        var armorSplit;
        if (!vm.compare.location.inWeapons) {
          vm.similarTypes = _.where(vm.similarTypes, { classType: vm.compare.classType });
          armorSplit = _.reduce(vm.compare.stats, function(memo, stat) {
            return memo + (stat.base === 0 ? 0 : stat.statHash);
          }, 0);
        }

        vm.archeTypes = _.filter(vm.similarTypes, function(item) {
          if (item.location.inWeapons) {
            var arch = _.find(item.stats, { statHash: vm.compare.stats[0].statHash });
            if (!arch) {
              return false;
            }
            return arch.base === _.find(vm.compare.stats, { statHash: vm.compare.stats[0].statHash }).base;
          }
          return _.reduce(item.stats, function(memo, stat) {
            return memo + (stat.base === 0 ? 0 : stat.statHash);
          }, 0) === armorSplit;
        });
        vm.comparisons = _.where(dimItemService.getItems(), { hash: vm.compare.hash });
      } else if (!_.findWhere(vm.comparisons, { hash: args.item.hash, id: args.item.id })) {
        vm.comparisons.push(args.item);
      }
    };

    vm.remove = function remove(item) {
      vm.comparisons = vm.comparisons.filter(function(compare) {
        return compare.index !== item.index;
      });

      if (!vm.comparisons.length) {
        vm.cancel();
        return;
      }
    };

    $scope.$watch('vm.comparisons', function() {
      var statBuckets = {};

      _.each(vm.comparisons, function(item) {
        _.each(item.stats, function(stat) {
          (statBuckets[stat.statHash] = statBuckets[stat.statHash] || []).push(stat.value);
        });
      });

      vm.statRanges = {};
      _.each(statBuckets, function(bucket, hash) {
        vm.statRanges[hash] = {
          min: Math.min(...bucket),
          max: Math.max(...bucket)
        };
      });
    }, true);
  }
})();
<commit_msg>Show trimmed talent grid<commit_after>(function() {
  'use strict';

  angular.module('dimApp').directive('dimCompare', Compare);

  Compare.$inject = [];

  function Compare() {
    return {
      controller: CompareCtrl,
      controllerAs: 'vm',
      bindToController: true,
      scope: {},
      template: `

             1" class="dim-button" ng-click="vm.compareSimilar('archetype')" translate="{{ vm.compare.location.inWeapons ? 'Compare.Archetype' : 'Compare.Splits'}}" translate-values="{ quantity:  vm.archeTypes.length }">
             1" class="dim-button" ng-click="vm.compareSimilar()" translate="Compare.All" translate-values="{ type: vm.compare.typeName, quantity: vm.similarTypes.length}">
            Compare.Close

              <dim-item-tag ng-if="vm.featureFlags.tagsEnabled" item="item"></dim-item-tag>

                ({{::stat.qualityPercentage.range}})

               {{node.name}}

      `
    };
  }

  CompareCtrl.$inject = ['$scope', 'toaster', 'dimCompareService', 'dimItemService', 'dimFeatureFlags', '$translate'];

  function CompareCtrl($scope, toaster, dimCompareService, dimItemService, dimFeatureFlags, $translate) {
    var vm = this;
    vm.featureFlags = dimFeatureFlags;
    vm.show = dimCompareService.dialogOpen;

    vm.comparisons = [];
    vm.statRanges = {};

    $scope.$on('dim-store-item-compare', function(event, args) {
      vm.show = true;
      dimCompareService.dialogOpen = true;

      vm.add(args);
    });

    vm.cancel = function cancel() {
      vm.comparisons = [];
      vm.statRanges = {};
      vm.similarTypes = [];
      vm.archeTypes = [];
      vm.highlight = null;
      vm.sortedHash = null;
      vm.show = false;
      dimCompareService.dialogOpen = false;
    };

    vm.compareSimilar = function(type) {
      vm.comparisons = _.union(vm.comparisons, type === 'archetype' ? vm.archeTypes : vm.similarTypes);
    };

    vm.sort = function(statHash) {
      vm.sortedHash = statHash;
      vm.comparisons = _.sortBy(_.sortBy(_.sortBy(vm.comparisons, 'index'), 'name').reverse(), function(item) {
        return _.findWhere(item.stats, { statHash: statHash }).value;
      }).reverse();
    };

    vm.add = function add(args) {
      if (!args.item.talentGrid || !args.item.equipment) {
        return;
      }

      if (vm.comparisons.length && vm.comparisons[0].typeName && args.item.typeName !== vm.comparisons[0].typeName) {
        if (vm.comparisons[0].classType && args.item.classType !== vm.comparisons[0].classType) {
          toaster.pop('warning', args.item.name, $translate.instant(Compare.Error.Class, vm.comparisons[0].classType));
          return;
        }
        toaster.pop('warning', args.item.name, $translate.instant(Compare.Error.Archetype, vm.comparisons[0].typeName));
        return;
      }

      if (args.dupes) {
        vm.compare = args.item;
        vm.similarTypes = _.where(dimItemService.getItems(), { typeName: vm.compare.typeName });
        var armorSplit;
        if (!vm.compare.location.inWeapons) {
          vm.similarTypes = _.where(vm.similarTypes, { classType: vm.compare.classType });
          armorSplit = _.reduce(vm.compare.stats, function(memo, stat) {
            return memo + (stat.base === 0 ? 0 : stat.statHash);
          }, 0);
        }

        vm.archeTypes = _.filter(vm.similarTypes, function(item) {
          if (item.location.inWeapons) {
            var arch = _.find(item.stats, { statHash: vm.compare.stats[0].statHash });
            if (!arch) {
              return false;
            }
            return arch.base === _.find(vm.compare.stats, { statHash: vm.compare.stats[0].statHash }).base;
          }
          return _.reduce(item.stats, function(memo, stat) {
            return memo + (stat.base === 0 ? 0 : stat.statHash);
          }, 0) === armorSplit;
        });
        vm.comparisons = _.where(dimItemService.getItems(), { hash: vm.compare.hash });
      } else if (!_.findWhere(vm.comparisons, { hash: args.item.hash, id: args.item.id })) {
        vm.comparisons.push(args.item);
      }
    };

    vm.remove = function remove(item) {
      vm.comparisons = vm.comparisons.filter(function(compare) {
        return compare.index !== item.index;
      });

      if (!vm.comparisons.length) {
        vm.cancel();
        return;
      }
    };

    $scope.$watch('vm.comparisons', function() {
      var statBuckets = {};

      _.each(vm.comparisons, function(item) {
        _.each(item.stats, function(stat) {
          (statBuckets[stat.statHash] = statBuckets[stat.statHash] || []).push(stat.value);
        });
      });

      vm.statRanges = {};
      _.each(statBuckets, function(bucket, hash) {
        vm.statRanges[hash] = {
          min: Math.min(...bucket),
          max: Math.max(...bucket)
        };
      });

      const nodeCounts = {};
      vm.talentGrids = {};
      _.each(vm.comparisons, (item) => {
        _.each(item.talentGrid.nodes, (node) => {
          if (!nodeCounts[node.hash]) {
            nodeCounts[node.hash] = 0;
          }
          nodeCounts[node.hash]++;
        });
      });

      const commonNodes = new Set();
      _.each(nodeCounts, (count, hash) => {
        if (count === vm.comparisons.length) {
          commonNodes.add(hash);
        }
      });

      vm.talentGrids = {};
      _.each(vm.comparisons, (item) => {
        vm.talentGrids[item.id] = trimTalentGrid(item.talentGrid, commonNodes);
      });
    }, true);

    function trimTalentGrid(talentGrid, commonNodes) {
      const trimmedGrid = angular.copy(talentGrid);
      trimmedGrid.nodes = _.reject(trimmedGrid.nodes, (n) => commonNodes.has(n.hash.toString()));
      if (trimmedGrid.nodes.length) {
        return trimmedGrid;
      } else {
        return null;
      }
    }
  }
})();
<|endoftext|>


<commit_before>/* eslint-env node */
var isMasterBuild = process.env.TRAVIS_BRANCH === 'master';
var allBrowsers = [
  'Chrome', 'Firefox', 'BS_Safari_Current', 'BS_Safari_Last', 'BS_MS_Edge', 'BS_IE_11'
];
var localBrowsers = ['Chrome'];
var ciBrowsers = isMasterBuild ? allBrowsers : localBrowsers;

module.exports = {
  'test_page': 'tests/index.html?hidepassed',
  'disable_watching': true,
  timeout: 1200,
  browser_start_timeout: 2000,
  parallel: 4,
  'launch_in_ci': ciBrowsers,
  'launch_in_dev': localBrowsers,
  'browser_args': {
    'Chrome': [
      '--disable-gpu',
      '--headless',
      '--remote-debugging-port=9222',
      '--window-size=1440,900'
    ],
    'Firefox': [
      '-headless'
    ]
  },
  launchers: {
    BS_Safari_Current: {
      exe: 'node_modules/.bin/browserstack-launch',
      args: [
        '--os',
        'OS X',
        '--osv',
        'High Sierra',
        '--b',
        'Safari',
        '--bv',
        'latest',
        '-t',
        '1200',
        '--u',
        '<url>'
      ],
      protocol: 'browser'
    },
    BS_Safari_Last: {
      exe: 'node_modules/.bin/browserstack-launch',
      args: [
        '--os',
        'OS X',
        '--osv',
        'Sierra',
        '--b',
        'safari',
        '--bv',
        '10.1',
        '-t',
        '1200',
        '--u',
        '<url>'
      ],
      protocol: 'browser'
    },
    BS_MS_Edge: {
      exe: 'node_modules/.bin/browserstack-launch',
      args: [
        '--os',
        'Windows',
        '--osv',
        '10',
        '--b',
        'edge',
        '--bv',
        'latest',
        '-t',
        '1200',
        '--u',
        '<url>'
      ],
      protocol: 'browser'
    },
    BS_IE_11: {
      exe: 'node_modules/.bin/browserstack-launch',
      args: [
        '--os',
        'Windows',
        '--osv',
        '7',
        '--b',
        'ie',
        '--bv',
        '11.0',
        '-t',
        '1500',
        '--u',
        '<url>'
      ],
      protocol: 'browser'
    }
  }
};
<commit_msg>Don't run browserstack in PRs<commit_after>/* eslint-env node */
var isMasterBuild = process.env.TRAVIS_BRANCH === 'master' && `${process.env.TRAVIS_PULL_REQUEST}` !== "false" ;
var allBrowsers = [
  'Chrome', 'Firefox', 'BS_Safari_Current', 'BS_Safari_Last', 'BS_MS_Edge', 'BS_IE_11'
];
var localBrowsers = ['Chrome'];
var ciBrowsers = isMasterBuild ? allBrowsers : localBrowsers;

module.exports = {
  'test_page': 'tests/index.html?hidepassed',
  'disable_watching': true,
  timeout: 1200,
  browser_start_timeout: 2000,
  parallel: 4,
  'launch_in_ci': ciBrowsers,
  'launch_in_dev': localBrowsers,
  'browser_args': {
    'Chrome': [
      '--disable-gpu',
      '--headless',
      '--remote-debugging-port=9222',
      '--window-size=1440,900'
    ],
    'Firefox': [
      '-headless'
    ]
  },
  launchers: {
    BS_Safari_Current: {
      exe: 'node_modules/.bin/browserstack-launch',
      args: [
        '--os',
        'OS X',
        '--osv',
        'High Sierra',
        '--b',
        'Safari',
        '--bv',
        'latest',
        '-t',
        '1200',
        '--u',
        '<url>'
      ],
      protocol: 'browser'
    },
    BS_Safari_Last: {
      exe: 'node_modules/.bin/browserstack-launch',
      args: [
        '--os',
        'OS X',
        '--osv',
        'Sierra',
        '--b',
        'safari',
        '--bv',
        '10.1',
        '-t',
        '1200',
        '--u',
        '<url>'
      ],
      protocol: 'browser'
    },
    BS_MS_Edge: {
      exe: 'node_modules/.bin/browserstack-launch',
      args: [
        '--os',
        'Windows',
        '--osv',
        '10',
        '--b',
        'edge',
        '--bv',
        'latest',
        '-t',
        '1200',
        '--u',
        '<url>'
      ],
      protocol: 'browser'
    },
    BS_IE_11: {
      exe: 'node_modules/.bin/browserstack-launch',
      args: [
        '--os',
        'Windows',
        '--osv',
        '7',
        '--b',
        'ie',
        '--bv',
        '11.0',
        '-t',
        '1500',
        '--u',
        '<url>'
      ],
      protocol: 'browser'
    }
  }
};
<|endoftext|>


<commit_before>/*jshint node:true*/
module.exports = {
  "framework": "qunit",
  "test_page": "tests/index.html?hidepassed",
  "disable_watching": true,
  "launch_in_ci": [
    "PhantomJS"
  ],
  "launch_in_dev": [
    "PhantomJS",
    "Chrome"
  ]
};
<commit_msg>Change to use Chrome for CI testing<commit_after>module.exports = {
  test_page: 'tests/index.html?hidepassed',
  disable_watching: true,
  launch_in_ci: [
    'Chrome'
  ],
  launch_in_dev: [
    'Chrome'
  ],
  browser_args: {
    Chrome: {
      mode: 'ci',
      args: [
        // --no-sandbox is needed when running Chrome inside a container
        process.env.TRAVIS ? '--no-sandbox' : null,

        '--disable-gpu',
        '--headless',
        '--remote-debugging-port=0',
        '--window-size=1440,900'
      ].filter(Boolean)
    }
  }
};
<|endoftext|>


<commit_before>// end-to-end correctness testing

// helpful tool for chaining callback functions
var async = require('async');

// main entry point - start the go server and run the tests one by one, failing
// immediately if any of them fail.
function main() {
  require("child_process").spawn("./pad", []).stdout.on('data', function() {
    async.series([
      testSingleWriter,
      testSerializedMultipleWriters,
      testConcurrentNoConflicts,
      // testConcurrentConflictingWrites,
      // testRandom,
    ], function(err, results) {
      if (err) {
        console.log("FAIL: ", err);
        phantom.exit(1);
      } else {
        console.log("PASS")
        phantom.exit(0);
      }
    });
  });
}

// spawns numClients PadClient objects. calls ret(err, clients)
function spawnClients(numClients, ret) {

  // new doc ID to separate tests from eachother
  var docID = "testing-id-" + (+ new Date());

  // keeps trying to create a pad client and calls cb(client) when done.
  function spawnClient(cb) {
    var url = "http://localhost:8080/docs";
    var client = new PadClient(url, docID, function(err, data) {
      if (err == null) {
        cb(null, client);
      } else {
        // this is the error case. this could happen because PhantomJS is weird.
        // if that's the case, simply toss this client and try, try again.
        client.close();
        spawnClient(cb);
      }
    });
  };

  // assemble list of tasks where each is to spawn a client
  var tasks = [];
  for (var i = 0; i < numClients; i += 1) {
    tasks.push(spawnClient);
  }

  // execute that task. assign clients to this chain's context
  var that = this;
  // parallel doesn't work for some reason... see
  // https://github.com/ariya/phantomjs/issues/11408. so this would be better
  // written as a normal iteration, but maybe one day parallel creation of
  // clients will work...
  async.series(tasks, function(err, results) {
    that.clients = results;
    ret(err, results);
  });

};

// test case where there are multiple clients. only the first client writes
// anything, and after each write, the test waits for the commit to propagate
// then checks that every client has the same state, which is text which the
// first client most recently committed.
function testSingleWriter(ret) {

  console.log("Testing: serialized writes, single writer");

  var numClients = 10,
      numChecks = 10,
      pause = 200;

  spawnClients(numClients, function(err, clients) {
    var doCheck = function() {
      text = "testing @ " + (+ new Date());
      clients[0].setText(text);
      setTimeout(function() {
        for (var i = 0; i < numClients; i += 1) {
          var clientText = clients[i].getText();
          if (clientText !== text) {
            ret("client " + i + " had " + clientText + ", not " + text);
            return;
          }
        }
        numChecks -= 1;
        if (numChecks > 0) {
          doCheck();
        } else {
          // cleanup clients
          for (var i = 0; i < numClients; i += 1) {
            clients[i].close();
          }
          // finally return success
          ret(null, 'success');
        }
      }, pause);
    };
    doCheck();
  });

};

// same as testSingleWriter, except at each round, a different client writes.
function testSerializedMultipleWriters(ret) {

  console.log("Testing: serialized writes, multiple writers");

  var numClients = 10,
      numChecks = 10, // should be the same as numClients
      pause = 100;

  spawnClients(numClients, function(err, clients) {
    var doCheck = function() {
      text = "testing @ " + (+ new Date());
      clients[numChecks - 1].setText(text);
      setTimeout(function() {
        for (var i = 0; i < numClients; i += 1) {
          var clientText = clients[i].getText();
          if (clientText !== text) {
            ret("client " + i + " had " + clientText + ", not " + text);
          }
        }
        numChecks -= 1;
        if (numChecks > 0) {
          doCheck();
        } else {
          // cleanup clients
          for (var i = 0; i < numClients; i += 1) {
            clients[i].close();
          }
          // finally return success
          ret(null, 'success');
        }
      }, pause);
    };
    doCheck();
  });

};

// in this test, multiple clients write concurrent but non-conflicting updates.
// this is made explicit by first pausing all clients, setting their text, then
// unpausing them so the changes can propagate, waiting for them to propagate,
// then testing to ensure all clients have the same state.
function testConcurrentNoConflicts(ret) {

  console.log("Testing concurrent, nonconflicting writers");

  var numClients = 10,
      numChecks = 10, // should be the same as numClients
      pause = 500; // requires much longer wait due to rebasing

  spawnClients(numClients, function(err, clients) {
    var doCheck = function() {
      // pause clients so they don't immediately propagate their changes.
      clients.forEach(function(client) {
        client.pause();
      });
      // have each client make changes. since they are paused, it is as if they
      // are all happening at the same time. record what their text should be to
      // double check their text has not progressed.
      var expectedTexts = [];
      clients.forEach(function(client, i) {
        var text = client.getText();
        var lines = text.split("\n");
        lines[i] += i;
        var newText = lines.join("\n");
        expectedTexts.push(newText);
        client.setText(newText);
      });
      // unpause each client, first check to make sure their current text hasn't
      // changed. if it had, then pause is not working correctly.
      clients.forEach(function(client, i) {
        var text = client.getText();
        if (text !== expectedTexts[i]) {
          ret("client " + i + " jumped: " + expectedTexts[i] + " to " + text);
          return;
        }
        client.play();
      });
      // wait for all changes to propagate
      setTimeout(function() {
        // use the text of the first client as a starting point, but really they
        // just all need to be the same.
        var text = clients[0].getText();
        for (var i = 0; i < numClients; i += 1) {
          var clientText = clients[i].getText();
          if (clientText !== text) {
            ret("client " + i + " had " + clientText + ", not " + text);
            return;
          }
        }
        numChecks -= 1;
        if (numChecks > 0) {
          doCheck();
        } else {
          // cleanup clients
          for (var i = 0; i < numClients; i += 1) {
            clients[i].close();
          }
          // finally return success
          ret(null, 'success');
        }
      }, pause);
    };
    // the state will be a line per client, and each client only modifies its
    // line. this way, no updates are conflicting.
    var startStateArray = [];
    while (startStateArray.length < numClients - 1) {
      startStateArray.push("\n");
    }
    var startState = startStateArray.join("");
    clients[0].setText(startState);
    setTimeout(doCheck, pause);
  });

};

// class which abstracts the notion of a pad client. encapsulates the details of
// creating a headless client, loading the page and instantiating a tester
// Javascript Pad client object.
function PadClient(url, docID, cb) {

  // initialize testing pad client at url and doc ID
  var page = require('webpage').create();
  page.onConsoleMessage = function(msg) {
    console.log("Client Console:", msg);
  };
  page.open(url, function(success) {
    if (success !== 'success') {
      cb("Failed to open webpage.")
    }
    page.evaluate(function(docID) {
      // define bind; apparently PhantomJS doesn't support this?
      if (!Function.prototype.bind) {
        Function.prototype.bind = function (oThis) {
          if (typeof this !== "function") {
            // closest thing possible to the ECMAScript 5 internal IsCallable function
            throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
          }

          var aArgs = Array.prototype.slice.call(arguments, 1),
              fToBind = this,
              fNOP = function () {},
              fBound = function () {
                return fToBind.apply(this instanceof fNOP && oThis
                                       ? this
                                       : oThis,
                                     aArgs.concat(Array.prototype.slice.call(arguments)));
              };

          fNOP.prototype = this.prototype;
          fBound.prototype = new fNOP();

          return fBound;
        };
      }
      // set up pad
      if (typeof Pad === 'undefined') {
        throw "Pad undefined...";
      }
      var myState = {
        text: "",
        selectionStart: 0,
        selectionEnd: 0,
      }
      var pad = new Pad({
        getState: function() {
          return myState;
        },
        setState: function(newState) {
          myState = newState;
        },
        docID: docID,
      });
      window.pad = pad;
    }, docID);
    cb();
  });

  // executes f on the webpage
  this.evaluate = function(f) {
    return page.evaluate(f);
  }

  // get this pad client's text
  this.getText = function() {
    return page.evaluate(function() {
      return pad.getState().text;
    });
  }

  // set this pad client's value and commits
  this.setText = function(newText) {
    page.evaluate(function(newText) {
      var state = pad.getState();
      state.text = newText;
      pad.setState(state);
      pad.tryCommit();
    }, newText);
  }

  this.pause = function() {
    page.evaluate(function() {
      pad.pause();
    });
  }

  this.play = function() {
    page.evaluate(function() {
      pad.play();
    });
  }

  this.close = function() {
    page.close();
  }
}

main();
<commit_msg>add harder tests for conflicting updates<commit_after>// end-to-end correctness testing

// helpful tool for chaining callback functions
var async = require('async');

// main entry point - start the go server and run the tests one by one, failing
// immediately if any of them fail.
function main() {
  require("child_process").spawn("./pad", []).stdout.on('data', function() {
    async.series([
      testSingleWriter,
      testSerializedMultipleWriters,
      testConcurrentNoConflicts,
      testConcurrentConflicts,
      testRandom,
    ], function(err, results) {
      if (err) {
        console.log("FAIL: ", err);
        phantom.exit(1);
      } else {
        console.log("PASS")
        phantom.exit(0);
      }
    });
  });
}

// spawns numClients PadClient objects. calls ret(err, clients)
function spawnClients(numClients, ret) {

  // new doc ID to separate tests from eachother
  var docID = "testing-id-" + (+ new Date());

  // keeps trying to create a pad client and calls cb(client) when done.
  function spawnClient(cb) {
    var url = "http://localhost:8080/docs";
    var client = new PadClient(url, docID, function(err, data) {
      if (err == null) {
        cb(null, client);
      } else {
        // this is the error case. this could happen because PhantomJS is weird.
        // if that's the case, simply toss this client and try, try again.
        client.close();
        spawnClient(cb);
      }
    });
  };

  // assemble list of tasks where each is to spawn a client
  var tasks = [];
  for (var i = 0; i < numClients; i += 1) {
    tasks.push(spawnClient);
  }

  // execute that task. assign clients to this chain's context
  var that = this;
  // parallel doesn't work for some reason... see
  // https://github.com/ariya/phantomjs/issues/11408. so this would be better
  // written as a normal iteration, but maybe one day parallel creation of
  // clients will work...
  async.series(tasks, function(err, results) {
    that.clients = results;
    ret(err, results);
  });

};

// test case where there are multiple clients. only the first client writes
// anything, and after each write, the test waits for the commit to propagate
// then checks that every client has the same state, which is text which the
// first client most recently committed.
function testSingleWriter(ret) {

  console.log("Testing: serialized writes, single writer");

  var numClients = 10,
      numChecks = 10,
      pause = 100;

  spawnClients(numClients, function(err, clients) {
    var doCheck = function() {
      text = "testing @ " + (+ new Date());
      clients[0].setText(text);
      setTimeout(function() {
        for (var i = 0; i < numClients; i += 1) {
          var clientText = clients[i].getText();
          if (clientText !== text) {
            ret("client " + i + " had " + clientText + ", not " + text);
            return;
          }
        }
        numChecks -= 1;
        if (numChecks > 0) {
          doCheck();
        } else {
          // cleanup clients
          for (var i = 0; i < numClients; i += 1) {
            clients[i].close();
          }
          // finally return success
          ret(null, 'success');
        }
      }, pause);
    };
    doCheck();
  });

};

// same as testSingleWriter, except at each round, a different client writes.
function testSerializedMultipleWriters(ret) {

  console.log("Testing: serialized writes, multiple writers");

  var numClients = 10,
      numChecks = 10, // should be the same as numClients
      pause = 100;

  spawnClients(numClients, function(err, clients) {
    var doCheck = function() {
      text = "testing @ " + (+ new Date());
      clients[numChecks - 1].setText(text);
      setTimeout(function() {
        for (var i = 0; i < numClients; i += 1) {
          var clientText = clients[i].getText();
          if (clientText !== text) {
            ret("client " + i + " had " + clientText + ", not " + text);
          }
        }
        numChecks -= 1;
        if (numChecks > 0) {
          doCheck();
        } else {
          // cleanup clients
          for (var i = 0; i < numClients; i += 1) {
            clients[i].close();
          }
          // finally return success
          ret(null, 'success');
        }
      }, pause);
    };
    doCheck();
  });

};

// in this test, multiple clients write concurrent but non-conflicting updates.
// this is made explicit by first pausing all clients, setting their text, then
// unpausing them so the changes can propagate, waiting for them to propagate,
// then testing to ensure all clients have the same state.
function testConcurrentNoConflicts(ret) {

  console.log("Testing: concurrent, nonconflicting writers");

  var numClients = 10,
      numChecks = 10, // should be the same as numClients
      pause = 500; // requires much longer wait due to rebasing

  spawnClients(numClients, function(err, clients) {
    var doCheck = function() {
      // pause clients so they don't immediately propagate their changes.
      clients.forEach(function(client) {
        client.pause();
      });
      // have each client make changes. since they are paused, it is as if they
      // are all happening at the same time. record what their text should be to
      // double check their text has not progressed.
      var expectedTexts = [];
      clients.forEach(function(client, i) {
        var text = client.getText();
        var lines = text.split("\n");
        lines[i] += i;
        var newText = lines.join("\n");
        expectedTexts.push(newText);
        client.setText(newText);
      });
      // unpause each client, first check to make sure their current text hasn't
      // changed. if it had, then pause is not working correctly.
      clients.forEach(function(client, i) {
        var text = client.getText();
        if (text !== expectedTexts[i]) {
          ret("client " + i + " jumped: " + expectedTexts[i] + " to " + text);
          return;
        }
        client.play();
      });
      // wait for all changes to propagate
      setTimeout(function() {
        // use the text of the first client as a starting point, but really they
        // just all need to be the same.
        var text = clients[0].getText();
        for (var i = 0; i < numClients; i += 1) {
          var clientText = clients[i].getText();
          if (clientText !== text) {
            ret("client " + i + " had " + clientText + ", not " + text);
            return;
          }
        }
        numChecks -= 1;
        if (numChecks > 0) {
          doCheck();
        } else {
          // cleanup clients
          for (var i = 0; i < numClients; i += 1) {
            clients[i].close();
          }
          // finally return success
          ret(null, 'success');
        }
      }, pause);
    };
    // the state will be a line per client, and each client only modifies its
    // line. this way, no updates are conflicting.
    var startStateArray = [];
    while (startStateArray.length < numClients - 1) {
      startStateArray.push("\n");
    }
    var startState = startStateArray.join("");
    clients[0].setText(startState);
    setTimeout(doCheck, pause);
  });

};

// this tests many client making concurrent updates, made to be explictly
// conflicting via pause/play.
function testConcurrentConflicts(ret) {

  console.log("Testing: concurrent, conflicting writers");

  var numClients = 10,
      numChecks = 10, // should be the same as numClients
      pause = 2000; // requires much longer wait due to rebasing

  spawnClients(numClients, function(err, clients) {
    var doCheck = function() {
      // pause clients so they don't immediately propagate their changes.
      clients.forEach(function(client) {
        client.pause();
      });
      // have each client make changes. since they are paused, it is as if they
      // are all happening at the same time. record what their text should be to
      // double check their text has not progressed.
      var expectedTexts = [];
      clients.forEach(function(client, i) {
        var text = client.getText();
        var lines = text.split("\n");
        // adjust lines within a range, so overlap with other clients conflict.
        lines[i] += i;
        if (i + 1 < lines.length) {
          lines[i + 1] += i;
        } else if (i - 1 >= 0) {
          lines[i - 1] += i;
        }
        var newText = lines.join("\n");
        expectedTexts.push(newText);
        client.setText(newText);
      });
      // unpause each client, first check to make sure their current text hasn't
      // changed. if it had, then pause is not working correctly.
      clients.forEach(function(client, i) {
        var text = client.getText();
        if (text !== expectedTexts[i]) {
          ret("client " + i + " jumped: " + expectedTexts[i] + " to " + text);
          return;
        }
        client.play();
      });
      // wait for all changes to propagate
      setTimeout(function() {
        // use the text of the first client as a starting point, but really they
        // just all need to be the same.
        var text = clients[0].getText();
        for (var i = 0; i < numClients; i += 1) {
          var clientText = clients[i].getText();
          if (clientText !== text) {
            ret("client " + i + " had " + clientText + ", not " + text);
            return;
          }
        }
        numChecks -= 1;
        if (numChecks > 0) {
          doCheck();
        } else {
          // cleanup clients
          for (var i = 0; i < numClients; i += 1) {
            clients[i].close();
          }
          // finally return success
          ret(null, 'success');
        }
      }, pause);
    };
    // the state will be a line per client, and each client only modifies its
    // line. this way, no updates are conflicting.
    var startStateArray = [];
    while (startStateArray.length < numClients - 1) {
      startStateArray.push("\n");
    }
    var startState = startStateArray.join("");
    clients[0].setText(startState);
    setTimeout(doCheck, pause);
  });
}

// tests in bursts of 5s on, 5s off, making random, concurrent, potentially
// conflicting edits. after the 5s off, consistency amongst all clients is
// confirmed.
function testRandom(ret) {

  console.log("Testing: random concurrent updates...");

  var numClients = 10,
      numChecks = 10, // should be the same as numClients
      period = 20, // requires much longer wait due to rebasing
      docSize = 20;

  function doRound(clients, done) {
    // 5s of doing work
    (function doLoop() {
      clients.forEach(function(client) {
        client.pause();
      })
      clients.forEach(function(client, index) {
        var text = client.getText();
        if (text.length < docSize) {
          // do insert
          var toInsert = "" + parseInt(Math.random() * numClients);
          var i = parseInt(Math.random() * text.length);
          var newText = text.substring(0, i) + toInsert + text.substring(i);
          client.setText(newText);
        } else {
          var i = parseInt(Math.random() * text.length);
          var j = i + parseInt(3 * Math.random());
          var newText = text.substring(0, i) + text.substring(j);
          client.setText(newText);
        }
      });
      clients.forEach(function(client) {
        client.play();
      })
      setTimeout(function() {
        var text = clients[0].getText();
        for (var i = 0; i < numClients; i += 1) {
          var clientText = clients[i].getText();
          if (clientText !== text) {
            ret("client " + i + " had \n" + clientText + "\n\tnot\n" + text);
            return;
          }
        }
        done();
      }, period)
    })();
  }

  spawnClients(numClients, function(err, clients) {
    var check = 0;
    function checkDoRound() {
      if (check < numChecks) {
        check += 1
        doRound(clients, checkDoRound);
      } else {
        ret();
      }
    }
    checkDoRound();
  });

}

// class which abstracts the notion of a pad client. encapsulates the details of
// creating a headless client, loading the page and instantiating a tester
// Javascript Pad client object.
function PadClient(url, docID, cb) {

  // initialize testing pad client at url and doc ID
  var page = require('webpage').create();
  page.onConsoleMessage = function(msg) {
    console.log("Client Console:", msg);
  };
  page.open(url, function(success) {
    if (success !== 'success') {
      cb("Failed to open webpage.")
    }
    page.evaluate(function(docID) {
      // define bind; apparently PhantomJS doesn't support this?
      if (!Function.prototype.bind) {
        Function.prototype.bind = function (oThis) {
          if (typeof this !== "function") {
            // closest thing possible to the ECMAScript 5 internal IsCallable function
            throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
          }

          var aArgs = Array.prototype.slice.call(arguments, 1),
              fToBind = this,
              fNOP = function () {},
              fBound = function () {
                return fToBind.apply(this instanceof fNOP && oThis
                                       ? this
                                       : oThis,
                                     aArgs.concat(Array.prototype.slice.call(arguments)));
              };

          fNOP.prototype = this.prototype;
          fBound.prototype = new fNOP();

          return fBound;
        };
      }
      // set up pad
      if (typeof Pad === 'undefined') {
        throw "Pad undefined...";
      }
      var myState = {
        text: "",
        selectionStart: 0,
        selectionEnd: 0,
      }
      var pad = new Pad({
        getState: function() {
          return myState;
        },
        setState: function(newState) {
          myState = newState;
        },
        docID: docID,
      });
      window.pad = pad;
    }, docID);
    cb();
  });

  // executes f on the webpage
  this.evaluate = function(f) {
    return page.evaluate(f);
  }

  // get this pad client's text
  this.getText = function() {
    return page.evaluate(function() {
      return pad.getState().text;
    });
  }

  // set this pad client's value and commits
  this.setText = function(newText) {
    page.evaluate(function(newText) {
      var state = pad.getState();
      state.text = newText;
      pad.setState(state);
      pad.tryCommit();
    }, newText);
  }

  this.pause = function() {
    page.evaluate(function() {
      pad.pause();
    });
  }

  this.play = function() {
    page.evaluate(function() {
      pad.play();
    });
  }

  this.close = function() {
    page.close();
  }
}

main();
<|endoftext|>


<commit_before>const path = require('path');
const cp = require('child_process');
const fs = require('fs');

const PACKAGE_ROOT = path.join(__dirname, '..');

// install addon deps
const addonsPath = path.join(PACKAGE_ROOT, 'addons');
if (fs.existsSync(addonsPath)) {
  console.log('pulling addon dependencies...');

  // whether to use yarn or npm
  let hasYarn = false;
  try {
    cp.execSync('yarn --version').toString();
    hasYarn = true;
  } catch(e) {}

  // walk all addon folders
  fs.readdir(addonsPath, (err, files) => {
    files.forEach(folder => {
      const addonPath = path.join(addonsPath, folder);

      // install only if there are dependencies listed
      // also skip addon if it does not contain any package.json
      // (might happen after branch switches)
      let packageJson;
      try {
        packageJson = require(path.join(addonPath, 'package.json'));
      } catch (e) {}
      if (packageJson
            && (
              (packageJson.devDependencies && Object.keys(packageJson.devDependencies).length)
              || (packageJson.dependencies && Object.keys(packageJson.dependencies).length)
            )
          )
      {
        console.log('Preparing', folder);
        if (hasYarn) {
          cp.execSync('yarn', {cwd: addonPath});
        } else {
          cp.execSync('npm install', {cwd: addonPath});
        }
      } else {
        console.log('Skipped', folder);
      }
    });
  });
}
<commit_msg>add copyright note<commit_after>/**
 * Copyright (c) 2019 The xterm.js authors. All rights reserved.
 * @license MIT
 *
 * Script to initialize addon packages under "addons/" with outer deps.
 */

const path = require('path');
const cp = require('child_process');
const fs = require('fs');

const PACKAGE_ROOT = path.join(__dirname, '..');

// install addon deps
const addonsPath = path.join(PACKAGE_ROOT, 'addons');
if (fs.existsSync(addonsPath)) {
  console.log('pulling addon dependencies...');

  // whether to use yarn or npm
  let hasYarn = false;
  try {
    cp.execSync('yarn --version').toString();
    hasYarn = true;
  } catch(e) {}

  // walk all addon folders
  fs.readdir(addonsPath, (err, files) => {
    files.forEach(folder => {
      const addonPath = path.join(addonsPath, folder);

      // install only if there are dependencies listed
      // also skip addon if it does not contain any package.json
      // (might happen after branch switches)
      let packageJson;
      try {
        packageJson = require(path.join(addonPath, 'package.json'));
      } catch (e) {}
      if (packageJson
            && (
              (packageJson.devDependencies && Object.keys(packageJson.devDependencies).length)
              || (packageJson.dependencies && Object.keys(packageJson.dependencies).length)
            )
          )
      {
        console.log('Preparing', folder);
        if (hasYarn) {
          cp.execSync('yarn', {cwd: addonPath});
        } else {
          cp.execSync('npm install', {cwd: addonPath});
        }
      } else {
        console.log('Skipped', folder);
      }
    });
  });
}
<|endoftext|>


<commit_before>/**This module searches for new ip addresses and tests thhem for validity**/
//Main process tells you to stop searching
//you return -1 for no tested ip found but search is still on
//you return -2 for no tested ip found and all untested ips have been tested and search has stopped
//Exports important functions to calling program
module.exports = function(cb , urlObj , done) {
	console.log(cb);
	console.log('tester working');

	var request = require('request');
	var curl = require('curlrequest');
	var LineByLineReader = require('line-by-line');

	var goodIps = [];
	var goodIpIndex = 0;

	var untestedIps = [];
	var untestedIpIndex=0;

	//
	var STOP_SEARCH =false;

	//
	function getIp(){
		if(!STOP_SEARCH){
			 request.get('http://gimmeproxy.com/api/getProxy' , function(err , response , body){
				 if(err){
					 //console.log('cannot get ip address');
					 getIp();
				 }
				 else {
					 if(untestedIps.length > 2500){
						 STOP_SEARCH = true;
					 }

					 var rawIp = JSON.parse(body);
					 untestedIps.push(rawIp);
					 setTimeout(function(){
					 	getIp();
					 } ,1000)

				 }
			 });
		}
		else{
			console.log('ip searching stopped');
			return;
		}
	};
	//Kick start the getting ip process
	getIp();

	//
	var testIp = function(){
		if(untestedIpIndex<untestedIps.length){
			var raw = untestedIps[untestedIpIndex];
			console.log(raw);

		    var options = {
				url: 'https://fg1.herokuapp.com',
				retries: 5,
				headers: {
					'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',
				},
				timeout: 15,
				proxy: raw.curl
			 };

			 curl.request(options, function(err, res) {
				   if(err){
						 console.log('Cannot test proxy');
						 untestedIpIndex++;
						 return testIp();
					 }
					 else {
						 if(res){
							 console.log('test done');
							 goodIps.push(raw.curl);
							 untestedIpIndex++;
							 cb(raw.curl , urlObj.url);
							 testIp();
						 }
						 else {
							 console.log('invalid proxy');
							 untestedIpIndex++;
							 return testIp();
						 }
					 }
			 });
		}
		else{
		    if(STOP_SEARCH && (untestedIpIndex==untestedIps.length)){
		    	 console.log('All ips have been tested stopping testing phase');
		    	 done();
				 return;
			}
			else{
			    console.log('No untested ips will retry in 30secs');
				return setTimeout(function(){
					return testIp();
				} , 30000);
			}

		}

	}
	//Kick start the testing process
	testIp();

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//

	//
	var stopSearch = function(cb){
		STOP_SEARCH = true;
		cb();
	}

	//
	var getFound = function(){
		return {good:goodIps.length, tested:untestedIpIndex};
	}

	return {
	    getFound:getFound,
	    stopSearch : stopSearch
	}

};<commit_msg>tweaked<commit_after>/**This module searches for new ip addresses and tests thhem for validity**/
//Main process tells you to stop searching
//you return -1 for no tested ip found but search is still on
//you return -2 for no tested ip found and all untested ips have been tested and search has stopped
//Exports important functions to calling program
module.exports = function(cb , urlObj , done) {
	console.log(cb);
	console.log('tester working');

	var request = require('request');
	var curl = require('curlrequest');
	var LineByLineReader = require('line-by-line');

	var goodIps = [];
	var goodIpIndex = 0;

	var untestedIps = [];
	var untestedIpIndex=0;

	//
	var STOP_SEARCH =false;

	//
	function getIp(){
		if(!STOP_SEARCH){
			 request.get('http://gimmeproxy.com/api/get/fc640de59e8e0022c01e14d4b4c0a0ef/?timeout=0' , function(err , response , body){
				 if(err){
					 //console.log('cannot get ip address');
					 getIp();
				 }
				 else {
					 if(untestedIps.length > 2500){
						 STOP_SEARCH = true;
					 }

					 var rawIp = JSON.parse(body);
					 untestedIps.push(rawIp);
					 setTimeout(function(){
					 	getIp();
					 } ,500)

				 }
			 });
		}
		else{
			console.log('ip searching stopped');
			return;
		}
	};
	//Kick start the getting ip process
	getIp();

	//
	var testIp = function(){
		if(untestedIpIndex<untestedIps.length){
			var raw = untestedIps[untestedIpIndex];
			console.log(raw);

		    var options = {
				url: 'https://fg1.herokuapp.com',
				retries: 5,
				headers: {
					'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',
				},
				timeout: 15,
				proxy: raw.curl
			 };

			 curl.request(options, function(err, res) {
				   if(err){
						 console.log('Cannot test proxy');
						 untestedIpIndex++;
						 return testIp();
					 }
					 else {
						 if(res){
							 console.log('test done');
							 goodIps.push(raw.curl);
							 untestedIpIndex++;
							 cb(raw.curl , urlObj.url);
							 testIp();
						 }
						 else {
							 console.log('invalid proxy');
							 untestedIpIndex++;
							 return testIp();
						 }
					 }
			 });
		}
		else{
		    if(STOP_SEARCH && (untestedIpIndex==untestedIps.length)){
		    	 console.log('All ips have been tested stopping testing phase');
		    	 done();
				 return;
			}
			else{
			    console.log('No untested ips will retry in 30secs');
				return setTimeout(function(){
					return testIp();
				} , 30000);
			}

		}

	}
	//Kick start the testing process
	testIp();

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//

	//
	var stopSearch = function(cb){
		STOP_SEARCH = true;
		cb();
	}

	//
	var getFound = function(){
		return {good:goodIps.length, tested:untestedIpIndex};
	}

	return {
	    getFound:getFound,
	    stopSearch : stopSearch
	}

};<|endoftext|>


<commit_before>//var preflopModule = require('./modules/preflop');
var isPremiumHand = function(hole_cards){
  return true;
};

module.exports = {

  VERSION: "Default JavaScript folding player",

  bet_request: function(game_state, bet) {
    var player = game_state.players[game_state.in_action];
    var hole_cards = player.hole_cards;
    if(isPremiumHand(hole_cards)){
      bet(player.stack);
    }
    else {
      bet(0);
    }
    return;

    if (game_state.community_cards.length === 0) {
      preflop.eval(game_state, bet);
    } else {
      bet(game_state.players[game_state.in_action].stack);
      console.log(game_state);
    }
  },

  showdown: function(game_state) {

  }
};
<commit_msg>added modules<commit_after>//var preflopModule = require('./modules/preflop');
var preflop = require('./modules/preflop');
var isPremiumHand = function(hole_cards) {
  return true;
};

module.exports = {

  VERSION: "Default JavaScript folding player",

  bet_request: function(game_state, bet) {
    // var player = game_state.players[game_state.in_action];
    // var hole_cards = player.hole_cards;
    // if (isPremiumHand(hole_cards)) {
    //   bet(player.stack);
    // } else {
    //   bet(0);
    // }
    // return;

    switch (game_state.community_cards.length) {
      case 0:
        preflop.eval(game_state, bet);
        break;
        default:
          bet(game_state.players[game_state.in_action].stack);
        break;
    }
  },

  showdown: function(game_state) {

  }
};
<|endoftext|>


<commit_before>/*
 * CoreSlider v1.0.0
 * Copyright 2016 Pavel Davydov
 *
 * Licensed under MIT (http://opensource.org/licenses/MIT)
 */

(function($) {

  'use strict';

  $.coreSlider = function(container, options) {

    this.defaults = {
      interval: 5000,                                         // Interval of time between slide changes
      loop: true,                                             // When slider finish, should it loop again from first slide?
      slideshow: true,                                        // Enable/Disable automatic slideshow
      resize: true,                                           // Should be slider responsive on screen resize
      pauseOnHover: true,                                     // Pause the slideshow when hovering over slider
      startOnHover: false,                                    // Start the slideshow when hovering over slider
      sliderSelector: '.core-slider_list',                    // List selector (all items are inside this container)
      viewportSelector: '.core-slider_viewport',              // Viewport selector
      itemSelector: '.core-slider_item',                      // Slider items selector
      navEnabled: true,                                       // Enable/Disable navigation arrows
      navSelector: '.core-slider_nav',                        // Selector for navigation arrows container
      navItemNextSelector: '.core-slider_arrow__right',       // 'Next' arrow selector
      navItemPrevSelector: '.core-slider_arrow__left',        // 'Prev' arrow selector
      controlNavEnabled: false,                               // Enable/Disable control navigation (dots)
      controlNavSelector: '.core-slider_control-nav',         // Control navigation container selector (inside will be created dots items)
      controlNavItemSelector: 'core-slider_control-nav-item', // Single control nav dot (created dynamically. Write without dot. If you need more that one class - add them with space separator)
      loadedClass: 'is-loaded',                               // Classname, that will be added when slider is fully loaded
      clonedClass: 'is-cloned',                               // Classname, that will be added to cloned slides (see option 'clone')
      disabledClass: 'is-disabled',                           // Classname, that will be added it item is disabled (in most of cases - item will be display: noned)
      activeClass: 'is-active',                               // Classname, that will be added to active items (for example control navs, etc.)
      reloadGif: false,                                       // Reload gif's on slide change for replaying cycled animation inside current slide
      clone: false,                                           // Indicates, that at begin and at end of slider carousel items will be cloned to create 'infitite' carousel illusion
      items: 1,                                               // How mutch items will be placed inside viewport. Leave 1 if this is slider, 2 ot more - it will look like a carousel
      itemsPerSlide: 1,                                       // How many items must be slided by one action (NOTE: Must be less than 'items' option)
      cloneItems: 0                                           // How mutch items will be cloned at begin and at end of slider
    };

    // Extend defaults with settings passed on init
    this.settings = $.extend({}, this.defaults, options);

    var self = this,
        animateInterval,
        $sliderContainer = $(container),
        $sliderViewport = $sliderContainer.find(self.settings.viewportSelector),
        $slider = $sliderContainer.find(self.settings.sliderSelector),
        $sliderItems = $sliderContainer.find(self.settings.itemSelector),
        $clonedSliderItems = null,
        $sliderNav = $sliderContainer.find(self.settings.navSelector),
        $sliderPrevBtn = $sliderContainer.find(self.settings.navItemPrevSelector),
        $sliderNextBtn = $sliderContainer.find(self.settings.navItemNextSelector),
        $sliderControlNav = $sliderContainer.find(self.settings.controlNavSelector),
        $sliderControlNavItems,
        slideCount = $sliderItems.length - 1, // Count, with counter, starting from zero
        slideCountTotal = $sliderItems.length,
        slideWidth, // Single slide width
        currentSlide = 0,
        transformPrefix = getVendorPrefixes(["transform", "msTransform", "MozTransform", "WebkitTransform"]),
        resizeTimeout,
        currentUrl = null,
        currentTags = null,
        remainingItems = {
          left: 0,
          right: 0
        }, // Number of items remaining on left and on right around visible part
        isFirstLoad = true; // Indicates, that slider was first loaded

    // Getter for vendor prefixes
    function getVendorPrefixes(prefixes) {
      var tmp = document.createElement("div"),
          result = ""; // Store results here
      for (var i = 0; i < prefixes.length; i++) {
        if (typeof tmp.style[prefixes[i]] != 'undefined') {
          result = prefixes[i];
          break;
        } else {
          result = null;
        }
      }
      return result;
    }

    function getTranslateX(offset) {
      return 'translateX(' + offset + 'px)';
    }

    // Initialization of slider
    this.init = function() {
      // Set inner container sizes
      $sliderContainer.addClass(self.settings.loadedClass);
      if (self.settings.clone) {
        // If clone is enabled - clone slides on end and on begin of slider
        self.cloneSlides();
      }
      self.setSizes();
      self.setSlide(currentSlide, false);
      if (self.settings.slideshow) {
        self.play();
      }
      if (self.settings.resize) {
        self.resize();
      }
      // Pause on hover events
      if (self.settings.pauseOnHover && self.settings.slideshow) {
        $sliderContainer.mouseenter(function() {
          self.stop();
        });
        $sliderContainer.mouseleave(function() {
          self.play();
        });
      }
      // Start on hover events
      if (self.settings.startOnHover && self.settings.slideshow) {
        $sliderContainer.mouseenter(function() {
          self.play();
        });
        $sliderContainer.mouseleave(function() {
          self.stop();
        });
      }

      // Add handlers for slider navs (prev/next)
      if (self.settings.navEnabled) {
        $sliderPrevBtn.on('click', function() {
          if(!$(this).hasClass(self.settings.disabledClass)) {
            self.setSlide(currentSlide - self.settings.itemsPerSlide, true);
          }
        });
        $sliderNextBtn.on('click', function() {
          if(!$(this).hasClass(self.settings.disabledClass)) {
            self.setSlide(currentSlide + self.settings.itemsPerSlide, true);
          }
        });
      } else {
        // Add disabled class for navigration arrows
        $sliderNav.addClass(self.settings.disabledClass);
      }

      // Add handlers and init slider control navs
      if (self.settings.controlNavEnabled) {
        // Create dynamically dot items and append them to container
        var buffer = []; // Container of all dot items that will be created later
        for (var i = 0; i < slideCount + 1; i++) {
          if (i == currentSlide) {
            // Make current item active from begin
            buffer.push('

');
          } else {
            buffer.push('

');
          }
        }
        $sliderControlNav.append(buffer.join(''));
        // Cache all items in variable
        $sliderControlNavItems = $sliderControlNav.children();
        // Add event handlers to container
        $sliderControlNav.on('click', $sliderControlNavItems, function(e) {
          self.setSlide($(e.target).index(), false);
        });
        // If items are less then viewport - add disabled classes
        if (slideCountTotal <= self.settings.items) {
          $sliderNextBtn.addClass(self.settings.disabledClass);
          $sliderPrevBtn.addClass(self.settings.disabledClass);
        }
      } else {
        // Add disabled class for navigration dots
        $sliderControlNav.addClass(self.settings.disabledClass);
      }
    };

    this.cloneSlides = function() {
      // Prepend first last items at begin of slider and first elements on end of slider
      $slider.append($sliderItems.slice(0, self.settings.cloneItems).clone().addClass(self.settings.clonedClass));
      $slider.prepend($sliderItems.slice(slideCount - self.settings.cloneItems + 1, slideCount + 1).clone().addClass(self.settings.clonedClass));
      // Cache cloned items in variable
      $clonedSliderItems = $sliderContainer.find(self.settings.itemSelector).filter('.' + self.settings.clonedClass);
    };

    // Function for setting sizes for each item in slider
    this.setSizes = function() {
      slideWidth = $sliderViewport.width() / self.settings.items;
      $sliderItems.add($clonedSliderItems).css('width', slideWidth);
      $slider.css('width', slideWidth * (slideCount + self.settings.cloneItems*2 +  1));
      // $slider.css('width', slideWidth * (slideCount + self.settings.items * 2 + 1) * 1.3);
    };

    // Main function that moves slides. Set slide by passed index as parameter
    this.setSlide = function(index, isDirectionNav) {
      var isDirectionNavClick = isDirectionNav; // Indicates that click was from arrow navigation

      self.stop();

      if(remainingItems.left === 0 && !self.settings.loop) {
        $sliderPrevBtn.addClass(self.settings.disabledClass);
      }

      // Play animation only if total number of items is less than number visible in viewport
      if (slideCountTotal > self.settings.items && isDirectionNavClick) {
        // Get number of remaining on right items
        remainingItems.right = (slideCount + 1) - currentSlide - self.settings.items;
        remainingItems.left = currentSlide;

        $sliderNextBtn.removeClass(self.settings.disabledClass);
        $sliderPrevBtn.removeClass(self.settings.disabledClass);

        // Get direction
        if (currentSlide - index < 0) {
          // Right direction
          if (remainingItems.right <= self.settings.itemsPerSlide) {
            index = slideCount - self.settings.items + 1;
            // Set disabled class for nav
            if (!self.settings.loop) {
              $sliderNextBtn.addClass(self.settings.disabledClass);
            }
          }
          if (remainingItems.right == 0) {
            index = 0; // If loop enavled - rollup to first slide
          }
        } else {
          // Left direction
          if (remainingItems.left <= self.settings.itemsPerSlide) {
            index = 0;
            if (!self.settings.loop) {
              $sliderPrevBtn.addClass(self.settings.disabledClass);
            }
          }
          if (remainingItems.left == 0 && !isFirstLoad) {
            index = slideCount - self.settings.items + 1;
          }
        }

        // Replay possible animations in gif's
        if (self.settings.reloadGif) {
          currentTags = $sliderItems.eq(index).find('img');
          currentTags.each(function() {
            var $this = $(this);
            currentUrl = $this.attr('src');
            $this.attr('src', '');
            $this.attr('src', currentUrl);
          });
        }
      }

      if(!isDirectionNavClick && self.settings.controlNavEnabled) {
        // Set slide directly (for example from dots or from extenal API), including items cloning
        index = (index > slideCount - self.settings.items + self.settings.cloneItems + 1) ? slideCount - self.settings.items + self.settings.cloneItems + 1 : index;
      }

      // Set active new control nav item
      if (self.settings.controlNavEnabled && typeof $sliderControlNavItems !== 'undefined') {
        $sliderControlNavItems.removeClass(self.settings.activeClass);
        $sliderControlNavItems.eq(index).addClass(self.settings.activeClass);
      }

      // Apply CSS transition to block
      $slider.css(transformPrefix, getTranslateX(-(index + self.settings.cloneItems) * slideWidth));

      currentSlide = index;
      isFirstLoad = false; // Change loaded indicator
    };

    // Resize handler function
    this.resize = function() {
      $(window).resize(function() {
        if (resizeTimeout) {
          clearTimeout(resizeTimeout);
          resizeTimeout = null;
        }
        resizeTimeout = setTimeout(function() {
          self.setSizes();
          self.setSlide(currentSlide, false);
        }, 250);
      });
    };

    this.destroy = function() {
      $sliderContainer.removeClass(self.settings.loadedClass);
      clearInterval(animateInterval);
    };

    this.play = function() {
      animateInterval = setInterval(function() {
        self.setSlide(currentSlide + self.settings.itemsPerSlide, true);
        self.play();
      }, self.settings.interval);
    };

    this.stop = function() {
      clearInterval(animateInterval);
    };

    // Finally init slider
    this.init();
  };

  $.fn.coreSlider = function(options) {
    if (options === undefined) {
      options = {};
    }
    if (typeof options === 'object') {
      return this.each(function() {
        new $.coreSlider(this, options);
      });
    }
  }

})(jQuery);
<commit_msg>Updated !<commit_after><|endoftext|>


<commit_before>
module.exports = {

  VERSION: "Randomolunk Egyet",

  bet_request: function(game_state, bet) {
    try {
      bet(100);
    } catch (e) {
      console.log(e);
      bet(0);
    }
  },

  showdown: function(game_state) {

  }
};
<commit_msg>Avoide low cards or go all in<commit_after>
module.exports = {

  VERSION: "Randomolunk Egyet",

  bet_request: function(game_state, bet) {
    try {
      ours = game_state.players[game_state.in_action].hole_cards;
      if (ours[0] < 6 && ours[1] < 6) {
        bet 10;
      } else {
        bet 10000;
      }
    } catch (e) {
      console.log(e);
      bet(0);
    }
  },

  showdown: function(game_state) {

  }
};
<|endoftext|>


<commit_before>pc.script.attribute('thrust', 'number', 350)
pc.script.attribute('torque', 'number', 40)

pc.script.create('player', function (context) {

    var Player = function (entity) {
        // self-reference
        this.entity = entity

        // vectors
        this.thrustVec = new pc.Vec3()
    }

    Player.prototype = {
        initialize: function () {

        },

        update: function (dt) {
            if (context.keyboard.isPressed(pc.input.KEY_A)) {
                this.entity.rigidbody.applyTorqueImpulse(0, 0, this.torque)
            }

            if (context.keyboard.isPressed(pc.input.KEY_D)) {
                this.entity.rigidbody.applyTorqueImpulse(0, 0, -this.torque)
            }

            if (context.keyboard.isPressed(pc.input.KEY_SPACE)) {
                this.thrustVec.copy(this.entity.up).scale(this.thrust)
                this.entity.rigidbody.applyImpulse(this.thrustVec)
            }
        }
    }

    return Player
})
<commit_msg>Added player start coords, created reset function<commit_after>pc.script.attribute('PLAYER_START_X', 'number', 0)
pc.script.attribute('PLAYER_START_Y', 'number', 10)
pc.script.attribute('PLAYER_START_Z', 'number', 0)

pc.script.attribute('thrust', 'number', 350)
pc.script.attribute('torque', 'number', 40)

pc.script.create('player', function (context) {

    var Player = function (entity) {
        // self-reference
        this.entity = entity

        // vectors
        this.thrustVec = new pc.Vec3()
    }

    Player.prototype = {
        initialize: function () {
            // start at reset position
            // this.reset()
        },

        update: function (dt) {
            // rotation control
            if (context.keyboard.isPressed(pc.input.KEY_A)) {
                this.entity.rigidbody.applyTorqueImpulse(0, 0, this.torque)
            }

            if (context.keyboard.isPressed(pc.input.KEY_D)) {
                this.entity.rigidbody.applyTorqueImpulse(0, 0, -this.torque)
            }

            // thrust control
            if (context.keyboard.isPressed(pc.input.KEY_SPACE)) {
                this.thrustVec.copy(this.entity.up).scale(this.thrust)
                this.entity.rigidbody.applyImpulse(this.thrustVec)
            }

            // player rest
            if (context.keyboard.isPressed(pc.input.KEY_ENTER)) {
                this.reset()
            }
        },

        reset: function () {
            this.entity.setPosition(this.PLAYER_START_X, this.PLAYER_START_Y, this.PLAYER_START_Z)
            this.entity.setEulerAngles(0, 0, 0)

            this.entity.rigidbody.syncEntityToBody()
            this.entity.rigidbody.linearVelocity = pc.Vec3.ZERO
            this.entity.rigidbody.angularVelocity = pc.Vec3.ZERO
        }
    }

    return Player
})
<|endoftext|>


<commit_before>l = console.log;

function toNum(c) {
    switch(c) {
        case 'J':
            return 11;
            break;
        case 'Q':
            return 12;
            break;
        case 'K':
            return 13;
            break;
        case 'A':
            return 14;
            break;

        default:
            return card
    }
}

function compute_avg_stack(players) {
    var sum = 0;
    for (var i in players) {
        sum += players.stack;
    }
    return sum / players.length;
}

function compute_chip_factor(g) {
    var average_stack = compute_avg_stack(g.players);
    var myself = g.players[g.in_action];

    var strength = (myself.stack > average_stack) ? (myself.stack / average_stack) : 0.5;

    if (g.current_buy_in < g.pot) {
        return strength;
    }
    else {
        return strength * g.pot / g.current_buy_in;
    }
}

module.exports = {

    VERSION: "Jofogas's Zsozsobot v3.2",

  bet_request: function(g) {
    var myself = g.players[g.in_action];

    // just in case!!!
    if (myself.status != "active") {
        return "OK";
    }
    if (myself.hole_cards[0].rank == myself.hole_cards[1].rank) {
        return myself.stack;
    }
    var average_stack = compute_avg_stack(g.players);

    if (myself.stack > average_stack) {
        /* brave */
        var bet = g.current_buy_in - myself["bet"] + g.minimum_raise * 2;
        l("fearlessly raising: ", bet);
        return bet;
    }
    else {
        /* tight */
        l("fearfully not raising: ", 0);
        return 0;
    }
  },

    showdown: function(g) {
        return 'what is this for?';
    }
};
<commit_msg>make it more brave<commit_after>l = console.log;

function toNum(c) {
    switch(c) {
        case 'J':
            return 11;
            break;
        case 'Q':
            return 12;
            break;
        case 'K':
            return 13;
            break;
        case 'A':
            return 14;
            break;

        default:
            return card
    }
}

function compute_avg_stack(players) {
    var sum = 0;
    for (var i in players) {
        sum += players.stack;
    }
    return sum / players.length;
}

function compute_chip_factor(g) {
    var average_stack = compute_avg_stack(g.players);
    var myself = g.players[g.in_action];

    var strength = (myself.stack > average_stack) ? (myself.stack / average_stack) : 0.5;

    if (g.current_buy_in < g.pot) {
        return strength;
    }
    else {
        return strength * g.pot / g.current_buy_in;
    }
}

module.exports = {

    VERSION: "Jofogas's Zsozsobot v3.2",

  bet_request: function(g) {
    var myself = g.players[g.in_action];

    // just in case!!!
    if (myself.status != "active") {
        return "OK";
    }
    if (myself.hole_cards[0].rank == myself.hole_cards[1].rank) {
        return myself.stack;
    }
    var average_stack = compute_avg_stack(g.players);

    if (myself.stack > average_stack * 0.7) {
        /* brave */
        var bet = g.current_buy_in - myself["bet"] + g.minimum_raise * 2;
        l("fearlessly raising: ", bet);
        return bet;
    }
    else {
        /* tight */
        l("fearfully not raising: ", 0);
        return 0;
    }
  },

    showdown: function(g) {
        return 'what is this for?';
    }
};
<|endoftext|>


<commit_before>var _ = require('lodash')
var inherits = require('inherits')
var aabb = require('aabb-2d')
var math = require('mathjs')
var transform = require('./transform.js')
var circle = require('./geo/circle.js')
var Collision = require('./collision.js')
var Fixmove = require('./fixmove.js')
var Automove = require('./automove.js')
var Freemove = require('./freemove.js')
var Entity = require('crtrdg-entity')

module.exports = Player;
inherits(Player, Entity);

function Player(opts){
  this.geometry = circle({
    position: opts.position,
    angle: opts.angle,
    fill: opts.fill,
    stroke: opts.stroke,
    scale: opts.scale,
    thickness: opts.thickness,
    children: [
      circle({fill: opts.fill, stroke: opts.stroke, thickness: opts.thickness,
        position: [-0.7, -.9], scale: 0.6, angle: -45, aspect: 0.6}),
      circle({fill: opts.fill, stroke: opts.stroke, thickness: opts.thickness,
        position: [0.7, -.9], scale: 0.6, angle: 45, aspect: 0.6})
    ]
  })
  this.movement = {}
  this.movement.center = new Fixmove({speed: opts.speed})
  this.movement.tile = new Automove({
    keymap: ['A', 'D', 'W'],
    heading: [-60, 60, 0],
    shift: [0, 0, 8],
    speed: opts.speed
  })
  this.movement.path = new Automove({
    keymap: ['A', 'D'],
    heading: [-180, 180],
    shift: [8, 8],
    speed: opts.speed
  })
  this.collision = new Collision()
  this.waiting = true
}

Player.prototype.move = function(keyboard, world) {
  var self = this

  var current = self.geometry.transform
  var tile = world.tiles[world.locate(self.position())]
  var inside =  tile.children[0].contains(current.position())
  var keys = keyboard.keysDown

  var delta
  if (inside) {
    if (self.movement.tile.keypress(keys)) self.waiting = false
    if (self.waiting) {
      var center = {
        position: [tile.transform.position()[0], tile.transform.position()[1]]
      }
      delta = self.movement.center.compute(current, center)
    } else {
      delta = self.movement.tile.compute(keys, current, tile.transform)
    }
  } else {
    self.waiting = true
    self.movement.tile.reset()
    delta = self.movement.path.compute(keys, current)
  }

  self.geometry.update(delta)
  self.collision.handle(world, self.geometry, delta)
}

Player.prototype.draw = function(context, camera) {
  this.geometry.draw(context, camera, {order: 'bottom'})
}

Player.prototype.position = function() {
  return this.geometry.transform.position()
}

Player.prototype.angle = function() {
  return this.geometry.transform.angle()
}

Player.prototype.scale = function() {
  return this.geometry.transform.scale()
}
<commit_msg>Add arrow support<commit_after>var _ = require('lodash')
var inherits = require('inherits')
var aabb = require('aabb-2d')
var math = require('mathjs')
var transform = require('./transform.js')
var circle = require('./geo/circle.js')
var Collision = require('./collision.js')
var Fixmove = require('./fixmove.js')
var Automove = require('./automove.js')
var Freemove = require('./freemove.js')
var Entity = require('crtrdg-entity')

module.exports = Player;
inherits(Player, Entity);

function Player(opts){
  this.geometry = circle({
    position: opts.position,
    angle: opts.angle,
    fill: opts.fill,
    stroke: opts.stroke,
    scale: opts.scale,
    thickness: opts.thickness,
    children: [
      circle({fill: opts.fill, stroke: opts.stroke, thickness: opts.thickness,
        position: [-0.7, -.9], scale: 0.6, angle: -45, aspect: 0.6}),
      circle({fill: opts.fill, stroke: opts.stroke, thickness: opts.thickness,
        position: [0.7, -.9], scale: 0.6, angle: 45, aspect: 0.6})
    ]
  })
  this.movement = {}
  this.movement.center = new Fixmove({speed: opts.speed})
  this.movement.tile = new Automove({
    keymap: ['A', 'D', 'W', '<left>', '<right>', '<up>'],
    heading: [-60, 60, 0, -60, 60, 0],
    shift: [0, 0, 8, 0, 0, 8],
    speed: opts.speed
  })
  this.movement.path = new Automove({
    keymap: ['A', 'D', '<left>', '<right>'],
    heading: [-180, 180, -180, 180],
    shift: [8, 8, 8, 8],
    speed: opts.speed
  })
  this.collision = new Collision()
  this.waiting = true
}

Player.prototype.move = function(keyboard, world) {
  var self = this

  var current = self.geometry.transform
  var tile = world.tiles[world.locate(self.position())]
  var inside =  tile.children[0].contains(current.position())
  var keys = keyboard.keysDown

  var delta
  if (inside) {
    if (self.movement.tile.keypress(keys)) self.waiting = false
    if (self.waiting) {
      var center = {
        position: [tile.transform.position()[0], tile.transform.position()[1]]
      }
      delta = self.movement.center.compute(current, center)
    } else {
      delta = self.movement.tile.compute(keys, current, tile.transform)
    }
  } else {
    self.waiting = true
    self.movement.tile.reset()
    delta = self.movement.path.compute(keys, current)
  }

  self.geometry.update(delta)
  self.collision.handle(world, self.geometry, delta)
}

Player.prototype.draw = function(context, camera) {
  this.geometry.draw(context, camera, {order: 'bottom'})
}

Player.prototype.position = function() {
  return this.geometry.transform.position()
}

Player.prototype.angle = function() {
  return this.geometry.transform.angle()
}

Player.prototype.scale = function() {
  return this.geometry.transform.scale()
}
<|endoftext|>


<commit_before>'use strict';

let gameState, myplayer, folded;
module.exports = {
  VERSION: "Kickstarter",
  bet_request: function(game_state, bet) {
    new Promise(resolve => {
        folded = false;
        gameState =  game_state;
        myplayer = game_state.players[game_state.in_action];
        console.log(myplayer.hole_cards);
        console.log(game_state);

        //Check for zero phase

        if(gameState.community_cards.length === 0){
          resolve(phase_zero());
        }else if(gameState.community_cards.length <= 3){
          resolve(phase_three());
        }else if(gameState.community_cards.length === 4){
          resolve(phase_four());
        }else {
          resolve(phase_five());
        }
    }).then(value => {
        bet(value);
    }).catch(err => {
        console.log('ERROR', err);
    });
  },
  showdown: function(game_state) {
  }
};

function phase_zero (){
  folded = false;
  if(myplayer.hole_cards.length < 2){
    return 0;
  }

  console.log("phase zero");
  const rank = evaluate(myplayer.hole_cards);
  if(rank === 3){
    return gameState.minimum_raise;
  }else if (rank ===2) {
    return call();
  }
  folded = true;
  return fold();
}

function phase_three (){
  if(folded) return fold();

  const rank = evaluate(myplayer.hole_cards);
  if(rank === 3){
    return gameState.minimum_raise;
  }else if (rank ===2) {
    return call();
  }
  return fold();
}

function phase_four (game_state, bet){
  if(folded) return fold();

  const rank = evaluate(myplayer.hole_cards);
  if(rank === 3){
    return gameState.minimum_raise;
  }else if (rank ===2) {
    return call();
  }
  folded = true;
  return fold();
}

function phase_five (game_state, bet){
  if(folded) return fold();

  const rank = evaluate(myplayer.hole_cards);
  if(rank === 3){
    return gameState.minimum_raise;
  }else if (rank ===2) {
    return call();
  }
  folded = true;
  return fold();
}

function evaluate (cards){
  const first = cards[0];
  const second = cards[1];
  if(first.rank === second.rank){
    return 3;
  }else if(isSuited(cards)){
    return 2;
  } else {
    return 0;
  }
}

function isSuited(cards){
  const reds = ['clubs','spades'];
  const blacks = ['hearts', 'diamonds'];
  const first = cards[0];
  const second = cards[1];
  if((reds.indexOf(first.suit) >= 0  && reds.indexOf(second.suit)>= 0) || (blacks.indexOf(first.suit) >= 0  && blacks.indexOf(second.suit) >= 0)){
    return true;
  }else{
    return false;
  }
}

function call (){
  const c = gameState.current_buy_in - gameState.players[gameState.in_action].bet;
  return c;
}

function allIn(){
  const c = myplayer.stack;
  return c;
}

function fold(){
  return 0;
}
<commit_msg>suit fail fix<commit_after>'use strict';

let gameState, myplayer, folded;
module.exports = {
  VERSION: "Kickstarter",
  bet_request: function(game_state, bet) {
    new Promise(resolve => {
        folded = false;
        gameState =  game_state;
        myplayer = game_state.players[game_state.in_action];
        console.log(myplayer.hole_cards);
        console.log(game_state);

        //Check for zero phase

        if(gameState.community_cards.length === 0){
          resolve(phase_zero());
        }else if(gameState.community_cards.length <= 3){
          resolve(phase_three());
        }else if(gameState.community_cards.length === 4){
          resolve(phase_four());
        }else {
          resolve(phase_five());
        }
    }).then(value => {
        bet(value);
    }).catch(err => {
        console.log('ERROR', err);
    });
  },
  showdown: function(game_state) {
  }
};

function phase_zero (){
  folded = false;
  if(myplayer.hole_cards.length < 2){
    return 0;
  }

  console.log("phase zero");
  const rank = evaluate(myplayer.hole_cards);
  if(rank === 3){
    return gameState.minimum_raise;
  }else if (rank ===2) {
    return call();
  }
  folded = true;
  return fold();
}

function phase_three (){
  if(folded) return fold();

  const rank = evaluate(myplayer.hole_cards);
  if(rank === 3){
    return gameState.minimum_raise;
  }else if (rank ===2) {
    return call();
  }
  return fold();
}

function phase_four (game_state, bet){
  if(folded) return fold();

  const rank = evaluate(myplayer.hole_cards);
  if(rank === 3){
    return gameState.minimum_raise;
  }else if (rank ===2) {
    return call();
  }
  folded = true;
  return fold();
}

function phase_five (game_state, bet){
  if(folded) return fold();

  const rank = evaluate(myplayer.hole_cards);
  if(rank === 3){
    return gameState.minimum_raise;
  }else if (rank ===2) {
    return call();
  }
  folded = true;
  return fold();
}

function evaluate (cards){
  const first = cards[0];
  const second = cards[1];
  if(first.rank === second.rank){
    return 3;
  }else if(isSuited(cards)){
    return 2;
  } else {
    return 0;
  }
}

function isSuited(cards){
  const first = cards[0];
  const second = cards[1];
  if(first.suit === second.suit){
    return true;
  }
  return false;

}

function call (){
  const c = gameState.current_buy_in - gameState.players[gameState.in_action].bet;
  return c;
}

function allIn(){
  const c = myplayer.stack;
  return c;
}

function fold(){
  return 0;
}
<|endoftext|>


<commit_before>var METER  = TILE;
var GRAVITY = METER * 9.8 * 3;
var MAXDX = METER * 10;
var MAXDY = METER * 15;
var ACCEL = MAXDX * 2;
var JUMP = METER * 1500;
var FRICTION = MAXDX * 6;

var LEFT = 0;
var RIGHT = 1;

var ANIM_IDLE = 0;
var ANIM_JUMP = 1;
var ANIM_WALK_LEFT = 2;
var ANIM_WALK_RIGHT = 3;
var ANIM_MAX = 4;

var Player = function(){

	this.sprite = new Sprite("p1_spritesheet.png");
	this.sprite.buildAnimation(7, 3, 73.5, 95, 0.05,
		[4]);
	this.sprite.buildAnimation(7, 3, 73, 94, 0.05,
		[13, 13]);
	this.sprite.buildAnimation(7, 3, 72.7, 97, 0.05,
		[0, 1, 2, 7, 9, 10, 3, 4, 5]);
	this.sprite.buildAnimation(7, 3, 72.7, 97, 0.05,
		[5, 4, 3, 10, 9, 7, 2, 1, 0]);

	for(var i=0; i<ANIM_MAX; i++)
	{
		this.sprite.setAnimationOffset(i, -55, -87);
	}

	this.x = SCREEN_WIDTH/2;
	this.y = SCREEN_HEIGHT/2;
	this.width = 73.5;
	this.height = 95;

	this.velocityX =  0;
	this.velocityY = 0;
	this.angularVelocity = 0;
	this.rotation = 0;

	this.falling = true;
	this.jumping = false;

	this.offset_x = -55;
	this.offset_y = -87;

	this.lives = 3;
	this.shooting = false;
	this.ammo = 7;

	this.score = 0;

	this.direction = LEFT;

};

Player.prototype.Update = function(deltaTime) {

	this.sprite.update(deltaTime);

	GRAVITY = METER * 9.8 * 3;

	var tx = pixel2Tile(this.x);
	var ty = pixel2Tile(this.y);

	var nx = this.x % TILE;
	var ny = this.y % TILE;

	var cell = 		 cellAtTileCoord(LAYER_GROUND, tx, 		ty);
	var cellRight =	 cellAtTileCoord(LAYER_GROUND, tx + 1, 	ty);
	var cellDown  =	 cellAtTileCoord(LAYER_GROUND, tx, 		ty + 1);
	var cellDiag  =  cellAtTileCoord(LAYER_GROUND, tx + 1, 	ty + 1);

	var cellDoor = cellAtTileCoord(LAYER_DOORS, tx, 		ty);

	var left, right, jump;
	left = right = jump = false;

	//changing anmiation and direction for left
	if(keyboard.isKeyDown(keyboard.KEY_LEFT)){
		left = true;
		this.direction = LEFT;
		if(this.sprite.currentAnimation != ANIM_WALK_LEFT)
			this.sprite.setAnimation(ANIM_WALK_LEFT);
	}

	//changing anmiation and direction for right
	else if (keyboard.isKeyDown(keyboard.KEY_RIGHT)){
		right = true;
		this.direction = RIGHT;
		if(this.sprite.currentAnimation != ANIM_WALK_RIGHT)
			this.sprite.setAnimation(ANIM_WALK_RIGHT);
	}

	if ((keyboard.isKeyDown(keyboard.KEY_SPACE)) || (keyboard.isKeyDown(keyboard.KEY_UP))){
		jump = true;
		this.score += 1;
		if(this.sprite.currentAnimation != ANIM_JUMP)
			this.sprite.setAnimation(ANIM_JUMP);
	}

	if ((keyboard.isKeyDown(keyboard.KEY_CTRL)) && cellDoor){
		CurrentLevel = level1_blue;
		initialize(CurrentLevel);
	}

	//jump = keyboard.isKeyDown(keyboard.KEY_SPACE);

	var wasleft = this.velocityX < 0;
	var wasright = this.velocityX > 0;

	var falling = this.falling;
	var ddx = 0;			 //ACCELERATION
	var ddy = GRAVITY;

	if (left){
		ddx -= ACCEL;
	}
	else if (wasleft){
		ddx += FRICTION;
	}

	if (right){
		ddx += ACCEL;
	}
	else if (wasright){
		ddx -= FRICTION
	}

	if (jump && !this.jumping && !falling){
		ddy -= JUMP;
		this.jumping = true;

	}

	//calculate the new postioin and velocity:
	this.x += deltaTime * this.velocityX;
	this.y += deltaTime * this.velocityY;
	this.velocityX = bound(this.velocityX + (deltaTime * ddx), -MAXDX, MAXDX);
	this.velocityY = bound(this.velocityY + (deltaTime * ddy), -MAXDY, MAXDY);

	if (this.y > SCREEN_HEIGHT){
			this.lives --;
			if (this.lives <= 0){
				curGameState = GAMESTATE_ENDGAME;

			}

			else{
				this.respawn();
			}

		}

	if ( (wasleft && (this.velocityX > 0)) || (wasright && (this.velocityX < 0))){
		//clamp at zero to prevbent frition from making us jiggle side to side
		this.velocityX = 0;
	}

	//rotation when walking
	//if ( this.velocityX > 0){
	//	this.rotation = (this.velocityX / MAXDX) * (Math.PI / 8) ;
	//}
	//else if (this.velocityX < 0){
	//	this.rotation = (-this.velocityX / MAXDX) * (-Math.PI /8);
	//}
	//else{
	//	this.rotation = 0;
	//}

	//CEILING
	if(this.velocityY > 0){
		if ((cellDown & !cell) || (cellDiag && !cellRight && nx)){
			this.y = tile2Pixel(ty);
			this.velocityY = 0;
			this.falling = false;
			this.jumping = false;
			ny = 0;
		}

	}
	//FLOOR
	else if (this.velocityY < 0) {
		if ((cell && !cellDown) || (cellRight && !cellDiag && nx)){
			//calmp the y poition to avoid jumping into platform above

			this.y = tile2Pixel(ty + 1);
			this.velocityY = 0; 		//stop upward velocity

			cell = cellDown;
			cellRight = cellDiag;
			ny = 0;
		}
	}

	if (this.velocityX > 0){
		if ((cellRight && !cell) || (cellDiag && !cellDown && ny)){
			//clamp the x position to avoid moving into the platform we just hit
			this.x = tile2Pixel(tx);
			this.velocityX = 0;
		}
	}

	else if (this.velocityX < 0){
		if((cell && !cellRight) || (cellDown && !cellDiag && ny)){
			this.x = tile2Pixel(tx + 1);
			this.velocityX = 0;
		}
	}

Player.prototype.respawn = function(){
	this.x = SCREEN_WIDTH/2;
	this.y = SCREEN_HEIGHT/2;
	this.width = 73.5;
	this.height = 95;

	this.offset_x = -55;
	this.offset_y = -87;

	this.velocityX =  0;
	this.velocityY = 0;
	this.angularVelocity = 0;
	this.rotation = 0;

	this.shooting = false;
	this.ammo = 7;
}

};

Player.prototype.Draw = function(_cam_x, _cam_y){

	this.sprite.draw(context, this.x, this.y);
//	context.save();
//
//		context.translate(this.x + _cam_x, this.y + _cam_y);
//		context.rotate(this.rotation);
//		context.drawImage(this.image,
//							-this.width/2,
//							-this.height/2)
//
//	context.restore();
//
	context.save();

	context.beginPath();
	context.rect(this.x - (this.width/2)  , this.y - (this.height/2), this.width, this.height);
	context.stroke();
	context.restore();

};

<commit_msg>moved the player to the hitbox<commit_after>var METER  = TILE;
var GRAVITY = METER * 9.8 * 3;
var MAXDX = METER * 10;
var MAXDY = METER * 15;
var ACCEL = MAXDX * 2;
var JUMP = METER * 1500;
var FRICTION = MAXDX * 6;

var LEFT = 0;
var RIGHT = 1;

var ANIM_IDLE = 0;
var ANIM_JUMP = 1;
var ANIM_WALK_LEFT = 2;
var ANIM_WALK_RIGHT = 3;
var ANIM_MAX = 4;

var Player = function(){

	this.sprite = new Sprite("p1_spritesheet.png");
	this.sprite.buildAnimation(7, 3, 73.5, 95, 0.05,
		[4]);
	this.sprite.buildAnimation(7, 3, 73, 94, 0.05,
		[13, 13]);
	this.sprite.buildAnimation(7, 3, 72.7, 97, 0.05,
		[0, 1, 2, 7, 9, 10, 3, 4, 5]);
	this.sprite.buildAnimation(7, 3, 72.7, 97, 0.05,
		[5, 4, 3, 10, 9, 7, 2, 1, 0]);

	for(var i=0; i<ANIM_MAX; i++)
	{
		this.sprite.setAnimationOffset(i, -55, -87);
	}

	this.x = SCREEN_WIDTH/2;
	this.y = SCREEN_HEIGHT/2;
	this.width = 72.5;
	this.height = 95;

	this.velocityX =  0;
	this.velocityY = 0;
	this.angularVelocity = 0;
	this.rotation = 0;

	this.falling = true;
	this.jumping = false;

	this.offset_x = -55;
	this.offset_y = -87

	this.lives = 3;
	this.shooting = false;
	this.ammo = 7;

	this.score = 0;

	this.direction = LEFT;

};

Player.prototype.Update = function(deltaTime) {

	this.sprite.update(deltaTime);

	GRAVITY = METER * 9.8 * 3;

	var tx = pixel2Tile(this.x);
	var ty = pixel2Tile(this.y);

	var nx = this.x % TILE;
	var ny = this.y % TILE;

	var cell = 		 cellAtTileCoord(LAYER_GROUND, tx, 		ty);
	var cellRight =	 cellAtTileCoord(LAYER_GROUND, tx + 1, 	ty);
	var cellDown  =	 cellAtTileCoord(LAYER_GROUND, tx, 		ty + 1);
	var cellDiag  =  cellAtTileCoord(LAYER_GROUND, tx + 1, 	ty + 1);

	var cellDoor = cellAtTileCoord(LAYER_DOORS, tx, 		ty);

	var left, right, jump;
	left = right = jump = false;

	//changing anmiation and direction for left
	if(keyboard.isKeyDown(keyboard.KEY_LEFT)){
		left = true;
		this.direction = LEFT;
		if(this.sprite.currentAnimation != ANIM_WALK_LEFT)
			this.sprite.setAnimation(ANIM_WALK_LEFT);
	}

	//changing anmiation and direction for right
	else if (keyboard.isKeyDown(keyboard.KEY_RIGHT)){
		right = true;
		this.direction = RIGHT;
		if(this.sprite.currentAnimation != ANIM_WALK_RIGHT)
			this.sprite.setAnimation(ANIM_WALK_RIGHT);
	}

	if ((keyboard.isKeyDown(keyboard.KEY_SPACE)) || (keyboard.isKeyDown(keyboard.KEY_UP))){
		jump = true;
		this.score += 1;
		if(this.sprite.currentAnimation != ANIM_JUMP)
			this.sprite.setAnimation(ANIM_JUMP);
	}

	if ((keyboard.isKeyDown(keyboard.KEY_CTRL)) && cellDoor){
		CurrentLevel = level1_blue;
		initialize(CurrentLevel);
	}

	//jump = keyboard.isKeyDown(keyboard.KEY_SPACE);

	var wasleft = this.velocityX < 0;
	var wasright = this.velocityX > 0;

	var falling = this.falling;
	var ddx = 0;			 //ACCELERATION
	var ddy = GRAVITY;

	if (left){
		ddx -= ACCEL;
	}
	else if (wasleft){
		ddx += FRICTION;
	}

	if (right){
		ddx += ACCEL;
	}
	else if (wasright){
		ddx -= FRICTION
	}

	if (jump && !this.jumping && !falling){
		ddy -= JUMP;
		this.jumping = true;

	}

	//calculate the new postioin and velocity:
	this.x += deltaTime * this.velocityX;
	this.y += deltaTime * this.velocityY;
	this.velocityX = bound(this.velocityX + (deltaTime * ddx), -MAXDX, MAXDX);
	this.velocityY = bound(this.velocityY + (deltaTime * ddy), -MAXDY, MAXDY);

	if (this.y > SCREEN_HEIGHT){
			this.lives --;
			if (this.lives <= 0){
				curGameState = GAMESTATE_ENDGAME;

			}

			else{
				this.respawn();
			}

		}

	if ( (wasleft && (this.velocityX > 0)) || (wasright && (this.velocityX < 0))){
		//clamp at zero to prevbent frition from making us jiggle side to side
		this.velocityX = 0;
	}

	//rotation when walking
	//if ( this.velocityX > 0){
	//	this.rotation = (this.velocityX / MAXDX) * (Math.PI / 8) ;
	//}
	//else if (this.velocityX < 0){
	//	this.rotation = (-this.velocityX / MAXDX) * (-Math.PI /8);
	//}
	//else{
	//	this.rotation = 0;
	//}

	//CEILING
	if(this.velocityY > 0){
		if ((cellDown & !cell) || (cellDiag && !cellRight && nx)){
			this.y = tile2Pixel(ty);
			this.velocityY = 0;
			this.falling = false;
			this.jumping = false;
			ny = 0;
		}

	}
	//FLOOR
	else if (this.velocityY < 0) {
		if ((cell && !cellDown) || (cellRight && !cellDiag && nx)){
			//calmp the y poition to avoid jumping into platform above

			this.y = tile2Pixel(ty + 1);
			this.velocityY = 0; 		//stop upward velocity

			cell = cellDown;
			cellRight = cellDiag;
			ny = 0;
		}
	}

	if (this.velocityX > 0){
		if ((cellRight && !cell) || (cellDiag && !cellDown && ny)){
			//clamp the x position to avoid moving into the platform we just hit
			this.x = tile2Pixel(tx);
			this.velocityX = 0;
		}
	}

	else if (this.velocityX < 0){
		if((cell && !cellRight) || (cellDown && !cellDiag && ny)){
			this.x = tile2Pixel(tx + 1);
			this.velocityX = 0;
		}
	}

Player.prototype.respawn = function(){
	this.x = SCREEN_WIDTH/2;
	this.y = SCREEN_HEIGHT/2;
	this.width = 73.5;
	this.height = 95;

	this.offset_x = -55;
	this.offset_y = -87;

	this.velocityX =  0;
	this.velocityY = 0;
	this.angularVelocity = 0;
	this.rotation = 0;

	this.shooting = false;
	this.ammo = 7;
}

};

Player.prototype.Draw = function(_cam_x, _cam_y){

	this.sprite.draw(context, this.x + (this.width/2), this.y + (this.height/2));
//	context.save();
//
//		context.translate(this.x + _cam_x, this.y + _cam_y);
//		context.rotate(this.rotation);
//		context.drawImage(this.image,
//							-this.width/2,
//							-this.height/2)
//
//	context.restore();
//
	context.save();

	context.beginPath();

	//context.rect(this.x - (this.width/2)  , this.y - (this.height/2), this.width, this.height);
	context.stroke();
	context.restore();

};

<|endoftext|>