<commit_before>$(document).ready(function() {
	var apiEndpoint = "answers";
	var currentPage = 1;
	var pageSize = 100;
	var sort = ByCreationDate;
	$("#blaze-api-key-field").focus();

	InitSiteAPIKeyAutocomplete();

	$(".blaze-logo").click(function()
	{
		$("table tr").remove();
		$(".blaze-header").fadeIn();
		$(".site-api-key-form").fadeIn();
		$("nav").fadeOut();
	});
	$("#select-answers").click(function()
	{
		$(".blaze-fetch-items").html("Fetch Answers");
		apiEndpoint = 'answers';
	});
	$("#select-comments").click(function()
	{
		$(".blaze-fetch-items").html("Fetch Comments");
		apiEndpoint = 'comments';
	});
	$("#select-questions").click(function()
	{
		$(".blaze-fetch-items").html("Fetch Questions");
		apiEndpoint = 'questions';
	});
	$(".blaze-fetch-items").click(function() {
		RefreshData();
	});
	$(".refresh-current-data-button").click(function()
	{
		var oldHTML = $(this).html();
		$(this).html("working...");

		$("table tr").remove();

		RefreshData(function()
			{
				$(".refresh-current-data-button").html(oldHTML);
			});
	});
	$(document).keypress(function(e) {
		if(e.which == 13) {
			RefreshData();
		}
	});
	function RefreshData(f)
	{
		var site = $("#blaze-api-key-field").val();

		var oldButtonText = $(".blaze-fetch-items").html();
		$(".blaze-fetch-items").html("Loading...");

		console.log(site);

		var argString = "page=" + currentPage + "&pagesize=" + pageSize + "&key=" + "p3YZ1qDutpcBd7Bte2mcDw((" + "&site=" + site + "&order=" + "desc" + "&sort=" + "creation" + "&filter=" + "!LeJQlFEfIbsDDTG1lReSJX";
		if (apiEndpoint == "questions") argString = "page=" + currentPage + "&pagesize=" + pageSize + "&key=" + "p3YZ1qDutpcBd7Bte2mcDw((" + "&site=" + site + "&order=" + "desc" + "&sort=" + "creation" + "&filter=" + "!)Q7pHZaD2SW58N2KuVqkwvB5";
		if (apiEndpoint == "comments") argString = "page=" + currentPage + "&pagesize=" + pageSize + "&key=" + "p3YZ1qDutpcBd7Bte2mcDw((" + "&site=" + site + "&order=" + "desc" + "&sort=" + "creation" + "&filter=" + "!)Q3IqX*j)mxF9SKNRz3tb5yK";
		var url = "https://api.stackexchange.com/2.2/" + apiEndpoint;
		$.ajax({
			type: "GET",
			url: url,
			data: argString,
			success: function(data)
			{
				console.log(data["items"]);

				$(".blaze-header").fadeOut();
				$(".site-api-key-form").fadeOut();

				$("nav").fadeIn();

				var items = data["items"];

				items.sort(sort);

				jQuery.each(items, function(index, item) {
					if (apiEndpoint == 'questions')
					{
						$("table").append(RenderQuestion(item));
					}
					else if (apiEndpoint == 'answers')
					{
						$("table").append(RenderAnswer(item));
					}
					else if (apiEndpoint == 'comments')
					{
						$("table").append(RenderComment(item));
					}

				});

				$(".blaze-fetch-items").html(oldButtonText);

				$("div.alert.alert-danger").remove();

				if (typeof f == "function") f();
			},
			error: function(data)
			{
				string = '
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>';
				string = string + data.responseJSON["error_message"].charAt(0).toUpperCase() + data.responseJSON["error_message"].slice(1);
				string = string + '
';
				$("div.alert.alert-danger").remove();
				$(".site-api-key-form").prepend(string);
				$(".blaze-fetch-items").html(oldButtonText);
			}
		});
	}

	// Array sorting functions:

	function ByLength(a, b){
		var aLength = a["body"].length;
		var bLength = b["body"].length;
		return ((aLength < bLength) ? -1 : ((aLength > bLength) ? 1 : 0));
	}
	function ByCreationDate(a, b){
		var aDate = a["creation_date"];
		var bDate = b["creation_date"];
		return ((aDate > bDate) ? -1 : ((aDate < bDate) ? 1 : 0));
	}

	$("#sort-by-newest-creation").click(function() {
		sort = ByCreationDate;
		$("table tr").remove();
		$("#current-sort-indicator").html("Working...");
		RefreshData(function()
			{
				$("#current-sort-indicator").html("Newest");
			});
	});
	$("#sort-by-shortest-length").click(function() {
		sort = ByLength;
		console.log($("#current-sort-indicator"));
		$("table tr").remove();
		RefreshData(function()
			{
				$("#current-sort-indicator").html("Shortest");
			});
	});
	$(document).on('click', 'btn.flag', function(event) {
		console.log("flag button pressed");
		var postLink = $(this).attr("postLink");
		console.log(postLink);
		var argString = "url=" + postLink;
		$.ajax({
		    type: "POST",
		 	url: "http://erwaysoftware.com/blaze/posttochat.php",
		 	data: argString,
		 	success: function(data) {
		 		console.log("success")
			},
			error: function(data) {
				console.log("error")
			}
		});
	});

	//Rendering things

	function RenderAnswer(item)
	{
		var string = '

';
		string = string + item["score"];
		string = string + '

';
		string = string + item["title"];
		string = string + '';
		string = string + '

';
		string = string + item["body"];
		string = string + '<btn class="btn btn-danger btn-xs flag" style="float:left" href="#" postLink="' + item["link"] + '">flag</btn>';
		string = string + '
posted by ';
		var owner = item["owner"];
		string = string + '';
		string = string + owner["display_name"];
		if (owner['user_type'] == 'moderator') string = string + ' ♦';
		string = string + ' '
		string = string + '';
		string = string + '

';
		string = string + '

'; //flag
		return string;
	}
	function RenderQuestion(item)
	{
		var string = '

';
		string = string + item["score"];
		string = string + '

';
		string = string + item["title"];
		string = string + '';
		string = string + "
";
		for (var i = 0; i < item["tags"].length; i++) {
			string = string + '' + item["tags"][i] + ' ';
		};
		string = string + "";
		string = string + '

';
		string = string + item["body"];
		string = string + '
posted by ';
		var owner = item["owner"];
		string = string + '';
		string = string + owner["display_name"];
		if (owner['user_type'] == 'moderator') string = string + ' ♦';
		string = string + ' '
		string = string + '';
		string = string + '

';
		return string;
	}
	function RenderComment(item)
	{
		var string = '

';
		if (item["score"] != "0") string = string + item["score"];
		string = string + '

';
		string = string + '';
		string = string + item["body"];
		string = string + ' - ';
		string = string + item["owner"]["display_name"];
		if (item["owner"]["user_type"] == 'moderator') string = string + " ♦";
		string = string + ' ';
		string = string + '

';
		return string;
	}

	//Autocomplete things

	function InitSiteAPIKeyAutocomplete()
	{
		$.ajax({
			type: "GET",
			url: "https://api.stackexchange.com/2.2/sites",
			data: "pagesize=1000&filter=!mszzl.y_MC",
			success: function(data)
			{
				var items = data["items"];

				var siteApiKeys = [];

				jQuery.each(items, function(index, item) {
					siteApiKeys.push(item["api_site_parameter"]);
				});

				$("#blaze-api-key-field").autocomplete({
					source: siteApiKeys
				});
			},
			error: function(data) {}
		});
	}
});
<commit_msg>feedback! Yay!<commit_after>$(document).ready(function() {
	var apiEndpoint = "answers";
	var currentPage = 1;
	var pageSize = 100;
	var sort = ByCreationDate;
	$("#blaze-api-key-field").focus();

	InitSiteAPIKeyAutocomplete();

	$(".blaze-logo").click(function()
	{
		$("table tr").remove();
		$(".blaze-header").fadeIn();
		$(".site-api-key-form").fadeIn();
		$("nav").fadeOut();
	});
	$("#select-answers").click(function()
	{
		$(".blaze-fetch-items").html("Fetch Answers");
		apiEndpoint = 'answers';
	});
	$("#select-comments").click(function()
	{
		$(".blaze-fetch-items").html("Fetch Comments");
		apiEndpoint = 'comments';
	});
	$("#select-questions").click(function()
	{
		$(".blaze-fetch-items").html("Fetch Questions");
		apiEndpoint = 'questions';
	});
	$(".blaze-fetch-items").click(function() {
		RefreshData();
	});
	$(".refresh-current-data-button").click(function()
	{
		var oldHTML = $(this).html();
		$(this).html("working...");

		$("table tr").remove();

		RefreshData(function()
			{
				$(".refresh-current-data-button").html(oldHTML);
			});
	});
	$(document).keypress(function(e) {
		if(e.which == 13) {
			RefreshData();
		}
	});
	function RefreshData(f)
	{
		var site = $("#blaze-api-key-field").val();

		var oldButtonText = $(".blaze-fetch-items").html();
		$(".blaze-fetch-items").html("Loading...");

		console.log(site);

		var argString = "page=" + currentPage + "&pagesize=" + pageSize + "&key=" + "p3YZ1qDutpcBd7Bte2mcDw((" + "&site=" + site + "&order=" + "desc" + "&sort=" + "creation" + "&filter=" + "!LeJQlFEfIbsDDTG1lReSJX";
		if (apiEndpoint == "questions") argString = "page=" + currentPage + "&pagesize=" + pageSize + "&key=" + "p3YZ1qDutpcBd7Bte2mcDw((" + "&site=" + site + "&order=" + "desc" + "&sort=" + "creation" + "&filter=" + "!)Q7pHZaD2SW58N2KuVqkwvB5";
		if (apiEndpoint == "comments") argString = "page=" + currentPage + "&pagesize=" + pageSize + "&key=" + "p3YZ1qDutpcBd7Bte2mcDw((" + "&site=" + site + "&order=" + "desc" + "&sort=" + "creation" + "&filter=" + "!)Q3IqX*j)mxF9SKNRz3tb5yK";
		var url = "https://api.stackexchange.com/2.2/" + apiEndpoint;
		$.ajax({
			type: "GET",
			url: url,
			data: argString,
			success: function(data)
			{
				console.log(data["items"]);

				$(".blaze-header").fadeOut();
				$(".site-api-key-form").fadeOut();

				$("nav").fadeIn();

				var items = data["items"];

				items.sort(sort);

				jQuery.each(items, function(index, item) {
					if (apiEndpoint == 'questions')
					{
						$("table").append(RenderQuestion(item));
					}
					else if (apiEndpoint == 'answers')
					{
						$("table").append(RenderAnswer(item));
					}
					else if (apiEndpoint == 'comments')
					{
						$("table").append(RenderComment(item));
					}

				});

				$(".blaze-fetch-items").html(oldButtonText);

				$("div.alert.alert-danger").remove();

				if (typeof f == "function") f();
			},
			error: function(data)
			{
				string = '
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>';
				string = string + data.responseJSON["error_message"].charAt(0).toUpperCase() + data.responseJSON["error_message"].slice(1);
				string = string + '
';
				$("div.alert.alert-danger").remove();
				$(".site-api-key-form").prepend(string);
				$(".blaze-fetch-items").html(oldButtonText);
			}
		});
	}

	// Array sorting functions:

	function ByLength(a, b){
		var aLength = a["body"].length;
		var bLength = b["body"].length;
		return ((aLength < bLength) ? -1 : ((aLength > bLength) ? 1 : 0));
	}
	function ByCreationDate(a, b){
		var aDate = a["creation_date"];
		var bDate = b["creation_date"];
		return ((aDate > bDate) ? -1 : ((aDate < bDate) ? 1 : 0));
	}

	$("#sort-by-newest-creation").click(function() {
		sort = ByCreationDate;
		$("table tr").remove();
		$("#current-sort-indicator").html("Working...");
		RefreshData(function()
			{
				$("#current-sort-indicator").html("Newest");
			});
	});
	$("#sort-by-shortest-length").click(function() {
		sort = ByLength;
		console.log($("#current-sort-indicator"));
		$("table tr").remove();
		RefreshData(function()
			{
				$("#current-sort-indicator").html("Shortest");
			});
	});
	$(document).on('click', 'btn.flag', function(event) {
		console.log("flag button pressed");
		var flagButton = $(this);
		flagButton.html("working...");
		var postLink = $(this).attr("postLink");
		console.log(postLink);
		var argString = "url=" + postLink;
		$.ajax({
		    type: "POST",
		 	url: "http://erwaysoftware.com/blaze/posttochat.php",
		 	data: argString,
		 	success: function(data) {
		 		console.log("success");
		 		flagButton.html("flagged");
			},
			error: function(data) {
				console.log("error")
			}
		});
	});

	//Rendering things

	function RenderAnswer(item)
	{
		var string = '

';
		string = string + item["score"];
		string = string + '

';
		string = string + item["title"];
		string = string + '';
		string = string + '

';
		string = string + item["body"];
		string = string + '<btn class="btn btn-danger btn-xs flag" style="float:left" href="#" postLink="' + item["link"] + '">flag</btn>';
		string = string + '
posted by ';
		var owner = item["owner"];
		string = string + '';
		string = string + owner["display_name"];
		if (owner['user_type'] == 'moderator') string = string + ' ♦';
		string = string + ' '
		string = string + '';
		string = string + '

';
		string = string + '

'; //flag
		return string;
	}
	function RenderQuestion(item)
	{
		var string = '

';
		string = string + item["score"];
		string = string + '

';
		string = string + item["title"];
		string = string + '';
		string = string + "
";
		for (var i = 0; i < item["tags"].length; i++) {
			string = string + '' + item["tags"][i] + ' ';
		};
		string = string + "";
		string = string + '

';
		string = string + item["body"];
		string = string + '
posted by ';
		var owner = item["owner"];
		string = string + '';
		string = string + owner["display_name"];
		if (owner['user_type'] == 'moderator') string = string + ' ♦';
		string = string + ' '
		string = string + '';
		string = string + '

';
		return string;
	}
	function RenderComment(item)
	{
		var string = '

';
		if (item["score"] != "0") string = string + item["score"];
		string = string + '

';
		string = string + '';
		string = string + item["body"];
		string = string + ' - ';
		string = string + item["owner"]["display_name"];
		if (item["owner"]["user_type"] == 'moderator') string = string + " ♦";
		string = string + ' ';
		string = string + '

';
		return string;
	}

	//Autocomplete things

	function InitSiteAPIKeyAutocomplete()
	{
		$.ajax({
			type: "GET",
			url: "https://api.stackexchange.com/2.2/sites",
			data: "pagesize=1000&filter=!mszzl.y_MC",
			success: function(data)
			{
				var items = data["items"];

				var siteApiKeys = [];

				jQuery.each(items, function(index, item) {
					siteApiKeys.push(item["api_site_parameter"]);
				});

				$("#blaze-api-key-field").autocomplete({
					source: siteApiKeys
				});
			},
			error: function(data) {}
		});
	}
});
<|endoftext|>


<commit_before>exports.locate = function(load) {
  console.log();
  return window.location.protocol + '//' + load.name;
};

exports.fetch = function(load) {
  return new Promise(function(resolve, reject) {
    var head = document.getElementsByTagName('head')[0];
    var s = document.createElement('script');
    s.async = true;

    function complete(evt) {
      if (s.readyState && s.readyState !== 'loaded' && s.readyState != 'complete'){
        return;
      }
      cleanup();
    }

    function error(evt) {
      cleanup();
      reject(evt);
    }

    if (s.attachEvent) {
      s.attachEvent('onreadystatechange', complete);
    }
    else {
      s.addEventListener('load', complete, false);
      s.addEventListener('error', error, false);
    }

    s.src = load.address;
    head.appendChild(s);

    function cleanup() {
      if (s.detachEvent){
        s.detachEvent('onreadystatechange', complete);
      }
      else {
        s.removeEventListener('load', complete, false);
        s.removeEventListener('error', error, false);
      }
      head.removeChild(s);
    }
  });
};<commit_msg>Resolve promise<commit_after>exports.locate = function(load) {
  console.log();
  return window.location.protocol + '//' + load.name;
};

exports.fetch = function(load) {
  return new Promise(function(resolve, reject) {
    var head = document.getElementsByTagName('head')[0];
    var s = document.createElement('script');
    s.async = true;

    function complete(evt) {
      if (s.readyState && s.readyState !== 'loaded' && s.readyState != 'complete'){
        return;
      }
      cleanup();
      resolve('');
    }

    function error(evt) {
      cleanup();
      reject(evt);
    }

    if (s.attachEvent) {
      s.attachEvent('onreadystatechange', complete);
    }
    else {
      s.addEventListener('load', complete, false);
      s.addEventListener('error', error, false);
    }

    s.src = load.address;
    head.appendChild(s);

    function cleanup() {
      if (s.detachEvent){
        s.detachEvent('onreadystatechange', complete);
      }
      else {
        s.removeEventListener('load', complete, false);
        s.removeEventListener('error', error, false);
      }
      head.removeChild(s);
    }
  });
};<|endoftext|>


<commit_before>// Copyright 2014-2015, University of Colorado Boulder

/**
 * View for the 'Energy Systems' screen of the Energy Forms And Changes simulation.
 *
 * @author  John Blanco
 * @author  Martin Veillette (Berea College)
 * @author  Jesse Greenberg
 * @author  Andrew Adare
 */
define( function( require ) {
  'use strict';

  // Modules
  var BeakerHeaterNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/BeakerHeaterNode' );
  var BeltNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/BeltNode' );
  var BikerNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/BikerNode' );
  var Bounds2 = require( 'DOT/Bounds2' );
  var CheckBox = require( 'SUN/CheckBox' );
  var EFACConstants = require( 'ENERGY_FORMS_AND_CHANGES/common/EFACConstants' );
  var EnergyChunkLegend = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/EnergyChunkLegend' );
  var energyFormsAndChanges = require( 'ENERGY_FORMS_AND_CHANGES/energyFormsAndChanges' );
  var EnergySystemElementSelector = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/EnergySystemElementSelector' );
  var EnergyChunkNode = require( 'ENERGY_FORMS_AND_CHANGES/common/view/EnergyChunkNode' );
  var EnergyType = require( 'ENERGY_FORMS_AND_CHANGES/common/model/EnergyType' );
  var FaucetAndWaterNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/FaucetAndWaterNode' );
  var FluorescentBulbNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/FluorescentBulbNode' );
  var GeneratorNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/GeneratorNode' );
  // var HSlider = require( 'SUN/HSlider' );
  // var Image = require( 'SCENERY/nodes/Image' );
  var IncandescentBulbNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/IncandescentBulbNode' );
  var inherit = require( 'PHET_CORE/inherit' );
  var LayoutBox = require( 'SCENERY/nodes/LayoutBox' );
  var ModelViewTransform2 = require( 'PHETCOMMON/view/ModelViewTransform2' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Panel = require( 'SUN/Panel' );
  var PhetFont = require( 'SCENERY_PHET/PhetFont' );
  // var Property = require( 'AXON/Property' );
  var Rectangle = require( 'SCENERY/nodes/Rectangle' );
  var ResetAllButton = require( 'SCENERY_PHET/buttons/ResetAllButton' );
  var ScreenView = require( 'JOIST/ScreenView' );
  var SunNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/SunNode' );
  var SolarPanelNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/SolarPanelNode' );
  var TeaPotNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/TeaPotNode' );
  var Text = require( 'SCENERY/nodes/Text' );
  var Vector2 = require( 'DOT/Vector2' );

  // Images
  // var mockupImage = require( 'image!ENERGY_FORMS_AND_CHANGES/mockup_energy_systems.png' );

  // Strings
  var energySymbolsString = require( 'string!ENERGY_FORMS_AND_CHANGES/energySymbols' );

  // Constants
  var EDGE_INSET = 10;

  /**
   * @param {EnergySystemsModel} model
   * @constructor
   */
  function EnergySystemsScreenView( model ) {

    ScreenView.call( this, {
      // Boundaries taken from original Java sim
      layoutBounds: new Bounds2( 0, 0, 1008, 679 )
    } );

    // Bounds2 object for use as primary geometric reference
    var stage = this.layoutBounds;

    // Upper y-border of play/pause control panel.
    // The subtracted offset is from eyeballing a match to the mockup image.
    // var playControlYborder = stage.maxY - 75;
    var playControlYborder = stage.maxY;

    // Node for back-most layer
    var backLayer = new Node();
    this.addChild( backLayer );

    // ScreenView handle for use inside functions
    var thisScreenView = this;

    // Create the model-view transform.  The primary units used in the model are
    // meters, so significant zoom is used. The multipliers for the 2nd parameter
    // can be used to adjust where the point (0, 0) in the model, which is on the
    // middle of the screen above the counter as located in the view. Final arg
    // is zoom factor from original Java sim - smaller zooms out, larger zooms in.
    var mvtOriginX = Math.round( stage.width * 0.5 );
    var mvtOriginY = Math.round( stage.height * 0.475 );
    var modelViewTransform = ModelViewTransform2.createSinglePointScaleInvertedYMapping(
      Vector2.ZERO, new Vector2( mvtOriginX, mvtOriginY ), 2200 );

    // Add beige background rectangle
    function addBackground() {
      backLayer.addChild( new Rectangle( stage, {
        fill: EFACConstants.SECOND_TAB_BACKGROUND_COLOR
      } ) );
    }

    // Create a background rectangle for the play/pause controls.
    function addPlayControls() {
      var bottomPanel = new Rectangle( 0, playControlYborder, stage.width, stage.height, 0, 0, {
        fill: EFACConstants.CLOCK_CONTROL_BACKGROUND_COLOR,
        stroke: 'black'
      } );
      backLayer.addChild( bottomPanel );
    }

    // //Show the mock-up and a slider to change its transparency
    // function addMockupImage() {
    //   var opacity = new Property( 0.0 );
    //   var image = new Image( mockupImage, {
    //     pickable: false
    //   } );
    //   image.scale( stage.width / image.width );
    //   opacity.linkAttribute( image, 'opacity' );
    //   thisScreenView.addChild( image );
    //   thisScreenView.addChild( new HSlider( opacity, {
    //     min: 0,
    //     max: 1
    //   }, {
    //     top: 100,
    //     left: stage.width - 150
    //   } ) );
    // }

    // Create the legend for energy chunk types
    function addEnergyChunkLegend() {
      var legend = new EnergyChunkLegend();
      legend.center = new Vector2( 0.9 * stage.width, 0.5 * stage.height );
      thisScreenView.addChild( legend );
    }

    // Check box panel to display energy chunks
    function addCheckBoxPanel() {
      var label = new Text( energySymbolsString, {
        font: new PhetFont( 20 )
      } );

      var energyChunkNode = EnergyChunkNode.createEnergyChunkNode( EnergyType.THERMAL );
      energyChunkNode.scale( 1.0 );
      energyChunkNode.pickable = false;

      var checkBox = new CheckBox( new LayoutBox( {
        children: [ label, energyChunkNode ],
        orientation: 'horizontal',
        spacing: 5
      } ), model.energyChunksVisibleProperty );

      var panel = new Panel( checkBox, {
        fill: EFACConstants.CONTROL_PANEL_BACKGROUND_COLOR,
        stroke: EFACConstants.CONTROL_PANEL_OUTLINE_STROKE,
        lineWidth: EFACConstants.CONTROL_PANEL_OUTLINE_LINE_WIDTH
      } );
      panel.rightTop = new Vector2( stage.width - EDGE_INSET, EDGE_INSET );
      thisScreenView.addChild( panel );
    }

    // Create and add the Reset All Button in the bottom right, which resets the model
    function addResetButton() {
      var resetAllButton = new ResetAllButton( {
        listener: function() {
          model.reset();
        },
        right: stage.maxX - 10,
        bottom: stage.maxY - 10
      } );
      thisScreenView.addChild( resetAllButton );
    }

    // Create the carousel control nodes.
    function createCarousels() {

      // Instantiate nodes for the three carousels
      var sourcesCarousel = new EnergySystemElementSelector( model.energySourcesCarousel );
      var convertersCarousel = new EnergySystemElementSelector( model.energyConvertersCarousel );
      var usersCarousel = new EnergySystemElementSelector( model.energyUsersCarousel );

      // Position carousels
      // Assume all carousels have the height of the sources Carousel
      var centerY = playControlYborder - sourcesCarousel.height / 2 - 5;
      var spacing = 50;
      sourcesCarousel.leftCenter = new Vector2( EDGE_INSET, centerY );
      convertersCarousel.leftCenter = new Vector2( sourcesCarousel.rightCenter.x + spacing, centerY );
      usersCarousel.leftCenter = new Vector2( convertersCarousel.rightCenter.x + spacing, centerY );

      return [ sourcesCarousel, convertersCarousel, usersCarousel ];
    }

    addBackground();
    addPlayControls();
    addEnergyChunkLegend();
    addCheckBoxPanel();
    addResetButton();

    // Energy sources
    var faucetNode = new FaucetAndWaterNode( model.faucet, model.energyChunksVisibleProperty, modelViewTransform );
    var sunNode = new SunNode( model.sun, model.energyChunksVisibleProperty, modelViewTransform );
    this.teaPotNode = new TeaPotNode( model.teaPot, model.energyChunksVisibleProperty, modelViewTransform );
    var bikerNode = new BikerNode( model.biker, model.energyChunksVisibleProperty, modelViewTransform );

    this.addChild( sunNode );
    this.addChild( faucetNode );
    this.addChild( bikerNode );
    this.addChild( this.teaPotNode );

    // Energy users
    this.beakerHeaterNode = new BeakerHeaterNode( model.beakerHeater, model.energyChunksVisibleProperty, modelViewTransform );
    var incandescentBulbNode = new IncandescentBulbNode( model.incandescentBulb, model.energyChunksVisibleProperty, modelViewTransform );
    var fluorescentBulbNode = new FluorescentBulbNode( model.fluorescentBulb, model.energyChunksVisibleProperty, modelViewTransform );

    this.addChild( this.beakerHeaterNode );
    this.addChild( incandescentBulbNode );
    this.addChild( fluorescentBulbNode );

    // Energy converters
    var generatorNode = new GeneratorNode( model.generator, modelViewTransform );
    var beltNode = new BeltNode( model.belt, modelViewTransform );
    var solarPanelNode = new SolarPanelNode( model.solarPanel, modelViewTransform );

    this.addChild( generatorNode );
    this.addChild( beltNode );
    this.addChild( solarPanelNode );

    var carousels = createCarousels();
    carousels.forEach( function( carousel ) {
      thisScreenView.addChild( carousel );
    } );
  }

  energyFormsAndChanges.register( 'EnergySystemsScreenView', EnergySystemsScreenView );

  return inherit( ScreenView, EnergySystemsScreenView, {
    step: function( dt ) {
      this.teaPotNode.steamNode.step( dt );
      this.beakerHeaterNode.beakerView.water.step( dt );
    }
  } );
} );

<commit_msg>Add energy sources last so energy chunks are not hidden<commit_after>// Copyright 2014-2015, University of Colorado Boulder

/**
 * View for the 'Energy Systems' screen of the Energy Forms And Changes simulation.
 *
 * @author  John Blanco
 * @author  Martin Veillette (Berea College)
 * @author  Jesse Greenberg
 * @author  Andrew Adare
 */
define( function( require ) {
  'use strict';

  // Modules
  var BeakerHeaterNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/BeakerHeaterNode' );
  var BeltNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/BeltNode' );
  var BikerNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/BikerNode' );
  var Bounds2 = require( 'DOT/Bounds2' );
  var CheckBox = require( 'SUN/CheckBox' );
  var EFACConstants = require( 'ENERGY_FORMS_AND_CHANGES/common/EFACConstants' );
  var EnergyChunkLegend = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/EnergyChunkLegend' );
  var energyFormsAndChanges = require( 'ENERGY_FORMS_AND_CHANGES/energyFormsAndChanges' );
  var EnergySystemElementSelector = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/EnergySystemElementSelector' );
  var EnergyChunkNode = require( 'ENERGY_FORMS_AND_CHANGES/common/view/EnergyChunkNode' );
  var EnergyType = require( 'ENERGY_FORMS_AND_CHANGES/common/model/EnergyType' );
  var FaucetAndWaterNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/FaucetAndWaterNode' );
  var FluorescentBulbNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/FluorescentBulbNode' );
  var GeneratorNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/GeneratorNode' );
  // var HSlider = require( 'SUN/HSlider' );
  // var Image = require( 'SCENERY/nodes/Image' );
  var IncandescentBulbNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/IncandescentBulbNode' );
  var inherit = require( 'PHET_CORE/inherit' );
  var LayoutBox = require( 'SCENERY/nodes/LayoutBox' );
  var ModelViewTransform2 = require( 'PHETCOMMON/view/ModelViewTransform2' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Panel = require( 'SUN/Panel' );
  var PhetFont = require( 'SCENERY_PHET/PhetFont' );
  // var Property = require( 'AXON/Property' );
  var Rectangle = require( 'SCENERY/nodes/Rectangle' );
  var ResetAllButton = require( 'SCENERY_PHET/buttons/ResetAllButton' );
  var ScreenView = require( 'JOIST/ScreenView' );
  var SunNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/SunNode' );
  var SolarPanelNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/SolarPanelNode' );
  var TeaPotNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/TeaPotNode' );
  var Text = require( 'SCENERY/nodes/Text' );
  var Vector2 = require( 'DOT/Vector2' );

  // Images
  // var mockupImage = require( 'image!ENERGY_FORMS_AND_CHANGES/mockup_energy_systems.png' );

  // Strings
  var energySymbolsString = require( 'string!ENERGY_FORMS_AND_CHANGES/energySymbols' );

  // Constants
  var EDGE_INSET = 10;

  /**
   * @param {EnergySystemsModel} model
   * @constructor
   */
  function EnergySystemsScreenView( model ) {

    ScreenView.call( this, {
      // Boundaries taken from original Java sim
      layoutBounds: new Bounds2( 0, 0, 1008, 679 )
    } );

    // Bounds2 object for use as primary geometric reference
    var stage = this.layoutBounds;

    // Upper y-border of play/pause control panel.
    // The subtracted offset is from eyeballing a match to the mockup image.
    // var playControlYborder = stage.maxY - 75;
    var playControlYborder = stage.maxY;

    // Node for back-most layer
    var backLayer = new Node();
    this.addChild( backLayer );

    // ScreenView handle for use inside functions
    var thisScreenView = this;

    // Create the model-view transform.  The primary units used in the model are
    // meters, so significant zoom is used. The multipliers for the 2nd parameter
    // can be used to adjust where the point (0, 0) in the model, which is on the
    // middle of the screen above the counter as located in the view. Final arg
    // is zoom factor from original Java sim - smaller zooms out, larger zooms in.
    var mvtOriginX = Math.round( stage.width * 0.5 );
    var mvtOriginY = Math.round( stage.height * 0.475 );
    var modelViewTransform = ModelViewTransform2.createSinglePointScaleInvertedYMapping(
      Vector2.ZERO, new Vector2( mvtOriginX, mvtOriginY ), 2200 );

    // Add beige background rectangle
    function addBackground() {
      backLayer.addChild( new Rectangle( stage, {
        fill: EFACConstants.SECOND_TAB_BACKGROUND_COLOR
      } ) );
    }

    // Create a background rectangle for the play/pause controls.
    function addPlayControls() {
      var bottomPanel = new Rectangle( 0, playControlYborder, stage.width, stage.height, 0, 0, {
        fill: EFACConstants.CLOCK_CONTROL_BACKGROUND_COLOR,
        stroke: 'black'
      } );
      backLayer.addChild( bottomPanel );
    }

    // //Show the mock-up and a slider to change its transparency
    // function addMockupImage() {
    //   var opacity = new Property( 0.0 );
    //   var image = new Image( mockupImage, {
    //     pickable: false
    //   } );
    //   image.scale( stage.width / image.width );
    //   opacity.linkAttribute( image, 'opacity' );
    //   thisScreenView.addChild( image );
    //   thisScreenView.addChild( new HSlider( opacity, {
    //     min: 0,
    //     max: 1
    //   }, {
    //     top: 100,
    //     left: stage.width - 150
    //   } ) );
    // }

    // Create the legend for energy chunk types
    function addEnergyChunkLegend() {
      var legend = new EnergyChunkLegend();
      legend.center = new Vector2( 0.9 * stage.width, 0.5 * stage.height );
      thisScreenView.addChild( legend );
    }

    // Check box panel to display energy chunks
    function addCheckBoxPanel() {
      var label = new Text( energySymbolsString, {
        font: new PhetFont( 20 )
      } );

      var energyChunkNode = EnergyChunkNode.createEnergyChunkNode( EnergyType.THERMAL );
      energyChunkNode.scale( 1.0 );
      energyChunkNode.pickable = false;

      var checkBox = new CheckBox( new LayoutBox( {
        children: [ label, energyChunkNode ],
        orientation: 'horizontal',
        spacing: 5
      } ), model.energyChunksVisibleProperty );

      var panel = new Panel( checkBox, {
        fill: EFACConstants.CONTROL_PANEL_BACKGROUND_COLOR,
        stroke: EFACConstants.CONTROL_PANEL_OUTLINE_STROKE,
        lineWidth: EFACConstants.CONTROL_PANEL_OUTLINE_LINE_WIDTH
      } );
      panel.rightTop = new Vector2( stage.width - EDGE_INSET, EDGE_INSET );
      thisScreenView.addChild( panel );
    }

    // Create and add the Reset All Button in the bottom right, which resets the model
    function addResetButton() {
      var resetAllButton = new ResetAllButton( {
        listener: function() {
          model.reset();
        },
        right: stage.maxX - 10,
        bottom: stage.maxY - 10
      } );
      thisScreenView.addChild( resetAllButton );
    }

    // Create the carousel control nodes.
    function createCarousels() {

      // Instantiate nodes for the three carousels
      var sourcesCarousel = new EnergySystemElementSelector( model.energySourcesCarousel );
      var convertersCarousel = new EnergySystemElementSelector( model.energyConvertersCarousel );
      var usersCarousel = new EnergySystemElementSelector( model.energyUsersCarousel );

      // Position carousels
      // Assume all carousels have the height of the sources Carousel
      var centerY = playControlYborder - sourcesCarousel.height / 2 - 5;
      var spacing = 50;
      sourcesCarousel.leftCenter = new Vector2( EDGE_INSET, centerY );
      convertersCarousel.leftCenter = new Vector2( sourcesCarousel.rightCenter.x + spacing, centerY );
      usersCarousel.leftCenter = new Vector2( convertersCarousel.rightCenter.x + spacing, centerY );

      return [ sourcesCarousel, convertersCarousel, usersCarousel ];
    }

    addBackground();
    addPlayControls();
    addEnergyChunkLegend();
    addCheckBoxPanel();
    addResetButton();

    // Energy users
    this.beakerHeaterNode = new BeakerHeaterNode( model.beakerHeater, model.energyChunksVisibleProperty, modelViewTransform );
    var incandescentBulbNode = new IncandescentBulbNode( model.incandescentBulb, model.energyChunksVisibleProperty, modelViewTransform );
    var fluorescentBulbNode = new FluorescentBulbNode( model.fluorescentBulb, model.energyChunksVisibleProperty, modelViewTransform );

    this.addChild( this.beakerHeaterNode );
    this.addChild( incandescentBulbNode );
    this.addChild( fluorescentBulbNode );

    // Energy converters
    var generatorNode = new GeneratorNode( model.generator, modelViewTransform );
    var beltNode = new BeltNode( model.belt, modelViewTransform );
    var solarPanelNode = new SolarPanelNode( model.solarPanel, modelViewTransform );

    this.addChild( generatorNode );
    this.addChild( beltNode );
    this.addChild( solarPanelNode );

    // Energy sources
    var faucetNode = new FaucetAndWaterNode( model.faucet, model.energyChunksVisibleProperty, modelViewTransform );
    var sunNode = new SunNode( model.sun, model.energyChunksVisibleProperty, modelViewTransform );
    this.teaPotNode = new TeaPotNode( model.teaPot, model.energyChunksVisibleProperty, modelViewTransform );
    var bikerNode = new BikerNode( model.biker, model.energyChunksVisibleProperty, modelViewTransform );

    this.addChild( sunNode );
    this.addChild( faucetNode );
    this.addChild( bikerNode );
    this.addChild( this.teaPotNode );

    var carousels = createCarousels();
    carousels.forEach( function( carousel ) {
      thisScreenView.addChild( carousel );
    } );
  }

  energyFormsAndChanges.register( 'EnergySystemsScreenView', EnergySystemsScreenView );

  return inherit( ScreenView, EnergySystemsScreenView, {
    step: function( dt ) {
      this.teaPotNode.steamNode.step( dt );
      this.beakerHeaterNode.beakerView.water.step( dt );
    }
  } );
} );

<|endoftext|>


<commit_before><commit_msg>Rename data in test<commit_after>if (!(typeof MochaWeb === 'undefined')){
  MochaWeb.testOnly(function(){
    describe("Giblet Methods", function(){
      before(function(done) {
        var gibletData = {
          taskname: 'Find tandem bike',
          url: 'https://sfbay.craigslist.org/search/bik',
          keywords: 'tandem'
        };
        done();
      });

      it("should add new Giblet when addGiblet is called", function(){
        chai.assert.equal(5,5);
      });

    });
  });
}

// if (!(typeof MochaWeb === 'undefined')){
//   MochaWeb.testOnly(function(){
//     var selectGraceHopper = function(){
//       Session.set("selected_player", Players.findOne({name: "Grace Hopper"})._id);
//     };

//     var unselectPlayer = function(){
//       Session.set("selected_player", null);
//       Meteor.flush();
//     }

//     describe("Select Grace Hopper", function(){
//       before(function(done){
//         Meteor.autorun(function(){
//           var grace = Players.findOne({name: "Grace Hopper"});
//           if (grace){
//             selectGraceHopper();
//             done();
//           }
//         })
//       });

//       it("should show Grace the inside div class='name' (above the give points button)", function(){
//         Meteor.flush();
//         chai.assert.equal($("div.details > div.name").html(), "Grace Hopper");
//       });
//     });

//     describe("Point Assignment", function(){
//       before(function(){
//         selectGraceHopper();
//       });

//       it("should give a player 5 points when they are selected and the button is pressed", function(){
//         var graceInitialPoints = Players.findOne({name: "Grace Hopper"}).score;
//         $("input:button").click();
//         chai.assert.equal(graceInitialPoints + 5, Players.findOne({name: "Grace Hopper"}).score);
//       });
//     });
//   });
// }
<|endoftext|>


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

import {CACHE_KEYS, MODES, cacheParam, getSwgMode} from './services';

describes.sandboxed('services', {}, () => {
  beforeEach(() => {
    self.location.hash = '';
  });

  describe('runtime mode', () => {
    it('should return default values', () => {
      expect(getSwgMode()).to.deep.equal(MODES.default);
    });

    it('should overide withe swg.mode=prod', () => {
      self.location.hash = 'swg.mode=prod';
      expect(getSwgMode()).to.deep.equal(MODES.prod);
    });

    it('should overide withe swg.mode=qual', () => {
      self.location.hash = 'swg.mode=qual';
      expect(getSwgMode()).to.deep.equal(MODES.qual);
    });

    it('should overide withe swg.mode=autopush', () => {
      self.location.hash = 'swg.mode=autopush';
      expect(getSwgMode()).to.deep.equal(MODES.autopush);
    });
  });

  describe('cache', () => {
    const now = 1520624744987;

    beforeEach(() => {
      sandbox.stub(Date, 'now').callsFake(() => now);
    });

    it('should only allow simple keys', () => {
      for (const k in CACHE_KEYS) {
        if (k == '$frontendCache$') {
          continue;
        }
        expect(k).to.match(/^[a-z]+[0-9]*$/);
      }
    });

    it('should resolve nocache', () => {
      expect(cacheParam('nocache')).to.equal('1520624744987');
    });

    it('should resolve hr1', () => {
      expect(cacheParam('hr1')).to.equal('422395');
    });

    it('should resolve hr12', () => {
      expect(cacheParam('hr12')).to.equal('35199');
    });

    it('should resolve zero', () => {
      expect(cacheParam('zero')).to.equal('_');
    });

    it('should resolve unknown value', () => {
      expect(cacheParam('unknown')).to.equal('1520624744987');
    });
  });
});
<commit_msg>typos<commit_after>/**
 * Copyright 2018 The Subscribe with Google Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {CACHE_KEYS, MODES, cacheParam, getSwgMode} from './services';

describes.sandboxed('services', {}, () => {
  beforeEach(() => {
    self.location.hash = '';
  });

  describe('runtime mode', () => {
    it('should return default values', () => {
      expect(getSwgMode()).to.deep.equal(MODES.default);
    });

    it('should overide with swg.mode=prod', () => {
      self.location.hash = 'swg.mode=prod';
      expect(getSwgMode()).to.deep.equal(MODES.prod);
    });

    it('should overide with swg.mode=qual', () => {
      self.location.hash = 'swg.mode=qual';
      expect(getSwgMode()).to.deep.equal(MODES.qual);
    });

    it('should overide with swg.mode=autopush', () => {
      self.location.hash = 'swg.mode=autopush';
      expect(getSwgMode()).to.deep.equal(MODES.autopush);
    });
  });

  describe('cache', () => {
    const now = 1520624744987;

    beforeEach(() => {
      sandbox.stub(Date, 'now').callsFake(() => now);
    });

    it('should only allow simple keys', () => {
      for (const k in CACHE_KEYS) {
        if (k == '$frontendCache$') {
          continue;
        }
        expect(k).to.match(/^[a-z]+[0-9]*$/);
      }
    });

    it('should resolve nocache', () => {
      expect(cacheParam('nocache')).to.equal('1520624744987');
    });

    it('should resolve hr1', () => {
      expect(cacheParam('hr1')).to.equal('422395');
    });

    it('should resolve hr12', () => {
      expect(cacheParam('hr12')).to.equal('35199');
    });

    it('should resolve zero', () => {
      expect(cacheParam('zero')).to.equal('_');
    });

    it('should resolve unknown value', () => {
      expect(cacheParam('unknown')).to.equal('1520624744987');
    });
  });
});
<|endoftext|>


<commit_before>angular.module('utils.fileUpload', ['utils.fileReader'])

.factory('fileUpload', ['fileReader', 'fileTransfer', 'webRTC', function(fileReader, fileTransfer, webRTC) {
  var fileUploadObj = {};

  fileUploadObj.getFiles = function() {
    return document.getElementById('filesId').files;
  };

  fileUploadObj.convertFromBinary = function(data) {
    var kit = {};
    kit.href = URL.createObjectURL(data.file);
    kit.name = data.name;
    kit.size = data.size;
    return kit;
  };

  fileUploadObj.convertFileSize = function(num) {
    if (num > 1000000000) {
      return (num / 1000000000).toFixed(2) + ' GB';
    } else if (num > 1000000) {
      return (num / 1000000).toFixed(2) + ' MB';
    } else {
      return (num / 1000).toFixed(2) + ' kB';
    }
  };

  fileUploadObj.acceptFileOffer = function(offer) {
    fileTransfer.downloadQueue.push(offer);
    var index = fileTransfer.offers.indexOf(offer);
    fileTransfer.offers.splice(index, 1);
    webRTC.checkDownloadQueue();
  };

  fileUploadObj.rejectFileOffer = function(offer) {
    var index = fileTransfer.offers.indexOf(offer);
    fileTransfer.offers.splice(index, 1);
  };

  var convertRate = function(rate) {
    // expects kB/s
    if (rate > 1000) {
      return (rate / 1000).toFixed(2).toString() + ' MB/s';
    } else {
      return rate.toFixed(2).toString() + ' kB/s';
    }
  };

  var convertTime = function(timeInSeconds) {
    // expects seconds
    var sec_num = parseInt(timeInSeconds, 10); // don't forget the second param
    var hours = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
    var seconds = sec_num - (hours * 3600) - (minutes * 60);
    if (hours < 10) {
      hours = "0" + hours;
    }
    if (minutes < 10) {
      minutes = "0" + minutes;
    }
    if (seconds < 10) {
      seconds = "0" + seconds;
    }
    var time = minutes + ':' + seconds;
    if (hours > 0) {
      time = hours + ':' + time;
    }
    return time;
  };

  fileUploadObj.getTransferRate = function(transferObj) {
    var currentTime = Date.now();
    var timeToWait = 1000; // ms
    if (currentTime >= transferObj.nextTime) {
      transferObj.nextTime = Date.now() + timeToWait;
      var pastBytes = transferObj.stored;
      transferObj.stored = transferObj.progress;
      var rate = ((transferObj.stored - pastBytes)) / (timeToWait); // B/ms (kB/s)
      var maxFileSize = transferObj.size;
      timeRemaining = (maxFileSize - transferObj.stored) / rate / 1000; // ms/1000 -> s
      // console.log('CURRENT BYTES', transferObj.stored);
      // console.log('PASTCOUNT', pastBytes);
      // console.log('DIFFERENCE', transferObj.stored - pastBytes);
      // console.log('maxFileSize', maxFileSize);
      // console.log('REMAINING BYTES', maxFileSize - transferObj.stored);
      console.log('RATE:', convertRate(rate));
      console.log('TIME REMAINING:', convertTime(timeRemaining));
    }
  };

  return fileUploadObj;

}]);
<commit_msg>[refactor] Add return values to getTransferRate in fileUploadFactory.js<commit_after>angular.module('utils.fileUpload', ['utils.fileReader'])

.factory('fileUpload', ['fileReader', 'fileTransfer', 'webRTC', function(fileReader, fileTransfer, webRTC) {
  var fileUploadObj = {};

  fileUploadObj.getFiles = function() {
    return document.getElementById('filesId').files;
  };

  fileUploadObj.convertFromBinary = function(data) {
    var kit = {};
    kit.href = URL.createObjectURL(data.file);
    kit.name = data.name;
    kit.size = data.size;
    return kit;
  };

  fileUploadObj.convertFileSize = function(num) {
    if (num > 1000000000) {
      return (num / 1000000000).toFixed(2) + ' GB';
    } else if (num > 1000000) {
      return (num / 1000000).toFixed(2) + ' MB';
    } else {
      return (num / 1000).toFixed(2) + ' kB';
    }
  };

  fileUploadObj.acceptFileOffer = function(offer) {
    fileTransfer.downloadQueue.push(offer);
    var index = fileTransfer.offers.indexOf(offer);
    fileTransfer.offers.splice(index, 1);
    webRTC.checkDownloadQueue();
  };

  fileUploadObj.rejectFileOffer = function(offer) {
    var index = fileTransfer.offers.indexOf(offer);
    fileTransfer.offers.splice(index, 1);
  };

  var convertRate = function(rate) {
    // expects kB/s
    if (rate > 1000) {
      return (rate / 1000).toFixed(2).toString() + ' MB/s';
    } else {
      return rate.toFixed(2).toString() + ' kB/s';
    }
  };

  var convertTime = function(timeInSeconds) {
    // expects seconds
    var sec_num = parseInt(timeInSeconds, 10); // don't forget the second param
    var hours = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
    var seconds = sec_num - (hours * 3600) - (minutes * 60);
    if (hours < 10) {
      hours = "0" + hours;
    }
    if (minutes < 10) {
      minutes = "0" + minutes;
    }
    if (seconds < 10) {
      seconds = "0" + seconds;
    }
    var time = minutes + ':' + seconds;
    if (hours > 0) {
      time = hours + ':' + time;
    }
    return time;
  };

  fileUploadObj.getTransferRate = function(transferObj) {
    var currentTime = Date.now();
    var timeToWait = 1000; // ms
    if (currentTime >= transferObj.nextTime) {
      transferObj.nextTime = Date.now() + timeToWait;
      var pastBytes = transferObj.stored;
      transferObj.stored = transferObj.progress;
      var rate = ((transferObj.stored - pastBytes)) / (timeToWait); // B/ms (kB/s)
      var maxFileSize = transferObj.size;
      timeRemaining = (maxFileSize - transferObj.stored) / rate / 1000; // ms/1000 -> s
      // console.log('CURRENT BYTES', transferObj.stored);
      // console.log('PASTCOUNT', pastBytes);
      // console.log('DIFFERENCE', transferObj.stored - pastBytes);
      // console.log('maxFileSize', maxFileSize);
      // console.log('REMAINING BYTES', maxFileSize - transferObj.stored);

      convertedRate = convertRate(rate);
      convertedTime = convertTime(timeRemaining);
      console.log('RATE:', convertedRate);
      console.log('TIME REMAINING:', convertedTime);

      return {
        rate: convertedRate,
        time: convertedTime
      };

    }
  };

  return fileUploadObj;

}]);
<|endoftext|>


<commit_before>/**
 *
 */
var snake, food, colour, reversePower;
var scoreText = 'SCORE :', deadText = "Dead :'( \nClick to Try Again";
const L=1, R=2, D=4, U=8;

function reset(){
	console.log("Reset");
	snake = new Snake();
	food = new Food();
	colour = new Colour();
	reversePower = new ReversePower();
	console.log(self.innerWidth +" - "+ self.innerHeight);
}

function setup() {
	if(horz > vert)
		var px = self.innerHeight/45, horz = self.innerWidth/px, vert = 45;
	else
		var px = self.innerHeight/60, horz = 60, vert = self.innerHeight/px;
	createCanvas(horz * px, vert * px);
	noStroke();
	frameRate(10);
	reset();
	textAlign(RIGHT);
}

function draw() {
	background(54, 53, 55);
	if(snake.dead){
		text(deadText, horz/2*px, vert/2*px);
		return;
		}
	fill(0, 100, 0);
	rect(px, px, (horz-2)*px, (vert-6)*px);
	rect(px, (vert-4)*px, (horz-2)*px, 3*px);
	fill(0);
	text(screen.width + " x " + screen.height, 11*px, (2)*px);
	if(food.createFood){
		food.update();
	}
	if(snake.ate(food)){
		food.createFood =true;
	}
	if(snake.powerCount%reversePower.powerValue==0){
		reversePower.update();
		snake.powerCount = 1;
	}
	if(reversePower.showPower)
		snake.tookPower(reversePower);
	if(reversePower.showPower)
		reversePower.draw();
	if(reversePower.acquiredPower)
		snake.limitPower(reversePower);
	snake.update();
	food.draw();
	snake.draw();
	score = snake.length;
	scoreWidth = textWidth(score);
	fill(250);
	textSize(px*2);
	textFont("Helvetica");
	text(scoreText, 10*px, (vert-2)*px);
	text(score, 11*px+scoreWidth, (vert-2)*px);
}

function keyPressed() {
	if (keyCode === LEFT_ARROW && (snake.directionPower || snake.direction != R)) {
		snake.direction=L;
	} else if (keyCode === RIGHT_ARROW && (snake.directionPower || snake.direction != L)) {
		snake.direction=R;
	} else if (keyCode === UP_ARROW && (snake.directionPower || snake.direction != D)) {
		snake.direction=D;
	} else if (keyCode === DOWN_ARROW && (snake.directionPower || snake.direction != U)) {
		snake.direction=U;
	}
}

<commit_msg>roll back<commit_after>/**
 *
 */
var snake, food, colour, reversePower;
var px = 20, horz = 60, vert = 45, scoreText = 'SCORE :', deadText = "Dead :'( \nClick to Try Again";
const L=1, R=2, D=4, U=8;

function reset(){
	console.log("Reset");
	snake = new Snake();
	food = new Food();
	colour = new Colour();
	reversePower = new ReversePower();
	console.log(self.innerWidth +" - "+ document.documentElement.clientWidth +" - "+ document.body.clientWidth +" - "+ self.innerWidth );
}

function setup() {
	createCanvas(horz * px, vert * px);
	noStroke();
	frameRate(10);
	reset();
	textAlign(RIGHT);
}

function draw() {
	background(54, 53, 55);
	if(snake.dead){
		text(deadText, horz/2*px, vert/2*px);
		return;
		}
	fill(0, 100, 0);
	rect(px, px, (horz-2)*px, (vert-6)*px);
	rect(px, (vert-4)*px, (horz-2)*px, 3*px);
	fill(0);
	text(screen.width + " x " + screen.height, 11*px, (2)*px);
	if(food.createFood){
		food.update();
	}
	if(snake.ate(food)){
		food.createFood =true;
	}
	if(snake.powerCount%reversePower.powerValue==0){
		reversePower.update();
		snake.powerCount = 1;
	}
	if(reversePower.showPower)
		snake.tookPower(reversePower);
	if(reversePower.showPower)
		reversePower.draw();
	if(reversePower.acquiredPower)
		snake.limitPower(reversePower);
	snake.update();
	food.draw();
	snake.draw();
	score = snake.length;
	scoreWidth = textWidth(score);
	fill(250);
	textSize(px*2);
	textFont("Helvetica");
	text(scoreText, 10*px, (vert-2)*px);
	text(score, 11*px+scoreWidth, (vert-2)*px);
}

function keyPressed() {
	if (keyCode === LEFT_ARROW && (snake.directionPower || snake.direction != R)) {
		snake.direction=L;
	} else if (keyCode === RIGHT_ARROW && (snake.directionPower || snake.direction != L)) {
		snake.direction=R;
	} else if (keyCode === UP_ARROW && (snake.directionPower || snake.direction != D)) {
		snake.direction=D;
	} else if (keyCode === DOWN_ARROW && (snake.directionPower || snake.direction != U)) {
		snake.direction=U;
	}
}

<|endoftext|>


<commit_before>'use strict';

/*global N, _*/

// stdlib
var fs    = require('fs');
var path  = require('path');

// 3rd-party
var apiTree       = require('nlib').ApiTree;
var async         = require('nlib').Vendor.Async;
var fstools       = require('nlib').Vendor.FsTools;
var safePropName  = require('nlib').Support.safePropName;
var findRequires  = require('find-requires');

// internal
var findPaths = require('./find_paths');

////////////////////////////////////////////////////////////////////////////////

function Requisite() {
  this.requires = {};
  this.idx      = 1;
}

Requisite.prototype.process = function (source, pathname) {
  var
  self  = this,
  files = findRequires(source, { raw: true }),
  o, p;

  while (files.length) {
    o = files.shift();

    if (!o.value) {
      return new Error("Cannot handle non-string required path: " + o.raw);
    }

    try {
      p = require.resolve(path.resolve(path.dirname(pathname.toString()), o.value));
    } catch (err) {
      throw new Error(err.message +
                      ' (require: ' + o.value + ') (in: ' + pathname + ')');
    }

    if (undefined === this.requires[p]) {
      this.requires[p] = { idx: this.idx++, source: null };
      // prevent from "cyclic" loops
      this.requires[p].source = this.process(fs.readFileSync(p, 'utf8'), p);
    }

    source = source.replace(o.value, this.requires[p].idx);
  }

  return source;
};

Requisite.prototype.bundle = function () {
  var parts = [];

  parts.push(
    '(function () {',
      'var modules = {};',
      'function define(name, init) {',
        'modules[name] = { init: init };',
      '}',
      'function require(name) {',
        'if (!modules[name]) { throw new Error("Unknown module " + name); }',
        'if (!modules[name].module) {',
          'modules[name].module = { exports: {} };',
          'modules[name].init.call(modules[name].module.exports, ',
            'modules[name].module.exports, modules[name].module, ',
            'require);',
        '}',
        'return modules[name].module.exports;',
      '}'
  );

  _.each(this.requires, function (dep, pathname) {
    parts.push(
      'define(' + dep.idx + ', function (exports, module, require, define, modules) {',
      dep.source,
      '});'
    );
  });

  parts.push(
      'return require;',
    '}())'
  );

  return parts.join('\n');
};

// produces bundled server/client (js) trees for the browswers
function browserifyClient(callback) {
  var
  bundleConfig  = require('../../../bundle.yml'),
  packageConfig = bundleConfig.packages.fontello,
  clientConfig  = packageConfig.client,
  clientRoot    = path.resolve(N.runtime.apps[0].root, clientConfig.root),
  findOptions   = _.pick(clientConfig, 'include', 'exclude');

  findOptions.root = clientRoot;

  findPaths(findOptions, function (err, pathnames) {
    var heads = [], bodies = [], requisite = new Requisite();

    if (err) {
      callback(err);
      return;
    }

    async.forEachSeries(pathnames, function (pathname, nextPath) {
      pathname.read('utf8', function (err, source) {
        var // [ '["foo"]', '["bar"]', '["baz"]' ]
        apiPathParts = pathname.apiPath.split('.').map(safePropName);

        if (err) {
          nextPath(err);
          return;
        }

        // feed all parents of apiPath into heads array
        apiPathParts.reduce(function (prev, curr) {
          if (-1 === heads.indexOf(prev)) {
            heads.push(prev);
          }

          return prev + curr;
        });

        try {
          source = requisite.process(source, pathname);
        } catch (err) {
          nextPath(err);
          return;
        }

        bodies.push(
          ('this' + apiPathParts.join('') + ' = (function (require) {'),
            ('(function (exports, module) {'),
            source,
            ('}.call(this.exports, this.exports, this));'),
            ('return this.exports;'),
          ('}.call({ exports: {} }, require));')
        );

        nextPath();
      });
    }, function (err) {
      var head = _.uniq(heads.sort(), true).map(function (api) {
        return 'this' + api + ' = {};';
      }).join('\n');

      callback(err, [
        '(function () {',
        'var require = ' + requisite.bundle() + ';\n\n',
        head + '\n\n' + bodies.join('\n'),
        '}.call(N.client));'
      ].join('\n'));
    });
  });
}

////////////////////////////////////////////////////////////////////////////////

// buildApiTree(root, callback(err)) -> Void
// - root (String): Pathname where to save browserified api.js.
// - callback (Function): Executed once everything is done.
//
// Browserifies server/client trees into api.js file.
//
module.exports = function buildApiTree(root, callback) {
  browserifyClient(function (err, client) {
    var server;

    if (err) {
      callback(err);
      return;
    }

    server = apiTree.browserifyServerTree(N.server, 'this.N.server', {
      method: 'N.io.apiTree'
    });

    fs.writeFile(path.join(root, 'api.js'), server + '\n\n' + client, callback);
  });
};
<commit_msg>Run init in the bottom of bundle<commit_after>'use strict';

/*global N, _*/

// stdlib
var fs    = require('fs');
var path  = require('path');

// 3rd-party
var apiTree       = require('nlib').ApiTree;
var async         = require('nlib').Vendor.Async;
var fstools       = require('nlib').Vendor.FsTools;
var safePropName  = require('nlib').Support.safePropName;
var findRequires  = require('find-requires');

// internal
var findPaths = require('./find_paths');

////////////////////////////////////////////////////////////////////////////////

function Requisite() {
  this.requires = {};
  this.idx      = 1;
}

Requisite.prototype.process = function (source, pathname) {
  var
  self  = this,
  files = findRequires(source, { raw: true }),
  o, p;

  while (files.length) {
    o = files.shift();

    if (!o.value) {
      return new Error("Cannot handle non-string required path: " + o.raw);
    }

    try {
      p = require.resolve(path.resolve(path.dirname(pathname.toString()), o.value));
    } catch (err) {
      throw new Error(err.message +
                      ' (require: ' + o.value + ') (in: ' + pathname + ')');
    }

    if (undefined === this.requires[p]) {
      this.requires[p] = { idx: this.idx++, source: null };
      // prevent from "cyclic" loops
      this.requires[p].source = this.process(fs.readFileSync(p, 'utf8'), p);
    }

    source = source.replace(o.value, this.requires[p].idx);
  }

  return source;
};

Requisite.prototype.bundle = function () {
  var parts = [];

  parts.push(
    '(function () {',
      'var modules = {};',
      'function define(name, init) {',
        'modules[name] = { init: init };',
      '}',
      'function require(name) {',
        'if (!modules[name]) { throw new Error("Unknown module " + name); }',
        'if (!modules[name].module) {',
          'modules[name].module = { exports: {} };',
          'modules[name].init.call(modules[name].module.exports, ',
            'modules[name].module.exports, modules[name].module, ',
            'require);',
        '}',
        'return modules[name].module.exports;',
      '}'
  );

  _.each(this.requires, function (dep, pathname) {
    parts.push(
      'define(' + dep.idx + ', function (exports, module, require, define, modules) {',
      dep.source,
      '});'
    );
  });

  parts.push(
      'return require;',
    '}())'
  );

  return parts.join('\n');
};

// produces bundled server/client (js) trees for the browswers
function browserifyClient(callback) {
  var
  bundleConfig  = require('../../../bundle.yml'),
  packageConfig = bundleConfig.packages.fontello,
  clientConfig  = packageConfig.client,
  clientRoot    = path.resolve(N.runtime.apps[0].root, clientConfig.root),
  findOptions   = _.pick(clientConfig, 'include', 'exclude');

  findOptions.root = clientRoot;

  findPaths(findOptions, function (err, pathnames) {
    var heads = [], bodies = [], export_list= [], requisite = new Requisite();

    if (err) {
      callback(err);
      return;
    }

    async.forEachSeries(pathnames, function (pathname, nextPath) {
      pathname.read('utf8', function (err, source) {
        var // [ '["foo"]', '["bar"]', '["baz"]' ]
        apiPathParts = pathname.apiPath.split('.').map(safePropName);

        if (err) {
          nextPath(err);
          return;
        }

        // feed all parents of apiPath into heads array
        apiPathParts.reduce(function (prev, curr) {
          if (-1 === heads.indexOf(prev)) {
            heads.push(prev);
          }

          return prev + curr;
        });

        try {
          source = requisite.process(source, pathname);
        } catch (err) {
          nextPath(err);
          return;
        }

        bodies.push(
          ('this' + apiPathParts.join('') + ' = (function (require) {'),
            ('(function (exports, module) {'),
            source,
            ('}.call(this.exports, this.exports, this));'),
            ('return this.exports;'),
          ('}.call({ exports: {} }, require));')
        );

        export_list.push('this' + apiPathParts.join(''));

        nextPath();
      });
    }, function (err) {
      var head = _.uniq(heads.sort(), true).map(function (api) {
        return 'this' + api + ' = {};';
      }).join('\n');

      callback(err, [
        '(function () {',
        'var require = ' + requisite.bundle() + ';\n\n',
        head + '\n\n' + bodies.join('\n') + '\n\n',
        '_.map([' + export_list.sort().join(',') + '], function (api) {',
        'var init = api && api.init || api;',
        'if (_.isFunction(init)) { init(window, document, N); }',
        '});',
        '}.call(N.client));'
      ].join('\n'));
    });
  });
}

////////////////////////////////////////////////////////////////////////////////

// buildApiTree(root, callback(err)) -> Void
// - root (String): Pathname where to save browserified api.js.
// - callback (Function): Executed once everything is done.
//
// Browserifies server/client trees into api.js file.
//
module.exports = function buildApiTree(root, callback) {
  browserifyClient(function (err, client) {
    var server;

    if (err) {
      callback(err);
      return;
    }

    server = apiTree.browserifyServerTree(N.server, 'this.N.server', {
      method: 'N.io.apiTree'
    });

    fs.writeFile(path.join(root, 'api.js'), server + '\n\n' + client, callback);
  });
};
<|endoftext|>


<commit_before>/*global describe, it, browser, expect, exports */
/*eslint-env node */
/*eslint strict: ["error", "global"] */
'use strict';
var fs = require('fs');

function load(file) {
    var contents = fs.readFileSync(__dirname + '/' + file);
    return JSON.parse(contents);
}

function buildAttribute(element) {
    if (element instanceof Array) {
        return element.map(function (element) {
            return buildAttribute(element);
        }).join('');
    } else {
        return '[data-k-b-testhook-' + element.type + '="' + element.value + '"]';
    }
}
function buildSelector(path) {
    return path.map(function (element) {
        return buildAttribute(element);
    }).join(' ');
}
function extend(path, elements) {
    var newPath = path.map(function (el) {
        return el;
    });
    elements.forEach(function (element) {
        newPath.push(element);
    });
    return newPath;
}
function makeSelector(base, selector) {
    if (selector instanceof Array) {
        selector = {
            type: 'relative',
            path: selector
        };
    }
    var fullPath;
    switch (selector.type) {
    case 'relative':
        fullPath = extend(base, selector.path);
        break;
    case 'absolute':
        fullPath = selector.path;
        break;
    }
    return buildSelector(fullPath);

}
function info() {
    let args = Array.prototype.slice.call(arguments);
    process.stdout.write(args.join(' ') + '\n');
}
function doTask(spec, task, testData) {
    if (task.selector) {
        var selector = makeSelector(spec.baseSelector, task.selector);
        var result = true;
        if (task.wait) {
            result = browser.waitForExist(selector, task.wait);
        } if (task.waitForText) {
            result = browser.waitForText(selector, task.waitForText);
        } else if (task.waitUntilText) {
            result = browser.waitUntil(function () {
                try {
                    var text = browser.getText(selector);
                    return (text === task.waitUntilText.value);
                } catch (ex) {
                    return false;
                }
            }, task.waitUntilText.wait);
        } else if (task.exists) {
            result = browser.isExisting(selector);
            expect(result).toBe(true);
        }

        if (!result) {
            return;
        }

        // only proceed with a further action if succeeded so far.
        if (task.text) {
            let text = browser.getText(selector);
            expect(text).toEqual(task.text);
        } else if (task.match) {
            let toMatch = browser.getText(selector);
            expect(toMatch).toMatch(new RegExp(task.text));
        } else if (task.number) {
            let toCompare = browser.getText(selector);
            expect(toCompare).toBeDefined();
            let theNumber = Number(toCompare.replace(/,/g, ''));

            Object.keys(task.number).forEach(function (comparison) {
                var comparisonValue = task.number[comparison];
                switch (comparison) {
                case 'greaterThan':
                    expect(theNumber).toBeGreaterThan(comparisonValue);
                    break;
                case 'greaterThanOrEqual':
                    expect(theNumber).toBeGreaterThanOrEqual(comparisonValue);
                    break;
                case 'lessThan':
                    expect(theNumber).toBeLessThan(comparisonValue);
                    break;
                case 'lessThanOrEqual':
                    expect(theNumber).toBeLessThanOrEqual(comparisonValue);
                    break;
                case 'equal':
                    expect(theNumber).toEqual(comparisonValue);
                    break;
                }
            });
        }

        // Actions
        if (task.action) {
            switch (task.action) {
            case 'click':
                browser.click(selector);
                break;
            case 'set-session-cookie':
                browser.setCookie({
                    name: 'kbase_session',
                    value: testData.token,
                    path: '/'
                });
                var cookie = browser.getCookie('kbase_session');
                expect(cookie.value).toEqual(testData.token);
                break;
            case 'delete-cookie':
                browser.deleteCookie();
                expect(browser.getCookie('kbase_session')).toBeNull();
                break;
            case 'navigate':
                browser.url(task.params.url);
                break;
            case 'set-value':
                browser.setValue(selector, task.params.value);
                break;
            case 'keys':
                browser.keys(task.params.keys);
                break;
            default:
                throw new Error('Unknown task action ' + task.action);
            }
        }
    } else if (task.navigate) {
        browser.url('#' + task.navigate.path);
    }
}

function doTasks(spec, tasks, testData, common) {
    tasks.forEach(function (task) {
        if (task.disabled) {
            info('-- skipping task', task.title);
            return;
        }
        if (task.subtask) {
            doTasks(spec, common[task.subtask], testData, common);
            return;
        }
        doTask(spec, task, testData);
    });
}

function runTest(test, common) {
    var testData = load('../config.json');
    describe(test.description, function () {
        if (test.disabled) {
            return;
        }
        var defaultUrl = test.defaultUrl || '/';
        test.specs.forEach(function (spec) {
            if (spec.disabled) {
                return;
            }
            it(spec.description, function () {
                if (spec.disabled) {
                    info('skipping spec', spec.description);
                    return;
                }
                var url = spec.url || defaultUrl;
                browser.url(url);
                doTasks(spec, spec.tasks, testData, common);
                browser.deleteCookie();
            });
        });
    });
}

function runTests(tests, common) {
    tests.forEach(function (test) {
        runTest(test, common);
    });
}

exports.runTests = runTests;
exports.load = load;<commit_msg>add test condition for node count for selector [SCT-644] - supports, e.g., a given # of repeated items occuring<commit_after>/*global describe, it, browser, expect, exports */
/*eslint-env node */
/*eslint strict: ["error", "global"] */
'use strict';
var fs = require('fs');

function load(file) {
    var contents = fs.readFileSync(__dirname + '/' + file);
    return JSON.parse(contents);
}

function buildAttribute(element) {
    if (element instanceof Array) {
        return element.map(function (element) {
            return buildAttribute(element);
        }).join('');
    } else {
        return '[data-k-b-testhook-' + element.type + '="' + element.value + '"]';
    }
}
function buildSelector(path) {
    return path.map(function (element) {
        return buildAttribute(element);
    }).join(' ');
}
function extend(path, elements) {
    var newPath = path.map(function (el) {
        return el;
    });
    elements.forEach(function (element) {
        newPath.push(element);
    });
    return newPath;
}
function makeSelector(base, selector) {
    if (selector instanceof Array) {
        selector = {
            type: 'relative',
            path: selector
        };
    }
    var fullPath;
    switch (selector.type) {
    case 'relative':
        fullPath = extend(base, selector.path);
        break;
    case 'absolute':
        fullPath = selector.path;
        break;
    }
    return buildSelector(fullPath);

}
function info() {
    let args = Array.prototype.slice.call(arguments);
    process.stdout.write(args.join(' ') + '\n');
}
function doTask(spec, task, testData) {
    if (task.selector) {
        var selector = makeSelector(spec.baseSelector, task.selector);
        var result = true;
        if (task.wait) {
            result = browser.waitForExist(selector, task.wait);
        } if (task.waitForText) {
            result = browser.waitForText(selector, task.waitForText);
        } else if (task.waitUntilText) {
            result = browser.waitUntil(function () {
                try {
                    var text = browser.getText(selector);
                    return (text === task.waitUntilText.value);
                } catch (ex) {
                    return false;
                }
            }, task.waitUntilText.wait);
        } else if (task.exists) {
            result = browser.isExisting(selector);
            expect(result).toBe(true);
        }

        if (!result) {
            return;
        }

        // only proceed with a further action if succeeded so far.
        if (task.text) {
            let text = browser.getText(selector);
            expect(text).toEqual(task.text);
        } else if (task.match) {
            let toMatch = browser.getText(selector);
            expect(toMatch).toMatch(new RegExp(task.text));
        } else if (task.number) {
            let toCompare = browser.getText(selector);
            expect(toCompare).toBeDefined();
            let theNumber = Number(toCompare.replace(/,/g, ''));

            Object.keys(task.number).forEach(function (comparison) {
                var comparisonValue = task.number[comparison];
                switch (comparison) {
                case 'greaterThan':
                    expect(theNumber).toBeGreaterThan(comparisonValue);
                    break;
                case 'greaterThanOrEqual':
                    expect(theNumber).toBeGreaterThanOrEqual(comparisonValue);
                    break;
                case 'lessThan':
                    expect(theNumber).toBeLessThan(comparisonValue);
                    break;
                case 'lessThanOrEqual':
                    expect(theNumber).toBeLessThanOrEqual(comparisonValue);
                    break;
                case 'equal':
                    expect(theNumber).toEqual(comparisonValue);
                    break;
                }
            });
        } else if (task.count) {
            // count the elements which matched this selector
            let toCompare = browser.elements(selector).value.length;
            expect(toCompare).toBeDefined();

            Object.keys(task.count).forEach(function (comparison) {
                var comparisonValue = task.count[comparison];
                switch (comparison) {
                case 'greaterThan':
                    expect(toCompare).toBeGreaterThan(comparisonValue);
                    break;
                case 'greaterThanOrEqual':
                    expect(toCompare).toBeGreaterThanOrEqual(comparisonValue);
                    break;
                case 'lessThan':
                    expect(toCompare).toBeLessThan(comparisonValue);
                    break;
                case 'lessThanOrEqual':
                    expect(toCompare).toBeLessThanOrEqual(comparisonValue);
                    break;
                case 'equal':
                    expect(toCompare).toEqual(comparisonValue);
                    break;
                }
            });
        }

        // Actions
        if (task.action) {
            switch (task.action) {
            case 'click':
                browser.click(selector);
                break;
            case 'set-session-cookie':
                browser.setCookie({
                    name: 'kbase_session',
                    value: testData.token,
                    path: '/'
                });
                var cookie = browser.getCookie('kbase_session');
                expect(cookie.value).toEqual(testData.token);
                break;
            case 'delete-cookie':
                browser.deleteCookie();
                expect(browser.getCookie('kbase_session')).toBeNull();
                break;
            case 'navigate':
                browser.url(task.params.url);
                break;
            case 'set-value':
                browser.setValue(selector, task.params.value);
                break;
            case 'keys':
                browser.keys(task.params.keys);
                break;
            default:
                throw new Error('Unknown task action ' + task.action);
            }
        }
    } else if (task.navigate) {
        browser.url('#' + task.navigate.path);
    }
}

function doTasks(spec, tasks, testData, common) {
    tasks.forEach(function (task) {
        if (task.disabled) {
            info('-- skipping task', task.title);
            return;
        }
        if (task.subtask) {
            doTasks(spec, common[task.subtask], testData, common);
            return;
        }
        doTask(spec, task, testData);
    });
}

function runTest(test, common) {
    var testData = load('../config.json');
    describe(test.description, function () {
        if (test.disabled) {
            return;
        }
        var defaultUrl = test.defaultUrl || '/';
        test.specs.forEach(function (spec) {
            if (spec.disabled) {
                return;
            }
            it(spec.description, function () {
                if (spec.disabled) {
                    info('skipping spec', spec.description);
                    return;
                }
                var url = spec.url || defaultUrl;
                browser.url(url);
                doTasks(spec, spec.tasks, testData, common);
                browser.deleteCookie();
            });
        });
    });
}

function runTests(tests, common) {
    tests.forEach(function (test) {
        runTest(test, common);
    });
}

exports.runTests = runTests;
exports.load = load;<|endoftext|>


<commit_before>// d3.tip
// Copyright (c) 2013 Justin Palmer
//
// Tooltips for d3.js SVG visualizations

// Public - contructs a new tooltip
//
// Returns a tip
d3.tip = function() {
  var direction = d3_tip_direction,
      offset    = d3_tip_offset,
      html      = d3_tip_html,
      node      = initNode(),
      svg       = null,
      point     = null,
      target    = null

  function tip(vis) {
    svg = getSVGNode(vis)
    point = svg.createSVGPoint()
    document.body.appendChild(node)
  }

  // Public - show the tooltip on the screen
  //
  // Returns a tip
  tip.show = function() {
    var args = Array.prototype.slice.call(arguments)
    if(args.length > 1) target = args.pop()

    var content = html.apply(this, args),
        poffset = offset.apply(this, args),
        dir     = direction.apply(this, args),
        nodel   = d3.select(node), i = 0,
        coords

    nodel.html(content)
      .style({ opacity: 1, 'pointer-events': 'all' })

    while(i--) nodel.classed(directions[i], false)
    coords = direction_callbacks.get(dir).apply(this)
    nodel.classed(dir, true).style({
      top: (coords.top +  poffset[0]) + 'px',
      left: (coords.left + poffset[1]) + 'px'
    })

    return tip
  }

  // Public - hide the tooltip
  //
  // Returns a tip
  tip.hide = function() {
    nodel = d3.select(node)
    nodel.style({ opacity: 0, 'pointer-events': 'none' })
    return tip
  }

  // Public: Proxy attr calls to the d3 tip container.  Sets or gets attribute value.
  //
  // n - name of the attribute
  // v - value of the attribute
  //
  // Returns tip or attribute value
  tip.attr = function(n, v) {
    if (arguments.length < 2 && typeof n === 'string') {
      return d3.select(node).attr(n)
    } else {
      var args =  Array.prototype.slice.call(arguments)
      d3.selection.prototype.attr.apply(d3.select(node), args)
    }

    return tip
  }

  // Public: Proxy style calls to the d3 tip container.  Sets or gets a style value.
  //
  // n - name of the property
  // v - value of the property
  //
  // Returns tip or style property value
  tip.style = function(n, v) {
    if (arguments.length < 2 && typeof n === 'string') {
      return d3.select(node).style(n)
    } else {
      var args =  Array.prototype.slice.call(arguments)
      d3.selection.prototype.style.apply(d3.select(node), args)
    }

    return tip
  }

  // Public: Set or get the direction of the tooltip
  //
  // v - One of n(north), s(south), e(east), or w(west), nw(northwest),
  //     sw(southwest), ne(northeast) or se(southeast)
  //
  // Returns tip or direction
  tip.direction = function(v) {
    if (!arguments.length) return direction
    direction = v == null ? v : d3.functor(v)

    return tip
  }

  // Public: Sets or gets the offset of the tip
  //
  // v - Array of [x, y] offset
  //
  // Returns offset or
  tip.offset = function(v) {
    if (!arguments.length) return offset
    offset = v == null ? v : d3.functor(v)

    return tip
  }

  // Public: sets or gets the html value of the tooltip
  //
  // v - String value of the tip
  //
  // Returns html value or tip
  tip.html = function(v) {
    if (!arguments.length) return html
    html = v == null ? v : d3.functor(v)

    return tip
  }

  function d3_tip_direction() { return 'n' }
  function d3_tip_offset() { return [0, 0] }
  function d3_tip_html() { return ' ' }

  var direction_callbacks = d3.map({
    n:  direction_n,
    s:  direction_s,
    e:  direction_e,
    w:  direction_w,
    nw: direction_nw,
    ne: direction_ne,
    sw: direction_sw,
    se: direction_se
  }),

  directions = direction_callbacks.keys()

  function direction_n() {
    var bbox = getScreenBBox()
    return {
      top:  bbox.n.y - node.offsetHeight,
      left: bbox.n.x - node.offsetWidth / 2
    }
  }

  function direction_s() {
    var bbox = getScreenBBox()
    return {
      top:  bbox.s.y,
      left: bbox.s.x - node.offsetWidth / 2
    }
  }

  function direction_e() {
    var bbox = getScreenBBox()
    return {
      top:  bbox.e.y - node.offsetHeight / 2,
      left: bbox.e.x
    }
  }

  function direction_w() {
    var bbox = getScreenBBox()
    return {
      top:  bbox.w.y - node.offsetHeight / 2,
      left: bbox.w.x - node.offsetWidth
    }
  }

  function direction_nw() {
    var bbox = getScreenBBox()
    return {
      top:  bbox.nw.y - node.offsetHeight,
      left: bbox.nw.x - node.offsetWidth
    }
  }

  function direction_ne() {
    var bbox = getScreenBBox()
    return {
      top:  bbox.ne.y - node.offsetHeight,
      left: bbox.ne.x
    }
  }

  function direction_sw() {
    var bbox = getScreenBBox()
    return {
      top:  bbox.sw.y,
      left: bbox.sw.x - node.offsetWidth
    }
  }

  function direction_se() {
    var bbox = getScreenBBox()
    return {
      top:  bbox.se.y,
      left: bbox.e.x
    }
  }

  function initNode() {
    var node = d3.select(document.createElement('div'))
    node.style({
      position: 'absolute',
      opacity: 0,
      pointerEvents: 'none',
      boxSizing: 'border-box'
    })

    return node.node()
  }

  function getSVGNode(el) {
    el = el.node()
    if(el.tagName.toLowerCase() == 'svg')
      return el

    return el.ownerSVGElement
  }

  // Private - gets the screen coordinates of a shape
  //
  // Given a shape on the screen, will return an SVGPoint for the directions
  // n(north), s(south), e(east), w(west), ne(northeast), se(southeast), nw(northwest),
  // sw(southwest).
  //
  //    +-+-+
  //    |   |
  //    +   +
  //    |   |
  //    +-+-+
  //
  // Returns an Object {n, s, e, w, nw, sw, ne, se}
  function getScreenBBox() {
    var targetel   = target || d3.event.target,
        bbox       = {},
        matrix     = targetel.getScreenCTM(),
        tbbox      = targetel.getBBox(),
        width      = tbbox.width,
        height     = tbbox.height,
        x          = tbbox.x,
        y          = tbbox.y,
        scrollTop  = document.documentElement.scrollTop || document.body.scrollTop,
        scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft

    point.x = x + scrollLeft
    point.y = y + scrollTop
    bbox.nw = point.matrixTransform(matrix)
    point.x += width
    bbox.ne = point.matrixTransform(matrix)
    point.y += height
    bbox.se = point.matrixTransform(matrix)
    point.x -= width
    bbox.sw = point.matrixTransform(matrix)
    point.y -= height / 2
    bbox.w  = point.matrixTransform(matrix)
    point.x += width
    bbox.e = point.matrixTransform(matrix)
    point.x -= width / 2
    point.y -= height / 2
    bbox.n = point.matrixTransform(matrix)
    point.y += height
    bbox.s = point.matrixTransform(matrix)

    return bbox
  }

  return tip
};
<commit_msg>check if the last item passed to ship show is an svgelement before we pop the array<commit_after>// d3.tip
// Copyright (c) 2013 Justin Palmer
//
// Tooltips for d3.js SVG visualizations

// Public - contructs a new tooltip
//
// Returns a tip
d3.tip = function() {
  var direction = d3_tip_direction,
      offset    = d3_tip_offset,
      html      = d3_tip_html,
      node      = initNode(),
      svg       = null,
      point     = null,
      target    = null

  function tip(vis) {
    svg = getSVGNode(vis)
    point = svg.createSVGPoint()
    document.body.appendChild(node)
  }

  // Public - show the tooltip on the screen
  //
  // Returns a tip
  tip.show = function() {
    var args = Array.prototype.slice.call(arguments)
    if(args[args.length - 1] instanceof SVGElement) target = args.pop()

    var content = html.apply(this, args),
        poffset = offset.apply(this, args),
        dir     = direction.apply(this, args),
        nodel   = d3.select(node), i = 0,
        coords

    nodel.html(content)
      .style({ opacity: 1, 'pointer-events': 'all' })

    while(i--) nodel.classed(directions[i], false)
    coords = direction_callbacks.get(dir).apply(this)
    nodel.classed(dir, true).style({
      top: (coords.top +  poffset[0]) + 'px',
      left: (coords.left + poffset[1]) + 'px'
    })

    return tip
  }

  // Public - hide the tooltip
  //
  // Returns a tip
  tip.hide = function() {
    nodel = d3.select(node)
    nodel.style({ opacity: 0, 'pointer-events': 'none' })
    return tip
  }

  // Public: Proxy attr calls to the d3 tip container.  Sets or gets attribute value.
  //
  // n - name of the attribute
  // v - value of the attribute
  //
  // Returns tip or attribute value
  tip.attr = function(n, v) {
    if (arguments.length < 2 && typeof n === 'string') {
      return d3.select(node).attr(n)
    } else {
      var args =  Array.prototype.slice.call(arguments)
      d3.selection.prototype.attr.apply(d3.select(node), args)
    }

    return tip
  }

  // Public: Proxy style calls to the d3 tip container.  Sets or gets a style value.
  //
  // n - name of the property
  // v - value of the property
  //
  // Returns tip or style property value
  tip.style = function(n, v) {
    if (arguments.length < 2 && typeof n === 'string') {
      return d3.select(node).style(n)
    } else {
      var args =  Array.prototype.slice.call(arguments)
      d3.selection.prototype.style.apply(d3.select(node), args)
    }

    return tip
  }

  // Public: Set or get the direction of the tooltip
  //
  // v - One of n(north), s(south), e(east), or w(west), nw(northwest),
  //     sw(southwest), ne(northeast) or se(southeast)
  //
  // Returns tip or direction
  tip.direction = function(v) {
    if (!arguments.length) return direction
    direction = v == null ? v : d3.functor(v)

    return tip
  }

  // Public: Sets or gets the offset of the tip
  //
  // v - Array of [x, y] offset
  //
  // Returns offset or
  tip.offset = function(v) {
    if (!arguments.length) return offset
    offset = v == null ? v : d3.functor(v)

    return tip
  }

  // Public: sets or gets the html value of the tooltip
  //
  // v - String value of the tip
  //
  // Returns html value or tip
  tip.html = function(v) {
    if (!arguments.length) return html
    html = v == null ? v : d3.functor(v)

    return tip
  }

  function d3_tip_direction() { return 'n' }
  function d3_tip_offset() { return [0, 0] }
  function d3_tip_html() { return ' ' }

  var direction_callbacks = d3.map({
    n:  direction_n,
    s:  direction_s,
    e:  direction_e,
    w:  direction_w,
    nw: direction_nw,
    ne: direction_ne,
    sw: direction_sw,
    se: direction_se
  }),

  directions = direction_callbacks.keys()

  function direction_n() {
    var bbox = getScreenBBox()
    return {
      top:  bbox.n.y - node.offsetHeight,
      left: bbox.n.x - node.offsetWidth / 2
    }
  }

  function direction_s() {
    var bbox = getScreenBBox()
    return {
      top:  bbox.s.y,
      left: bbox.s.x - node.offsetWidth / 2
    }
  }

  function direction_e() {
    var bbox = getScreenBBox()
    return {
      top:  bbox.e.y - node.offsetHeight / 2,
      left: bbox.e.x
    }
  }

  function direction_w() {
    var bbox = getScreenBBox()
    return {
      top:  bbox.w.y - node.offsetHeight / 2,
      left: bbox.w.x - node.offsetWidth
    }
  }

  function direction_nw() {
    var bbox = getScreenBBox()
    return {
      top:  bbox.nw.y - node.offsetHeight,
      left: bbox.nw.x - node.offsetWidth
    }
  }

  function direction_ne() {
    var bbox = getScreenBBox()
    return {
      top:  bbox.ne.y - node.offsetHeight,
      left: bbox.ne.x
    }
  }

  function direction_sw() {
    var bbox = getScreenBBox()
    return {
      top:  bbox.sw.y,
      left: bbox.sw.x - node.offsetWidth
    }
  }

  function direction_se() {
    var bbox = getScreenBBox()
    return {
      top:  bbox.se.y,
      left: bbox.e.x
    }
  }

  function initNode() {
    var node = d3.select(document.createElement('div'))
    node.style({
      position: 'absolute',
      opacity: 0,
      pointerEvents: 'none',
      boxSizing: 'border-box'
    })

    return node.node()
  }

  function getSVGNode(el) {
    el = el.node()
    if(el.tagName.toLowerCase() == 'svg')
      return el

    return el.ownerSVGElement
  }

  // Private - gets the screen coordinates of a shape
  //
  // Given a shape on the screen, will return an SVGPoint for the directions
  // n(north), s(south), e(east), w(west), ne(northeast), se(southeast), nw(northwest),
  // sw(southwest).
  //
  //    +-+-+
  //    |   |
  //    +   +
  //    |   |
  //    +-+-+
  //
  // Returns an Object {n, s, e, w, nw, sw, ne, se}
  function getScreenBBox() {
    var targetel   = target || d3.event.target,
        bbox       = {},
        matrix     = targetel.getScreenCTM(),
        tbbox      = targetel.getBBox(),
        width      = tbbox.width,
        height     = tbbox.height,
        x          = tbbox.x,
        y          = tbbox.y,
        scrollTop  = document.documentElement.scrollTop || document.body.scrollTop,
        scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft

    point.x = x + scrollLeft
    point.y = y + scrollTop
    bbox.nw = point.matrixTransform(matrix)
    point.x += width
    bbox.ne = point.matrixTransform(matrix)
    point.y += height
    bbox.se = point.matrixTransform(matrix)
    point.x -= width
    bbox.sw = point.matrixTransform(matrix)
    point.y -= height / 2
    bbox.w  = point.matrixTransform(matrix)
    point.x += width
    bbox.e = point.matrixTransform(matrix)
    point.x -= width / 2
    point.y -= height / 2
    bbox.n = point.matrixTransform(matrix)
    point.y += height
    bbox.s = point.matrixTransform(matrix)

    return bbox
  }

  return tip
};
<|endoftext|>


<commit_before>"use strict";

(function () {
    angular
        .module("argo")
        .factory("positionsService", positionsService);

    positionsService.$inject = ["$http", "$q", "sessionService"];
    function positionsService($http, $q, sessionService) {
        var service = {
            getPositions: getPositions
        };

        return service;

        function getPositions() {
            var deferred = $q.defer();

            sessionService.isLogged().then(function (credentials) {
                $http.post("/api/positions", {
                    environment: credentials.environment,
                    token: credentials.token,
                    accountId: credentials.accountId
                }).then(function (positions) {
                    var data = [];

                    positions.data.forEach(function (position) {
                        var side,
                            longUnits,
                            shortUnits,
                            units,
                            avgPrice;

                        longUnits = position.long &&
                            parseInt(position.long.units, 10);
                        shortUnits = position.short &&
                            parseInt(position.short.units, 10);
                        units = longUnits || shortUnits;
                        side = position.longUnits > 0 ? "buy" : "sell";
                        avgPrice = (longUnits && position.long.averagePrice)
                             || (shortUnits && position.short.averagePrice);

                        data.push({
                            side: side,
                            instrument: position.instrument,
                            units: units,
                            avgPrice: avgPrice
                        });
                    });
                    deferred.resolve(data);
                });
            });

            return deferred.promise;
        }

    }

}());
<commit_msg>fix(positions): use units to get the side<commit_after>"use strict";

(function () {
    angular
        .module("argo")
        .factory("positionsService", positionsService);

    positionsService.$inject = ["$http", "$q", "sessionService"];
    function positionsService($http, $q, sessionService) {
        var service = {
            getPositions: getPositions
        };

        return service;

        function getPositions() {
            var deferred = $q.defer();

            sessionService.isLogged().then(function (credentials) {
                $http.post("/api/positions", {
                    environment: credentials.environment,
                    token: credentials.token,
                    accountId: credentials.accountId
                }).then(function (positions) {
                    var data = [];

                    positions.data.forEach(function (position) {
                        var side,
                            longUnits,
                            shortUnits,
                            units,
                            avgPrice;

                        longUnits = position.long &&
                            parseInt(position.long.units, 10);
                        shortUnits = position.short &&
                            parseInt(position.short.units, 10);
                        units = longUnits || shortUnits;
                        side = units > 0 ? "buy" : "sell";
                        avgPrice = (longUnits && position.long.averagePrice)
                             || (shortUnits && position.short.averagePrice);

                        data.push({
                            side: side,
                            instrument: position.instrument,
                            units: units,
                            avgPrice: avgPrice
                        });
                    });
                    deferred.resolve(data);
                });
            });

            return deferred.promise;
        }

    }

}());
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 by Aaron Parecki. All rights reserved.  Use of this
 * source code is governed by a BSD-style license that can be found in the
 * LICENSE file.
 */

function bindTwitter() {
    $("a.js-action-reply").each(function(i,e){
      $(e).click(function(evt){
        var tweet = $(evt.target).parents(".tweet");
        var url = "https://twitter.com/" + $(tweet).data('screen-name') + "/status/" + $(tweet).attr('data-item-id');

        // TODO: THIS IS A HACK! see below.
        var postURL = "http://pk2.dev/admin/?reply_to=" + encodeURI(url);
        window.open(postURL);

        // TODO: Need to either get the page URL from the extension preferences, or send an event to the extension
        // where the extension can open the new window
        // chrome.extension.sendMessage({url: url}, function(response) {
        //   console.log(response);
        // });

        return false;
      });
    });
}

bindTwitter();
setTimeout(bindTwitter, 5000);

$("a[data-reply-to='']").each(function(i,e){
  $(e).click(function(evt){
    var post = $(evt.target).parents(".post-container");
    var url = "https://alpha.app.net/" + $(post).data('post-author-username') + "/post/" + $(post).attr('data-post-id');
    var postURL = "http://pk2.dev/admin/?reply_to=" + encodeURI(url);
    window.open(postURL);
    return false;
  });
});
<commit_msg>Unbind so we don't double-fire the click event<commit_after>/*
 * Copyright (c) 2012 by Aaron Parecki. All rights reserved.  Use of this
 * source code is governed by a BSD-style license that can be found in the
 * LICENSE file.
 */

function bindTwitter() {
    $("a.js-action-reply").each(function(i,e){
      $(e).unbind("click").click(function(evt){
        var tweet = $(evt.target).parents(".tweet");
        var url = "https://twitter.com/" + $(tweet).data('screen-name') + "/status/" + $(tweet).attr('data-item-id');

        // TODO: THIS IS A HACK! see below.
        var postURL = "http://pk.dev/admin/?reply_to=" + encodeURI(url);
        window.open(postURL);

        // TODO: Need to either get the page URL from the extension preferences, or send an event to the extension
        // where the extension can open the new window
        // chrome.extension.sendMessage({url: url}, function(response) {
        //   console.log(response);
        // });

        return false;
      });
    });
}

bindTwitter();
setTimeout(bindTwitter, 5000);

$("a[data-reply-to='']").each(function(i,e){
  $(e).click(function(evt){
    var post = $(evt.target).parents(".post-container");
    var url = "https://alpha.app.net/" + $(post).data('post-author-username') + "/post/" + $(post).attr('data-post-id');
    var postURL = "http://pk.dev/admin/?reply_to=" + encodeURI(url);
    window.open(postURL);
    return false;
  });
});
<|endoftext|>