<commit_before>/*jshint regexp: false */
/*global $:true, window: true */

(function() {

	var main_text = $("div[role=main]").text();

	var conditions = {
		"initial": function() { return window.location.href === "http://localhost:9009/" && $.trim(main_text) === "" },
		"step2": function() { return window.location.href === "http://localhost:9009/" && $.trim(main_text) === "This is just a placeholder." },
		"step3": function() { return window.location.href === "http://localhost:9009/" && $("div[role=main] p").length < 1 },
		"step4": function() { return window.location.href !== "http://localhost:9009/about" && $(".navbar").children().length < 1 },
		"step5": function() { return window.location.href === "http://localhost:9009/about" && $(".navbar").children().length < 1 },
		"step6": function() { return window.location.href === "http://localhost:9009/about" && $(".navbar").children().length > 1 },
		"step7": function() { return window.location.href !== "http://localhost:9009/about" && $("div[role=main] img").length < 1 },
		"step8": function() { return true }
	};

	var messages = {
			"initial": "Thanks for trying out Punch! This quick hands-on tutorial will help you to get familiar with the basics of Punch (It won't take more than 15 minutes).\b[Let's Start!](#show_help)",

			"step1": "We believe the separation of content from its presentation is important for any kind of site. To make this easy, Punch creates two directories named `contents` and `templates`. All information you wish to communicate should go in `contents`; all presentational elements (layouts, assets) should be placed in `templates`.\bIf you go inside the `templates` directory, you will find a file named `_layout.mustache`. This is the main layout of your site. You can create different layouts for different sections of your site. For now, we shall use the main layout to render all pages.\bOpen the `_layout.mustache` and place the tag `{{{intro}}}` inside `<div role=\"main\"></div>`.\bReload this page when you're done.",

			"step2": "Did you notice that the `intro` tag you just placed, got replaced with some placeholder text? Let's try to figure out how it happened.\bWhen Punch serves a request, it looks for the best matching content and layout to render the requested page. In this case, we requested for the `/index.html` page. So, Punch chose `contents/index.json` as the best matching content and the main layout to render the page.\bIf you look in `contents/index.json`, you will find the `intro` property defined. You can change its value and see the effect.\bReload this page after changing the value of `intro`.",

			"step3": "Nice! You should now see the value you just defined got rendered on the page. [JSON](http://json.org) is a good way to define short, structured content. But what about long, formatted texts we often want to insert into our pages? It would be cumbersome if we had to write HTML tags inside JSON strings. Well, there's a smarter option - [Markdown](http://daringfireball.net/projects/markdown/).\bLet's try to define the intro text using Markdown. For that, we need to create a directory named `_index` under `contents`. Then inside it, create a file named `intro.markdown`. Write the intro in that file, using Markdown. Make sure you break the text into multiple paragraphs, emphasize points and add links.\bReload the page again, to see how updated intro will render.",

			"step4": "You're picking up so fast! Notice how you can provide content for a page, in a JSON file named by the page name(`index.json`) and/or a directory named by the page name preceded with an underscore(`_index`), placed inside `contents`.\bSuch a directory, is known as extended contents, can contain parsable content such as Markdown files or even JSON files. Those content can be accessed in layouts by the name of the file (eg. intro.markdown is accessed as `intro`).\bFollowing these concepts, let's add a About page to the site. Create a directory named `_about` in `contents` and place a `intro.markdown` file for the About page as well.\bOnce done, visit [http://localhost:9009/about](http://localhost:9009/about) to see the About page you just created.",

			"step5": "Great job! Since there are already two pages in the site, it's better to add a navbar.\bOpen the `shared.json` file in `contents` and modify the `navbar` property to look like this:\b
\"navbar\": [\n    { \"label\": \"Home\", \"href\": \"/\" },\n    { \"label\": \"About\", \"href\": \"/about\" }\n]
\bAlso, you can change the title of your site by changing the `site-title` property.\bReload the page, when you're done.",

			"step6": "Sweet! This site is coming up nicely. If you want to change the markup used for the site title and navbar, you can do it by editing `templates/_header.mustache`. Layout files, other than the `_layout.mustache`, that has a name starting with an underscore are known as partial layouts. You can include them in other layouts, using the following syntax - `{{> header }}`.\bAlso note, any property you define in `contents/shared.json` is made available to all pages of the site.\bNow let's go back to [homepage](/) and try to make it little prominent.",

			"step7": "So far we used the main layout (`templates/_layout.mustache`) to render all pages of the site. We shall create a separate layout for the homepage to make it more prominent.\bYou can create a new layout by simply copying the `_layout.mustache` into a new file. Save it as `index.mustache`.\bIf there's a layout by the name of a requested page, Punch will use that layout to render the page (eg. `index.mustache` will be picked to render `/index` request).\bThere are many interesting things you can try on homepage; but for now we'll just insert a banner image. Copy a suitable image into `templates` directory. Then, modify the markup of `index.mustache` to show the image:\b
<div role=\"main\">\n  <img src=\"banner.jpg\">\n  {{{intro}}}\n</div>
Reload the page, when you're done.",

			"step8": "Woah! Look you just created a nice little site with Punch :)\bTo learn further on the concepts we touched upon and discover other great features in Punch, you can peruse [Punch Guide](https://github.com/laktek/punch/wiki).\bTo remove this block, go to `templates/_footer.mustache` and remove the tag `{{{first_run}}}`.\bHappy Hacking!",

			"skip": "To remove this block, go to `templates/_footer.mustache` and remove the tag `{{{first_run}}}`.\bBTW, [Punch Guide](https://github.com/laktek/punch/wiki) might come in handy, when you want to refer how to get certain things done.\bHappy Hacking!"
	};

	var setupHelpBox = function() {
		var help_box = $("
").attr("id", "punch-help-box");
		var help_message = $("
").attr("class", "message");
		var sticky_links = $("").append("Got stuck? Seek help | Skip the tutorial");

		$(help_box).append(help_message).append(sticky_links);
		$("div[role=main]").append(help_box);
	};

	var setMessage = function(msg, replace) {
		var msg_lines = messages[msg].split("\b");
		var help_box = $("#punch-help-box .message");
		var formatted_msg = $("
");

		var add_markup = function(text) {
			return text.replace(/`([^`]*)`/g, "$1").replace(/\[([^\]]*)\]\(([\S]*)\)/g, "$1");
		};

		for(var i = 0; i < msg_lines.length; i++) {
			formatted_msg.append($("
").html(add_markup(msg_lines[i])));
		}

		if (replace) {
			help_box.html(formatted_msg);
		} else {
			help_box.append(formatted_msg);
		}
	};

	var checkConditions = function(){
		$.each(conditions, function(key, value) {
			if(value()) {
				setMessage(key);
				return false;
			}
		});
	};

	$("div[role=main]").delegate("a", "click", function() {
		var link = $(this).attr("href");

		if(link === "#show_help") {
			setMessage("step1", true);
			return false;
		} else if(link === "#no_help") {
			setMessage("skip", true);
			return false;
		} else {
			$(this).attr("target", "_blank");
		}
	});

	setupHelpBox();
	checkConditions();

})();
<commit_msg>Updated first run tutorial as per some suggestions provided by @sayanee<commit_after>/*jshint regexp: false */
/*global $:true, window: true */

(function() {

	var main_text = $("div[role=main]").text();

	var conditions = {
		"initial": function() { return window.location.href === "http://localhost:9009/" && $.trim(main_text) === "" },
		"step2": function() { return window.location.href === "http://localhost:9009/" && $.trim(main_text) === "This is just a placeholder." },
		"step3": function() { return window.location.href === "http://localhost:9009/" && $("div[role=main] p").length < 1 },
		"step4": function() { return window.location.href !== "http://localhost:9009/about" && $(".navbar").children().length < 1 },
		"step5": function() { return window.location.href === "http://localhost:9009/about" && $(".navbar").children().length < 1 },
		"step6": function() { return window.location.href === "http://localhost:9009/about" && $(".navbar").children().length > 1 },
		"step7": function() { return window.location.href !== "http://localhost:9009/about" && $("div[role=main] img").length < 1 },
		"step8": function() { return true }
	};

	var messages = {
			"initial": "Thanks for trying out Punch! This quick hands-on tutorial will help you to get familiar with the basics of Punch (It won't take more than 15 minutes).\b[Let's Start!](#show_help)",

			"step1": "We believe the separation of content from its presentation is important for any kind of site. To make this easy, Punch creates two directories named `contents` and `templates`. All information you wish to communicate should go in `contents`; all presentational elements (layouts, assets) should be placed in `templates`.\bIf you go inside the `templates` directory, you will find a file named `_layout.mustache`. This is the main layout of your site. You can create different layouts for different sections of your site. For now, we shall use the main layout to render all pages.\bOpen the `_layout.mustache` and place the tag `{{{intro}}}` inside `<div role=\"main\"></div>`.\bReload this page when you're done.",

			"step2": "Did you notice that the `intro` tag you just placed, got replaced with some placeholder text? Let's try to figure out how it happened.\bWhen Punch serves a request, it looks for the best matching content and layout to render the requested page. In this case, we requested for the `/index.html` page. So, Punch chose `contents/index.json` as the best matching content and the main layout to render the page.\bIf you look in `contents/index.json`, you will find the `intro` property defined. You can change its value and see the effect.\bReload this page after changing the value of `intro`.",

			"step3": "Nice! You should now see the value you just defined got rendered on the page. [JSON](http://json.org) is a good way to define short, structured content. But what about long, formatted texts we often want to insert into our pages? It would be cumbersome if we had to write HTML tags inside JSON strings. Well, there's a smarter option - [Markdown](http://daringfireball.net/projects/markdown/).\bLet's try to define the intro text using Markdown. For that, we need to create a directory named `_index` under `contents`. Then inside it, create a file named `intro.markdown`. Write the intro in that file, using Markdown. Make sure you break the text into multiple paragraphs, emphasize points and add links.\bReload the page again, to see how updated intro will render.",

			"step4": "You're picking up so fast! Notice how you can provide content for a page, in a JSON file named by the page name(`index.json`) and/or a directory named by the page name preceded with an underscore(`_index`), placed inside `contents`.\bSuch a directory, is known as extended contents, can contain parsable content such as Markdown files or even JSON files. Those content can be accessed in layouts by the name of the file (eg. `intro.markdown` is accessed as `intro`).\bFollowing these concepts, let's add a About page to the site. Create a directory named `_about` in `contents` and place a `intro.markdown` file for the About page as well.\bOnce done, visit [http://localhost:9009/about](http://localhost:9009/about) to see the About page you just created.",

			"step5": "Great job! Since there are already two pages in the site, it's better to add a navbar.\bOpen the `shared.json` file in `contents` and modify the `navbar` property to look like this:\b
\"navbar\": [\n    { \"label\": \"Home\", \"href\": \"/\" },\n    { \"label\": \"About\", \"href\": \"/about\" }\n]
\bAlso, you can change the title of your site by changing the `site-title` property.\bReload the page, when you're done.",

			"step6": "Sweet! This site is coming up nicely. If you want to change the markup used for the site title and navbar, you can do it by editing `templates/_header.mustache`. Layout files, other than the `_layout.mustache`, that has a name starting with an underscore are known as partial layouts. You can include them in other layouts, using the following syntax - `{{> header }}`.\bAlso note, any property you define in `contents/shared.json` is made available to all pages of the site.\bNow let's go back to [homepage](/) and try to make it little prominent.",

			"step7": "So far we used the main layout (`templates/_layout.mustache`) to render all pages of the site. We shall create a separate layout for the homepage to make it more prominent.\bYou can create a new layout by simply copying the `_layout.mustache` into a new file. Save it as `index.mustache`.\bIf there's a layout by the name of a requested page, Punch will use that layout to render the page (eg. `index.mustache` will be picked to render `/index` request).\bThere are many interesting things you can try on homepage; but for now we'll just insert a banner image. Copy a suitable image into `templates` directory. Then, modify the markup of `index.mustache` to show the image:\b
<div role=\"main\">\n  <img src=\"banner.jpg\">\n  {{{intro}}}\n</div>
Reload the page, when you're done.",

			"step8": "Woah! Look you just created a nice little site with Punch :)\bTo learn further on the concepts we touched upon and discover other great features in Punch, you can peruse [Punch Guide](https://github.com/laktek/punch/wiki).\bTo remove this block, go to `templates/_footer.mustache` and remove the tag `{{{first_run}}}`.\bHappy Hacking!",

			"skip": "To remove this block, go to `templates/_footer.mustache` and remove the tag `{{{first_run}}}`.\bBTW, [Punch Guide](https://github.com/laktek/punch/wiki) might come in handy, when you want to refer how to get certain things done.\bHappy Hacking!"
	};

	var setupHelpBox = function() {
		var help_box = $("
").attr("id", "punch-help-box");
		var help_message = $("
").attr("class", "message");
		var sticky_links = $("").append("Got stuck? Seek help | Skip the tutorial");

		$(help_box).append(help_message).append(sticky_links);
		$("div[role=main]").append(help_box);
	};

	var setMessage = function(msg, replace) {
		var msg_lines = messages[msg].split("\b");
		var help_box = $("#punch-help-box .message");
		var formatted_msg = $("
");

		var add_markup = function(text) {
			return text.replace(/`([^`]*)`/g, "$1").replace(/\[([^\]]*)\]\(([\S]*)\)/g, "$1");
		};

		for(var i = 0; i < msg_lines.length; i++) {
			formatted_msg.append($("
").html(add_markup(msg_lines[i])));
		}

		if (replace) {
			help_box.html(formatted_msg);
		} else {
			help_box.append(formatted_msg);
		}
	};

	var checkConditions = function(){
		$.each(conditions, function(key, value) {
			if(value()) {
				setMessage(key);
				return false;
			}
		});
	};

	$("div[role=main]").delegate("a", "click", function() {
		var link = $(this).attr("href");

		if(link === "#show_help") {
			setMessage("step1", true);
			return false;
		} else if(link === "#no_help") {
			setMessage("skip", true);
			return false;
		}
	});

	setupHelpBox();
	checkConditions();

})();
<|endoftext|>


<commit_before>/**
 * @preserve FormDataBuilder.js (c) 2015 KNOWLEDGECODE | MIT
 */
/*jslint plusplus: true */
/*global Blob, define */
(function (global) {
    'use strict';

    var FormDataBuilder = function () {
        this.boundary = '----WebKitFormBoundary' + Math.random().toString(36).slice(2);
        this.type = 'multipart/form-data; boundary=' + this.boundary;
        this.crlf = '\r\n';
        this.pairs = [];
    };

    FormDataBuilder.prototype.append = function (name, value) {
        var pair = {
            disposition: 'form-data; name="' + (name || '').replace(/"/g, '%22') + '"'
        };

        if (value instanceof Blob) {
            pair.disposition += '; filename="' + (value.name || 'blob').replace(/"/g, '%22') + '"';
            pair.type = value.type || 'application/octet-stream';
            pair.value = value;
        } else {
            pair.value = String(value);
        }
        this.pairs.push(pair);
    };
    FormDataBuilder.prototype.getBlob = function () {
        var array = [], i, len = this.pairs.length;

        for (i = 0; i < len; i++) {
            array.push('--' + this.boundary + this.crlf + 'Content-Disposition: ' + this.pairs[i].disposition);
            if (this.pairs[i].type) {
                array.push(this.crlf + 'Content-Type: ' + this.pairs[i].type);
            }
            array.push(this.crlf + this.crlf);
            array.push(this.pairs[i].value);
            array.push(this.crlf);
        }
        if (len) {
            array.push('--' + this.boundary + '--' + this.crlf);
        }
        return new Blob(array);
    };

    if (typeof define === 'function' && define.amd) {
        define([], function () {
            return FormDataBuilder;
        });
    } else {
        global.FormDataBuilder = FormDataBuilder;
    }

}(this));
<commit_msg>improve for cross-browser<commit_after>/**
 * @preserve FormDataBuilder.js (c) 2015 KNOWLEDGECODE | MIT
 */
(function (global) {
    'use strict';

    var FormDataBuilder = function () {
        this.boundary = '----WebKitFormBoundary' + Math.random().toString(36).slice(2);
        this.type = 'multipart/form-data; boundary=' + this.boundary;
        this.crlf = '\r\n';
        this.pairs = [];
    };

    FormDataBuilder.prototype.append = function (name, value) {
        var type = Object.prototype.toString.call(value),
            enc = function (str) {
                // WebKit's behavior
                return str.replace(/\r/g, '%0D').replace(/\n/g, '%0A').replace(/"/g, '%22');
            },
            pair = {
                disposition: 'form-data; name="' + enc(name || '') + '"'
            };

        // WebKit's behavior
        if (!name) {
            return;
        }
        if (type === '[object File]' || type === '[object Blob]') {
            pair.disposition += '; filename="' + enc(value.name || 'blob') + '"';
            pair.type = value.type || 'application/octet-stream';
            pair.value = value;
        } else {
            pair.value = String(value);
        }
        this.pairs.push(pair);
    };
    FormDataBuilder.prototype.getBlob = function () {
        var array = [], i, len = this.pairs.length;

        for (i = 0; i < len; i++) {
            array.push('--' + this.boundary + this.crlf + 'Content-Disposition: ' + this.pairs[i].disposition);
            if (this.pairs[i].type) {
                array.push(this.crlf + 'Content-Type: ' + this.pairs[i].type);
            }
            array.push(this.crlf + this.crlf);
            array.push(this.pairs[i].value);
            array.push(this.crlf);
        }
        array.push('--' + this.boundary + '--' + this.crlf);
        return global.Blob ? new Blob(array) : new global.FileReaderSync().readAsArrayBuffer((function (data) {
            var Builder = global.BlobBuilder || global.WebKitBlobBuilder || global.MSBlobBuilder,
                blob = new Builder();

            (data || []).forEach(function (d) {
                blob.append(d);
            });
            return blob.getBlob();
        }(array)));
    };

    global.FormDataBuilder = FormDataBuilder;

}(this));
<|endoftext|>


<commit_before>
module.exports = {

  VERSION: "Mr Bazinga version 0.1",

  bet_request: function(game_state) {
    return 100;
  },

  showdown: function(game_state) {

  }
};
<commit_msg>Toss it bro'<commit_after>module.exports = {

    VERSION: "Mr Bazinga version 0.1",

    bet_request: function (game_state) {
        console.log('Do you see me?');
        return 100;
    },

    showdown: function (game_state) {

    }
};
<|endoftext|>


<commit_before>//This page handles all resources page content

//jquery for phone fields
$(".required").keyup(function () {
    if (this.value.length == this.maxLength) {
      var $next = $(this).next('.required');
      if ($next.length)
          $(this).next('.required').focus();
      else
          $(this).blur();
    }
});

const btnLogout = document.getElementById('btnLogout');

//Add logout event
btnLogout.addEventListener('click', e => {
	auth.signOut();

});

const auth = firebase.auth();

//Add a realtime listener
auth.onAuthStateChanged(function(firebaseUser) {
	if(firebaseUser) {
		console.log(firebaseUser);
		btnLogout.classList.remove('hide');

    console.log(firebaseUser.email);

	} else {
		console.log('not logged in');
		btnLogout.classList.add('hide');
	}

});

//Loads all resources on page load
window.onload = allStatistics();
var resourceRef = firebase.database();

function updateStatistics(statisticID) {
	var id = statisticID;
	var statValue = id + "Value";

	var valueUpdate = document.getElementById(statValue);

	resourceRef.ref("data_dashboard").child(id).update({
		value: ""+ valueUpdate.value +"",
	});
};

function deleteResource(statisticID) {
	var id = statisticID;
	resourceRef.ref("data_dashboard").child(""+id+"").remove();

	allStatistics();
};

//Filters all resources
function allStatistics() {

	//Clears table of resources
	var tableRef = document.getElementById('table_body');
	while ( tableRef.rows.length > 0 )
	{
	 tableRef.deleteRow(0);
	}

	//Pull resources from Firebase database
	rootref.child("data_dashboard").on("child_added", function(snap) {

		//store data from firebase to be used in table
		var id = snap.key;
		var stringID = id.toString();
		var statValue = snap.val();

		//Creates table with resources pulled from firebase
		$("#table_body").append("
<input id='"+id+"Statistic' type='text' value=\""+stringID+"\" ></input>	<input id='"+id+"Value' type='text'  value=\""+statValue+"\" ></input>	<input type='submit' class='btn btn-success btn-send' value='Delete' onclick='deleteResource(\""+ stringID + "\")'></input>	<input type='submit' class='btn btn-success btn-send' value='Update' onclick='updateResource(\""+ stringID + "\")''></input>
"
		);
		});
};
<commit_msg>Update firebase-edit-data-dashboard.js<commit_after>//This page handles all resources page content

//jquery for phone fields
$(".required").keyup(function () {
    if (this.value.length == this.maxLength) {
      var $next = $(this).next('.required');
      if ($next.length)
          $(this).next('.required').focus();
      else
          $(this).blur();
    }
});

const btnLogout = document.getElementById('btnLogout');

//Add logout event
btnLogout.addEventListener('click', e => {
	auth.signOut();

});

const auth = firebase.auth();

//Add a realtime listener
auth.onAuthStateChanged(function(firebaseUser) {
	if(firebaseUser) {
		console.log(firebaseUser);
		btnLogout.classList.remove('hide');

    console.log(firebaseUser.email);

	} else {
		console.log('not logged in');
		btnLogout.classList.add('hide');
	}

});

//Loads all statistics on page load
window.onload = allStatistics();
var statRef = firebase.database();

function updateStatistics(statisticID) {
	var id = statisticID;
	var statValue = id + "Value";

	var valueUpdate = document.getElementById(statValue);

	statRef.ref("data_dashboard").child(id).update({
		value: ""+ valueUpdate.value +"",
	});
};

function deleteStatistic(statisticID) {
	var id = statisticID;
	statRef.ref("data_dashboard").child(""+id+"").remove();

	allStatistics();
};

//Filters all statistics
function allStatistics() {

	//Clears table of statistics
	var tableRef = document.getElementById('table_body');
	while ( tableRef.rows.length > 0 )
	{
	 tableRef.deleteRow(0);
	}

	//Pull statistics from Firebase database
	rootref.child("data_dashboard").on("child_added", function(snap) {

		//store data from firebase to be used in table
		var id = snap.key;
		var stringID = id.toString();
		var statValue = snap.val();

		//Creates table with statistics pulled from firebase
		$("#table_body").append("
<input id='"+id+"Statistic' type='text' value=\""+stringID+"\" ></input>	<input id='"+id+"Value' type='text'  value=\""+statValue+"\" ></input>	<input type='submit' class='btn btn-success btn-send' value='Delete' onclick='deleteStatistic(\""+ stringID + "\")'></input>	<input type='submit' class='btn btn-success btn-send' value='Update' onclick='updateStatistic(\""+ stringID + "\")''></input>
"
		);
		});
};
<|endoftext|>


<commit_before>'use strict';

define(['./module', 'darkwallet', 'frontend/port', 'bitcoinjs-lib', 'util/btc'], function (controllers, DarkWallet, Port, Bitcoin, BtcUtils) {

  // Controller
  controllers.controller('BrowserCtrl', ['$scope', 'modals', 'notify', '$routeParams', '$location', function($scope, modals, notify, $routeParams, $location) {

  $scope.bytesToHex = Bitcoin.convert.bytesToHex;

  /*********************************
   * Transactions
   */

  $scope.txHash = '';
  $scope.transaction = '';

  /**
   * Show an input (extracts the address sending)
   */
  $scope.showInput = function(anIn) {
      var identity = DarkWallet.getIdentity();

      var address = BtcUtils.getInputAddress(anIn, identity.wallet.versions);

      var lastScriptByte = anIn.script.buffer[anIn.script.buffer.length-1];
      var notes;

      if (anIn.script.chunks[0] == 0 && lastScriptByte == Bitcoin.Opcode.map.OP_CHECKMULTISIG) {
          // multisig
          var fundScript = bytesToHex(anIn.script.chunks[anIn.script.chunks.length-1]);
          var multisig = BtcUtils.importMultiSig(fundScript);
          notes = (anIn.script.chunks.length-2) + "/" + multisig.pubKeys.length + " sigs"
      } else if (anIn.outpoint.hash == '0000000000000000000000000000000000000000000000000000000000000000') {
          result = '';
          notes = "coinbase";
      } else {
          console.log('unknown', anIn);
          notes = '';
      }
      return {address: address, notes: notes};
  };

  /**
   * Process a transaction to extract some info
   */
  var processTransaction = function(tx) {
      tx = BtcUtils.fixTxVersions(tx, DarkWallet.getIdentity());
      tx.ins.forEach(function(anIn, i) {
          var pubKeys = anIn.script.extractPubkeys();
          anIn.address = $scope.showInput(anIn);

      })
  };

  /**
   * Transaction received callback
   */
  var onFetchTransaction = function(err, data) {
      $scope.fetching = false;
      if (err) {
          notify.warning("Transaction not found", err.message);
          return;
      } else {
          $scope.txName = $scope.txHash;
          $scope.tx = new Bitcoin.Transaction(data);
          $scope.address = '';
          $scope.history = '';
          processTransaction($scope.tx);
      }
      $scope.$apply();
  };

  /**
   * Direct search for a transaction
   */
  $scope.searchTransaction = function(txHash) {
      var client = DarkWallet.getClient();
      $scope.fetching = true;
      client.fetch_transaction(txHash||$scope.txHash, onFetchTransaction);
  }

  /*********************************
   * Addresses
   */

  $scope.filterHistoryRows = function(page) {
      $scope.page=page;
      $scope.history = $scope.allHistory.slice(page*limit, (page*limit)+limit)
  }

  /**
   * History received callback
   */
  $scope.page = 0;
  var limit = 25;
  var onFetchHistory = function(err, history) {
      $scope.fetching = false;
      if (err) {
          notify.warning("Address not found!", err.message);
          return;
      } else {
          $scope.txName = '';
          $scope.tx = false;
          $scope.allHistory = history;
          $scope.nPages = Math.ceil(history.length / limit);
          $scope.filterHistoryRows(0);
          var inConfirmed = 0;
          var inUnconfirmed = 0;
          var outConfirmed = 0;
          var outUnconfirmed = 0;
          history.forEach(function(row) {
              var value = row[3];
              // Check spend
              if (row[4]) {
                   if (!row[6]) { // spend height
                       outUnconfirmed+=value;
                   } else {
                       outConfirmed+=value;
                   }
              }
              // Check input
              if (row[2]) { // our height
                  inConfirmed+=value;
              } else {
                  inUnconfirmed+=value;
              }
          });
          $scope.balance = {confirmed: inConfirmed-outConfirmed, unconfirmed: inUnconfirmed-outUnconfirmed};
          $scope.balanceIn = {confirmed: inConfirmed, unconfirmed: inUnconfirmed};
          $scope.balanceOut = {confirmed: outConfirmed, unconfirmed: outUnconfirmed};
      }
      $scope.$apply();
  };

  /**
   * Direct address search
   */
  $scope.searchAddress = function(address) {
      var client = DarkWallet.getClient();
      $scope.address = address;
      $scope.fetching = true;
      client.fetch_history(address, 0, onFetchHistory);
  }

  /**
   * General search... search anything!
   */
  $scope.search = function(data) {
      data = data || $scope.txHash;
      $location.path('/browser/'+data);
  }

  $scope.searchReally = function(data) {
      data = data || $scope.txHash;
      if (data.length < 40) {
          $scope.searchAddress(data);
      } else {
          $scope.searchTransaction(data);
      }
  }

  /**
   * Open a link. Currently searches but could go to some url
   */
  $scope.openLink = function(data) {
      $scope.search(data);
  }

  /**
   * Handle route parameters so we can receive url like #browser/<search>
   */
  if ($routeParams.search) {
      $scope.txHash = $routeParams.search;
      $scope.searchReally($routeParams.search);
  }

}]);
});
<commit_msg>fix for incorrect call.<commit_after>'use strict';

define(['./module', 'darkwallet', 'frontend/port', 'bitcoinjs-lib', 'util/btc'], function (controllers, DarkWallet, Port, Bitcoin, BtcUtils) {

  // Controller
  controllers.controller('BrowserCtrl', ['$scope', 'modals', 'notify', '$routeParams', '$location', function($scope, modals, notify, $routeParams, $location) {

  $scope.bytesToHex = Bitcoin.convert.bytesToHex;

  /*********************************
   * Transactions
   */

  $scope.txHash = '';
  $scope.transaction = '';

  /**
   * Show an input (extracts the address sending)
   */
  $scope.showInput = function(anIn) {
      var identity = DarkWallet.getIdentity();

      var address = BtcUtils.getInputAddress(anIn, identity.wallet.versions);

      var lastScriptByte = anIn.script.buffer[anIn.script.buffer.length-1];
      var notes;

      if (anIn.script.chunks[0] == 0 && lastScriptByte == Bitcoin.Opcode.map.OP_CHECKMULTISIG) {
          // multisig
          var fundScript = $scope.bytesToHex(anIn.script.chunks[anIn.script.chunks.length-1]);
          var multisig = BtcUtils.importMultiSig(fundScript);
          notes = (anIn.script.chunks.length-2) + "/" + multisig.pubKeys.length + " sigs"
      } else if (anIn.outpoint.hash == '0000000000000000000000000000000000000000000000000000000000000000') {
          result = '';
          notes = "coinbase";
      } else {
          console.log('unknown', anIn);
          notes = '';
      }
      return {address: address, notes: notes};
  };

  /**
   * Process a transaction to extract some info
   */
  var processTransaction = function(tx) {
      tx = BtcUtils.fixTxVersions(tx, DarkWallet.getIdentity());
      tx.ins.forEach(function(anIn, i) {
          var pubKeys = anIn.script.extractPubkeys();
          anIn.address = $scope.showInput(anIn);

      })
  };

  /**
   * Transaction received callback
   */
  var onFetchTransaction = function(err, data) {
      $scope.fetching = false;
      if (err) {
          notify.warning("Transaction not found", err.message);
          return;
      } else {
          $scope.txName = $scope.txHash;
          $scope.tx = new Bitcoin.Transaction(data);
          $scope.address = '';
          $scope.history = '';
          processTransaction($scope.tx);
      }
      $scope.$apply();
  };

  /**
   * Direct search for a transaction
   */
  $scope.searchTransaction = function(txHash) {
      var client = DarkWallet.getClient();
      $scope.fetching = true;
      client.fetch_transaction(txHash||$scope.txHash, onFetchTransaction);
  }

  /*********************************
   * Addresses
   */

  $scope.filterHistoryRows = function(page) {
      $scope.page=page;
      $scope.history = $scope.allHistory.slice(page*limit, (page*limit)+limit)
  }

  /**
   * History received callback
   */
  $scope.page = 0;
  var limit = 25;
  var onFetchHistory = function(err, history) {
      $scope.fetching = false;
      if (err) {
          notify.warning("Address not found!", err.message);
          return;
      } else {
          $scope.txName = '';
          $scope.tx = false;
          $scope.allHistory = history;
          $scope.nPages = Math.ceil(history.length / limit);
          $scope.filterHistoryRows(0);
          var inConfirmed = 0;
          var inUnconfirmed = 0;
          var outConfirmed = 0;
          var outUnconfirmed = 0;
          history.forEach(function(row) {
              var value = row[3];
              // Check spend
              if (row[4]) {
                   if (!row[6]) { // spend height
                       outUnconfirmed+=value;
                   } else {
                       outConfirmed+=value;
                   }
              }
              // Check input
              if (row[2]) { // our height
                  inConfirmed+=value;
              } else {
                  inUnconfirmed+=value;
              }
          });
          $scope.balance = {confirmed: inConfirmed-outConfirmed, unconfirmed: inUnconfirmed-outUnconfirmed};
          $scope.balanceIn = {confirmed: inConfirmed, unconfirmed: inUnconfirmed};
          $scope.balanceOut = {confirmed: outConfirmed, unconfirmed: outUnconfirmed};
      }
      $scope.$apply();
  };

  /**
   * Direct address search
   */
  $scope.searchAddress = function(address) {
      var client = DarkWallet.getClient();
      $scope.address = address;
      $scope.fetching = true;
      client.fetch_history(address, 0, onFetchHistory);
  }

  /**
   * General search... search anything!
   */
  $scope.search = function(data) {
      data = data || $scope.txHash;
      $location.path('/browser/'+data);
  }

  $scope.searchReally = function(data) {
      data = data || $scope.txHash;
      if (data.length < 40) {
          $scope.searchAddress(data);
      } else {
          $scope.searchTransaction(data);
      }
  }

  /**
   * Open a link. Currently searches but could go to some url
   */
  $scope.openLink = function(data) {
      $scope.search(data);
  }

  /**
   * Handle route parameters so we can receive url like #browser/<search>
   */
  if ($routeParams.search) {
      $scope.txHash = $routeParams.search;
      $scope.searchReally($routeParams.search);
  }

}]);
});
<|endoftext|>


<commit_before>var vanya = require('./vanya.js');
var cards = require('./cards.js');
var _ = require('lodash');

function all_in() {
    return 5000;
}

function pass() {
    return 0;
}

function raise() {
    return 2000;
}

function check() {
    return 1000;
}

module.exports = {

  VERSION: "0.1.0",

  bet_request: function(game_state) {
      console.log(JSON.stringify(game_state, null, 2));

      var our_cards = cards.ourCards(game_state);
      var table_cards = game_state.community_cards;
  try {
      switch(vanya(our_cards.concat(table_cards))) {
          case 0:
          case 1:
          case 2:
              return pass();
          break;

          case 3:
          case 4:
          case 5:
              return raise();
          break;

          case 6:
          case 7:
          case 8:
              return all_in();
          break;
      }
  } catch(e) {
      console.log('WTF!!!???')
  }
    return check();
  },

  showdown: function(game_state) {

  },

  getMaxBetFromState: function getMaxBetFromState(game_state) {
      var bets = _.pluck(game_state.players, 'bet');

      var maxBet = bets.reduce(function (max, current) {
          return current < max ? max : current;
      }, 0);

      return maxBet;
  }
};
<commit_msg>improve raise<commit_after>var vanya = require('./vanya.js');
var cards = require('./cards.js');
var _ = require('lodash');

function all_in() {
    return 5000;
}

function pass() {
    return 0;
}

function raise() {
    var cur_bet = getMaxState();
    return cur_bet + game_state.minimum_raise;
    //return 2000;
}

function check() {
    return getMaxState();
    //return 1000;
}

module.exports = {

  VERSION: "0.1.0",

  bet_request: function(game_state) {
      console.log(JSON.stringify(game_state, null, 2));

      var our_cards = cards.ourCards(game_state);
      var table_cards = game_state.community_cards;
  try {
      switch(vanya(our_cards.concat(table_cards))) {
          case 0:
          case 1:
          case 2:
              return pass();
          break;

          case 3:
              return check();
          break;

          case 4:
          case 5:
              return raise();
          break;

          case 6:
          case 7:
          case 8:
              return all_in();
          break;
      }
  } catch(e) {
      console.log('WTF!!!???')
  }
    return check();
  },

  showdown: function(game_state) {

  },

  getMaxBetFromState: function getMaxBetFromState(game_state) {
      var bets = _.pluck(game_state.players, 'bet');

      var maxBet = bets.reduce(function (max, current) {
          return current < max ? max : current;
      }, 0);

      return maxBet;
  }
};
<|endoftext|>


<commit_before>
(function (plugin, core, scene) {
    var DEFAULTS = {
        DefaultUpColor: new THREE.Color('#00000f'),
        DefaultDownColor: new THREE.Color('#8080ff'),
        FieldOfView : scene.getCamera()
    };
     var plug = new plugin.Rendering({
        name: "Global",
        tooltip: "Global Tooltip",
        icon: "img/icons/global.png"
    }, DEFAULTS);

    var cullingWidget, topColor, bottomColor, fovWidget;

    plug._init = function (guiBuilder) {

        cullingWidget = guiBuilder.Choice({
            label: "Backface Culling",
            tooltip: "Enable/disable Backface Culling",
            options: [
                {content: "on", value: true},
                {content: "off", value: false, selected: true}
            ]
        });

        fovWidget = guiBuilder.RangedFloat({
            label: "Field of View",
            tooltip: "Change the field of view of the camera.",
            min: 5, max: 90, step: 5,
            defval: DEFAULTS.FieldOfView,
            bindTo: (function() {
                var bindToFun = function (size, overlay) {
                   scene.getCamera().fov=fovWidget.getValue();
                   scene.getCamera().updateProjectionMatrix();
                   MLJ.core.Scene.render();
                };
                bindToFun.toString = function () { return 'FieldOfView'; }
                return bindToFun;
            }())
        });

        statsWidget = guiBuilder.Choice({
            label: "Show Stats",
            tooltip: "Enable/disable the display of rendering performance stats",
            options: [
                {content: "on", value: true},
                {content: "off", value: false, selected: true}
            ],
            bindTo: (function() {

                var stats;
                var show = false;
                var req;

                var updateStats = function() {
                    if (show) {
                        stats.begin();
                        scene.render(true);
                        stats.end();
                        req = requestAnimationFrame(updateStats);
                    } else {
                        stats.active = false;
                        stats.domElement.style.visibility = 'hidden';
                        window.cancelAnimationFrame(req);
                    }
                };

                var callback = function (value) {
                    if (!show) {
                        if (value) {
                            show = true;
                            stats = scene.getStats();
                            stats.active = true;
                            stats.domElement.style.visibility = 'visible';
                            updateStats();
                        }
                    } else show = value;
                };

                callback.toString = function () { return "showStats"; };
                return callback;
            }())
        });
        topColor = guiBuilder.Color({
            label: "Background Top Color",
            tooltip: "Change the default background color of render panel, obtained mixing two different colors by linear-gradient function, at the top",
            color: "#" + DEFAULTS.DefaultUpColor.getHexString(),
            bindTo: (function() {
                var bindToFun = function (color) {
                    $('#_3D').css('background', 'linear-gradient('+topColor.getColor()+','+bottomColor.getColor()+')');
                };
                bindToFun.toString = function () { return 'DefaultUpColor'; }
                return bindToFun;
            }())
        });
        bottomColor = guiBuilder.Color({
            label: "Background Bottom Color",
            tooltip: "Change the default background color of render panel, obtained mixing two different colors by linear-gradient function, at the bottom",
            color:  "#" + DEFAULTS.DefaultDownColor.getHexString(),
            bindTo: (function() {
                var bindToFun = function (color) {
                    $('#_3D').css('background', 'linear-gradient('+topColor.getColor()+','+bottomColor.getColor()+')');
                };
                bindToFun.toString = function () { return 'DefaultDownColor'; }
                return bindToFun;
            }())
        });

    };
    plug._applyTo = function (meshFile, on) {
        alert(scene.getCamera());
    }
    plug.getBackfaceCullingValue = function (type) {
        return cullingWidget.getValue();
    };

    plug.getShowStatsValue = function (type) {
        return statsWidget.getValue();
    };
    plugin.Manager.install(plug);

})(MLJ.core.plugin, MLJ.core, MLJ.core.Scene);<commit_msg>Removed debug alert<commit_after>
(function (plugin, core, scene) {
    var DEFAULTS = {
        DefaultUpColor: new THREE.Color('#00000f'),
        DefaultDownColor: new THREE.Color('#8080ff'),
        FieldOfView : scene.getCamera()
    };
     var plug = new plugin.Rendering({
        name: "Global",
        tooltip: "Global Tooltip",
        icon: "img/icons/global.png"
    }, DEFAULTS);

    var cullingWidget, topColor, bottomColor, fovWidget;

    plug._init = function (guiBuilder) {

        cullingWidget = guiBuilder.Choice({
            label: "Backface Culling",
            tooltip: "Enable/disable Backface Culling",
            options: [
                {content: "on", value: true},
                {content: "off", value: false, selected: true}
            ]
        });

        fovWidget = guiBuilder.RangedFloat({
            label: "Field of View",
            tooltip: "Change the field of view of the camera.",
            min: 5, max: 90, step: 5,
            defval: DEFAULTS.FieldOfView,
            bindTo: (function() {
                var bindToFun = function (size, overlay) {
                   scene.getCamera().fov=fovWidget.getValue();
                   scene.getCamera().updateProjectionMatrix();
                   MLJ.core.Scene.render();
                };
                bindToFun.toString = function () { return 'FieldOfView'; }
                return bindToFun;
            }())
        });

        statsWidget = guiBuilder.Choice({
            label: "Show Stats",
            tooltip: "Enable/disable the display of rendering performance stats",
            options: [
                {content: "on", value: true},
                {content: "off", value: false, selected: true}
            ],
            bindTo: (function() {

                var stats;
                var show = false;
                var req;

                var updateStats = function() {
                    if (show) {
                        stats.begin();
                        scene.render(true);
                        stats.end();
                        req = requestAnimationFrame(updateStats);
                    } else {
                        stats.active = false;
                        stats.domElement.style.visibility = 'hidden';
                        window.cancelAnimationFrame(req);
                    }
                };

                var callback = function (value) {
                    if (!show) {
                        if (value) {
                            show = true;
                            stats = scene.getStats();
                            stats.active = true;
                            stats.domElement.style.visibility = 'visible';
                            updateStats();
                        }
                    } else show = value;
                };

                callback.toString = function () { return "showStats"; };
                return callback;
            }())
        });
        topColor = guiBuilder.Color({
            label: "Background Top Color",
            tooltip: "Change the default background color of render panel, obtained mixing two different colors by linear-gradient function, at the top",
            color: "#" + DEFAULTS.DefaultUpColor.getHexString(),
            bindTo: (function() {
                var bindToFun = function (color) {
                    $('#_3D').css('background', 'linear-gradient('+topColor.getColor()+','+bottomColor.getColor()+')');
                };
                bindToFun.toString = function () { return 'DefaultUpColor'; }
                return bindToFun;
            }())
        });
        bottomColor = guiBuilder.Color({
            label: "Background Bottom Color",
            tooltip: "Change the default background color of render panel, obtained mixing two different colors by linear-gradient function, at the bottom",
            color:  "#" + DEFAULTS.DefaultDownColor.getHexString(),
            bindTo: (function() {
                var bindToFun = function (color) {
                    $('#_3D').css('background', 'linear-gradient('+topColor.getColor()+','+bottomColor.getColor()+')');
                };
                bindToFun.toString = function () { return 'DefaultDownColor'; }
                return bindToFun;
            }())
        });

    };
    plug._applyTo = function (meshFile, on) {
        //alert(scene.getCamera());
    }
    plug.getBackfaceCullingValue = function (type) {
        return cullingWidget.getValue();
    };

    plug.getShowStatsValue = function (type) {
        return statsWidget.getValue();
    };
    plugin.Manager.install(plug);

})(MLJ.core.plugin, MLJ.core, MLJ.core.Scene);<|endoftext|>


<commit_before>var rank = require('./rank');

Array.prototype.contains = function (element) {
    return this.indexOf(element) > -1;
};

module.exports = {

    VERSION: "MadFoldBot v2.4",

    bet_request: function (game_state, bet) {
        return this.strategy1(game_state, bet);
    },

    showdown: function (game_state) {

    },

    strategy1: function (game_state, bet) {
        var our_bet = this.getBet(game_state);
        console.log('OUR BET: ' + our_bet);

        bet(our_bet);
    },

    getBet: function (game_state) {
        var all_cards = this.getAllCards(game_state);
        var myself = game_state.players[game_state.in_action];
        var call = game_state.current_buy_in - myself["bet"];

        var isAllIn = this.isAllIn(game_state);
        console.log('CURRENT CALL: ' + call);

        if (
            (myself.hole_cards[0].rank == 'A' && myself.hole_cards[1].rank == 'A') ||
            (myself.hole_cards[0].rank == 'K' && myself.hole_cards[1].rank == 'K') ||
            (myself.hole_cards[0].rank == 'Q' && myself.hole_cards[1].rank == 'Q') ||
            (myself.hole_cards[0].rank == 'A' && myself.hole_cards[1].rank == 'K') ||
            (myself.hole_cards[0].rank == 'K' && myself.hole_cards[1].rank == 'A')
        ) {
            return 10000;
        }

        if (false && isAllIn) {
            console.log("WARNING - ALL IN!!!");

            if (game_state.community_cards.length < 1) {
                if (
                    (myself.hole_cards[0].rank == 'A' && myself.hole_cards[1].rank == 'A') ||
                    (myself.hole_cards[0].rank == 'K' && myself.hole_cards[1].rank == 'K') ||
                    (myself.hole_cards[0].rank == 'Q' && myself.hole_cards[1].rank == 'Q') ||
                    (myself.hole_cards[0].rank == 'A' && myself.hole_cards[1].rank == 'K') ||
                    (myself.hole_cards[0].rank == 'K' && myself.hole_cards[1].rank == 'A')
                ) {
                } else {
                    return 0;
                }
            }
        } else {

        }

        if (game_state.community_cards.length < 1) {
            console.log('PREFLOP');
            // we're before flop
            if (lameCards(myself.hole_cards)) {
                console.log('LAME CARDS');
                return 0;
            } else {
                if (toNum(myself.hole_cards[1].rank) > 11 && toNum(myself.hole_cards[0].rank) > 11) {
                    console.log('HIGH CARDS. DOING CALL');
                    return myself.stack;
                }

                if (compute_chip_factor(game_state) > 3) {
                    console.log('CHIP FACTOR');
                    return call;
                }
                else {
                    return 0;
                }
            }
        }

        var our_hand = rank.rank(all_cards);

        console.log('OUR HAND');
        console.log(our_hand);

        if (our_hand.contains('flush')) {
            return 10000;
        }

        if (our_hand.contains('full_house')) {
            return 10000;
        }

        if (our_hand.contains('tree_of_a_kind')) {
            return 10000;
        }

        if (our_hand.contains('two_pairs')) {
            return 500;
        }

        if (our_hand.contains('pair')) {
            return 0;
        }

        return 0;
    },

    isAllIn: function (game_state) {
        var players = game_state.players;

        for (var i in players) {
            if (i != game_state.in_action && players[i].status == "active" && players[i].stack == 0 && players[i].bet > 200) {
                return true;
            }
        }

        return false;
    },

    getAllCards: function (game_state) {
        var cards = [];
        var community_cards = game_state.community_cards;

        for (var p in game_state.players) {
            if (typeof game_state.players[p]['hole_cards'] != 'undefined') {
                cards = game_state.players[p]['hole_cards'];
            }
        }

        cards = cards.concat(community_cards);

        return cards;
    }

};

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

        default:
            return c;
    }
}

function lameCards(cards) {
    /* if (
     toNum(cards[0].rank) >= 12 || toNum(cards[1].rank) >= 12
     ) {
     return false;
     } else if (cards[0].rank == 'A' || cards[1].rank == 'A') {
     return false;
     }
     else */
    if (
        (toNum(cards[0].rank) < 7 || toNum(cards[1].rank) < 7) && cards[0].rank != cards[1].rank
    ) {
        return true
    } else {
        return false
    }
}

function compute_avg_stack(players) {
    var sum = 0;
    for (var i in players) {
        if (players[i].status == "active") {
            sum += players[i].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;
    }
}<commit_msg>game state<commit_after>var rank = require('./rank');

Array.prototype.contains = function (element) {
    return this.indexOf(element) > -1;
};

module.exports = {

    VERSION: "MadFoldBot v2.4",

    bet_request: function (game_state, bet) {
        return this.strategy1(game_state, bet);
    },

    showdown: function (game_state) {

    },

    strategy1: function (game_state, bet) {
        var our_bet = this.getBet(game_state);
        console.log('OUR BET: ' + our_bet);

        bet(our_bet);
    },

    getBet: function (game_state) {
        var all_cards = this.getAllCards(game_state);
        var myself = game_state.players[game_state.in_action];
        var call = game_state.current_buy_in - myself["bet"];

        var isAllIn = this.isAllIn(game_state);
        console.log('CURRENT CALL: ' + call);

        if (
            (myself.hole_cards[0].rank == 'A' && myself.hole_cards[1].rank == 'A') ||
            (myself.hole_cards[0].rank == 'K' && myself.hole_cards[1].rank == 'K') ||
            (myself.hole_cards[0].rank == 'Q' && myself.hole_cards[1].rank == 'Q') ||
            (myself.hole_cards[0].rank == 'A' && myself.hole_cards[1].rank == 'K') ||
            (myself.hole_cards[0].rank == 'K' && myself.hole_cards[1].rank == 'A')
        ) {
            return 10000;
        }

        if (false && isAllIn) {
            console.log("WARNING - ALL IN!!!");

            if (game_state.community_cards.length < 1) {
                if (
                    (myself.hole_cards[0].rank == 'A' && myself.hole_cards[1].rank == 'A') ||
                    (myself.hole_cards[0].rank == 'K' && myself.hole_cards[1].rank == 'K') ||
                    (myself.hole_cards[0].rank == 'Q' && myself.hole_cards[1].rank == 'Q') ||
                    (myself.hole_cards[0].rank == 'A' && myself.hole_cards[1].rank == 'K') ||
                    (myself.hole_cards[0].rank == 'K' && myself.hole_cards[1].rank == 'A')
                ) {
                } else {
                    return 0;
                }
            }
        } else {

        }

        if (game_state.community_cards.length < 1) {
            console.log('PREFLOP');
            // we're before flop
            if (lameCards(myself.hole_cards)) {
                console.log('LAME CARDS');
                return 0;
            } else {
                if (toNum(myself.hole_cards[1].rank) > 11 && toNum(myself.hole_cards[0].rank) > 11) {
                    console.log('HIGH CARDS. DOING CALL');
                    return myself.stack;
                }

                if (compute_chip_factor(game_state) > 3) {
                    console.log('CHIP FACTOR');
                    return call;
                }
                else {
                    return 0;
                }
            }
        }

        var our_hand = rank.rank(all_cards);

        console.log('OUR HAND');
        console.log(our_hand);

        if (our_hand.contains('flush')) {
            return 10000;
        }

        if (our_hand.contains('full_house')) {
            return 10000;
        }

        if (our_hand.contains('tree_of_a_kind')) {
            return 10000;
        }

        if (our_hand.contains('two_pairs')) {
            return 500;
        }

        if (our_hand.contains('pair')) {
            return 10;
        }

        return 0;
    },

    isAllIn: function (game_state) {
        var players = game_state.players;

        for (var i in players) {
            if (i != game_state.in_action && players[i].status == "active" && players[i].stack == 0 && players[i].bet > 200) {
                return true;
            }
        }

        return false;
    },

    getAllCards: function (game_state) {
        var cards = [];
        var community_cards = game_state.community_cards;

        for (var p in game_state.players) {
            if (typeof game_state.players[p]['hole_cards'] != 'undefined') {
                cards = game_state.players[p]['hole_cards'];
            }
        }

        cards = cards.concat(community_cards);

        return cards;
    }

};

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

        default:
            return c;
    }
}

function lameCards(cards) {
    /* if (
     toNum(cards[0].rank) >= 12 || toNum(cards[1].rank) >= 12
     ) {
     return false;
     } else if (cards[0].rank == 'A' || cards[1].rank == 'A') {
     return false;
     }
     else */
    if (
        (toNum(cards[0].rank) < 7 || toNum(cards[1].rank) < 7) && cards[0].rank != cards[1].rank
    ) {
        return true
    } else {
        return false
    }
}

function compute_avg_stack(players) {
    var sum = 0;
    for (var i in players) {
        if (players[i].status == "active") {
            sum += players[i].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;
    }
}<|endoftext|>


<commit_before>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');
    gvm.lastIdFromDb = -1;
    gvm.lastId = -1;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.projectCompletenessTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectCompletenessTitle");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.documents = ko.observableArray([]);

    gvm.addDocument = function(id, description, amount_required, weight) {
        var document = {id: id, description: description, amount_required: amount_required, weight: weight};
        gvm.documents.push(document);

        $('#removebtn-' + id).bind('click', function(event, data) {
            gvm.removeDocument(id, document);
            event.stopPropagation();
        })
    };

    gvm.addDocumentToSubmit = function() {
        ++gvm.lastId;
        gvm.addDocument(gvm.lastId, "", "", "");
    };

    gvm.getDocumentsToSubmit = function() {
        $.getJSON('/api/project/'+ gvm.projectId + '/documents', function(data) {
            $.each(data, function(i, item) {
                gvm.addDocument(item.id, item.description, item.amount_required, item.weight);
                gvm.lastIdFromDb = item.id;
                gvm.lastId = item.id;
            });
        });
    };

    gvm.removeDocument = function(id, document) {
        if(id <= gvm.lastIdFromDb) {
            $.ajax({
                url: "/api/delete/document/" + id,
                type: "DELETE",
                success: function() {
                    gvm.documents.remove(document);
                }
            });
        } else {
            gvm.documents.remove(document);
        }
    };

    gvm.saveDocumentsToSubmit = function() {
        console.log("/api/project/" + gvm.projectId + "/documents/" + gvm.lastId);
        $.ajax({
            url: "/api/project/" + 1 + "/documents/" + 1,
            type: "PUT",
            data: gvm.documents,
            success: function(data) {
                console.log("success");
            },
            error: function(data) {
                console.log("error");
            }
        });
    };
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getDocumentsToSubmit();
}<commit_msg>completeness page<commit_after>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');
    gvm.lastIdFromDb = -1;
    gvm.lastId = -1;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.projectCompletenessTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectCompletenessTitle");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.documents = ko.observableArray([]);

    gvm.addDocument = function(id, description, amount_required, weight) {
        var document = {id: id, description: description, amount_required: amount_required, weight: weight};
        gvm.documents.push(document);

        $('#removebtn-' + id).bind('click', function(event, data) {
            gvm.removeDocument(id, document);
            event.stopPropagation();
        })
    };

    gvm.addDocumentToSubmit = function() {
        ++gvm.lastId;
        gvm.addDocument(gvm.lastId, "", "", "");
    };

    gvm.getDocumentsToSubmit = function() {
        $.getJSON('/api/project/'+ gvm.projectId + '/documents', function(data) {
            $.each(data, function(i, item) {
                gvm.addDocument(item.id, item.description, item.amount_required, item.weight);
                gvm.lastIdFromDb = item.id;
                gvm.lastId = item.id;
            });
        });
    };

    gvm.removeDocument = function(id, document) {
        if(id <= gvm.lastIdFromDb) {
            $.ajax({
                url: "/api/delete/document/" + id,
                type: "DELETE",
                success: function() {
                    gvm.documents.remove(document);
                }
            });
        } else {
            gvm.documents.remove(document);
        }
    };

    gvm.saveDocumentsToSubmit = function() {
        console.log("/api/project/" + gvm.projectId + "/documents/" + gvm.lastId);
        $.ajax({
            url: "/api/project/" + gvm.projectId + "/documents/" + gvm.lastId,
            type: "POST",
            data: gvm.documents,
            success: function(data) {
                console.log("success");
            },
            error: function(data) {
                console.log("error");
            }
        });
    };
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getDocumentsToSubmit();
}<|endoftext|>


<commit_before>define(
[
    'models',
    'text!templates/common/navbar.html',
    'text!templates/common/nodes_stats.html',
    'text!templates/common/nodes_stats_popover.html',
    'text!templates/common/notifications.html',
    'text!templates/common/notifications_popover.html',
    'text!templates/common/breadcrumb.html'
],
function(models, navbarTemplate, nodesStatsTemplate, nodesStatsPopoverTemplate, notificationsTemplate, notificationsPopoverTemplate, breadcrumbTemplate) {
    'use strict';

    var views = {};

    views.Navbar = Backbone.View.extend({
        className: 'container',
        template: _.template(navbarTemplate),
        setActive: function(element) {
            this.$('.nav > li.active').removeClass('active');
            this.$('a[href="#' + element + '"]').parent().addClass('active');
        },
        initialize: function(options) {
            this.elements = _.isArray(options.elements) ? options.elements : [];
        },
        render: function() {
            this.$el.html(this.template({elements: this.elements}));
            this.stats = new views.NodesStats();
            this.registerSubView(this.stats);
            this.$('.nodes-summary-container').html(this.stats.render().el);
            this.notifications = new views.Notifications();
            this.registerSubView(this.notifications);
            this.$('.notifications').html(this.notifications.render().el);
            return this;
        }
    });

    views.NodesStats = Backbone.View.extend({
        updateInterval: 30000,
        template: _.template(nodesStatsTemplate),
        popoverTemplate: _.template(nodesStatsPopoverTemplate),
        popoverVisible: false,
        stats: {},
        events: {
            'mouseenter': 'showPopover',
            'mouseleave': 'hidePopover'
        },
        showPopover: function() {
            if (!this.popoverVisible) {
                this.popoverVisible = true;
                this.$el.popover({
                    placement: 'bottom',
                    trigger: 'manual',
                    title: 'Usage Statistics',
                    content: this.popoverTemplate({stats: this.stats})
                }).popover('show');
            }
        },
        hidePopover: function() {
            if (this.popoverVisible) {
                this.popoverVisible = false;
                this.$el.popover('destroy');
            }
        },
        scheduleUpdate: function() {
            _.delay(_.bind(this.update, this), this.updateInterval);
        },
        update: function() {
            this.nodes.fetch({complete: _.bind(this.scheduleUpdate, this)});
        },
        updateStats: function() {
            var stats = {};
            var roles = ['controller', 'compute', 'storage'];
            if (this.nodes.deferred.state() != 'pending') {
                _.each(roles, function(role) {
                    stats[role] = this.nodes.where({role: role}).length;
                }, this);
                stats.total = this.nodes.length;
                stats.unallocated = stats.total - stats.controller - stats.compute - stats.storage;
            }
            if (!_.isEqual(stats, this.stats)) {
                this.stats = stats;
                _.each(roles, function(role) {
                    stats[role] = this.nodes.where({role: role}).length;
                }, this);
                if (this.popoverVisible) {
                    this.hidePopover();
                    this.showPopover();
                }
                if (stats.unallocated) {
                    _.each(roles, function(role) {
                        this.$('.stats-' + role).width(stats.total ? (100 * stats[role] / stats.total) + '%' : 0);
                    }, this);
                } else if (stats.total) {
                    // all nodes have role assigned, working around "odd pixel" bug
                    var containerWidth = this.$('.nodes-summary-stat').width();
                    var barsWidth = 0;
                    _.each(_.initial(roles), function(role) {
                        var barWidth = Math.round(containerWidth * stats[role] / stats.total);
                        barsWidth += barWidth;
                        this.$('.stats-' + role).width(barWidth);
                    }, this);
                    this.$('.stats-' + _.last(roles)).width(containerWidth - barsWidth);
                } else {
                    this.$('.bar').width(0);
                }
            }
        },
        initialize: function(options) {
            this.nodes = new models.Nodes();
            this.nodes.deferred = this.nodes.fetch();
            this.nodes.deferred.done(_.bind(this.scheduleUpdate, this));
            this.nodes.bind('reset', this.updateStats, this);
        },
        render: function() {
            this.$el.html(this.template({stats: this.stats}));
            return this;
        }
    });

    views.Notifications = Backbone.View.extend({
        updateInterval: 5000,
        template: _.template(notificationsTemplate),
        popoverTemplate: _.template(notificationsPopoverTemplate),
        popoverVisible: false,
        displayCount: 5,
        events: {
            'click': 'togglePopover'
        },
        getUnreadNotifications: function() {
            return _.filter(this.notifications.last(this.displayCount), function(notification) {return notification.get('status') == 'unread';});
        },
        togglePopover: function() {
            if (!this.popoverVisible) {
                this.popoverVisible = true;
                $('.navigation-bar').after(this.popoverTemplate({notifications: this.notifications.last(this.displayCount)}));
                _.each(this.getUnreadNotifications(), function(notification) {
                    notification.set({'status': 'read'});
                });
                Backbone.sync('update', this.notifications).done(_.bind( function() {
                    $('html').on(this.eventNamespace, _.bind(function(e) {
                        if (!$(e.target).closest($('.message-list-placeholder')).length) {
                            $('html').off(this.eventNamespace);
                            this.popoverVisible = false;
                            $('.message-list-placeholder').remove();
                        }
                    }, this));
                    this.render;
                }, this));
            }
        },
        scheduleUpdate: function() {
            if (this.getUnreadNotifications().length) {
                this.render();
            }
            _.delay(_.bind(this.update, this), this.updateInterval);
        },
        update: function() {
            this.notifications.fetch({complete: _.bind(this.scheduleUpdate, this)});
        },
        initialize: function(options) {
            this.eventNamespace = 'click';
            this.notifications = new models.Notifications();
            this.notifications.deferred = this.notifications.fetch();
            this.notifications.deferred.done(_.bind(this.scheduleUpdate, this));
        },
        render: function() {
            this.$el.html(this.template({notifications: this.notifications}));
            return this;
        }
    });

    views.Breadcrumb = Backbone.View.extend({
        className: 'container',
        template: _.template(breadcrumbTemplate),
        path: [],
        setPath: function() {
            this.path = arguments;
            this.render();
        },
        render: function() {
            this.$el.html(this.template({path: this.path}));
            return this;
        }
    });

    return views;
});
<commit_msg>Bind click event to html: little fix<commit_after>define(
[
    'models',
    'text!templates/common/navbar.html',
    'text!templates/common/nodes_stats.html',
    'text!templates/common/nodes_stats_popover.html',
    'text!templates/common/notifications.html',
    'text!templates/common/notifications_popover.html',
    'text!templates/common/breadcrumb.html'
],
function(models, navbarTemplate, nodesStatsTemplate, nodesStatsPopoverTemplate, notificationsTemplate, notificationsPopoverTemplate, breadcrumbTemplate) {
    'use strict';

    var views = {};

    views.Navbar = Backbone.View.extend({
        className: 'container',
        template: _.template(navbarTemplate),
        setActive: function(element) {
            this.$('.nav > li.active').removeClass('active');
            this.$('a[href="#' + element + '"]').parent().addClass('active');
        },
        initialize: function(options) {
            this.elements = _.isArray(options.elements) ? options.elements : [];
        },
        render: function() {
            this.$el.html(this.template({elements: this.elements}));
            this.stats = new views.NodesStats();
            this.registerSubView(this.stats);
            this.$('.nodes-summary-container').html(this.stats.render().el);
            this.notifications = new views.Notifications();
            this.registerSubView(this.notifications);
            this.$('.notifications').html(this.notifications.render().el);
            return this;
        }
    });

    views.NodesStats = Backbone.View.extend({
        updateInterval: 30000,
        template: _.template(nodesStatsTemplate),
        popoverTemplate: _.template(nodesStatsPopoverTemplate),
        popoverVisible: false,
        stats: {},
        events: {
            'mouseenter': 'showPopover',
            'mouseleave': 'hidePopover'
        },
        showPopover: function() {
            if (!this.popoverVisible) {
                this.popoverVisible = true;
                this.$el.popover({
                    placement: 'bottom',
                    trigger: 'manual',
                    title: 'Usage Statistics',
                    content: this.popoverTemplate({stats: this.stats})
                }).popover('show');
            }
        },
        hidePopover: function() {
            if (this.popoverVisible) {
                this.popoverVisible = false;
                this.$el.popover('destroy');
            }
        },
        scheduleUpdate: function() {
            _.delay(_.bind(this.update, this), this.updateInterval);
        },
        update: function() {
            this.nodes.fetch({complete: _.bind(this.scheduleUpdate, this)});
        },
        updateStats: function() {
            var stats = {};
            var roles = ['controller', 'compute', 'storage'];
            if (this.nodes.deferred.state() != 'pending') {
                _.each(roles, function(role) {
                    stats[role] = this.nodes.where({role: role}).length;
                }, this);
                stats.total = this.nodes.length;
                stats.unallocated = stats.total - stats.controller - stats.compute - stats.storage;
            }
            if (!_.isEqual(stats, this.stats)) {
                this.stats = stats;
                _.each(roles, function(role) {
                    stats[role] = this.nodes.where({role: role}).length;
                }, this);
                if (this.popoverVisible) {
                    this.hidePopover();
                    this.showPopover();
                }
                if (stats.unallocated) {
                    _.each(roles, function(role) {
                        this.$('.stats-' + role).width(stats.total ? (100 * stats[role] / stats.total) + '%' : 0);
                    }, this);
                } else if (stats.total) {
                    // all nodes have role assigned, working around "odd pixel" bug
                    var containerWidth = this.$('.nodes-summary-stat').width();
                    var barsWidth = 0;
                    _.each(_.initial(roles), function(role) {
                        var barWidth = Math.round(containerWidth * stats[role] / stats.total);
                        barsWidth += barWidth;
                        this.$('.stats-' + role).width(barWidth);
                    }, this);
                    this.$('.stats-' + _.last(roles)).width(containerWidth - barsWidth);
                } else {
                    this.$('.bar').width(0);
                }
            }
        },
        initialize: function(options) {
            this.nodes = new models.Nodes();
            this.nodes.deferred = this.nodes.fetch();
            this.nodes.deferred.done(_.bind(this.scheduleUpdate, this));
            this.nodes.bind('reset', this.updateStats, this);
        },
        render: function() {
            this.$el.html(this.template({stats: this.stats}));
            return this;
        }
    });

    views.Notifications = Backbone.View.extend({
        updateInterval: 5000,
        template: _.template(notificationsTemplate),
        popoverTemplate: _.template(notificationsPopoverTemplate),
        popoverVisible: false,
        displayCount: 5,
        events: {
            'click': 'togglePopover'
        },
        getUnreadNotifications: function() {
            return _.filter(this.notifications.last(this.displayCount), function(notification) {return notification.get('status') == 'unread';});
        },
        togglePopover: function() {
            if (!this.popoverVisible) {
                this.popoverVisible = true;
                $('.navigation-bar').after(this.popoverTemplate({notifications: this.notifications.last(this.displayCount)}));
                _.each(this.getUnreadNotifications(), function(notification) {
                    notification.set({'status': 'read'});
                });
                Backbone.sync('update', this.notifications).done(_.bind( function() {
                    $('html').on(this.eventNamespace, _.bind(function(e) {
                        if (this.popoverVisible && !$(e.target).closest($('.message-list-placeholder')).length) {
                            $('html').off(this.eventNamespace);
                            this.popoverVisible = false;
                            $('.message-list-placeholder').remove();
                        }
                    }, this));
                    this.render;
                }, this));
            }
        },
        scheduleUpdate: function() {
            if (this.getUnreadNotifications().length) {
                this.render();
            }
            _.delay(_.bind(this.update, this), this.updateInterval);
        },
        update: function() {
            this.notifications.fetch({complete: _.bind(this.scheduleUpdate, this)});
        },
        initialize: function(options) {
            this.eventNamespace = 'click';
            this.notifications = new models.Notifications();
            this.notifications.deferred = this.notifications.fetch();
            this.notifications.deferred.done(_.bind(this.scheduleUpdate, this));
        },
        render: function() {
            this.$el.html(this.template({notifications: this.notifications}));
            return this;
        }
    });

    views.Breadcrumb = Backbone.View.extend({
        className: 'container',
        template: _.template(breadcrumbTemplate),
        path: [],
        setPath: function() {
            this.path = arguments;
            this.render();
        },
        render: function() {
            this.$el.html(this.template({path: this.path}));
            return this;
        }
    });

    return views;
});
<|endoftext|>


<commit_before>var WorkspaceToolbar = Backbone.View.extend({
    enabled: false,
    events: {
        'click a': 'call'
    },

    initialize: function(args) {
        this.workspace = args.workspace;
    },

    template: function() {
        return Saiku.template.get('WorkspaceToolbar')();
    },

    render: function() {
        $(this.el).html(this.template());

        return this;
    },

    call: function(event) {
        // Determine callback
        var callback = event.target.hash.replace('#', '');

        // Attempt to call callback
        try {
            ! $(event.target).hasClass('disabled_toolbar') && this[callback](args);
        } catch (e) {
            console &&
                console.log("Could not fire " + callback + ": " + e.message);
        }

        return false;
    },

    save_query: function() {
        // TODO - save query
    }
});<commit_msg>Automatic query execution<commit_after>var WorkspaceToolbar = Backbone.View.extend({
    enabled: false,
    events: {
        'click a': 'call'
    },

    initialize: function(args) {
        // Keep track of parent workspace
        this.workspace = args.workspace;
    },

    template: function() {
        return Saiku.template.get('WorkspaceToolbar')();
    },

    render: function() {
        $(this.el).html(this.template());

        return this;
    },

    call: function(event) {
        // Determine callback
        var callback = event.target.hash.replace('#', '');

        // Attempt to call callback
        try {
            ! $(event.target).hasClass('disabled_toolbar') && this[callback](event);
        } catch (e) {
            console &&
                console.log("Could not fire " + callback + ": " + e.message);
        }

        return false;
    },

    save_query: function(event) {
        // TODO - save query
    },

    automatic_execution: function(event) {
        // Change property
        var new_value = ! this.workspace.query.properties
            .get('saiku.olap.query.automatic_execution');
        this.workspace.query.properties.set({
            'saiku.olap.query.automatic_execution': new_value
        });
        console.log(this.workspace.query.properties);

        // Toggle state of button
        $(event.target).toggleClass('on');
    }
});<|endoftext|>


<commit_before>'use strict'

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

const log       = require ('ololog')
    , ansi      = require ('ansicolor').nice
    , chai      = require ('chai')
    , expect    = chai.expect
    , assert    = chai.assert

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

const printOrderBookOneLiner = (orderbook, method, symbol) => {

    const bids = orderbook.bids
    const asks = orderbook.asks

    log (symbol.toString ().green,
        method,
        orderbook['nonce'] || orderbook['datetime'],
        bids.length, 'bids:', bids[0],
        asks.length, 'asks:', asks[0])
}

/*  ------------------------------------------------------------------------ */

module.exports = (exchange, orderbook, method, symbol) => {

    const format = {
        // 'symbol': 'ETH/BTC', // reserved
        'bids': [],
        'asks': [],
        'timestamp': 1234567890,
        'datetime': '2017-09-01T00:00:00',
        'nonce': 134234234,
        // 'info': {},
    }

    expect (orderbook).to.have.all.keys (format)

    const bids = orderbook.bids
    const asks = orderbook.asks

    for (let i = 0; i < bids.length; i++) {
        if (bids.length > (i + 1)) {
            assert (bids[i][0] >= bids[i + 1][0])
        }
        assert (typeof bids[i][0] === 'number')
        assert (typeof bids[i][1] === 'number')
    }

    for (let i = 0; i < asks.length; i++) {
        if (asks.length > (i + 1)) {
            assert (asks[i][0] <= asks[i + 1][0])
        }
        assert (typeof asks[i][0] === 'number')
        assert (typeof asks[i][1] === 'number')
    }

    if (![

        'coinmarketcap',
        'xbtce',
        'upbit', // an orderbook might have a 0-price ask occasionally

    ].includes (exchange.id)) {

        if (bids.length && asks.length)
            assert (bids[0][0] <= asks[0][0],
                `bids[0][0]: ${bids[0][0]} (of ${bids.length}); asks[0][0]:${asks[0][0]} (of ${asks.length})`)

    }

    printOrderBookOneLiner (orderbook, method, symbol)
}<commit_msg>test.orderbook.js chai assertion on keys<commit_after>'use strict'

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

const log       = require ('ololog')
    , ansi      = require ('ansicolor').nice
    , chai      = require ('chai')
    , expect    = chai.expect
    , assert    = chai.assert

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

const printOrderBookOneLiner = (orderbook, method, symbol) => {

    const bids = orderbook.bids
    const asks = orderbook.asks

    log (symbol.toString ().green,
        method,
        orderbook['nonce'] || orderbook['datetime'],
        bids.length, 'bids:', bids[0],
        asks.length, 'asks:', asks[0])
}

/*  ------------------------------------------------------------------------ */

module.exports = (exchange, orderbook, method, symbol) => {

    const format = {
        // 'symbol': 'ETH/BTC', // reserved
        'bids': [],
        'asks': [],
        'timestamp': 1234567890,
        'datetime': '2017-09-01T00:00:00',
        'nonce': 134234234,
        // 'info': {},
    }

    expect (orderbook).to.include.all.keys (format)

    const bids = orderbook.bids
    const asks = orderbook.asks

    for (let i = 0; i < bids.length; i++) {
        if (bids.length > (i + 1)) {
            assert (bids[i][0] >= bids[i + 1][0])
        }
        assert (typeof bids[i][0] === 'number')
        assert (typeof bids[i][1] === 'number')
    }

    for (let i = 0; i < asks.length; i++) {
        if (asks.length > (i + 1)) {
            assert (asks[i][0] <= asks[i + 1][0])
        }
        assert (typeof asks[i][0] === 'number')
        assert (typeof asks[i][1] === 'number')
    }

    if (![

        'coinmarketcap',
        'xbtce',
        'upbit', // an orderbook might have a 0-price ask occasionally

    ].includes (exchange.id)) {

        if (bids.length && asks.length)
            assert (bids[0][0] <= asks[0][0],
                `bids[0][0]: ${bids[0][0]} (of ${bids.length}); asks[0][0]:${asks[0][0]} (of ${asks.length})`)

    }

    printOrderBookOneLiner (orderbook, method, symbol)
}<|endoftext|>


<commit_before>var DbCommand = require('../commands/db_command').DbCommand
  , utils = require('../utils')
  , format = require('util').format
  , Kerberos = require('kerberos').Kerberos;

var authenticate = function(db, username, password, authdb, options, callback) {
  var numberOfConnections = 0;
  var errorObject = null;

  if(options['connection'] != null) {
    //if a connection was explicitly passed on options, then we have only one...
    numberOfConnections = 1;
  } else {
    // Get the amount of connections in the pool to ensure we have authenticated all comments
    numberOfConnections = db.serverConfig.allRawConnections().length;
    options['onAll'] = true;
  }

  // Checkout connection
  var connection = db.serverConfig.checkoutWriter();
  // Start Auth process for a connection
  GSSAPIInitialize(db, username, password, authdb, connection, callback);
}

//
// Initialize step
var GSSAPIInitialize = function(db, username, password, authdb, connection, callback) {
  // Create Kerberos instance
  var kerberos = new Kerberos();
  // Right let's get sasl going
  var connection = db.serverConfig.checkoutWriter();
  // Create connection string
  var kerberos_connection_string = format("mongodb@%s", db.serverConfig.host);
  // Start the kerberos process
  kerberos.authGSSClientInit(kerberos_connection_string, Kerberos.GSS_C_MUTUAL_FLAG, function(err, context) {
    if(err) return callback(err, false);

    // Let's perform the first step
    kerberos.authGSSClientStep(context, '', function(err, result) {
      if(err) return callback(err, false);
      // Call next step
      MongoDBGSSAPIFirstStep(kerberos, context, db, username, password, authdb, connection, callback);
    });
  });
}

//
// Perform first step against mongodb
var MongoDBGSSAPIFirstStep = function(kerberos, context, db, username, password, authdb, connection, callback) {
  // Grab the payload
  var payload = context.response;
  // Build the sasl start command
  var command = {
      saslStart: 1
    , mechanism: 'GSSAPI'
    , payload: payload
    , autoAuthorize: 1
  };

  // Execute first sasl step
  db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) {
    if(err) return callback(err, false);
    // Get the payload
    doc = doc.documents[0];
    var db_payload = doc.payload;

    // Show payload
    kerberos.authGSSClientStep(context,  doc.payload, function(err, result) {
      if(err) return callback(err, false);
      // MongoDB API Second Step
      MongoDBGSSAPISecondStep(kerberos, context, doc, db, username, password, authdb, connection, callback);
    });
  });
}

//
// Perform first step against mongodb
var MongoDBGSSAPISecondStep = function(kerberos, context, doc, db, username, password, authdb, connection, callback) {
  // Get the payload
  var payload = context.response || '';

  // Build Authentication command to send to MongoDB
  var command = {
      saslContinue: 1
    , conversationId: doc.conversationId
    , payload: payload
  };

  // Execute the command
  db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) {
    if(err) return callback(err, false);

    // Get the result document
    doc = doc.documents[0];

    // GSS Client Unwrap
    kerberos.authGSSClientUnwrap(context, doc.payload, function(err, result) {
      if(err) return callback(err, false);

      var payload = context.response;
      // Wrap the response
      kerberos.authGSSClientWrap(context, payload, username, function(err, result) {
        if(err) return callback(err, false);

        // Call the last and third step
        MongoDBGSSAPIThirdStep(kerberos, context, doc, db, username, password, authdb, connection, callback);
      });
    });
  });
}

var MongoDBGSSAPIThirdStep = function(kerberos, context, doc, db, username, password, authdb, connection, callback) {
  var payload = context.response;

  // Build final command
  var command = {
      saslContinue: 1
    , conversationId: doc.conversationId
    , payload: payload
  };

  // Let's finish the auth process against mongodb
  db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) {
    if(err) return callback(err, false);

    // Clean up context
    kerberos.authGSSClientClean(context, function(err, result) {
      if(err) return callback(err, false);
      callback(null, true);
    });
  });
}

exports.authenticate = authenticate;<commit_msg>Added TODO's<commit_after>var DbCommand = require('../commands/db_command').DbCommand
  , utils = require('../utils')
  , format = require('util').format
  , Kerberos = require('kerberos').Kerberos;

var authenticate = function(db, username, password, authdb, options, callback) {
  var numberOfConnections = 0;
  var errorObject = null;

  if(options['connection'] != null) {
    //if a connection was explicitly passed on options, then we have only one...
    numberOfConnections = 1;
  } else {
    // Get the amount of connections in the pool to ensure we have authenticated all comments
    numberOfConnections = db.serverConfig.allRawConnections().length;
    options['onAll'] = true;
  }

  //
  // TODO: Authenticate all connections with the credentials
  // TODO: Ensure correct Re-Authentication of all connections on reconnects using GSSAPI
  //

  // Checkout connection
  var connection = db.serverConfig.checkoutWriter();
  // Start Auth process for a connection
  GSSAPIInitialize(db, username, password, authdb, connection, callback);
}

//
// Initialize step
var GSSAPIInitialize = function(db, username, password, authdb, connection, callback) {
  // Create Kerberos instance
  var kerberos = new Kerberos();
  // Right let's get sasl going
  var connection = db.serverConfig.checkoutWriter();
  // Create connection string
  var kerberos_connection_string = format("mongodb@%s", db.serverConfig.host);
  // Start the kerberos process
  kerberos.authGSSClientInit(kerberos_connection_string, Kerberos.GSS_C_MUTUAL_FLAG, function(err, context) {
    if(err) return callback(err, false);

    // Let's perform the first step
    kerberos.authGSSClientStep(context, '', function(err, result) {
      if(err) return callback(err, false);
      // Call next step
      MongoDBGSSAPIFirstStep(kerberos, context, db, username, password, authdb, connection, callback);
    });
  });
}

//
// Perform first step against mongodb
var MongoDBGSSAPIFirstStep = function(kerberos, context, db, username, password, authdb, connection, callback) {
  // Grab the payload
  var payload = context.response;
  // Build the sasl start command
  var command = {
      saslStart: 1
    , mechanism: 'GSSAPI'
    , payload: payload
    , autoAuthorize: 1
  };

  // Execute first sasl step
  db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) {
    if(err) return callback(err, false);
    // Get the payload
    doc = doc.documents[0];
    var db_payload = doc.payload;

    // Show payload
    kerberos.authGSSClientStep(context,  doc.payload, function(err, result) {
      if(err) return callback(err, false);
      // MongoDB API Second Step
      MongoDBGSSAPISecondStep(kerberos, context, doc, db, username, password, authdb, connection, callback);
    });
  });
}

//
// Perform first step against mongodb
var MongoDBGSSAPISecondStep = function(kerberos, context, doc, db, username, password, authdb, connection, callback) {
  // Get the payload
  var payload = context.response || '';

  // Build Authentication command to send to MongoDB
  var command = {
      saslContinue: 1
    , conversationId: doc.conversationId
    , payload: payload
  };

  // Execute the command
  db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) {
    if(err) return callback(err, false);

    // Get the result document
    doc = doc.documents[0];

    // GSS Client Unwrap
    kerberos.authGSSClientUnwrap(context, doc.payload, function(err, result) {
      if(err) return callback(err, false);

      var payload = context.response;
      // Wrap the response
      kerberos.authGSSClientWrap(context, payload, username, function(err, result) {
        if(err) return callback(err, false);

        // Call the last and third step
        MongoDBGSSAPIThirdStep(kerberos, context, doc, db, username, password, authdb, connection, callback);
      });
    });
  });
}

var MongoDBGSSAPIThirdStep = function(kerberos, context, doc, db, username, password, authdb, connection, callback) {
  var payload = context.response;

  // Build final command
  var command = {
      saslContinue: 1
    , conversationId: doc.conversationId
    , payload: payload
  };

  // Let's finish the auth process against mongodb
  db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) {
    if(err) return callback(err, false);

    // Clean up context
    kerberos.authGSSClientClean(context, function(err, result) {
      if(err) return callback(err, false);
      callback(null, true);
    });
  });
}

exports.authenticate = authenticate;<|endoftext|>