<commit_before>$(document).ready(function () {
  $("html, body").animate({ scrollTop: 0 }, 500);
  var Big = require("big.js");
  Big.DP = 30; // the digits of precision for divisions
  var printf = require("printf");

  var kmToPlanet = Module().cwrap("km_to_planet", "number", ["number", "number"]);

  const planets = [
    { name: "Mercury", id: 1, mass: Big("3.3022e23"), img: $("#planet-mercury") },
    { name: "Venus", id: 2, mass: Big("4.8676e24"), img: $("#planet-venus") },
    { name: "Mars", id: 4, mass: Big("6.4185e23"), img: $("#planet-mars") },
    { name: "Jupiter", id: 5, mass: Big("1.8986e27"), img: $("#planet-jupiter") },
    { name: "Saturn", id: 6, mass: Big("5.6846e26"), img: $("#planet-saturn") },
    { name: "Neptune", id: 7, mass: Big("1.0243e26"), img: $("#planet-neptune") },
    { name: "Uranus", id: 8, mass: Big("8.681e25"), img: $("#planet-uranus") },
    { name: "Pluto", id: 9, mass: Big("1.305e22"), img: $("#planet-pluto") }
  ];

  // display the object if it's gravitational pull >= the one of the planet at X meters
  const distanceThreshold = { "large-objects": 100, "medium-objects": 100, "large-animals": 10 };

  const stuff = [
    { name: "A super oil tanker ship", id: 1, mass: Big("650e6"), objClass: "large-objects" },
    { name: "An oil tanker ship", id: 2, mass: Big("300e6"), objClass: "large-objects" },
    { name: "A container carrier ship", id: 3, mass: Big("180e6"), objClass: "large-objects" },
    { name: "A cruise ship", id: 4, mass: Big("170e6"), objClass: "large-objects" },

    { name: "A train", id: 5, mass: Big("600e3"), objClass: "medium-objects" },
    { name: "An Airbus A380", id: 6, mass: Big("500e3"), objClass: "medium-objects" },
    { name: "A metro train", id: 7, mass: Big("200e3"), objClass: "medium-objects" },
    { name: "A truck", id: 8, mass: Big("20e3"), objClass: "medium-objects" },

    { name: "A blue whale", id: 9, mass: Big("19e3"), objClass: "large-animals" },
    { name: "An elephant", id: 10, mass: Big("7e3"), objClass: "large-animals" },
    { name: "A rhinoceros", id: 11, mass: Big("3.5e3"), objClass: "large-animals" },
    { name: "A hippopotamus", id: 12, mass: Big("2.5e3"), objClass: "large-animals" },
    { name: "A crocodile", id: 13, mass: Big("1e3"), objClass: "large-animals" },
    { name: "A lion", id: 14, mass: Big("2.5e2"), objClass: "large-animals" }
  ];

  function resetStuffStatus(stuff) {
    var stuffStatus = new Array(stuff.length + 1);
    for (var i = 1; i <= stuff.length; i++) { // btw, use stuffStatus.length here to make an infinite loop :-)
      stuffStatus[i] = { visible: false, compute: false };
    }
    stuffStatus[1].visible = true;
    stuffStatus[5].visible = true;
    stuffStatus[9].visible = true;
    return stuffStatus;
  }

  var stuffStatus = resetStuffStatus(stuff);

  const G = Big("6.67384e-11");
  const personMass = Big(70);
  const forceBase = G.times(personMass);
  const thousand = Big(1000);

  // http://yal.cc/string_thousands/
  function string_thousands(v) {
    var r, i;
    r = "" + v;
    for (i = r.length - 3; i > 0; i -= 3) {
      r = r.substr(0, i) + "," + r.substr(i);
    }
    return r;
  }

  var selectedPlanet;
  var equivalentDistance;

  // distance is in meters
  function showDistance(id, distance) {
    var units;
    var distanceInUnits;

    if (distance < 10) {
      // meters with millimeters
      var distanceInMillimeters = distance.times(1000).toFixed(0); // string_thousands doesn't work well with decimal digits
      var thousandifiedDistance = string_thousands(distanceInMillimeters);
      var decimalPointIndex = thousandifiedDistance.lastIndexOf(",");
      units = "m";
      distanceInUnits = thousandifiedDistance.substr(0, decimalPointIndex) + "." + thousandifiedDistance.substr(decimalPointIndex + 1, thousandifiedDistance.length);
    } else if (distance < 1000) {
      // meters
      units = "m";
      distanceInUnits = string_thousands(distance.toFixed(0));
    } else if (distance < 10000) {
      // km with meters
      var thousandifiedDistance = string_thousands(distance.toFixed(0));
      var decimalPointIndex = thousandifiedDistance.lastIndexOf(",");
      units = "km";
      distanceInUnits = thousandifiedDistance.substr(0, decimalPointIndex) + "." + thousandifiedDistance.substr(decimalPointIndex + 1, thousandifiedDistance.length);
    } else {
      // km
      units = "km";
      distanceInUnits = string_thousands(distance.div(1000).toFixed(0));
    }
    $("#stuff-" + id + " .distance").html("at " + distanceInUnits + " " + units).css({fontSize: "150%"});
  }

  function hideDistance(id) {
    $("#stuff-" + id + " .distance").css({fontSize: "0px"}).html("");
  }

  function tagFirstDistance() {
    var computedObjects = 0;
    stuff.forEach(function (thing) {
      if (stuffStatus[thing.id].compute) {
        computedObjects++;
      }
    });
    if ($("#first-distance").length == 1) {
      $("#first-distance").remove();
    }
    setTimeout(function () {
      $("p.show .distance").first().after('
pulls with the same force of ' +
                                          selectedPlanet.name + "
");
    }, 1000);
  }

  // print "number" with "digits" decimal digits
  function printDecimal(number, digits) {
    return number.toFixed(digits);
  }

  function distanceAndForce() {
    var now = new Date().getTime() / 86400000 + 2440587.5; // Julian day
    var distanceKm = Big(kmToPlanet(now, selectedPlanet.id));
    var distance = distanceKm.times(thousand); // meters
    var planetForce = forceBase.times(selectedPlanet.mass).div(distance).div(distance);
    var m2kg = forceBase.div(planetForce);

    $("#distance").html(string_thousands(distanceKm.toFixed(0)));

    // display the force with 5 non zero decimal digits
    var force = planetForce.toFixed(20);
    var i = 2;
    for (; i < force.length && force[i] == "0"; i++) {}
    $(".force-value").html(force.substr(0, i + 5));

    stuff.forEach(function (thing) {
      if (stuffStatus[thing.id].compute) {
        equivalentDistance = m2kg.times(thing.mass).sqrt();
        showDistance(thing.id, equivalentDistance);
      }
    });

  }

  var updateDistanceAndForce;

  //for (var planet of planets.values()) {
  planets.forEach(function (planet) {
    planet.img.on("click", function () {

      selectedPlanet = planet;
      $("#question-1").hide();
      $(".planet-name").html(planet.name);
      $("html, body").animate({ scrollTop: $("#first-object").offset().top }, 500);
      $("#planets").fadeOut({duration: 1000, complete: function () {
        $(".planet-image").attr({src: planet.img.attr("src")});
        $("#selected-planet").fadeIn({duration: 1000, complete: function () {
          distanceAndForce();
          $(".question-2").fadeIn(250);
          $("#reset-planet").css({visibility: "visible"});
          $("#large-objects").fadeIn(250);
          $("#medium-objects").fadeIn(250);
          $("#large-animals").fadeIn(250);
          $(".show").show();
          $(".more a").show();
          updateDistanceAndForce = setInterval(distanceAndForce, 1000);
        }});
      }});
    });
  });

  $("#reset-planet").on("click", function () {
    clearInterval(updateDistanceAndForce);
    selectedPlanet = undefined;
    $(".planet-name").html("");
    $("#selected-planet").fadeOut(250);
    $("#reset-planet").css({visibility: "hidden"});
    $(".question-2").fadeOut(250);
    $("#question-1").fadeIn(250);
    $("#planets").fadeIn(250);
    $("#large-objects").fadeOut(250);
    $("#medium-objects").fadeOut(250);
    $("#large-animals").fadeOut(250);
    stuffStatus = resetStuffStatus(stuff);
    $(".show").removeClass("show").addClass("hide");
    $(".hide").hide();
    $("#stuff-1").removeClass("hide").addClass("show");
    $("#stuff-5").removeClass("hide").addClass("show");
    $("#stuff-9").removeClass("hide").addClass("show");
    $(".distance").html("");
    $(".more").show();
  });

  stuff.forEach(function (thing) {
    $("#stuff-" + thing.id + " span.kg").html(string_thousands(thing.mass.toFixed(0)) + " kg");
  });

  $(".objects img").on("click", function () {
    var element = $(this);
    var transform1 = "rotateY(360deg)";
    var transition1Speed = "1.0s";
    var transform2 = "rotateY(0deg)";
    var transition2Speed = "0.0s";
    var delay = 1100;
    if (element.hasClass("rotate-x")) {
      transform1 = "rotateX(60deg)";
      transition1Speed = "0.25s";
      transform2 = "rotateX(0deg)";
      transition2Speed = "0.25s";
      delay = 260;
    }
    element.css({perspective: 1000, transform: transform1,
                 transition: transition1Speed, "transform-style": "preserve-3d" });
    // and reset the rotation to be able to rotate element again
    setTimeout(function() {
      element.css({perspective: 1000, transform: transform2,
                   transition: transition2Speed, "transform-style": "preserve-3d" });
    }, delay);

    var id = parseInt(element.data("stuff"), 10);
    // se è compute false, significa che era visibile ma non ancora cliccato e quindi niente distanza: si mostra la distanza
    // se è compute true, aveva la distanza calcolata: si nasconde
    var compute = stuffStatus[id].compute;
    var container = element.parent();
    if (container.siblings(".show").length == 0 && compute) {
      // if there are no other shown elements in this class of objects, don't allow to hide it
      return;
    }
    stuffStatus[id].compute = !compute; // when turned to true it allows the computation loop to display the distance
    if (compute) {
      hideDistance(id);
      container.removeClass("show").addClass("hide").fadeOut({ duration: 250, complete: function () {
        $("html, body").animate({ scrollTop: container.parent().children(".show").first().offset().top }, 500);
      }});
      container.siblings(".more").find("a").show();
    }
    tagFirstDistance();
  });

  $(".more a").on("click", function () {
    var more = $(this);
    var nextStuff = more.parents("div.objects").children("p.hide:first");
    var nextStuffImage = nextStuff.find("img");
    var id = parseInt(nextStuffImage.data("stuff"), 10);
    stuffStatus[id].visible = true;
    nextStuff.fadeIn(250);
    nextStuff.removeClass("hide").addClass("show");
    $("html, body").animate({ scrollTop: nextStuff.offset().top }, 500);
    if (more.parents("div.objects").children("p.hide:first").length == 0) {
      more.fadeOut(250);
    }
    return false;
  });

  $("#btw-1 a").on("click", function () {
    $("#btw-1").fadeOut({duration: 250, complete: function () {
      var colors = {color: "#ffffff", fontSize: "18px", lineHeight: "22px"};
      $("#btw").css(colors);
      $("#btw a").css(colors);
      $("#btw-2").fadeIn(250);
    }});
    return false;
  });
  $("#btw-2 a").on("click", function () {
    $("#btw-2 a").fadeOut({duration: 250, complete: function () {
      $("#btw-3").fadeIn(250);
    }});
    return false;
  });
  $("#btw-3 a").on("click", function () {
    $("#btw-3 a").fadeOut({duration: 250, complete: function () {
      $("#btw-4").fadeIn(250);
    }});
    return false;
  });
  $("#btw-4 a").on("click", function () {
    $("#btw-4 a").replaceWith("Do you remember that other Newton's law");
    $("#btw-5").fadeIn(250);
    return false;
  });
});
<commit_msg>Remove the explanation of the distance when changing the planet<commit_after>$(document).ready(function () {
  $("html, body").animate({ scrollTop: 0 }, 500);
  var Big = require("big.js");
  Big.DP = 30; // the digits of precision for divisions
  var printf = require("printf");

  var kmToPlanet = Module().cwrap("km_to_planet", "number", ["number", "number"]);

  const planets = [
    { name: "Mercury", id: 1, mass: Big("3.3022e23"), img: $("#planet-mercury") },
    { name: "Venus", id: 2, mass: Big("4.8676e24"), img: $("#planet-venus") },
    { name: "Mars", id: 4, mass: Big("6.4185e23"), img: $("#planet-mars") },
    { name: "Jupiter", id: 5, mass: Big("1.8986e27"), img: $("#planet-jupiter") },
    { name: "Saturn", id: 6, mass: Big("5.6846e26"), img: $("#planet-saturn") },
    { name: "Neptune", id: 7, mass: Big("1.0243e26"), img: $("#planet-neptune") },
    { name: "Uranus", id: 8, mass: Big("8.681e25"), img: $("#planet-uranus") },
    { name: "Pluto", id: 9, mass: Big("1.305e22"), img: $("#planet-pluto") }
  ];

  // display the object if it's gravitational pull >= the one of the planet at X meters
  const distanceThreshold = { "large-objects": 100, "medium-objects": 100, "large-animals": 10 };

  const stuff = [
    { name: "A super oil tanker ship", id: 1, mass: Big("650e6"), objClass: "large-objects" },
    { name: "An oil tanker ship", id: 2, mass: Big("300e6"), objClass: "large-objects" },
    { name: "A container carrier ship", id: 3, mass: Big("180e6"), objClass: "large-objects" },
    { name: "A cruise ship", id: 4, mass: Big("170e6"), objClass: "large-objects" },

    { name: "A train", id: 5, mass: Big("600e3"), objClass: "medium-objects" },
    { name: "An Airbus A380", id: 6, mass: Big("500e3"), objClass: "medium-objects" },
    { name: "A metro train", id: 7, mass: Big("200e3"), objClass: "medium-objects" },
    { name: "A truck", id: 8, mass: Big("20e3"), objClass: "medium-objects" },

    { name: "A blue whale", id: 9, mass: Big("19e3"), objClass: "large-animals" },
    { name: "An elephant", id: 10, mass: Big("7e3"), objClass: "large-animals" },
    { name: "A rhinoceros", id: 11, mass: Big("3.5e3"), objClass: "large-animals" },
    { name: "A hippopotamus", id: 12, mass: Big("2.5e3"), objClass: "large-animals" },
    { name: "A crocodile", id: 13, mass: Big("1e3"), objClass: "large-animals" },
    { name: "A lion", id: 14, mass: Big("2.5e2"), objClass: "large-animals" }
  ];

  function resetStuffStatus(stuff) {
    var stuffStatus = new Array(stuff.length + 1);
    for (var i = 1; i <= stuff.length; i++) { // btw, use stuffStatus.length here to make an infinite loop :-)
      stuffStatus[i] = { visible: false, compute: false };
    }
    stuffStatus[1].visible = true;
    stuffStatus[5].visible = true;
    stuffStatus[9].visible = true;
    return stuffStatus;
  }

  var stuffStatus = resetStuffStatus(stuff);

  const G = Big("6.67384e-11");
  const personMass = Big(70);
  const forceBase = G.times(personMass);
  const thousand = Big(1000);

  // http://yal.cc/string_thousands/
  function string_thousands(v) {
    var r, i;
    r = "" + v;
    for (i = r.length - 3; i > 0; i -= 3) {
      r = r.substr(0, i) + "," + r.substr(i);
    }
    return r;
  }

  var selectedPlanet;
  var equivalentDistance;

  // distance is in meters
  function showDistance(id, distance) {
    var units;
    var distanceInUnits;

    if (distance < 10) {
      // meters with millimeters
      var distanceInMillimeters = distance.times(1000).toFixed(0); // string_thousands doesn't work well with decimal digits
      var thousandifiedDistance = string_thousands(distanceInMillimeters);
      var decimalPointIndex = thousandifiedDistance.lastIndexOf(",");
      units = "m";
      distanceInUnits = thousandifiedDistance.substr(0, decimalPointIndex) + "." + thousandifiedDistance.substr(decimalPointIndex + 1, thousandifiedDistance.length);
    } else if (distance < 1000) {
      // meters
      units = "m";
      distanceInUnits = string_thousands(distance.toFixed(0));
    } else if (distance < 10000) {
      // km with meters
      var thousandifiedDistance = string_thousands(distance.toFixed(0));
      var decimalPointIndex = thousandifiedDistance.lastIndexOf(",");
      units = "km";
      distanceInUnits = thousandifiedDistance.substr(0, decimalPointIndex) + "." + thousandifiedDistance.substr(decimalPointIndex + 1, thousandifiedDistance.length);
    } else {
      // km
      units = "km";
      distanceInUnits = string_thousands(distance.div(1000).toFixed(0));
    }
    $("#stuff-" + id + " .distance").html("at " + distanceInUnits + " " + units).css({fontSize: "150%"});
  }

  function hideDistance(id) {
    $("#stuff-" + id + " .distance").css({fontSize: "0px"}).html("");
  }

  function tagFirstDistance() {
    var computedObjects = 0;
    stuff.forEach(function (thing) {
      if (stuffStatus[thing.id].compute) {
        computedObjects++;
      }
    });
    $("#first-distance").remove();
    setTimeout(function () {
      $("p.show .distance").first().after('
pulls with the same force of ' +
                                          selectedPlanet.name + "
");
    }, 1000);
  }

  // print "number" with "digits" decimal digits
  function printDecimal(number, digits) {
    return number.toFixed(digits);
  }

  function distanceAndForce() {
    var now = new Date().getTime() / 86400000 + 2440587.5; // Julian day
    var distanceKm = Big(kmToPlanet(now, selectedPlanet.id));
    var distance = distanceKm.times(thousand); // meters
    var planetForce = forceBase.times(selectedPlanet.mass).div(distance).div(distance);
    var m2kg = forceBase.div(planetForce);

    $("#distance").html(string_thousands(distanceKm.toFixed(0)));

    // display the force with 5 non zero decimal digits
    var force = planetForce.toFixed(20);
    var i = 2;
    for (; i < force.length && force[i] == "0"; i++) {}
    $(".force-value").html(force.substr(0, i + 5));

    stuff.forEach(function (thing) {
      if (stuffStatus[thing.id].compute) {
        equivalentDistance = m2kg.times(thing.mass).sqrt();
        showDistance(thing.id, equivalentDistance);
      }
    });

  }

  var updateDistanceAndForce;

  //for (var planet of planets.values()) {
  planets.forEach(function (planet) {
    planet.img.on("click", function () {

      selectedPlanet = planet;
      $("#question-1").hide();
      $(".planet-name").html(planet.name);
      $("html, body").animate({ scrollTop: $("#first-object").offset().top }, 500);
      $("#planets").fadeOut({duration: 1000, complete: function () {
        $(".planet-image").attr({src: planet.img.attr("src")});
        $("#selected-planet").fadeIn({duration: 1000, complete: function () {
          distanceAndForce();
          $(".question-2").fadeIn(250);
          $("#reset-planet").css({visibility: "visible"});
          $("#large-objects").fadeIn(250);
          $("#medium-objects").fadeIn(250);
          $("#large-animals").fadeIn(250);
          $(".show").show();
          $(".more a").show();
          updateDistanceAndForce = setInterval(distanceAndForce, 1000);
        }});
      }});
    });
  });

  $("#reset-planet").on("click", function () {
    clearInterval(updateDistanceAndForce);
    selectedPlanet = undefined;
    $(".planet-name").html("");
    $("#first-distance").remove();
    $("#selected-planet").fadeOut(250);
    $("#reset-planet").css({visibility: "hidden"});
    $(".question-2").fadeOut(250);
    $("#question-1").fadeIn(250);
    $("#planets").fadeIn(250);
    $("#large-objects").fadeOut(250);
    $("#medium-objects").fadeOut(250);
    $("#large-animals").fadeOut(250);
    stuffStatus = resetStuffStatus(stuff);
    $(".show").removeClass("show").addClass("hide");
    $(".hide").hide();
    $("#stuff-1").removeClass("hide").addClass("show");
    $("#stuff-5").removeClass("hide").addClass("show");
    $("#stuff-9").removeClass("hide").addClass("show");
    $(".distance").html("");
    $(".more").show();
  });

  stuff.forEach(function (thing) {
    $("#stuff-" + thing.id + " span.kg").html(string_thousands(thing.mass.toFixed(0)) + " kg");
  });

  $(".objects img").on("click", function () {
    var element = $(this);
    var transform1 = "rotateY(360deg)";
    var transition1Speed = "1.0s";
    var transform2 = "rotateY(0deg)";
    var transition2Speed = "0.0s";
    var delay = 1100;
    if (element.hasClass("rotate-x")) {
      transform1 = "rotateX(60deg)";
      transition1Speed = "0.25s";
      transform2 = "rotateX(0deg)";
      transition2Speed = "0.25s";
      delay = 260;
    }
    element.css({perspective: 1000, transform: transform1,
                 transition: transition1Speed, "transform-style": "preserve-3d" });
    // and reset the rotation to be able to rotate element again
    setTimeout(function() {
      element.css({perspective: 1000, transform: transform2,
                   transition: transition2Speed, "transform-style": "preserve-3d" });
    }, delay);

    var id = parseInt(element.data("stuff"), 10);
    // se è compute false, significa che era visibile ma non ancora cliccato e quindi niente distanza: si mostra la distanza
    // se è compute true, aveva la distanza calcolata: si nasconde
    var compute = stuffStatus[id].compute;
    var container = element.parent();
    if (container.siblings(".show").length == 0 && compute) {
      // if there are no other shown elements in this class of objects, don't allow to hide it
      return;
    }
    stuffStatus[id].compute = !compute; // when turned to true it allows the computation loop to display the distance
    if (compute) {
      hideDistance(id);
      container.removeClass("show").addClass("hide").fadeOut({ duration: 250, complete: function () {
        $("html, body").animate({ scrollTop: container.parent().children(".show").first().offset().top }, 500);
      }});
      container.siblings(".more").find("a").show();
    }
    tagFirstDistance();
  });

  $(".more a").on("click", function () {
    var more = $(this);
    var nextStuff = more.parents("div.objects").children("p.hide:first");
    var nextStuffImage = nextStuff.find("img");
    var id = parseInt(nextStuffImage.data("stuff"), 10);
    stuffStatus[id].visible = true;
    nextStuff.fadeIn(250);
    nextStuff.removeClass("hide").addClass("show");
    $("html, body").animate({ scrollTop: nextStuff.offset().top }, 500);
    if (more.parents("div.objects").children("p.hide:first").length == 0) {
      more.fadeOut(250);
    }
    return false;
  });

  $("#btw-1 a").on("click", function () {
    $("#btw-1").fadeOut({duration: 250, complete: function () {
      var colors = {color: "#ffffff", fontSize: "18px", lineHeight: "22px"};
      $("#btw").css(colors);
      $("#btw a").css(colors);
      $("#btw-2").fadeIn(250);
    }});
    return false;
  });
  $("#btw-2 a").on("click", function () {
    $("#btw-2 a").fadeOut({duration: 250, complete: function () {
      $("#btw-3").fadeIn(250);
    }});
    return false;
  });
  $("#btw-3 a").on("click", function () {
    $("#btw-3 a").fadeOut({duration: 250, complete: function () {
      $("#btw-4").fadeIn(250);
    }});
    return false;
  });
  $("#btw-4 a").on("click", function () {
    $("#btw-4 a").replaceWith("Do you remember that other Newton's law");
    $("#btw-5").fadeIn(250);
    return false;
  });
});
<|endoftext|>


<commit_before>import { LeagueActions } from '../../actions/LeagueActions';
import { LeagueStore } from '../../stores/LeagueStore';

import React, {	PropTypes, Component } from 'react';
import { Nav, NavItem } from 'react-bootstrap';
import LeagueTable from '../LeagueTable';

class League extends Component {

	constructor(props) {
		super(props);
		this.state = {
			tab: 1,
			data: []
		};
		this.updateFromStore();
	}

	updateFromStore = () => {
		let data = LeagueStore.getAll();
		if (data.length == 0) {
			return;
		}
		let table = data[0].table;
		let champion = data[1].table[0].name;
		champion = table.filter(x => x.name === champion)[0];
		champion.rowClass = 'champion';
		this.setState({
			data: table
		});
	}

  onStoreChange = (evt) => {
		this.updateFromStore();
  }

  componentDidMount = () => {
    this.unsubscribe = LeagueStore.listen(this.onStoreChange);
  }

  componentWillUnmount = () => {
  	this.unsubscribe();
  }

  handleSelect = (selectedKey) => {
  	this.setState({
  		tab: selectedKey
  	});
  }
	render = () => {
		return (

          <NavItem eventKey={1}>Current</NavItem>
          <NavItem eventKey={2}>All Time</NavItem>

        <LeagueTable data={this.state.data}/>

		);
	}
}

export default League;
<commit_msg>Different content for different tabs.<commit_after>import { LeagueActions } from '../../actions/LeagueActions';
import { LeagueStore } from '../../stores/LeagueStore';

import React, {	PropTypes, Component } from 'react';
import { Nav, NavItem } from 'react-bootstrap';
import LeagueTable from '../LeagueTable';

class League extends Component {

	constructor(props) {
		super(props);
		this.state = {
			tab: 1,
			data: []
		};
		this.updateFromStore();
	}

	updateFromStore = () => {
		let data = LeagueStore.getAll();
		if (data.length == 0) {
			return;
		}
		let table = data[0].table;
		let champion = data[1].table[0].name;
		champion = table.filter(x => x.name === champion)[0];
		champion.rowClass = 'champion';
		this.setState({
			data: table
		});
	}

  onStoreChange = (evt) => {
		this.updateFromStore();
  }

  componentDidMount = () => {
    this.unsubscribe = LeagueStore.listen(this.onStoreChange);
  }

  componentWillUnmount = () => {
  	this.unsubscribe();
  }

  handleSelect = (selectedKey) => {
  	this.setState({
  		tab: selectedKey
  	});
  }
	render = () => {
		var content;
		if (this.state.tab === 1) {
			content = <LeagueTable data={this.state.data}/>;
		}
		else {
			content = ;
		}
		return (

          <NavItem eventKey={1}>Current</NavItem>
          <NavItem eventKey={2}>All Time</NavItem>

				{content}

		);
	}
}

export default League;
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  Modal,
  TouchableWithoutFeedback,
  Animated,
} from 'react-native';
import { globalStyleVariables } from '../styles';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'flex-end',
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
  },
  innerContainer: {
    paddingHorizontal: 16,
    paddingVertical: 8,
    backgroundColor: '#fff',
  },
});

class PXBottomSheet extends Component {
  static defaultProps = {
    duration: 300,
    height: globalStyleVariables.WINDOW_HEIGHT -
      globalStyleVariables.APPBAR_HEIGHT -
      globalStyleVariables.STATUSBAR_HEIGHT,
  };

  constructor(props) {
    super(props);
    this.state = {
      animatedHeight: new Animated.Value(0),
      modalVisible: false,
    };
  }

  componentWillReceiveProps(nextProps) {
    const { visible } = nextProps;
    const { visible: prevVisible } = this.props;
    if (visible !== null && visible !== prevVisible) {
      this.setModalVisible(visible);
    }
  }

  setModalVisible = visible => {
    const { height, duration } = this.props;
    const { modalVisible, animatedHeight } = this.state;
    if (visible && !modalVisible) {
      this.setState({ modalVisible: visible });
      // if want to support orientation
      // const newHeight = height || (Dimensions.get('window').height - APPBAR_HEIGHT - STATUSBAR_HEIGHT);
      Animated.timing(animatedHeight, {
        toValue: height,
        duration,
      }).start();
    } else if (!visible && modalVisible) {
      Animated.timing(animatedHeight, {
        toValue: 0,
        duration,
      }).start(() => {
        this.setState({ modalVisible: visible });
      });
    }
  };

  render() {
    const { children, onCancel } = this.props;
    const { animatedHeight, modalVisible } = this.state;
    return (
      <Modal
        transparent
        visible={modalVisible}
        onRequestClose={() => this.setModalVisible(false)}
        animationType="none"
        supportedOrientations={[
          'portrait',
          'portrait-upside-down',
          'landscape',
          'landscape-left',
          'landscape-right',
        ]}
      >
        <TouchableWithoutFeedback onPress={onCancel}>
          <View style={styles.container}>
            <Animated.View
              style={[styles.innerContainer, { maxHeight: animatedHeight }]}
            >
              <TouchableWithoutFeedback>
                {children}
              </TouchableWithoutFeedback>
            </Animated.View>
          </View>
        </TouchableWithoutFeedback>
      </Modal>
    );
  }
}

export default PXBottomSheet;
<commit_msg>added fade animation to bottom sheet<commit_after>import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  Modal,
  TouchableWithoutFeedback,
  Animated,
} from 'react-native';
import { globalStyleVariables } from '../styles';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'flex-end',
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
  },
  innerContainer: {
    paddingHorizontal: 16,
    paddingVertical: 8,
    backgroundColor: '#fff',
  },
});

class PXBottomSheet extends Component {
  static defaultProps = {
    duration: 300,
    height: globalStyleVariables.WINDOW_HEIGHT -
      globalStyleVariables.APPBAR_HEIGHT -
      globalStyleVariables.STATUSBAR_HEIGHT,
  };

  constructor(props) {
    super(props);
    this.state = {
      animatedHeight: new Animated.Value(0),
      modalVisible: false,
    };
  }

  componentWillReceiveProps(nextProps) {
    const { visible } = nextProps;
    const { visible: prevVisible } = this.props;
    if (visible !== null && visible !== prevVisible) {
      this.setModalVisible(visible);
    }
  }

  setModalVisible = visible => {
    const { height, duration } = this.props;
    const { modalVisible, animatedHeight } = this.state;
    if (visible && !modalVisible) {
      this.setState({ modalVisible: visible });
      // if want to support orientation
      // const newHeight = height || (Dimensions.get('window').height - APPBAR_HEIGHT - STATUSBAR_HEIGHT);
      Animated.timing(animatedHeight, {
        toValue: height,
        duration,
      }).start();
    } else if (!visible && modalVisible) {
      Animated.timing(animatedHeight, {
        toValue: 0,
        duration,
      }).start(() => {
        this.setState({ modalVisible: visible });
      });
    }
  };

  handleOnCloseModal = () => {
    this.setModalVisible(false);
  };

  render() {
    const { children, onCancel } = this.props;
    const { animatedHeight, modalVisible } = this.state;
    return (
      <Modal
        transparent
        visible={modalVisible}
        onRequestClose={this.handleOnCloseModal}
        animationType="fade"
        supportedOrientations={[
          'portrait',
          'portrait-upside-down',
          'landscape',
          'landscape-left',
          'landscape-right',
        ]}
      >
        <TouchableWithoutFeedback onPress={onCancel}>
          <View style={styles.container}>
            <Animated.View
              style={[styles.innerContainer, { maxHeight: animatedHeight }]}
            >
              <TouchableWithoutFeedback>
                {children}
              </TouchableWithoutFeedback>
            </Animated.View>
          </View>
        </TouchableWithoutFeedback>
      </Modal>
    );
  }
}

export default PXBottomSheet;
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { Popover } from 'antd';
import PopoverMenu, { PopoverMenuItem } from './PopoverMenu/PopoverMenu';
import Topic from './Button/Topic';
import './TopicSelector.less';

class TopicSelector extends React.Component {
  static propTypes = {
    topics: PropTypes.arrayOf(PropTypes.string),
    onTopicClose: PropTypes.func,
    onSortChange: PropTypes.func
  }

  static defaultProps = {
    topics: [],
    onTopicClose: () => {},
    onSortChange: () => {},
  }

  state = {
    currentSort: 'trending',
    popoverVisible: false
  }

  onSelect = (key) => {
    this.setState({ currentSort: key, popoverVisible: false }, () => {
      this.props.onSortChange(key);
    });
  };
  onVisibleChange = visible => this.setState({ popoverVisible: visible });

  render() {
    const { topics, onTopicClose } = this.props;
    const { currentSort, popoverVisible } = this.state;

    return (

          {topics && topics.map(topic => (
            <Topic
              key={topic}
              closable
              name={topic}
              onClose={onTopicClose}
            />))}

          Sort by:
          <Popover
            trigger="click"
            visible={popoverVisible}
            onVisibleChange={this.onVisibleChange}
            content={
              <PopoverMenu onSelect={this.onSelect}>
                <PopoverMenuItem key="trending">Trending</PopoverMenuItem>
                <PopoverMenuItem key="created">Created</PopoverMenuItem>
                <PopoverMenuItem key="active">Active</PopoverMenuItem>
                <PopoverMenuItem key="cashout">Active</PopoverMenuItem>
                <PopoverMenuItem key="votes">Votes</PopoverMenuItem>
                <PopoverMenuItem key="children">Children</PopoverMenuItem>
                <PopoverMenuItem key="hot">Hot</PopoverMenuItem>
                <PopoverMenuItem key="comments">Comments</PopoverMenuItem>
                <PopoverMenuItem key="promoted">Promoted</PopoverMenuItem>
              </PopoverMenu>
            }
          >

              {currentSort.charAt(0).toUpperCase() + currentSort.slice(1)}

          </Popover>

    );
  }
}

export default TopicSelector;
<commit_msg>Fix Sorting menu label<commit_after>import React, { PropTypes } from 'react';
import { Popover } from 'antd';
import PopoverMenu, { PopoverMenuItem } from './PopoverMenu/PopoverMenu';
import Topic from './Button/Topic';
import './TopicSelector.less';

class TopicSelector extends React.Component {
  static propTypes = {
    topics: PropTypes.arrayOf(PropTypes.string),
    onTopicClose: PropTypes.func,
    onSortChange: PropTypes.func
  }

  static defaultProps = {
    topics: [],
    onTopicClose: () => {},
    onSortChange: () => {},
  }

  state = {
    currentSort: 'trending',
    popoverVisible: false
  }

  onSelect = (key) => {
    this.setState({ currentSort: key, popoverVisible: false }, () => {
      this.props.onSortChange(key);
    });
  };
  onVisibleChange = visible => this.setState({ popoverVisible: visible });

  render() {
    const { topics, onTopicClose } = this.props;
    const { currentSort, popoverVisible } = this.state;

    return (

          {topics && topics.map(topic => (
            <Topic
              key={topic}
              closable
              name={topic}
              onClose={onTopicClose}
            />))}

          Sort by:
          <Popover
            trigger="click"
            visible={popoverVisible}
            onVisibleChange={this.onVisibleChange}
            content={
              <PopoverMenu onSelect={this.onSelect}>
                <PopoverMenuItem key="trending">Trending</PopoverMenuItem>
                <PopoverMenuItem key="created">Created</PopoverMenuItem>
                <PopoverMenuItem key="active">Active</PopoverMenuItem>
                <PopoverMenuItem key="cashout">Cashout</PopoverMenuItem>
                <PopoverMenuItem key="votes">Votes</PopoverMenuItem>
                <PopoverMenuItem key="children">Children</PopoverMenuItem>
                <PopoverMenuItem key="hot">Hot</PopoverMenuItem>
                <PopoverMenuItem key="comments">Comments</PopoverMenuItem>
                <PopoverMenuItem key="promoted">Promoted</PopoverMenuItem>
              </PopoverMenu>
            }
          >

              {currentSort.charAt(0).toUpperCase() + currentSort.slice(1)}

          </Popover>

    );
  }
}

export default TopicSelector;
<|endoftext|>


<commit_before>angular
	.module('scraper', [ 'ui.router', 'angularFileUpload', 'ngSanitize', 'ngCsv'])

	.config(function($stateProvider, $urlRouterProvider) {

		// $urlRouterProvider.when('', 'home');
		// $urlRouterProvider.otherwise('/home')

	  	$stateProvider
		    .state('index', {
		      url: "/home",
      		  templateUrl: "./assets/landing.html"
		    })
		    .state('tnt', {
		      url: "/tnt",
		      templateUrl: './assets/radio.html',
		      abstract: true
		    })
		    .state('tnt.view', {
		    	url: '/other',
				views: {
					'tnt': {
						templateUrl: './assets/tnt.html',
						controller: 'tnt',
						controllerAs: 'tnt'
					},
					'tntlast': {
						templateUrl: './assets/tntlast.html',
						controller: 'tntlast',
						controllerAs: 'tntlast'
					}
				}
		    })
		    .state('startrack', {
		      url: "/startrack",
      		  templateUrl: "./assets/startrack.html",
      		  controller: "startrack",
      		  controllerAs: "startrack"
		    })
	})

	.factory('Add', function ($http, $location, $rootScope) {
		return {

			ship: function shipFile(data) {
				console.log('DATA COMING IN');
				console.log(data);
				return $http.post('/api/load', data).success(function (data) {
					console.log('DATA FIRED OUT');
					console.log(data);
				}).error(function (err) {
					console.info('error', err)
				});
			},
			exportExcel: function () {
				$http({method: 'GET', url: "/api/export",
				headers: {'Content-Type': "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
		        responseType: "arraybuffer"}).
		        success(function(data, status, headers, config) {
		            saveAs(new Blob([data],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}), "excel111.xlsx");
		        }).error(function(data, status, headers, config) {

				});
			}

		};
	})

<commit_msg>added route config<commit_after>angular
	.module('scraper', [ 'ui.router', 'angularFileUpload', 'ngSanitize', 'ngCsv'])

	.config(function($stateProvider, $urlRouterProvider) {

		// $urlRouterProvider.when('', 'home');
		$urlRouterProvider.otherwise('/home')

	  	$stateProvider
		    .state('index', {
		      url: "/home",
      		  templateUrl: "./assets/landing.html"
		    })
		    .state('tnt', {
		      url: "/tnt",
		      templateUrl: './assets/radio.html',
		      abstract: true
		    })
		    .state('tnt.view', {
		    	url: '/other',
				views: {
					'tnt': {
						templateUrl: './assets/tnt.html',
						controller: 'tnt',
						controllerAs: 'tnt'
					},
					'tntlast': {
						templateUrl: './assets/tntlast.html',
						controller: 'tntlast',
						controllerAs: 'tntlast'
					}
				}
		    })
		    .state('startrack', {
		      url: "/startrack",
      		  templateUrl: "./assets/startrack.html",
      		  controller: "startrack",
      		  controllerAs: "startrack"
		    })
	})

	.factory('Add', function ($http, $location, $rootScope) {
		return {

			ship: function shipFile(data) {
				console.log('DATA COMING IN');
				console.log(data);
				return $http.post('/api/load', data).success(function (data) {
					console.log('DATA FIRED OUT');
					console.log(data);
				}).error(function (err) {
					console.info('error', err)
				});
			},
			exportExcel: function () {
				$http({method: 'GET', url: "/api/export",
				headers: {'Content-Type': "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
		        responseType: "arraybuffer"}).
		        success(function(data, status, headers, config) {
		            saveAs(new Blob([data],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}), "excel111.xlsx");
		        }).error(function(data, status, headers, config) {

				});
			}

		};
	})

<|endoftext|>


<commit_before>'use strict';

var util = require('util');
var Lego = require('./lego');
var LegoPassthrough = require('./lego-passthrough');

function LegoContainer() {
  Lego.call(this);
  this.legos = [];

  Object.defineProperty(this, '_left', {
    value: new LegoPassthrough()
  });
  Object.defineProperty(this, '_right', {
    value: new LegoPassthrough()
  });

  this.on('available', this._left.input);
  this._right.on('data', this.output);
  this._left.snap(this._right);
}

util.inherits(LegoContainer, Lego);

LegoContainer.prototype.deconstruct = function deconstruct() {
  this._left.removeAllListeners('data');
  if (this.legos.length) {
    this.legos[this.legos.length - 1].removeListener('data', this._right);
  }

  for (var i = 0, len = this.legos.length - 1; i < len; i++) {
    var legoFrom = this.legos[i];
    var legoTo = this.legos[i + 1];
    legoFrom.unsnap(legoTo);
  }
};

LegoContainer.prototype.construct = function construct() {
  for (var i = 0, len = this.legos.length - 1; i < len; i++) {
    var legoFrom = this.legos[i];
    var legoTo = this.legos[i + 1];
    legoFrom.snap(legoTo);
  }

  if (this.legos.length) {
    this._left.snap(this.legos[0]);
    this.legos[this.legos.length - 1].snap(this._right);
  } else {
    this._left.snap(this._right);
  }
};

LegoContainer.prototype.push = function push(lego) {
  this.deconstruct();
  var res = Array.prototype.push.apply(this.legos, arguments);
  this.construct();
  return res;
};

LegoContainer.prototype.pop = function pop(lego) {
  this.deconstruct();
  var res = this.legos.push(lego);
  this.construct();
  return res;
};

LegoContainer.prototype.splice = function splice(start, del) {
  this.deconstruct();
  var res = Array.prototype.splice.apply(this.legos, arguments);
  this.construct();
  return res;
};

module.exports = LegoContainer;
<commit_msg>fixed deconstruct _right<commit_after>'use strict';

var util = require('util');
var Lego = require('./lego');
var LegoPassthrough = require('./lego-passthrough');

function LegoContainer() {
  Lego.call(this);
  this.legos = [];

  Object.defineProperty(this, '_left', {
    value: new LegoPassthrough()
  });
  Object.defineProperty(this, '_right', {
    value: new LegoPassthrough()
  });

  this.on('available', this._left.input);
  this._right.on('data', this.output);
  this._left.snap(this._right);
}

util.inherits(LegoContainer, Lego);

LegoContainer.prototype.deconstruct = function deconstruct() {
  this._left.removeAllListeners('data');
  if (this.legos.length) {
    this.legos[this.legos.length - 1].unsnap(this._right);
  }

  for (var i = 0, len = this.legos.length - 1; i < len; i++) {
    var legoFrom = this.legos[i];
    var legoTo = this.legos[i + 1];
    legoFrom.unsnap(legoTo);
  }
};

LegoContainer.prototype.construct = function construct() {
  for (var i = 0, len = this.legos.length - 1; i < len; i++) {
    var legoFrom = this.legos[i];
    var legoTo = this.legos[i + 1];
    legoFrom.snap(legoTo);
  }

  if (this.legos.length) {
    this._left.snap(this.legos[0]);
    this.legos[this.legos.length - 1].snap(this._right);
  } else {
    this._left.snap(this._right);
  }
};

LegoContainer.prototype.push = function push(lego) {
  this.deconstruct();
  var res = Array.prototype.push.apply(this.legos, arguments);
  this.construct();
  return res;
};

LegoContainer.prototype.pop = function pop(lego) {
  this.deconstruct();
  var res = this.legos.push(lego);
  this.construct();
  return res;
};

LegoContainer.prototype.splice = function splice(start, del) {
  this.deconstruct();
  var res = Array.prototype.splice.apply(this.legos, arguments);
  this.construct();
  return res;
};

module.exports = LegoContainer;
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import CSSModules from 'react-css-modules';

import Name from './Name';
import PeerDetails from './PeerDetails';
import ProgressBar from './ProgressBar';
import ProgressDetails from './ProgressDetails';

import styles from './styles';

class Torrent extends Component {
  render() {
    const torrent = this.props.torrent;

    return (

        <Name torrent={torrent} />
        <PeerDetails torrent={torrent} />
        <ProgressBar torrent={torrent} />
        <ProgressDetails torrent={torrent} />

    );
  }
}

export default CSSModules(Torrent, styles);
<commit_msg>Use decorator syntax<commit_after>import React, { Component } from 'react';
import CSSModules from 'react-css-modules';

import Name from './Name';
import PeerDetails from './PeerDetails';
import ProgressBar from './ProgressBar';
import ProgressDetails from './ProgressDetails';

import styles from './styles';

@CSSModules(styles)
class Torrent extends Component {
  render() {
    const torrent = this.props.torrent;

    return (

        <Name torrent={torrent} />
        <PeerDetails torrent={torrent} />
        <ProgressBar torrent={torrent} />
        <ProgressDetails torrent={torrent} />

    );
  }
}

export default Torrent;
<|endoftext|>


<commit_before>const functions = require('firebase-functions')
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)

exports.createPlayer = functions.auth.user().onCreate(event => {
  return admin.database()
    .ref('/players')
    .child(event.data.uid)
    .set({
      email: event.data.email,
      displayName: event.data.displayName,
      photoURL: event.data.photoURL,
      rating: 750
    })
})
exports.createMatch = functions.database.ref('/users/{userUid}/open-matches/{matchUid}')
  .onWrite(event => {
    if (event.auth.admin || event.data.previous.exists() || !event.data.exists()) { return }

    let match = event.data.val()
    if (match.player1Uid === match.player2Uid) { return }

    match.createdDate = new Date().toISOString()
    let details = {
      player1Uid: match.player1Uid,
      player2Uid: match.player2Uid,
      createdDate: match.createdDate,
      approvals: {player1: '', player2: ''},
      scores: {player1: 0, player2: 0}
    }

    return Promise.all([
      admin.database()
        .ref(`/users/${match.player1Uid}/open-matches`)
        .child(event.params.matchUid)
        .set(match),
      admin.database()
        .ref(`/users/${match.player2Uid}/open-matches`)
        .child(event.params.matchUid)
        .set(match),
      admin.database()
        .ref(`/open-match-details/${event.params.matchUid}`)
        .set(details)
    ])
  })
exports.rejectMatch = functions.database.ref('/open-match-details/{matchUid}/rejected')
  .onWrite(event => {
    if (event.auth.admin || !event.data.exists() || !event.data.val()) { return }

    return admin.database().ref(`/open-match-details/${event.params.matchUid}`)
      .once('value')
      .then((snap) => {
        let details = snap.val()
        return Promise.all([
          admin.database()
            .ref(`/users/${details.player1Uid}/open-matches/${event.params.matchUid}`)
            .set(null),
          admin.database()
            .ref(`/users/${details.player2Uid}/open-matches/${event.params.matchUid}`)
            .set(null),
          admin.database()
            .ref(`/open-match-details/${event.params.matchUid}`)
            .set(null)
        ])
      })
  })
exports.approvalsChanged = functions.database.ref('/open-match-details/{matchUid}/approvals')
  .onWrite((event) => {
    if (event.auth.admin || !event.data.exists() || !event.data.previous.exists()) { return }

    let approvals = event.data.val()
    if (!approvals.player1 || !approvals.player2) { return }

    return admin.database().ref(`/open-match-details/${event.params.matchUid}`)
      .once('value')
      .then((snap) => {
        let details = snap.val()
        let closingApproval = `${details.scores.player1}|${details.scores.player2}`
        if (closingApproval !== details.approvals.player1 ||
          closingApproval !== details.approvals.player2) {
          return
        }

        let finalMatch = {
          finalizedDate: new Date().toISOString(),
          createdDate: details.createdDate,
          player1Uid: details.player1Uid,
          player2Uid: details.player2Uid,
          scores: details.scores
        }
        return Promise.all([
          admin.database().ref(`/matches/${event.params.matchUid}`).set(finalMatch),
          admin.database().ref(`/users/${details.player1Uid}/matches/${event.params.matchUid}`).set(finalMatch),
          admin.database().ref(`/users/${details.player2Uid}/matches/${event.params.matchUid}`).set(finalMatch),
          admin.database().ref(`/users/${details.player1Uid}/open-matches/${event.params.matchUid}`).set(null),
          admin.database().ref(`/users/${details.player2Uid}/open-matches/${event.params.matchUid}`).set(null),
          admin.database().ref(`/open-match-details/${event.params.matchUid}`).set(null)
        ])
      })
  })
exports.updateRating = functions.database.ref('/matches/{matchUid}')
  .onWrite(event => {
    if (event.data.previous.exists() || !event.data.exists()) { return }

    let match = event.data.val()
    return Promise.all([
      admin.database().ref(`/players/${match.player1Uid}`).once('value'),
      admin.database().ref(`/players/${match.player2Uid}`).once('value')
    ]).then((playerRefs) => {
      let p1Rating = playerRefs[0].val().rating
      let p2Rating = playerRefs[1].val().rating
      let p1Score = Number(match.scores.player1)
      let p2Score = Number(match.scores.player2)
      let p1Prob = calcProbability(p1Rating, p2Rating)
      let p2Prob = calcProbability(p2Rating, p1Rating)
      let kFactor = 50 * calcKFactorMultiplier(p1Score, p2Score, p1Rating, p2Rating)

      let player1NewRating = calcNewRating(
        p1Prob, p1Score > p2Score ? 1 : p1Score < p2Score ? 0 : 0.5,
        p1Rating, kFactor
      )
      let player2NewRating = calcNewRating(
        p2Prob, p2Score > p1Score ? 1 : p2Score < p1Score ? 0 : 0.5,
        p2Rating, kFactor
      )
      let ratings = {
        player1Prev: p1Rating,
        player2Prev: p2Rating,
        player1New: player1NewRating,
        player2New: player2NewRating
      }

      return Promise.all([
        admin.database().ref(`/players/${match.player1Uid}/rating`)
          .set(player1NewRating),
        admin.database().ref(`/players/${match.player2Uid}/rating`)
          .set(player2NewRating),
        admin.database().ref(`/matches/${event.params.matchUid}/ratings`)
          .set(ratings),
        admin.database().ref(`/users/${match.player1Uid}/matches/${event.params.matchUid}/ratings`)
          .set(ratings),
        admin.database().ref(`/users/${match.player2Uid}/matches/${event.params.matchUid}/ratings`)
          .set(ratings)
      ])
    })
  })

let calcKFactorMultiplier = (score1, score2, rating1, rating2) => {
  let diff = Math.log(Math.abs(score1 - score2) + 1)
  let ratingDiff = score1 > score2 ? rating1 - rating2 : rating2 - rating1
  return diff * (2.2 / (ratingDiff * 0.01 + 2.2))
}
let calcNewRating = (expected, actual, current, kFactor) => {
  return Math.round(current + kFactor * (actual - expected))
}
let calcProbability = (rating1, rating2) => {
  return 1 / (1 + Math.pow(10, ((rating2 - rating1) / 400)))
}
<commit_msg>Moved back to 0.001 for multiplier<commit_after>const functions = require('firebase-functions')
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)

exports.createPlayer = functions.auth.user().onCreate(event => {
  return admin.database()
    .ref('/players')
    .child(event.data.uid)
    .set({
      email: event.data.email,
      displayName: event.data.displayName,
      photoURL: event.data.photoURL,
      rating: 750
    })
})
exports.createMatch = functions.database.ref('/users/{userUid}/open-matches/{matchUid}')
  .onWrite(event => {
    if (event.auth.admin || event.data.previous.exists() || !event.data.exists()) { return }

    let match = event.data.val()
    if (match.player1Uid === match.player2Uid) { return }

    match.createdDate = new Date().toISOString()
    let details = {
      player1Uid: match.player1Uid,
      player2Uid: match.player2Uid,
      createdDate: match.createdDate,
      approvals: {player1: '', player2: ''},
      scores: {player1: 0, player2: 0}
    }

    return Promise.all([
      admin.database()
        .ref(`/users/${match.player1Uid}/open-matches`)
        .child(event.params.matchUid)
        .set(match),
      admin.database()
        .ref(`/users/${match.player2Uid}/open-matches`)
        .child(event.params.matchUid)
        .set(match),
      admin.database()
        .ref(`/open-match-details/${event.params.matchUid}`)
        .set(details)
    ])
  })
exports.rejectMatch = functions.database.ref('/open-match-details/{matchUid}/rejected')
  .onWrite(event => {
    if (event.auth.admin || !event.data.exists() || !event.data.val()) { return }

    return admin.database().ref(`/open-match-details/${event.params.matchUid}`)
      .once('value')
      .then((snap) => {
        let details = snap.val()
        return Promise.all([
          admin.database()
            .ref(`/users/${details.player1Uid}/open-matches/${event.params.matchUid}`)
            .set(null),
          admin.database()
            .ref(`/users/${details.player2Uid}/open-matches/${event.params.matchUid}`)
            .set(null),
          admin.database()
            .ref(`/open-match-details/${event.params.matchUid}`)
            .set(null)
        ])
      })
  })
exports.approvalsChanged = functions.database.ref('/open-match-details/{matchUid}/approvals')
  .onWrite((event) => {
    if (event.auth.admin || !event.data.exists() || !event.data.previous.exists()) { return }

    let approvals = event.data.val()
    if (!approvals.player1 || !approvals.player2) { return }

    return admin.database().ref(`/open-match-details/${event.params.matchUid}`)
      .once('value')
      .then((snap) => {
        let details = snap.val()
        let closingApproval = `${details.scores.player1}|${details.scores.player2}`
        if (closingApproval !== details.approvals.player1 ||
          closingApproval !== details.approvals.player2) {
          return
        }

        let finalMatch = {
          finalizedDate: new Date().toISOString(),
          createdDate: details.createdDate,
          player1Uid: details.player1Uid,
          player2Uid: details.player2Uid,
          scores: details.scores
        }
        return Promise.all([
          admin.database().ref(`/matches/${event.params.matchUid}`).set(finalMatch),
          admin.database().ref(`/users/${details.player1Uid}/matches/${event.params.matchUid}`).set(finalMatch),
          admin.database().ref(`/users/${details.player2Uid}/matches/${event.params.matchUid}`).set(finalMatch),
          admin.database().ref(`/users/${details.player1Uid}/open-matches/${event.params.matchUid}`).set(null),
          admin.database().ref(`/users/${details.player2Uid}/open-matches/${event.params.matchUid}`).set(null),
          admin.database().ref(`/open-match-details/${event.params.matchUid}`).set(null)
        ])
      })
  })
exports.updateRating = functions.database.ref('/matches/{matchUid}')
  .onWrite(event => {
    if (event.data.previous.exists() || !event.data.exists()) { return }

    let match = event.data.val()
    return Promise.all([
      admin.database().ref(`/players/${match.player1Uid}`).once('value'),
      admin.database().ref(`/players/${match.player2Uid}`).once('value')
    ]).then((playerRefs) => {
      let p1Rating = playerRefs[0].val().rating
      let p2Rating = playerRefs[1].val().rating
      let p1Score = Number(match.scores.player1)
      let p2Score = Number(match.scores.player2)
      let p1Prob = calcProbability(p1Rating, p2Rating)
      let p2Prob = calcProbability(p2Rating, p1Rating)
      let kFactor = 50 * calcKFactorMultiplier(p1Score, p2Score, p1Rating, p2Rating)

      let player1NewRating = calcNewRating(
        p1Prob, p1Score > p2Score ? 1 : p1Score < p2Score ? 0 : 0.5,
        p1Rating, kFactor
      )
      let player2NewRating = calcNewRating(
        p2Prob, p2Score > p1Score ? 1 : p2Score < p1Score ? 0 : 0.5,
        p2Rating, kFactor
      )
      let ratings = {
        player1Prev: p1Rating,
        player2Prev: p2Rating,
        player1New: player1NewRating,
        player2New: player2NewRating
      }

      return Promise.all([
        admin.database().ref(`/players/${match.player1Uid}/rating`)
          .set(player1NewRating),
        admin.database().ref(`/players/${match.player2Uid}/rating`)
          .set(player2NewRating),
        admin.database().ref(`/matches/${event.params.matchUid}/ratings`)
          .set(ratings),
        admin.database().ref(`/users/${match.player1Uid}/matches/${event.params.matchUid}/ratings`)
          .set(ratings),
        admin.database().ref(`/users/${match.player2Uid}/matches/${event.params.matchUid}/ratings`)
          .set(ratings)
      ])
    })
  })

let calcKFactorMultiplier = (score1, score2, rating1, rating2) => {
  let diff = Math.log(Math.abs(score1 - score2) + 1)
  let ratingDiff = score1 > score2 ? rating1 - rating2 : rating2 - rating1
  return diff * (2.2 / (ratingDiff * 0.001 + 2.2))
}
let calcNewRating = (expected, actual, current, kFactor) => {
  return Math.round(current + kFactor * (actual - expected))
}
let calcProbability = (rating1, rating2) => {
  return 1 / (1 + Math.pow(10, ((rating2 - rating1) / 400)))
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Table } from 'react-bootstrap';

class AllTaskList extends Component {
    renderTasks() {
        const {tasks} = this.props.tasks;
        console.log('task to show', tasks);
        return (

Basic Table Layout

                        Task
                        Task Status

                    {
                        tasks.map(task => {
                            return(

                                    {task.task}
                                     Not implemented yet

                            );
                        })
                    }

        );
    }
    render() {
        return(

{this.renderTasks()}

        );
    };
}

function mapStateToProps(state) {
    console.log('mapStateToProps: ', state);
    return {tasks: state}
}

export default connect(mapStateToProps, null)(AllTaskList);<commit_msg>update all task list view<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Table, Panel } from 'react-bootstrap';

class AllTaskList extends Component {
    renderTasks() {
        const {tasks} = this.props.tasks;
        console.log('task to show', tasks);
        return (

                        Task
                        Task Status

                    {
                        tasks.map(task => {
                            return(

                                    {task.task}
                                     Not implemented yet

                            );
                        })
                    }

        );
    }
    render() {
        return(
            <Panel header='All Task List todo' bsStyle="primary">
                {this.renderTasks()}
            </Panel>
        );
    };
}

function mapStateToProps(state) {
    console.log('mapStateToProps: ', state);
    return {tasks: state}
}

export default connect(mapStateToProps, null)(AllTaskList);<|endoftext|>


<commit_before>/**
 * Create a console logger w/ formatting, timestamp, color, namespace
 *
 * Licensed under MIT.
 * Copyright (c) 2013 David Smith <https://github.com/codeactual/>
 */

/*jshint node:true*/
'use strict';

module.exports = {
  LongCon: LongCon,
  create: function() { return new LongCon(); },
  extend: function(ext) { extend(LongCon.prototype, ext); }
};

var clc = require('cli-color');
var util = require('util');
var sprintf = util.format;

var requireComponent = require('../component/require');
var configurable = requireComponent('configurable.js');
var extend  = requireComponent('extend');
var tea = requireComponent('tea-properties');
var getProp = tea.get;
var setProp = tea.set;

function create() {
  return new LongCon();
}

function LongCon() {
  this.settings = {
    namespace: '', // Prepend to each message
    nlFirst: false, // Prepend \n to first log
    quiet: false,
    time: true, // Prepend toUTCString()
    traceIndent: '    ', // Represent a trace level
    traceLanes: true // Prepend each traceIndent with '|'
  };

  this.traceDepth = 0;
  this.firstLine = true;
}

configurable(LongCon.prototype);

/**
 * util.format() wrapper with timestamp and injected output function.
 * Respects --quiet. Applies color selection.
 *
 * @param {string} name Source logger's name, ex. 'stderr'
 * @param {function} fn Ex. console.log
 * @param {string} color cli-color selection, ex. 'red.bold' or 'yellow'
 * @param {boolean} colorBody Apply color to log body in addition to name
 * @param {mixed} args* For util.format()
 */
LongCon.prototype.log = function(name, fn, color, colorBody) {
  if (this.get('quiet')) { return; }
  var colorFn = color ? getProp(clc, color) : defColorFn;
  var bodyColorFn = colorBody ? colorFn : defColorFn;
  var namespace = this.get('namespace');
  var indent = '';

  // Apply trace levels to indentation if push() and pop() were used.
  var traceIndent = this.get('traceIndent');
  var laneCx = traceIndent.length;
  indent = (new Array(this.traceDepth + 1)).join(traceIndent);
  if (this.get('traceLanes')) { // Prepend '|' to  every traceIndent section
    indent = indent.replace(new RegExp('.{1,' + laneCx + '}', 'g'), '|$&');
  }

  var sections = [
    indent,
    this.get('time') ? '[' + (new Date()).toUTCString() + '] ' : '',
    namespace ? namespace + ' ' : '',
    name ? colorFn(name) + ' ' : '',
    bodyColorFn(sprintf.apply(null, [].slice.call(arguments, 4)))
  ];
  var joined = sections.join('');

  // Ensure 1st line starts at col 0 for lane alignment
  if (this.firstLine && this.get('nlFirst')) {
    joined = '\n' + joined;
    this.firstLine = false;
  }

  fn(joined);
};

/**
 * Create a log() wrapper with fixed arguments.
 *
 * @param {string} name Source logger's name, ex. 'stderr'
 * @param {function} fn Ex. console.log
 * @param {string} color cli-color selection, ex. 'red.bold' or 'yellow'
 * @param {boolean} colorBody Apply color to log body in addition to name
 * @return {function} Accepts util.format() arguments
 *   {function} push: Accepts same args. Pushes a trace level.
 *   {function} pop: Accepts same args. Pops a trace level.
 */
LongCon.prototype.create = function(name, fn, color, colorBody) {
  var self = this;
  function logger() {
    self.log.apply(self, [name, fn, color, colorBody].concat([].slice.call(arguments)));
  }
  logger.push = function longConPush() {
    logger.apply(self, arguments); self.traceDepth++;
  };
  logger.pop = function longConPop() {
    self.traceDepth--;
    if (arguments.length) { logger.apply(self, arguments); }
  };
  return logger;
};

/**
 * Wrap an object's methods to automatically push/pop for (sync) tracing.
 *
 * @param {string} name Uniquely identify the object
 * @param {object} obj
 * @param {function} Logger from create()
 * @param {regexp} filter Include matching key names
 * @param {regexp} omit Exclude matching key names
 */
LongCon.prototype.traceMethods = function(name, obj, logger, filter, omit) {
  var self = this;
  filter = filter || /.?/;
  omit = omit || /a^/;
  Object.keys(obj).forEach(function longConTraceMethodsIter(key) {
    if (typeof obj[key] !== 'function') { return; }
    if (!filter.test(key)) { return; }
    if (omit.test(key)) { return; }
    var orig = obj[key];
    obj[key] = function longConTraceMethodsWrapper() {
      logger.push(name + '#' + key);
      var res = orig.apply(this, arguments);
      logger.pop();
      return res;
    };
  });
};

function defColorFn(str) { return str; }
<commit_msg>feat(timestamp): Omit by default<commit_after>/**
 * Create a console logger w/ formatting, timestamp, color, namespace
 *
 * Licensed under MIT.
 * Copyright (c) 2013 David Smith <https://github.com/codeactual/>
 */

/*jshint node:true*/
'use strict';

module.exports = {
  LongCon: LongCon,
  create: function() { return new LongCon(); },
  extend: function(ext) { extend(LongCon.prototype, ext); }
};

var clc = require('cli-color');
var util = require('util');
var sprintf = util.format;

var requireComponent = require('../component/require');
var configurable = requireComponent('configurable.js');
var extend  = requireComponent('extend');
var tea = requireComponent('tea-properties');
var getProp = tea.get;
var setProp = tea.set;

function LongCon() {
  this.settings = {
    namespace: '', // Prepend to each message
    nlFirst: false, // Prepend \n to first log
    quiet: false, // Drop all messages
    time: false, // Prepend toUTCString()
    traceIndent: '    ', // Represent a trace level
    traceLanes: true // Prepend each traceIndent with '|'
  };

  this.traceDepth = 0;
  this.firstLine = true;
}

configurable(LongCon.prototype);

/**
 * util.format() wrapper with timestamp and injected output function.
 * Respects --quiet. Applies color selection.
 *
 * @param {string} name Source logger's name, ex. 'stderr'
 * @param {function} fn Ex. console.log
 * @param {string} color cli-color selection, ex. 'red.bold' or 'yellow'
 * @param {boolean} colorBody Apply color to log body in addition to name
 * @param {mixed} args* For util.format()
 */
LongCon.prototype.log = function(name, fn, color, colorBody) {
  if (this.get('quiet')) { return; }
  var colorFn = color ? getProp(clc, color) : defColorFn;
  var bodyColorFn = colorBody ? colorFn : defColorFn;
  var namespace = this.get('namespace');
  var indent = '';

  // Apply trace levels to indentation if push() and pop() were used.
  var traceIndent = this.get('traceIndent');
  var laneCx = traceIndent.length;
  indent = (new Array(this.traceDepth + 1)).join(traceIndent);
  if (this.get('traceLanes')) { // Prepend '|' to  every traceIndent section
    indent = indent.replace(new RegExp('.{1,' + laneCx + '}', 'g'), '|$&');
  }

  var sections = [
    indent,
    this.get('time') ? '[' + (new Date()).toUTCString() + '] ' : '',
    namespace ? namespace + ' ' : '',
    name ? colorFn(name) + ' ' : '',
    bodyColorFn(sprintf.apply(null, [].slice.call(arguments, 4)))
  ];
  var joined = sections.join('');

  // Ensure 1st line starts at col 0 for lane alignment
  if (this.firstLine && this.get('nlFirst')) {
    joined = '\n' + joined;
    this.firstLine = false;
  }

  fn(joined);
};

/**
 * Create a log() wrapper with fixed arguments.
 *
 * @param {string} name Source logger's name, ex. 'stderr'
 * @param {function} fn Ex. console.log
 * @param {string} color cli-color selection, ex. 'red.bold' or 'yellow'
 * @param {boolean} colorBody Apply color to log body in addition to name
 * @return {function} Accepts util.format() arguments
 *   {function} push: Accepts same args. Pushes a trace level.
 *   {function} pop: Accepts same args. Pops a trace level.
 */
LongCon.prototype.create = function(name, fn, color, colorBody) {
  var self = this;
  function logger() {
    self.log.apply(self, [name, fn, color, colorBody].concat([].slice.call(arguments)));
  }
  logger.push = function longConPush() {
    logger.apply(self, arguments); self.traceDepth++;
  };
  logger.pop = function longConPop() {
    self.traceDepth--;
    if (arguments.length) { logger.apply(self, arguments); }
  };
  return logger;
};

/**
 * Wrap an object's methods to automatically push/pop for (sync) tracing.
 *
 * @param {string} name Uniquely identify the object
 * @param {object} obj
 * @param {function} Logger from create()
 * @param {regexp} filter Include matching key names
 * @param {regexp} omit Exclude matching key names
 */
LongCon.prototype.traceMethods = function(name, obj, logger, filter, omit) {
  var self = this;
  filter = filter || /.?/;
  omit = omit || /a^/;
  Object.keys(obj).forEach(function longConTraceMethodsIter(key) {
    if (typeof obj[key] !== 'function') { return; }
    if (!filter.test(key)) { return; }
    if (omit.test(key)) { return; }
    var orig = obj[key];
    obj[key] = function longConTraceMethodsWrapper() {
      logger.push(name + '#' + key);
      var res = orig.apply(this, arguments);
      logger.pop();
      return res;
    };
  });
};

function defColorFn(str) { return str; }
<|endoftext|>


<commit_before>import React from 'react';
import Config from '../../Config';

class Footer extends React.Component {
    render() {
        return (

Copyright © 2017 {Config.server_name}. All rights reserved.

Aria built by Alan Morel and Austin Adams.

        );
    }
}

export default Footer;
<commit_msg>Updated personal website link<commit_after>import React from 'react';
import Config from '../../Config';

class Footer extends React.Component {
    render() {
        return (

Copyright © 2017 {Config.server_name}. All rights reserved.

Aria built by Alan Morel and Austin Adams.

        );
    }
}

export default Footer;
<|endoftext|>


<commit_before>import React from 'react'
import DeckGL from 'deck.gl'
import { graphql } from 'react-apollo'

import Sidebar from 'components/sidebar/sidebar'

import { addDrones } from 'mapbox/creators/drones'
import { addHives } from 'mapbox/creators/hives'
import { createDroneLayers, createHiveLayers } from 'mapbox/layers'

import allHivesDrones from 'graphql/queries/all_hives_drones.gql'
import hiveAdded from 'graphql/subscriptions/hive_added.gql'
import droneAdded from 'graphql/subscriptions/drone_added.gql'

import {
	removeDroneFromStore,
	updateOrAddToStore as updateOrAddToStoreDrone,
} from 'graphql/local/droneUpdates'
import { updateOrAddToStore as updateOrAddToStoreHive } from 'graphql/local/hiveUpdates'

import './layers.css'

@graphql(allHivesDrones)
export default class MapLayers extends React.Component {
	constructor(props) {
		super(props)
		this.firstFetch = true
		this.isAnimating = false

		this.state = {
			hoveredItem: null,
			hiveData: [],
			droneData: [],
		}
	}

	componentWillMount() {
		this.props.data.subscribeToMore({
			document: hiveAdded,
			updateQuery: (prev, { subscriptionData }) => {
				if (!subscriptionData.data) {
					return prev
				}
				const hive = subscriptionData.data.hiveAdded

				const newData = updateOrAddToStoreHive(
					hive,
					prev.hives,
					this.state.hiveData,
				)

				this.setState({
					hiveData: newData.newLocalState,
				})

				return {
					...prev,
					hives: newData.newApolloStore,
				}
			},
		})

		this.props.data.subscribeToMore({
			document: droneAdded,
			updateQuery: (prev, { subscriptionData }) => {
				if (!subscriptionData.data) {
					return prev
				}
				const drone = subscriptionData.data.droneAdded

				const newData = updateOrAddToStoreDrone(
					drone,
					prev.drones,
					this.state.droneData,
				)

				this.setState({
					droneData: newData.newLocalState,
				})

				if (!this.isAnimating) {
					this.animate()
				}

				return {
					...prev,
					drones: newData.newApolloStore,
				}
			},
		})
	}

	onHover = ({ x, y, layer, picked }) => {
		const { hiveData } = this.state

		const layerName = layer.id
		const layerParts = layerName.split('-')
		const hive = hiveData.find(h => h.id === layerParts[2])
		this.setState({
			hoveredItem: hive,
			x,
			y,
			picked,
		})
	}

	renderHiveInfo() {
		const { x, y, hoveredItem, picked } = this.state

		if (!picked) {
			return null
		}

		return (
			hoveredItem && (

Location:

{hoveredItem.location}

			)
		)
	}

	createLayers() {
		const { hiveData, droneData } = this.state

		return [
			...createHiveLayers(hiveData, this.onHover),
			...createDroneLayers(droneData),
		]
	}

	animate() {
		this.isAnimating = true

		const { droneData } = this.state
		let newDroneData = droneData

		for (let drone of newDroneData) {
			const { position } = drone.data[0]
			const { coordinates } = drone.route[drone.route.length - 1].geometry
			if (position !== coordinates) {
				if (typeof drone.route[drone.counter] === 'undefined') {
					return
				}
				let newData = [{ ...drone.data[0] }]
				const { coordinates } = drone.route[drone.counter].geometry
				newData[0].position = coordinates
				drone.data = newData
				drone.counter++

				const index = newDroneData.findIndex(res => res.id === drone.id)
				newDroneData[index] = drone
			} else {
				newDroneData = newDroneData.filter(res => res.id !== drone.id)
				removeDroneFromStore(drone)
			}
		}

		this.setState({
			droneData: newDroneData,
		})

		if (newDroneData.length === 0) {
			this.isAnimating = false
			return
		}
		requestAnimationFrame(this.animate.bind(this))
	}

	render() {
		const { viewport, data } = this.props
		if (data.loading) {
			return
loading...

		} else if (this.firstFetch) {
			this.setState({
				hiveData: addHives(data.hives),
				droneData: addDrones(data.drones),
			})
			this.firstFetch = false
			this.animate()
			return
		}

		return (

				<DeckGL {...viewport} layers={this.createLayers()} />
				{this.renderHiveInfo()}
				<Sidebar data={data} />

		)
	}
}
<commit_msg>DLN-140 #time 10m prepare connection to redux store<commit_after>import React from 'react'
import DeckGL from 'deck.gl'
import { graphql } from 'react-apollo'
import { connect } from 'react-redux'

import Sidebar from 'components/sidebar/sidebar'

import { addDrones } from 'mapbox/creators/drones'
import { addHives } from 'mapbox/creators/hives'
import { createDroneLayers, createHiveLayers } from 'mapbox/layers'

import allHivesDrones from 'graphql/queries/all_hives_drones.gql'
import hiveAdded from 'graphql/subscriptions/hive_added.gql'
import droneAdded from 'graphql/subscriptions/drone_added.gql'

import {
	removeDroneFromStore,
	updateOrAddToStore as updateOrAddToStoreDrone,
} from 'graphql/local/droneUpdates'
import { updateOrAddToStore as updateOrAddToStoreHive } from 'graphql/local/hiveUpdates'

import './layers.css'

@connect()
@graphql(allHivesDrones)
export default class MapLayers extends React.Component {
	constructor(props) {
		super(props)
		this.firstFetch = true
		this.isAnimating = false

		this.state = {
			hoveredItem: null,
			hiveData: [],
			droneData: [],
		}
	}

	componentWillMount() {
		this.props.data.subscribeToMore({
			document: hiveAdded,
			updateQuery: (prev, { subscriptionData }) => {
				if (!subscriptionData.data) {
					return prev
				}
				const hive = subscriptionData.data.hiveAdded

				const newData = updateOrAddToStoreHive(
					hive,
					prev.hives,
					this.state.hiveData,
					//updateOrAddHiveToInfoStore
				)

				this.setState({
					hiveData: newData.newLocalState,
				})

				return {
					...prev,
					hives: newData.newApolloStore,
				}
			},
		})

		this.props.data.subscribeToMore({
			document: droneAdded,
			updateQuery: (prev, { subscriptionData }) => {
				if (!subscriptionData.data) {
					return prev
				}
				const drone = subscriptionData.data.droneAdded

				const newData = updateOrAddToStoreDrone(
					drone,
					prev.drones,
					this.state.droneData,
					//updateOrAddDroneToInfoStore
				)

				this.setState({
					droneData: newData.newLocalState,
				})

				if (!this.isAnimating) {
					this.animate()
				}

				return {
					...prev,
					drones: newData.newApolloStore,
				}
			},
		})
	}

	onHover = ({ x, y, layer, picked }) => {
		const { hiveData } = this.state

		const layerName = layer.id
		const layerParts = layerName.split('-')
		const hive = hiveData.find(h => h.id === layerParts[2])
		this.setState({
			hoveredItem: hive,
			x,
			y,
			picked,
		})
	}

	renderHiveInfo() {
		const { x, y, hoveredItem, picked } = this.state

		if (!picked) {
			return null
		}

		return (
			hoveredItem && (

Location:

{hoveredItem.location}

			)
		)
	}

	createLayers() {
		const { hiveData, droneData } = this.state

		return [
			...createHiveLayers(hiveData, this.onHover),
			...createDroneLayers(droneData),
		]
	}

	animate() {
		this.isAnimating = true

		const { droneData } = this.state
		let newDroneData = droneData

		for (let drone of newDroneData) {
			const { position } = drone.data[0]
			const { coordinates } = drone.route[drone.route.length - 1].geometry
			if (position !== coordinates) {
				if (typeof drone.route[drone.counter] === 'undefined') {
					return
				}
				let newData = [{ ...drone.data[0] }]
				const { coordinates } = drone.route[drone.counter].geometry
				newData[0].position = coordinates
				drone.data = newData
				drone.counter++

				const index = newDroneData.findIndex(res => res.id === drone.id)
				newDroneData[index] = drone
			} else {
				newDroneData = newDroneData.filter(res => res.id !== drone.id)
				// removeDroneFromInfoStore
				removeDroneFromStore(drone)
			}
		}

		this.setState({
			droneData: newDroneData,
		})

		if (newDroneData.length === 0) {
			this.isAnimating = false
			return
		}
		requestAnimationFrame(this.animate.bind(this))
	}

	render() {
		const { viewport, data } = this.props
		if (data.loading) {
			return
loading...

		} else if (this.firstFetch) {
			this.setState({
				hiveData: addHives(data.hives),
				droneData: addDrones(data.drones),
			})
			this.firstFetch = false
			this.animate()
			return
		}

		return (

				<DeckGL {...viewport} layers={this.createLayers()} />
				{this.renderHiveInfo()}
				<Sidebar data={data} />

		)
	}
}
<|endoftext|>


<commit_before>import { maskInput, conformToMask } from 'vanilla-text-mask';
import _ from 'lodash';
import { createNumberMask } from 'text-mask-addons';
import Input from '../_classes/input/Input';
import { getNumberSeparators, getNumberDecimalLimit } from '../../utils/utils';

export default class NumberComponent extends Input {
  static schema(...extend) {
    return Input.schema({
      type: 'number',
      label: 'Number',
      key: 'number',
      validate: {
        min: '',
        max: '',
        step: 'any',
        integer: ''
      }
    }, ...extend);
  }

  static get builderInfo() {
    return {
      title: 'Number',
      icon: 'hashtag',
      group: 'basic',
      documentation: 'http://help.form.io/userguide/#number',
      weight: 10,
      schema: NumberComponent.schema()
    };
  }

  constructor(...args) {
    super(...args);
    this.validators = this.validators.concat(['min', 'max']);

    const separators = getNumberSeparators(this.options.language);

    this.decimalSeparator = this.options.decimalSeparator
      || separators.decimalSeparator;

    if (this.component.delimiter) {
      if (this.options.hasOwnProperty('thousandsSeparator')) {
        console.warn("Property 'thousandsSeparator' is deprecated. Please use i18n to specify delimiter.");
      }

      this.delimiter = this.options.thousandsSeparator || separators.delimiter;
    }
    else {
      this.delimiter = '';
    }

    this.decimalLimit = getNumberDecimalLimit(this.component);

    // Currencies to override BrowserLanguage Config. Object key {}
    if (_.has(this.options, `languageOverride.${this.options.language}`)) {
      const override = _.get(this.options, `languageOverride.${this.options.language}`);
      this.decimalSeparator = override.decimalSeparator;
      this.delimiter = override.delimiter;
    }
    this.numberMask = createNumberMask({
      prefix: '',
      suffix: '',
      requireDecimal: _.get(this.component, 'requireDecimal', false),
      thousandsSeparatorSymbol: _.get(this.component, 'thousandsSeparator', this.delimiter),
      decimalSymbol: _.get(this.component, 'decimalSymbol', this.decimalSeparator),
      decimalLimit: _.get(this.component, 'decimalLimit', this.decimalLimit),
      allowNegative: _.get(this.component, 'allowNegative', true),
      allowDecimal: _.get(this.component, 'allowDecimal',
        !(this.component.validate && this.component.validate.integer))
    });
  }

  get defaultSchema() {
    return NumberComponent.schema();
  }

  get emptyValue() {
    return '';
  }

  parseNumber(value) {
    // Remove delimiters and convert decimal separator to dot.
    value = value.split(this.delimiter).join('').replace(this.decimalSeparator, '.');

    if (this.component.validate && this.component.validate.integer) {
      return parseInt(value, 10);
    }
    else {
      return parseFloat(value);
    }
  }

  setInputMask(input) {
    input.setAttribute('pattern', '\\d*');

    input.mask = maskInput({
      inputElement: input,
      mask: this.numberMask
    });
  }

  get inputInfo() {
    const info = super.inputInfo;
    info.attr.type = 'text';
    info.attr.inputmode = 'numeric';
    info.changeEvent = 'input';
    return info;
  }

  getValueAt(index) {
    if (!this.refs.input.length || !this.refs.input[index]) {
      return null;
    }

    const val = this.refs.input[index].value;

    if (!val) {
      return '';
    }

    return this.parseNumber(val);
  }

  clearInput(input) {
    let value = parseFloat(input);

    if (!_.isNaN(value)) {
      value = String(value).replace('.', this.decimalSeparator);
    }
    else {
      value = null;
    }

    return value;
  }

  formatValue(value) {
    if (this.component.requireDecimal && value && !value.includes(this.decimalSeparator)) {
      return `${value}${this.decimalSeparator}${_.repeat('0', this.decimalLimit)}`;
    }

    return value;
  }

  setValueAt(index, value) {
    return super.setValueAt(index, this.formatValue(this.clearInput(value)));
  }

  focus() {
    const input = this.refs.input[0];
    if (input) {
      input.focus();
      input.setSelectionRange(0, input.value.length);
    }
  }

  getMaskedValue(value) {
    return conformToMask(value.toString(), this.numberMask).conformedValue;
  }

  getView(value) {
    if (!value && value !== 0) {
      return '';
    }
    const widget = this.widget;
    if (widget && widget.getView) {
      return widget.getView(value);
    }

    if (Array.isArray(value)) {
      return value.map(this.getMaskedValue).join(', ');
    }
    return this.getMaskedValue(value);
  }
}
<commit_msg>(FOR-1759): Default Values doesn't include required decimals<commit_after>import { maskInput, conformToMask } from 'vanilla-text-mask';
import _ from 'lodash';
import { createNumberMask } from 'text-mask-addons';
import Input from '../_classes/input/Input';
import { getNumberSeparators, getNumberDecimalLimit } from '../../utils/utils';

export default class NumberComponent extends Input {
  static schema(...extend) {
    return Input.schema({
      type: 'number',
      label: 'Number',
      key: 'number',
      validate: {
        min: '',
        max: '',
        step: 'any',
        integer: ''
      }
    }, ...extend);
  }

  static get builderInfo() {
    return {
      title: 'Number',
      icon: 'hashtag',
      group: 'basic',
      documentation: 'http://help.form.io/userguide/#number',
      weight: 10,
      schema: NumberComponent.schema()
    };
  }

  constructor(...args) {
    super(...args);
    this.validators = this.validators.concat(['min', 'max']);

    const separators = getNumberSeparators(this.options.language);

    this.decimalSeparator = this.options.decimalSeparator
      || separators.decimalSeparator;

    if (this.component.delimiter) {
      if (this.options.hasOwnProperty('thousandsSeparator')) {
        console.warn("Property 'thousandsSeparator' is deprecated. Please use i18n to specify delimiter.");
      }

      this.delimiter = this.options.thousandsSeparator || separators.delimiter;
    }
    else {
      this.delimiter = '';
    }

    this.decimalLimit = getNumberDecimalLimit(this.component);

    // Currencies to override BrowserLanguage Config. Object key {}
    if (_.has(this.options, `languageOverride.${this.options.language}`)) {
      const override = _.get(this.options, `languageOverride.${this.options.language}`);
      this.decimalSeparator = override.decimalSeparator;
      this.delimiter = override.delimiter;
    }
    this.numberMask = createNumberMask({
      prefix: '',
      suffix: '',
      requireDecimal: _.get(this.component, 'requireDecimal', false),
      thousandsSeparatorSymbol: _.get(this.component, 'thousandsSeparator', this.delimiter),
      decimalSymbol: _.get(this.component, 'decimalSymbol', this.decimalSeparator),
      decimalLimit: _.get(this.component, 'decimalLimit', this.decimalLimit),
      allowNegative: _.get(this.component, 'allowNegative', true),
      allowDecimal: _.get(this.component, 'allowDecimal',
        !(this.component.validate && this.component.validate.integer))
    });
  }

  get defaultSchema() {
    return NumberComponent.schema();
  }

  get emptyValue() {
    return '';
  }

  parseNumber(value) {
    // Remove delimiters and convert decimal separator to dot.
    value = value.split(this.delimiter).join('').replace(this.decimalSeparator, '.');

    if (this.component.validate && this.component.validate.integer) {
      return parseInt(value, 10);
    }
    else {
      return parseFloat(value);
    }
  }

  setInputMask(input) {
    input.setAttribute('pattern', '\\d*');

    input.mask = maskInput({
      inputElement: input,
      mask: this.numberMask
    });
  }

  get inputInfo() {
    const info = super.inputInfo;
    info.attr.type = 'text';
    info.attr.inputmode = 'numeric';
    info.changeEvent = 'input';
    return info;
  }

  getValueAt(index) {
    if (!this.refs.input.length || !this.refs.input[index]) {
      return null;
    }

    const val = this.refs.input[index].value;

    if (!val) {
      return '';
    }

    return this.parseNumber(val);
  }

  clearInput(input) {
    let value = parseFloat(input);

    if (!_.isNaN(value)) {
      value = String(value).replace('.', this.decimalSeparator);
    }
    else {
      value = null;
    }

    return value;
  }

  formatValue(value) {
    if (this.component.requireDecimal && value && !value.includes(this.decimalSeparator)) {
      return `${value}${this.decimalSeparator}${_.repeat('0', this.decimalLimit)}`;
    }
    else if (this.component.requireDecimal && value && value.includes(this.decimalSeparator)) {
      return `${value}${_.repeat('0', this.decimalLimit - value.split(this.decimalSeparator)[1].length)})}`;
    }

    return value;
  }

  setValueAt(index, value) {
    return super.setValueAt(index, this.formatValue(this.clearInput(value)));
  }

  focus() {
    const input = this.refs.input[0];
    if (input) {
      input.focus();
      input.setSelectionRange(0, input.value.length);
    }
  }

  getMaskedValue(value) {
    return conformToMask(value.toString(), this.numberMask).conformedValue;
  }

  build(state) {
    super.build(state);
    this.inputs.forEach((input, index) => {
      this.addEventListener(input, 'blur', (event) => {
        if (this.component.requireDecimal) {
          this.setValueAt(index, event.target.value);
        }
      });
    });
  }

  getView(value) {
    if (!value && value !== 0) {
      return '';
    }
    const widget = this.widget;
    if (widget && widget.getView) {
      return widget.getView(value);
    }

    if (Array.isArray(value)) {
      return value.map(this.getMaskedValue).join(', ');
    }
    return this.getMaskedValue(value);
  }
}
<|endoftext|>


<commit_before>'use babel';

export default {
  config: {
    compilerExecPath: {
      title: 'Compiler Executable Path',
      description: 'The path (with excutable) to be run by the IDE in the background. By default the IDE will use the compiler in your path.',
      type: 'string',
      default: 'crystal'
    },
    buildArtifacts: {
      title: 'Output Build Artifacts',
      description: 'When true the compiler will create build artifacts when run by the linter.',
      type: 'boolean',
      default: false
    },
    colorOutput: {
      title: 'Compiler passing Color Output',
      description: 'When false the compiler will not pass ASCII color characters to the linter when run by the linter.',
      type: 'boolean',
      default: false
    },
    command: {
      title: 'Compiler Command',
      description: 'The command passed to the commpiler during linting.',
      type: 'string',
      default: 'build'
    }
  },

  activate: () => {
    // Show the user an error if they do not have the appropriate Crystal
    //  Language package from Atom Package Manager installed.
    if(!atom.packages.getLoadedPackages('language-crystal-actual')) {
      atom.notifications.addError(
        'Crystal Language Package not found.',
        {
          detail: 'Please install the `language-crystal-actual` package in your Settings view.'
        }
      )
    }

    // Show the user an error if they do not have an appropriate linter base
    //  package installed from Atom Package Manager. This will not be an issues
    //  after a base linter package is integrated into Atom, in the comming
    //  months.
    // TODO: Remove when Linter Base is integrated into Atom.
    if(!atom.packages.getLoadedPackages('linter')) {
      atom.notifications.addError(
        'Linter package not found.',
        {
          detail: 'Please install the `linter` package in your Settings view.'
        }
      )
    }
  },

  provideLinter: () => {
    const LinterProvider = require('./provider')
    var provider = new LinterProvider()
    return {
      grammarScopes: ['source.crystal'],
      scope: 'file',
      lint: provider.lint,
      lintOnFly: false
    }
  }
}
<commit_msg>Use const over var.<commit_after>'use babel';

export default {
  config: {
    compilerExecPath: {
      title: 'Compiler Executable Path',
      description: 'The path (with excutable) to be run by the IDE in the background. By default the IDE will use the compiler in your path.',
      type: 'string',
      default: 'crystal'
    },
    buildArtifacts: {
      title: 'Output Build Artifacts',
      description: 'When true the compiler will create build artifacts when run by the linter.',
      type: 'boolean',
      default: false
    },
    colorOutput: {
      title: 'Compiler passing Color Output',
      description: 'When false the compiler will not pass ASCII color characters to the linter when run by the linter.',
      type: 'boolean',
      default: false
    },
    command: {
      title: 'Compiler Command',
      description: 'The command passed to the commpiler during linting.',
      type: 'string',
      default: 'build'
    }
  },

  activate: () => {
    // Show the user an error if they do not have the appropriate Crystal
    //  Language package from Atom Package Manager installed.
    if(!atom.packages.getLoadedPackages('language-crystal-actual')) {
      atom.notifications.addError(
        'Crystal Language Package not found.',
        {
          detail: 'Please install the `language-crystal-actual` package in your Settings view.'
        }
      )
    }

    // Show the user an error if they do not have an appropriate linter base
    //  package installed from Atom Package Manager. This will not be an issues
    //  after a base linter package is integrated into Atom, in the comming
    //  months.
    // TODO: Remove when Linter Base is integrated into Atom.
    if(!atom.packages.getLoadedPackages('linter')) {
      atom.notifications.addError(
        'Linter package not found.',
        {
          detail: 'Please install the `linter` package in your Settings view.'
        }
      )
    }
  },

  provideLinter: () => {
    const LinterProvider = require('./provider')
    const provider = new LinterProvider()
    return {
      grammarScopes: ['source.crystal'],
      scope: 'file',
      lint: provider.lint,
      lintOnFly: false
    }
  }
}
<|endoftext|>