<commit_before>/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */
/* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */
/* eslint-disable import/no-mutable-exports */

import isPrototype from '../../utilities/warning/component-is-prototype';
import oneOfRequiredProperty from '../../utilities/warning/one-of-required-property';

let checkProps = function () {};

if (process.env.NODE_ENV !== 'production') {
	checkProps = function (COMPONENT, props) {
		isPrototype(COMPONENT);

		/* eslint-disable max-len */
		oneOfRequiredProperty(COMPONENT, {
			assistiveText: props.assistiveText,
			heading: props.heading,
		});
		/* eslint-enable max-len */
	};
}

export default checkProps;
<commit_msg>Remove Tree as prototype<commit_after>/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */
/* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */
/* eslint-disable import/no-mutable-exports */

import oneOfRequiredProperty from '../../utilities/warning/one-of-required-property';

let checkProps = function () {};

if (process.env.NODE_ENV !== 'production') {
	checkProps = function (COMPONENT, props) {
		/* eslint-disable max-len */
		oneOfRequiredProperty(COMPONENT, {
			assistiveText: props.assistiveText,
			heading: props.heading,
		});
		/* eslint-enable max-len */
	};
}

export default checkProps;
<|endoftext|>


<commit_before>(function (factory) {
	if (typeof define === 'function' && define.amd) {
		// AMD. Register as an anonymous module.
		define(['jquery'], factory);
	} else {
		// Browser globals
		factory(window.jQuery);
	}
}(function ($) {
	'use strict';

	// Utilities

	function toNumber (num) {
		return isFinite(num = parseFloat(num)) ? num : 0;
	}

	function throttle (fn, context) {
		var timer = false;
		return function () {
			var c = context || this;
			var a = arguments;
			if (false === timer) {
				timer = window.requestAnimationFrame(function () {
					fn.apply(c, a);
					timer = false;
				});
			}
		};
	}

	// Cling

	var positionMultiplier = {
		left: 0,
		top: 0,
		right: 1,
		bottom: 1,
		center: 0.5
	};

	var positionRegExp = /(left|right|center|\d+%)\s*(top|bottom|center|\d+%)/;

	function normalizePosition (position) {
		var normalized = [0.5, 0.5];

		position = positionRegExp.exec(position);

		for (var i = 1; i <= 2; i++) {
			if (!position[i]) {
				continue;
			} else if (positionMultiplier.hasOwnProperty(position[i])) {
				normalized[i - 1] = positionMultiplier[position[i]];
			} else if ('%' == position[i].substr(-1, 1)) {
				normalized[i - 1] = toNumber(position[i]);
			}
		}

		return normalized;
	}

	var offsetRegExp = /(-?\d+)\s*(-?\d+)?/;

	function normalizeOffset (offset) {
		var normalized = [0, 0];

		offset = offsetRegExp.exec(offset);

		for (var i = 1; i <= 2; i++) {
			if (offset[i]) {
				normalized[i - 1] = toNumber(offset[i]);
			}
		}

		return normalized;
	}

	function getScrollParents (element) {
		return element.parents().filter(function () {
			var parent = $(this);
			if (1 == element.nodeType && /auto|scroll/.test(parent.css('overflow') + parent.css('overflow-x') + parent.css('overflow-y'))) {
				return true;
			}
		});
	}

	function Cling (element, target, options) {
		// Throttle update method
		this.update = throttle(this.update, this);

		// Setup options
		this.e = element;
		this.t = target;
		this.options(options);

		// Add position styles if not already `absolute` or `fixed`
		if (!/absolute|fixed/.test(element.css('position'))) {
			element.css({
				position: 'absolute',
				left: 0,
				top: 0
			});
		}

		// Listen to scroll or resize on window
		$(window).on('scroll resize touchmove', this.update);

		// Get any scrollable parents, and listen for it scrolling
		var scrollParents = this.s = getScrollParents(target);
		if (scrollParents.length) {
			scrollParents.on('scroll', this.update);
		}

		// Store instance
		element.data('cling', this);

		this.update();
	}

	Cling.prototype = {
		defaults: {
			from: '',
			to: '',
			offset: ''
		},

		options: function (options) {
			options = $.extend(this.defaults, options);
			options.from = normalizePosition(options.from);
			options.to = normalizePosition(options.to);
			options.offset = normalizeOffset(options.offset);
			this.o = options;
		},

		update: function () {
			var element = this.e;
			var target = this.t;
			var options = this.o;

			var elementBounding = element.get(0).getBoundingClientRect();
			var targetBounding = target.get(0).getBoundingClientRect();

			// Dat Math
			// 1. The target point
			// 2. Subtract the element point
			// 3. Add the difference between the target and element's current position
			// 4. Add our offset
			// 5. Add the current left/top style -- prevents layout thrashing
			var left = (target.outerWidth() * options.from[0]) -
				(element.outerWidth() * options.to[0]) +
				(targetBounding.left - elementBounding.left) +
				options.offset[0] +
				toNumber(element.css('left'));

			var top = (target.outerHeight() * options.from[1]) -
				(element.outerHeight() * options.to[1]) +
				(targetBounding.top - elementBounding.top) +
				options.offset[1] +
				toNumber(element.css('top'));

			// Set the newly calculated positions
			element.css({
				left: Math.round(left),
				top: Math.round(top)
			});
		},

		destroy: function () {
			var element = this.e;
			var scrollParents = this.s;

			// Remove any applied styles
			element.css({
				position: '',
				left: '',
				top: ''
			});

			// Remove events
			$(window).off('scroll resize touchmove', this.update);

			if (scrollParents.length) {
				scrollParents.off('scroll', this.update);
			}

			// Remove stored instance
			element.removeData('cling');
		}
	};

	// jQuery Plugin
	$.fn.extend({
		cling: function (target, options) {
			target = $(target);

			return this.each(function () {
				var element = $(this);
				var instance = element.data('cling');

				if (instance instanceof Cling) {
					if ($.isFunction(instance[target])) {
						instance[target](options);
					}
				} else {
					new Cling(element, target, options);
				}
			});
		}
	});

	return Cling;
}));
<commit_msg>Minor tweaks to getScrollParents, instance handling, and comments.<commit_after>/*!
 * Cling - Copyright (c) 2015 Jacob Buck
 * https://github.com/jacobbuck/cling
 * Licensed under the terms of the MIT license.
 */
(function (factory) {
	// UMD yo!
	if (typeof define === 'function' && define.amd) {
		define(['jquery'], factory);
	} else {
		factory(window.jQuery);
	}
}(function ($) {
	'use strict';

	// Utilities

	function toNumber (num) {
		return isFinite(num = parseFloat(num)) ? num : 0;
	}

	function throttle (fn, context) {
		var timer = false;
		return function () {
			var c = context || this;
			var a = arguments;
			if (false === timer) {
				timer = window.requestAnimationFrame(function () {
					fn.apply(c, a);
					timer = false;
				});
			}
		};
	}

	// Cling

	var positionMultiplier = {
		left: 0,
		top: 0,
		right: 1,
		bottom: 1,
		center: 0.5
	};

	var positionRegExp = /(left|right|center|\d+%)\s*(top|bottom|center|\d+%)/;

	function normalizePosition (position) {
		var normalized = [0.5, 0.5];

		position = positionRegExp.exec(position);

		for (var i = 1; i <= 2; i++) {
			if (!position[i]) {
				continue;
			} else if (positionMultiplier.hasOwnProperty(position[i])) {
				normalized[i - 1] = positionMultiplier[position[i]];
			} else if ('%' == position[i].substr(-1, 1)) {
				normalized[i - 1] = toNumber(position[i]);
			}
		}

		return normalized;
	}

	var offsetRegExp = /(-?\d+)\s*(-?\d+)?/;

	function normalizeOffset (offset) {
		var normalized = [0, 0];

		offset = offsetRegExp.exec(offset);

		for (var i = 1; i <= 2; i++) {
			if (offset[i]) {
				normalized[i - 1] = toNumber(offset[i]);
			}
		}

		return normalized;
	}

	function getScrollParents (element) {
		return element.parentsUntil('html, body').filter(function () {
			var parent = $(this);
			return /auto|scroll/.test(parent.css('overflow') + parent.css('overflow-x') + parent.css('overflow-y'));
		});
	}

	function Cling (element, target, options) {
		// Setup options
		this.e = element;
		this.t = target;
		this.options(options);

		// Throttle update method
		this.update = throttle(this.update, this);

		// Add position styles if not already `absolute` or `fixed`
		if (!/absolute|fixed/.test(element.css('position'))) {
			element.css({
				position: 'absolute',
				left: 0,
				top: 0
			});
		}

		// Listen to scroll or resize on window
		$(window).on('scroll resize touchmove', this.update);

		// Get any scrollable parents of the target, and listen to scroll on them
		var scrollParents = this.s = getScrollParents(target);
		if (scrollParents.length) {
			scrollParents.on('scroll', this.update);
		}

		this.update();
	}

	Cling.prototype = {
		defaults: {
			from: '',
			to: '',
			offset: ''
		},

		options: function (options) {
			options = $.extend(this.defaults, options);
			options.from = normalizePosition(options.from);
			options.to = normalizePosition(options.to);
			options.offset = normalizeOffset(options.offset);
			this.o = options;
		},

		update: function () {
			var element = this.e;
			var target = this.t;
			var options = this.o;

			var elementBounding = element.get(0).getBoundingClientRect();
			var targetBounding = target.get(0).getBoundingClientRect();

			// Dat Math
			// 1. The target point
			// 2. Subtract the element point
			// 3. Add the difference between the target and element's current position
			// 4. Add our offset
			// 5. Add the current left/top style -- prevents layout thrashing
			var left = (target.outerWidth() * options.from[0]) -
				(element.outerWidth() * options.to[0]) +
				(targetBounding.left - elementBounding.left) +
				options.offset[0] +
				toNumber(element.css('left'));

			var top = (target.outerHeight() * options.from[1]) -
				(element.outerHeight() * options.to[1]) +
				(targetBounding.top - elementBounding.top) +
				options.offset[1] +
				toNumber(element.css('top'));

			// Set the newly calculated positions
			element.css({
				left: Math.round(left),
				top: Math.round(top)
			});
		},

		destroy: function () {
			var element = this.e;
			var scrollParents = this.s;

			// Remove any applied styles
			element.css({
				position: '',
				left: '',
				top: ''
			});

			// Unbind events
			$(window).off('scroll resize touchmove', this.update);

			if (scrollParents.length) {
				scrollParents.off('scroll', this.update);
			}
		}
	};

	// jQuery Plugin
	$.fn.extend({
		cling: function (target, options) {
			target = $(target);

			return this.each(function () {
				var element = $(this);
				var instance = element.data('cling');

				if (instance instanceof Cling) {
					if ($.isFunction(instance[target])) {
						instance[target](options);

						// Remove stored instance
						if ('destroy' == target) {
							element.removeData('cling');
						}
					}
				} else {
					element.data('cling', new Cling(element, target, options));
				}
			});
		}
	});

	return Cling;
}));
<|endoftext|>


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

/*var apiAccess = {};
apiAccess.callUrl = function(url, funct){

	var request = new XMLHttpRequest();
	request.onreadystatechange = function(){
		if(request.readyState == 4 && request.status == 200){
			funct(request.responseText);
		}
	}
	request.open("GET", url, true);
	request.send(null);
}*/

/*
 * How to use -
 * First, use datesSet(); to check if the starting dates for the Pre and Reg season have been set
 * If false, call getFirstWeeks(Int curYear) to set them, where curYear is an integer representing the year of the season. That is, if the season starts in 2016, it would be the int 2015
 * To ensure that the dates have been set, due to asyncronity, ensure that datesSet() returns true before moving on
 *
 * Setup is now completed.
 * To get a set of games, call getGamesOnDate(Date date, boolean includeAllForWeek), where the date is a Date object representing the day which you want to retrieve games for, and includeAllForWeek is true only if you want to return all games for that week, instead of just for that day
 * This will populate GamesForWeek with the output data in an object of the form {date:The date supplied for retrieval, data:an array of game items}
 * You can retrieve what is stored in GamesForWeek using getRetrievedGameData(), but again due to asyncronity, verify that the date is accurate before proceeding with use.
 *
 * For now, don't trust the scores, also the scores are strings. Game object is as such:
 * {date:a Date representing the game day,
 * 	awayTeam:String represnting team nick(name),
 * 	awayScore:String representing whatever was stored on the page for the score,
 * 	homeTeam,
 * 	homeScore}
 *
 */

var PRE0Date;
var evalDate;
var REG1Date;
var GamesForWeek = {};
var TeamsForWeek = [];

//NOTE: WEEK ENDS ON MONDAY!
function constructScoreURI(season, part, week){
	//http://www.nfl.com/scores/2016/PRE0
	//season is year, part is PRE, REG, POST
	return "http://www.nfl.com/scores/"+season+"/"+part+week;
}

function constructYahooURI(url, element, attrType, attrValue){

	//http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url=%22http://www.nfl.com/schedules%22%20and%20
	//	xpath=%27//div[@class=%22schedules-list%22]%27&format=json

	var head = "http://query.yahooapis.com/v1/public/yql?q=select * from html where url=\"" + url + "\"";
	var xpath = constructXpath(element, attrType, attrValue);
	var jsonTail = '&format=json';

	return head + " and " + xpath + jsonTail;
}

function constructXpath(elementType, attributeType, attributeValue){
	return "xpath='//" + elementType + "[@" + attributeType + "=\"" + attributeValue + "\"]'";
}

function getFirstWeeks(currentYearInt){
	var queryFirstPRE = constructYahooURI("http://www.nfl.com/scores/2016/PRE0", "span", "title", "Date Airing");
	var queryFirstREG = constructYahooURI("http://www.nfl.com/scores/2016/REG1", "span", "title", "Date Airing");

	console.log(queryFirstPRE);

	return Promise.all([apiAccess.callUrl(queryFirstPRE),apiAccess.callUrl(queryFirstREG)])
    .then(function(response){ preResponse(response[0]); regResponse(response[1]);});

    function preResponse(response){
      console.log("I am the response", response);
      var json = JSON.parse(response);
      var spans = json.query.results.span;
      var item = spans[spans.length-1] || spans;
      var date = item.content

      date += " " + currentYearInt;

      date = new Date(date);
      //sets the date to be the next Monday, staying the same if it's already a monday
      date.setDate( date.getDate() + ((Math.abs( date.getDay() - 7 ) + 1)%7) );
      PRE0Date = date;
      console.log("I am the PRE0Date", PRE0Date);
      console.log("dateSET",datesSet());
    }

    function regResponse(response){
      console.log("I am the response", response);
      var json = JSON.parse(response);
      var spans = json.query.results.span;
      var item = spans[spans.length-1] || spans;
      var date = item.content;

      date += " " + currentYearInt;

      date = new Date(date);
      //sets the date to be the next Monday, staying the same if it's already a monday
      date.setDate( date.getDate() + ((Math.abs( date.getDay() - 7 ) + 1)%7) );
      REG1Date = date;//end of first week of Reg season
      evalDate = new Date(date);
      evalDate.setDate(evalDate.getDate()-7);//end of last week of presesason
      console.log("RESONSE", REG1Date);
      console.log("dateSET",datesSet());
    }

}

function datesSet(){
	return PRE0Date != null && REG1Date != null;
}

function getGamesOnDate(date, includeAllGamesForWeek){
	var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
	var season = date.getYear() + 1900; //stupid epochs
	var part;
	var dateOfPart;
	var week;

	if(date >= evalDate){//Preseason
		part = "PRE";
		dateOfPart = PRE0Date;
	} else {
		part = "REG";
		dateOfPart = REG1Date;
	}
	//which week is it in?

	if(date <= dateOfPart){
		if(part=="PRE"){
			week = 0;
		} else {
			week = 1;
		}
	} else {
		//http://stackoverflow.com/questions/2627473/how-to-calculate-the-number-of-days-between-two-dates-using-javascript
		var diffDays = Math.round(Math.abs((date.getTime() - dateOfPart.getTime())/(oneDay)));
		var numWeeks = Math.round(diffDays / 7);
		week = 1+numWeeks;
	}

	var baseURI = constructScoreURI(season, part, week);
	var fullURI = constructYahooURI(baseURI, "div", "class", "scorebox-wrapper pre");

	return apiAccess.callUrl(fullURI)
    .then(function(response){
		var results = JSON.parse(response).query.results;

		output = results.div[0] ;
		//Date span is output.div[0].div.div[0].p.span[0];
		//TeamAway Nick is output.div[0].div.div[1].div[0].div.div.div.p[1].a.content
		//TeamAway totalScore is output.div[0].div.div[1].div[0].div.div.p.content
		//TeamHome Nick is output.div[0].div.div[1].div[1].div.div.div.p[1].a.content

		var gamesOnDay = [];

		for ( i in results.div ){
			var game = {};

			game.date = new Date( results.div[i].div[0].div.div[0].p.span[0].content + " " + (date.getYear() + 1900) )
			game.awayTeam = results.div[i].div[0].div.div[1].div[0].div.div.div.p[1].a.content;
			game.awayScore = results.div[i].div[0].div.div[1].div[0].div.div.p.content;
			game.homeTeam = results.div[i].div[0].div.div[1].div[1].div.div.div.p[1].a.content;
			game.homeScore = results.div[i].div[0].div.div[1].div[1].div.div.p.content
      TeamsForWeek.push(game.awayTeam, game.homeTeam);

			if(!includeAllGamesForWeek){
				if(game.date == date){
					gamesOnDay.push(game);
				}
			} else {
				gamesOnDay.push(game);
			}
		}

		GamesForWeek.date = date;
		GamesForWeek.data = gamesOnDay;
    return Promise.resolve(GamesForWeek);
	});

}

function getRetrievedGameData(){
	return GamesForWeek;
}

function getTeams() {
  return TeamsForWeek;
}

module.exports = {
  datesSet: datesSet,
  getFirstWeeks: getFirstWeeks,
  getGamesOnDate: getGamesOnDate,
  getRetrievedGameData: getRetrievedGameData,
  getTeams: getTeams
};
<commit_msg>adding changes to make you get teams for preseason<commit_after>var apiAccess = require('../config/apiAccess');

/*var apiAccess = {};
apiAccess.callUrl = function(url, funct){

	var request = new XMLHttpRequest();
	request.onreadystatechange = function(){
		if(request.readyState == 4 && request.status == 200){
			funct(request.responseText);
		}
	}
	request.open("GET", url, true);
	request.send(null);
}*/

/*
 * How to use -
 * First, use datesSet(); to check if the starting dates for the Pre and Reg season have been set
 * If false, call getFirstWeeks(Int curYear) to set them, where curYear is an integer representing the year of the season. That is, if the season starts in 2016, it would be the int 2015
 * To ensure that the dates have been set, due to asyncronity, ensure that datesSet() returns true before moving on
 *
 * Setup is now completed.
 * To get a set of games, call getGamesOnDate(Date date, boolean includeAllForWeek), where the date is a Date object representing the day which you want to retrieve games for, and includeAllForWeek is true only if you want to return all games for that week, instead of just for that day
 * This will populate GamesForWeek with the output data in an object of the form {date:The date supplied for retrieval, data:an array of game items}
 * You can retrieve what is stored in GamesForWeek using getRetrievedGameData(), but again due to asyncronity, verify that the date is accurate before proceeding with use.
 *
 * For now, don't trust the scores, also the scores are strings. Game object is as such:
 * {date:a Date representing the game day,
 * 	awayTeam:String represnting team nick(name),
 * 	awayScore:String representing whatever was stored on the page for the score,
 * 	homeTeam,
 * 	homeScore}
 *
 */

var PRE0Date;
var evalDate;
var REG1Date;
var GamesForWeek = {};
var TeamsForWeek = [];

//NOTE: WEEK ENDS ON MONDAY!
function constructScoreURI(season, part, week){
	//http://www.nfl.com/scores/2016/PRE0
	//season is year, part is PRE, REG, POST
	return "http://www.nfl.com/scores/"+season+"/"+part+week;
}

function constructYahooURI(url, element, attrType, attrValue){

	//http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url=%22http://www.nfl.com/schedules%22%20and%20
	//	xpath=%27//div[@class=%22schedules-list%22]%27&format=json

	var head = "http://query.yahooapis.com/v1/public/yql?q=select * from html where url=\"" + url + "\"";
	var xpath = constructXpath(element, attrType, attrValue);
	var jsonTail = '&format=json';

	return head + " and " + xpath + jsonTail;
}

function constructXpath(elementType, attributeType, attributeValue){
	return "xpath='//" + elementType + "[@" + attributeType + "=\"" + attributeValue + "\"]'";
}

function getFirstWeeks(currentYearInt){
	var queryFirstPRE = constructYahooURI("http://www.nfl.com/scores/2016/PRE0", "span", "title", "Date Airing");
	var queryFirstREG = constructYahooURI("http://www.nfl.com/scores/2016/REG1", "span", "title", "Date Airing");

	console.log(queryFirstPRE);

	return Promise.all([apiAccess.callUrl(queryFirstPRE),apiAccess.callUrl(queryFirstREG)])
    .then(function(response){ preResponse(response[0]); regResponse(response[1]);});

    function preResponse(response){
      var json = JSON.parse(response);
      var spans = json.query.results.span;
      var item = spans[spans.length-1] || spans;
      var date = item.content

      date += " " + currentYearInt;

      date = new Date(date);
      //sets the date to be the next Monday, staying the same if it's already a monday
      date.setDate( date.getDate() + ((Math.abs( date.getDay() - 7 ) + 1)%7) );
      PRE0Date = date;
    }

    function regResponse(response){
      var json = JSON.parse(response);
      var spans = json.query.results.span;
      var item = spans[spans.length-1] || spans;
      var date = item.content;

      date += " " + currentYearInt;

      date = new Date(date);
      //sets the date to be the next Monday, staying the same if it's already a monday
      date.setDate( date.getDate() + ((Math.abs( date.getDay() - 7 ) + 1)%7) );
      REG1Date = date;//end of first week of Reg season
      evalDate = new Date(date);
      evalDate.setDate(evalDate.getDate()-7);//end of last week of presesason
    }

}

function datesSet(){
	return PRE0Date != null && REG1Date != null;
}

function getGamesOnDate(date, includeAllGamesForWeek){
	var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
	var season = date.getYear() + 1900; //stupid epochs
	var part;
	var dateOfPart;
	var week;

	if(date <= evalDate){//Preseason
		part = "PRE";
		dateOfPart = PRE0Date;
	} else {
		part = "REG";
		dateOfPart = REG1Date;
	}
	//which week is it in?

	if(date <= dateOfPart){
		if(part=="PRE"){
			week = 1;
		} else {
			week = 1;
		}
	} else {
		//http://stackoverflow.com/questions/2627473/how-to-calculate-the-number-of-days-between-two-dates-using-javascript
		var diffDays = Math.round(Math.abs((date.getTime() - dateOfPart.getTime())/(oneDay)));
		var numWeeks = Math.round(diffDays / 7);
		week = 1+numWeeks;
	}

	var baseURI = constructScoreURI(season, part, week);
	var fullURI = constructYahooURI(baseURI, "div", "class", "scorebox-wrapper pre");

	return apiAccess.callUrl(fullURI)
    .then(function(response){

		var results = JSON.parse(response).query.results;

		output = results.div[0] ;
		//Date span is output.div[0].div.div[0].p.span[0];
		//TeamAway Nick is output.div[0].div.div[1].div[0].div.div.div.p[1].a.content
		//TeamAway totalScore is output.div[0].div.div[1].div[0].div.div.p.content
		//TeamHome Nick is output.div[0].div.div[1].div[1].div.div.div.p[1].a.content

		var gamesOnDay = [];

		for ( i in results.div ){
			var game = {};

			game.date = new Date( results.div[i].div[0].div.div[0].p.span[0].content + " " + (date.getYear() + 1900) )
			game.awayTeam = results.div[i].div[0].div.div[1].div[0].div.div.div.p[1].a.content;
			game.awayScore = results.div[i].div[0].div.div[1].div[0].div.div.p.content;
			game.homeTeam = results.div[i].div[0].div.div[1].div[1].div.div.div.p[1].a.content;
			game.homeScore = results.div[i].div[0].div.div[1].div[1].div.div.p.content
      TeamsForWeek.push(game.awayTeam, game.homeTeam);

			if(!includeAllGamesForWeek){
				if(game.date == date){
					gamesOnDay.push(game);
				}
			} else {
				gamesOnDay.push(game);
			}
		}

		GamesForWeek.date = date;
		GamesForWeek.data = gamesOnDay;
    console.log("I am this weeks games", GamesForWeek);
    return Promise.resolve(GamesForWeek);
	});

}

function getRetrievedGameData(){
	return GamesForWeek;
}

function getTeams() {
  return TeamsForWeek;
}

module.exports = {
  datesSet: datesSet,
  getFirstWeeks: getFirstWeeks,
  getGamesOnDate: getGamesOnDate,
  getRetrievedGameData: getRetrievedGameData,
  getTeams: getTeams
};
<|endoftext|>


<commit_before>/*
	Version : 0.0.1
	Created On : 11.03.2015

	-- hoverr_tera.js load this js
	-- It get data set by hoverr_tera.js
*/
(function() {
	var $isMobile = !!((/android|webos|iphone|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()))),
		$onceCalled = false,
		jqueryLink = '//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js',
		debugRequired = true,
		$,
		_window_dataObject = {};

	var Debugger = function () { };
	Debugger.log = function (message) {
		try {
			if(debugRequired) console.log(message);
		} catch (exception) {}
	};

	var findContainer = function(callback){
		var tempObject = [];

		var inlineContainer = undefined,
		intr = window.setInterval(function(){
			if($(_window_dataObject.selector).length != 0){
				window.clearInterval(intr);

				$(_window_dataObject.selector).each(function(){
					var containerDiv = $('

');
					$(this).after(containerDiv);

					tempObject.push({
						containerDiv: containerDiv,
						width: containerDiv.width(),
						position: $(this).offset()
					});
				});

				if(typeof(callback) === "function" && callback !== undefined) callback(tempObject);
				else return tempObject;
			}
		}, 100);
	};

	// Set attribute for elements
	var setAttributes = function(el, attrs) {
		for(var key in attrs) { if (attrs.hasOwnProperty(key)) el.setAttribute(key, attrs[key]); }
	};

	var putAd = function(container){
		var iframe = document.createElement('iframe'),
		$width = container.width,
		$iframeWidth = _window_dataObject.dimension.width,
		$iframeHeight = _window_dataObject.dimension.height,

		$scale = (($width / $iframeWidth) <= 1) ? ($width / $iframeWidth) : 1,
		$left = "left: "+ (($width - $iframeWidth)/2) +"px;",
		$bottom = Math.ceil((($iframeHeight * $scale) - $iframeHeight)/2),
		$cssText,
		$top,
		$adTag = _window_dataObject.tag,
		$key = [window._pm_object.host, window._pm_object.section, window._pm_object.web_or_mobile, _window_dataObject.id, _window_dataObject.is_default],
		$pixelPingHtml = '';

		$cssText = "height:"+ $iframeHeight +"px !important; min-height:"+ $iframeHeight +"px !important; width:"+ $iframeWidth +"px !important; overflow:hidden;"+ $left +"bottom:"+ $bottom +"px;margin:0 auto; position:absolute; background: transparent; z-index: 2; -moz-transform: scale("+ $scale +"); -o-transform: scale("+ $scale +"); -webkit-transform: scale("+ $scale +"); transform: scale("+ $scale +"); max-width:initial !important;";

		setAttributes(iframe, {"height": $iframeHeight, "scrolling": "no", "frameBorder": 0, "allowtransparency": "true", "class": "_adSenceImagePush", "width": $iframeWidth, "loadStatus": 0, "data-width": $iframeWidth, "data-height": $iframeHeight, "style":$cssText});

    console.log(iframe);

		container.containerDiv.append(iframe);

		try{
			Debugger.log('Log : Setting html content in try block !!');
			var doc = iframe.contentDocument || iframe.contentWindow.document;
			doc.open();
			doc.write('


<commit_before>import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';

const storyEntries = [
  {
    id: '2',
    author: 'Charlie',
    entryPartials: [
      {
        id: 'a',
        text:
          'Once upon a time there was a turkey called Rob.\nOne day Rob went to the toilet',
      },
    ],
  },
  {
    id: '1',
    author: 'Bob',
    entryPartials: [{ id: 'b', text: '.\nIn the toilet he did a piss' }],
  },
];

const nextEntryPartials = [
  {
    id: '3',
    author: 'Viki',
    entryPartials: [
      { id: 'c', text: ' ' },
      { id: 'd', text: ' a' },
      { id: 'e', text: ' an' },
      { id: 'f', text: ' and' },
      { id: 'g', text: ' and ' },
      { id: 'h', text: ' and p' },
      { id: 'i', text: ' and po' },
      { id: 'j', text: ' and poo' },
      { id: 'k', text: ' and pooe' },
      { id: 'l', text: ' and pooed' },
      { id: 'm', text: ' and pooed.' },
    ],
  },
  {
    id: '4',
    author: 'Viki',
    entryPartials: [
      { id: 'n', text: '\n' },
      { id: 'o', text: '\nW' },
      { id: 'p', text: '\nWh' },
      { id: 'q', text: '\nWhe' },
      { id: 'r', text: '\nWhen' },
      { id: 's', text: '\nWhen ' },
      { id: 't', text: '\nWhen h' },
      { id: 'u', text: '\nWhen he' },
      { id: 'v', text: '\nWhen h' },
      { id: 'w', text: '\nWhen hi' },
      { id: 'x', text: '\nWhen his' },
    ],
  },
];

export default class App extends React.Component {
  constructor(props) {
    super(props);

    this.play = this.play.bind(this);
    this.clearPlay = this.clearPlay.bind(this);
    this.addNextEntryPartialToStoryParagraphs = this.addNextEntryPartialToStoryParagraphs.bind(
      this,
    );
    this.addEntryTextToStoryParagraphs = this.addEntryTextToStoryParagraphs.bind(
      this,
    );
    this.hasNextEntryPartials = this.hasNextEntryPartials.bind(this);

    let storyParagraphs = [];

    storyEntries.forEach(({ author, entryPartials }) => {
      const { text, id } = entryPartials[entryPartials.length - 1];

      storyParagraphs = this.addEntryTextToStoryParagraphs(
        text,
        storyParagraphs,
        id,
      );
    });

    this.prevStoryParagraphs = storyParagraphs;
    this.nextEntryPartials = nextEntryPartials;

    this.state = {
      storyParagraphs,
      hasNextEntryPartials: this.hasNextEntryPartials(),
      playing: false,
    };
  }

  clearPlay() {
    this.setState({ playing: false });
    clearInterval(this.interval);
  }

  play() {
    if (this.nextEntryPartials.length) {
      this.setState({ playing: true });

      this.interval = setInterval(() => {
        if (this.nextEntryPartials.length) {
          this.addNextEntryPartialToStoryParagraphs();
        } else {
          this.clearPlay();
        }
      }, 100);
    }
  }

  addNextEntryPartialToStoryParagraphs() {
    if (!this.state.hasNextEntryPartials) {
      this.clearPlay();
      return;
    }

    const { text, id } = this.nextEntryPartials[0].entryPartials[0];

    const nextStoryParagraphs = this.addEntryTextToStoryParagraphs(
      text,
      this.prevStoryParagraphs,
      id,
    );

    if (this.nextEntryPartials[0].entryPartials.length === 1) {
      this.prevStoryParagraphs = nextStoryParagraphs;
      this.nextEntryPartials = this.nextEntryPartials.slice(1);
    } else {
      this.nextEntryPartials[0].entryPartials = this.nextEntryPartials[0].entryPartials.slice(
        1,
      );
    }

    this.setState({
      storyParagraphs: nextStoryParagraphs,
      hasNextEntryPartials: this.hasNextEntryPartials(),
    });
  }

  addEntryTextToStoryParagraphs(entryText, storyParagraphs, id) {
    let entryParagraphs = entryText.split('\n');

    if (!entryParagraphs.length) return storyParagraphs;

    entryParagraphs = entryParagraphs.map((text, i) => ({
      text,
      id: `${id}-text`,
    }));

    let nextStoryParagraphs = storyParagraphs.slice();

    if (nextStoryParagraphs.length) {
      const lastStoryParagraphIndex = nextStoryParagraphs.length - 1;
      const lastStoryParagraph = nextStoryParagraphs[lastStoryParagraphIndex];
      const firstEntryParagraph = entryParagraphs[0];

      nextStoryParagraphs[lastStoryParagraphIndex] = {
        text: `${lastStoryParagraph.text}${firstEntryParagraph.text}`,
        id: `${lastStoryParagraph.id}-${firstEntryParagraph.id}`,
      };

      entryParagraphs = entryParagraphs.slice(1);
    }

    nextStoryParagraphs = nextStoryParagraphs.concat(entryParagraphs);
    return nextStoryParagraphs;
  }

  hasNextEntryPartials() {
    return (
      this.nextEntryPartials.length &&
      this.nextEntryPartials[0].entryPartials.length
    );
  }

  render() {
    return (
      <View style={styles.container}>
        <View>
          {this.state.storyParagraphs.map(({ text, id }) => (
            <Text key={id}>{text}</Text>
          ))}
        </View>
        {this.state.hasNextEntryPartials &&
          !this.state.playing && (
            <TouchableOpacity onPress={this.play}>
              <View style={styles.button}>
                <Text style={styles.buttonText}>Play</Text>
              </View>
            </TouchableOpacity>
          )}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },

  button: {
    padding: 10,
    backgroundColor: 'blue',
    marginTop: 20,
  },

  buttonText: {
    color: 'white',
  },
});
<commit_msg>Fixed broken show button bool<commit_after>import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';

const storyEntries = [
  {
    id: '2',
    author: 'Charlie',
    entryPartials: [
      {
        id: 'a',
        text:
          'Once upon a time there was a turkey called Rob.\nOne day Rob went to the toilet',
      },
    ],
  },
  {
    id: '1',
    author: 'Bob',
    entryPartials: [{ id: 'b', text: '.\nIn the toilet he did a piss' }],
  },
];

const nextEntryPartials = [
  {
    id: '3',
    author: 'Viki',
    entryPartials: [
      { id: 'c', text: ' ' },
      { id: 'd', text: ' a' },
      { id: 'e', text: ' an' },
      { id: 'f', text: ' and' },
      { id: 'g', text: ' and ' },
      { id: 'h', text: ' and p' },
      { id: 'i', text: ' and po' },
      { id: 'j', text: ' and poo' },
      { id: 'k', text: ' and pooe' },
      { id: 'l', text: ' and pooed' },
      { id: 'm', text: ' and pooed.' },
    ],
  },
  {
    id: '4',
    author: 'Viki',
    entryPartials: [
      { id: 'n', text: '\n' },
      { id: 'o', text: '\nW' },
      { id: 'p', text: '\nWh' },
      { id: 'q', text: '\nWhe' },
      { id: 'r', text: '\nWhen' },
      { id: 's', text: '\nWhen ' },
      { id: 't', text: '\nWhen h' },
      { id: 'u', text: '\nWhen he' },
      { id: 'v', text: '\nWhen h' },
      { id: 'w', text: '\nWhen hi' },
      { id: 'x', text: '\nWhen his' },
    ],
  },
];

export default class App extends React.Component {
  constructor(props) {
    super(props);

    this.play = this.play.bind(this);
    this.clearPlay = this.clearPlay.bind(this);
    this.addNextEntryPartialToStoryParagraphs = this.addNextEntryPartialToStoryParagraphs.bind(
      this,
    );
    this.addEntryTextToStoryParagraphs = this.addEntryTextToStoryParagraphs.bind(
      this,
    );
    this.hasNextEntryPartials = this.hasNextEntryPartials.bind(this);

    let storyParagraphs = [];

    storyEntries.forEach(({ author, entryPartials }) => {
      const { text, id } = entryPartials[entryPartials.length - 1];

      storyParagraphs = this.addEntryTextToStoryParagraphs(
        text,
        storyParagraphs,
        id,
      );
    });

    this.prevStoryParagraphs = storyParagraphs;
    this.nextEntryPartials = nextEntryPartials;

    this.state = {
      storyParagraphs,
      hasNextEntryPartials: this.hasNextEntryPartials(),
      playing: false,
    };
  }

  clearPlay() {
    this.setState({ playing: false });
    clearInterval(this.interval);
  }

  play() {
    if (this.nextEntryPartials.length) {
      this.setState({ playing: true });

      this.interval = setInterval(() => {
        if (this.nextEntryPartials.length) {
          this.addNextEntryPartialToStoryParagraphs();
        } else {
          this.clearPlay();
        }
      }, 100);
    }
  }

  addNextEntryPartialToStoryParagraphs() {
    if (!this.state.hasNextEntryPartials) {
      this.clearPlay();
      return;
    }

    const { text, id } = this.nextEntryPartials[0].entryPartials[0];

    const nextStoryParagraphs = this.addEntryTextToStoryParagraphs(
      text,
      this.prevStoryParagraphs,
      id,
    );

    if (this.nextEntryPartials[0].entryPartials.length === 1) {
      this.prevStoryParagraphs = nextStoryParagraphs;
      this.nextEntryPartials = this.nextEntryPartials.slice(1);
    } else {
      this.nextEntryPartials[0].entryPartials = this.nextEntryPartials[0].entryPartials.slice(
        1,
      );
    }

    this.setState({
      storyParagraphs: nextStoryParagraphs,
      hasNextEntryPartials: this.hasNextEntryPartials(),
    });
  }

  addEntryTextToStoryParagraphs(entryText, storyParagraphs, id) {
    let entryParagraphs = entryText.split('\n');

    if (!entryParagraphs.length) return storyParagraphs;

    entryParagraphs = entryParagraphs.map((text, i) => ({
      text,
      id: `${id}-text`,
    }));

    let nextStoryParagraphs = storyParagraphs.slice();

    if (nextStoryParagraphs.length) {
      const lastStoryParagraphIndex = nextStoryParagraphs.length - 1;
      const lastStoryParagraph = nextStoryParagraphs[lastStoryParagraphIndex];
      const firstEntryParagraph = entryParagraphs[0];

      nextStoryParagraphs[lastStoryParagraphIndex] = {
        text: `${lastStoryParagraph.text}${firstEntryParagraph.text}`,
        id: `${lastStoryParagraph.id}-${firstEntryParagraph.id}`,
      };

      entryParagraphs = entryParagraphs.slice(1);
    }

    nextStoryParagraphs = nextStoryParagraphs.concat(entryParagraphs);
    return nextStoryParagraphs;
  }

  hasNextEntryPartials() {
    return (
      !!this.nextEntryPartials.length &&
      !!this.nextEntryPartials[0].entryPartials.length
    );
  }

  render() {
    const showButton = this.state.hasNextEntryPartials && !this.state.playing;

    return (
      <View style={styles.container}>
        <View>
          {this.state.storyParagraphs.map(({ text, id }) => (
            <Text key={id}>{text}</Text>
          ))}
        </View>
        {showButton && (
          <TouchableOpacity onPress={this.play}>
            <View style={styles.button}>
              <Text style={styles.buttonText}>Play</Text>
            </View>
          </TouchableOpacity>
        )}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },

  button: {
    padding: 10,
    backgroundColor: 'blue',
    marginTop: 20,
  },

  buttonText: {
    color: 'white',
  },
});
<|endoftext|>


<commit_before>/* # StoredObject Class
 * Handles storage of objects in the brower's LocalStorage.
 * Works with an ORM-like API.
 */
class StoredObject {

  // keyname at which all objects will be stored under
  static keyName() { return this.name }

  // constructor:
  // * sets all properties on given parameter as properties of this object;
  // * sets object's id;
  // * sets object's timestamp.
  constructor (params){
    if(!params.id){
      this.id = (new Date()).valueOf()
      this.createdAt = new Date()
    }
    for(let property in params){
      this[property] = params[property]
    }
  }

  // fetches list of all objects, straight from LocalStorage
  static fetch(){
    return JSON.parse(localStorage.getItem(this.keyName())) || []
  }

  // stores the list given to LocalStorage
  static store(objects){
    localStorage.setItem(this.keyName(), JSON.stringify(objects))
  }

  // fetches list of all objects, then return them as new Object()
  static list(){
    return this.fetch().map( (item) => new this(item) )
  }

  // stores an object:
  // * if there's no item with this ID yet, appends to the end of the current
  //   objects list then saves it.
  // * if theres an item w/ this ID, overwrites it in the list, then saves it.
  // returns the saved object.
  save (){
    const id = this.id
    const objects = this.constructor.fetch()

    const index = objects.findIndex( (item) => item.id == id )

    if(index != -1){
      objects[index] = this
    } else {
      objects.push(this)
    }

    this.constructor.store(objects)

    return this.constructor.get(id)
  }

  // fetches a specific object, by id
  static get (id) {
    const objects = this.fetch()
    return new this(objects.find( (item) => item.id == id ))
  }

  // returns an StoredObject whose id is saved at the PARAMId property.
  // ORM-like behavior for relationships.
  object (klass){
    const fieldName = `${klass.name.toLowerCase()}Id`
    return klass.get(this[fieldName])
  }
}

/* # Notes service
 */
app.factory('Note', ['Patient', '$filter', function(Patient, $filter){

  class Note extends StoredObject {

    // returs this note's Patient
    patient(){
      return this.object(Patient)
    }

    // overrides list() so that all Note objects listed
    // already have their Patients pre-fetched.
    static list(){
      return super.list().map((item) => {
        item.patient = item.patient()
        return item
      })
    }

    // returns a properly formated Note timestamp.
    get timestamp(){
      return $filter('date')(this.createdAt, 'yy-MM-dd, H:mm')
    }
  }

  return Note
}])

/* # Patients service
 */
app.factory('Patient', ['$injector', function($injector){

  class Patient extends StoredObject {

    // returns this patient's notes
    // uses depency injector, which isn't great.
    notes(){
      const notes = $injector.get('Note').fetch()
      const id = this.id
      return notes.filter((item) => item.patientId == id)
    }

    // property: number of Notes this patient has
    // uses this.notes()
    get numNotes(){
      return this.notes().length
    }

  }

  return Patient
}])
<commit_msg>Gets complete Notes objects on Patient's .notes() method.<commit_after>/* # StoredObject Class
 * Handles storage of objects in the brower's LocalStorage.
 * Works with an ORM-like API.
 */
class StoredObject {

  // keyname at which all objects will be stored under
  static keyName() { return this.name }

  // constructor:
  // * sets all properties on given parameter as properties of this object;
  // * sets object's id;
  // * sets object's timestamp.
  constructor (params){
    if(!params.id){
      this.id = (new Date()).valueOf()
      this.createdAt = new Date()
    }
    for(let property in params){
      this[property] = params[property]
    }
  }

  // fetches list of all objects, straight from LocalStorage
  static fetch(){
    return JSON.parse(localStorage.getItem(this.keyName())) || []
  }

  // stores the list given to LocalStorage
  static store(objects){
    localStorage.setItem(this.keyName(), JSON.stringify(objects))
  }

  // fetches list of all objects, then return them as new Object()
  static list(){
    return this.fetch().map( (item) => new this(item) )
  }

  // stores an object:
  // * if there's no item with this ID yet, appends to the end of the current
  //   objects list then saves it.
  // * if theres an item w/ this ID, overwrites it in the list, then saves it.
  // returns the saved object.
  save (){
    const id = this.id
    const objects = this.constructor.fetch()

    const index = objects.findIndex( (item) => item.id == id )

    if(index != -1){
      objects[index] = this
    } else {
      objects.push(this)
    }

    this.constructor.store(objects)

    return this.constructor.get(id)
  }

  // fetches a specific object, by id
  static get (id) {
    const objects = this.fetch()
    return new this(objects.find( (item) => item.id == id ))
  }

  // returns an StoredObject whose id is saved at the PARAMId property.
  // ORM-like behavior for relationships.
  object (klass){
    const fieldName = `${klass.name.toLowerCase()}Id`
    return klass.get(this[fieldName])
  }
}

/* # Notes service
 */
app.factory('Note', ['Patient', '$filter', function(Patient, $filter){

  class Note extends StoredObject {

    // returs this note's Patient
    patient(){
      return this.object(Patient)
    }

    // overrides list() so that all Note objects listed
    // already have their Patients pre-fetched.
    static list(){
      return super.list().map((item) => {
        item.patient = item.patient()
        return item
      })
    }

    // returns a properly formated Note timestamp.
    get timestamp(){
      return $filter('date')(this.createdAt, 'yy-MM-dd, H:mm')
    }
  }

  return Note
}])

/* # Patients service
 */
app.factory('Patient', ['$injector', function($injector){

  class Patient extends StoredObject {

    // returns this patient's notes
    // uses depency injector, which isn't great.
    notes(){
      const notes = $injector.get('Note').list()
      const id = this.id
      return notes.filter((item) => item.patientId == id)
    }

    // property: number of Notes this patient has
    // uses this.notes()
    get numNotes(){
      return this.notes().length
    }

  }

  return Patient
}])
<|endoftext|>


<commit_before>/* global moment:true */
import Ember from 'ember';

// DateTime picker component for Semantic UI (Semantic UI hasn't its own DateTime picker component yet).
export default Ember.Component.extend({
  // String with input css classes.
  classes: undefined,

  // Flag to make control readonly.
  readonly: undefined,

  // Flag to make control required.
  required: false,

  // Flag to show time in control and time picker inside date picker.
  hasTimePicker: false,

  // Type of input element for render.
  type: 'text',

  // Input value.
  value: undefined,

  // Invalid date for set to model value when needed.
  invalidDate: new Date('invalid'),

  // Default display format.
  dateTimeFormat: 'DD.MM.YYYY',

  // Init component when DOM is ready.
  didInsertElement: function() {
    var hasTimePicker = this.get('hasTimePicker');
    if (hasTimePicker) {
      this.dateTimeFormat = 'DD.MM.YYYY HH:mm:ss';
    }

    var val = this.get('value');
    var startDate = new Date();
    if (val !== undefined && moment(val).isValid()) {
      startDate = moment(val);
      this.$('input').val(startDate.format(this.dateTimeFormat));
    }

    var readonly = this.get('readonly');
    var _this = this;
    if (readonly === undefined) {
      this.$('input').daterangepicker(
      {
        startDate: startDate,
        singleDatePicker: true,
        showDropdowns: true,
        timePicker: hasTimePicker,
        timePickerIncrement: 1,
        timePicker12Hour: false,
        timePickerSeconds: true,
        format: this.dateTimeFormat
      },
      function(start, end, label) {
        var dateToSet = start.isValid() ? start.toDate() : _this.invalidDate;
        _this.set('value', dateToSet);
      }
      );
    }
  },

  // Set proper start date when value changed outside of component.
  _valueChanged: Ember.observer('value', function() {
    var val = this.get('value');
    var currValueDateTime = moment(val);
    if (currValueDateTime.isValid()) {
      var currInputDateTime = moment(this.$('input').val(), this.dateTimeFormat);

      // Change current date and time when changes were made outside of input element.
      if (!currValueDateTime.isSame(currInputDateTime)) {
        if (this.$('input').data('daterangepicker') !== undefined) {
          this.$('input').data('daterangepicker').setEndDate(currValueDateTime);
        }
        else {
          this.$('input').val(currValueDateTime.format(this.dateTimeFormat));
        }
      }
    }
  })
});
<commit_msg>Fixed datetime-picker component<commit_after>/* global moment:true */
import Ember from 'ember';

// DateTime picker component for Semantic UI (Semantic UI hasn't its own DateTime picker component yet).
export default Ember.Component.extend({
  // String with input css classes.
  classes: undefined,

  // Flag to make control readonly.
  readonly: undefined,

  // Flag to make control required.
  required: false,

  // Flag to show time in control and time picker inside date picker.
  hasTimePicker: false,

  // Type of input element for render.
  type: 'text',

  // Input value.
  value: undefined,

  // Invalid date for set to model value when needed.
  invalidDate: new Date('invalid'),

  // Default display format.
  dateTimeFormat: 'DD.MM.YYYY',

  // Init component when DOM is ready.
  didInsertElement: function() {
    var hasTimePicker = this.get('hasTimePicker');
    if (hasTimePicker) {
      this.dateTimeFormat = 'DD.MM.YYYY HH:mm:ss';
    }

    var val = this.get('value');
    var startDate = new Date();
    if (val !== undefined && moment(val).isValid()) {
      startDate = moment(val);
      this.$('input').val(startDate.format(this.dateTimeFormat));
    }

    var readonly = this.get('readonly');
    var _this = this;
    if (readonly === undefined) {
      this.$('input').daterangepicker(
      {
        startDate: startDate,
        singleDatePicker: true,
        showDropdowns: true,
        timePicker: hasTimePicker,
        timePickerIncrement: 1,
        timePicker12Hour: false,
        timePickerSeconds: true,
        format: this.dateTimeFormat
      },
      function(start, end, label) {
        _this.setValue(start);
      }
      );
      this.$('input').on('apply.daterangepicker', function(ev, picker) {
        var currentValue = _this.get('value');
        var pickerStartDateString = moment(picker.startDate.toDate()).format(_this.dateTimeFormat);
        if (!currentValue || !moment(moment(currentValue).format(_this.dateTimeFormat), _this.dateTimeFormat).isSame(moment(pickerStartDateString, _this.dateTimeFormat))) {
          _this.setValue(picker.startDate);
        }
      });
    }
  },

  setValue: function(dateFromPicker) {
    var dateToSet = dateFromPicker.isValid() ? dateFromPicker.toDate() : this.invalidDate;
    this.set('value', dateToSet);
  },

  // Set proper start date when value changed outside of component.
  _valueChanged: Ember.observer('value', function() {
    var val = this.get('value');
    var currValueDateTime = moment(val);
    if (currValueDateTime.isValid()) {
      var currInputDateTime = moment(this.$('input').val(), this.dateTimeFormat);

      // Change current date and time when changes were made outside of input element.
      if (!currValueDateTime.isSame(currInputDateTime)) {
        if (this.$('input').data('daterangepicker') !== undefined) {
          this.$('input').data('daterangepicker').setEndDate(currValueDateTime);
        }
        else {
          this.$('input').val(currValueDateTime.format(this.dateTimeFormat));
        }
      }
    }
  })
});
<|endoftext|>


<commit_before>module.exports = {
  name: 'Jump to Anchor',

  section: 'Other Stuff',

  subtitle (data) {
    return data.description ? `<font color="${data.color}">${data.description}</font>` : `Jump to ${data.jump_to_anchor ? `the "${data.jump_to_anchor}" anchor in your command if it exists!` : 'an anchor!'}`
  },

  fields: ['description', 'jump_to_anchor', 'color'],

  html () {
    return `

    Mod Info:

    This mod will jump to the specified anchor point

    without requiring you to edit any other skips or jumps.

    This is sensitive and must be exactly the same as your anchor name.

  Jump to Anchor ID:

  <input type="text" class="round" id="jump_to_anchor">

  Anchor Color:

  <input type="color" id="color">

  Description:

  <input type="text" class="round" id="description">

`
  },

  init () {},

  action (cache) {
    const id = cache.actions[cache.index].jump_to_anchor
    this.anchorJump(id, cache)
  },

  mod (DBM) {
    DBM.Actions.anchorJump = function (id, cache) {
      const anchorIndex = cache.actions.findIndex((a) => a.name === 'Create Anchor' && a.anchor_id === id)
      if (anchorIndex === -1) throw new Error('There was not an anchor found with that exact anchor ID!')
      cache.index = anchorIndex - 1
      this.callNextAction(cache)
    }

    DBM.Actions.anchorExist = function (id, cache) {
      const anchorIndex = cache.actions.findIndex((a) => a.name === 'Create Anchor' && a.anchor_id === id)
      if (anchorIndex === -1) {
        return false
      }
      return true
    }
  }
}
<commit_msg>Update anchor_jump_MOD.js (#433)<commit_after>module.exports = {
  name: 'Jump to Anchor',

  section: 'Other Stuff',

  subtitle (data) {
    return data.description ? `<font color="${data.color}">${data.description}</font>` : `Jump to ${data.jump_to_anchor ? `the "${data.jump_to_anchor}" anchor in your command if it exists!` : 'an anchor!'}`
  },

  fields: ['description', 'jump_to_anchor', 'color'],

  html () {
    return `

    Mod Info:

    This mod will jump to the specified anchor point

    without requiring you to edit any other skips or jumps.

    This is sensitive and must be exactly the same as your anchor name.

  Jump to Anchor ID:

  <input type="text" class="round" id="jump_to_anchor">

  Anchor Color:

  <input type="color" id="color">

  Description:

  <input type="text" class="round" id="description">

`
  },

  init () {},

  action (cache) {
    const id = this.evalMessage(cache.actions[cache.index].jump_to_anchor, cache)
    this.anchorJump(id, cache)
  },

  mod (DBM) {
    DBM.Actions.anchorJump = function (id, cache) {
      const anchorIndex = cache.actions.findIndex((a) => a.name === 'Create Anchor' && a.anchor_id === id)
      if (anchorIndex === -1) throw new Error('There was not an anchor found with that exact anchor ID!')
      cache.index = anchorIndex - 1
      this.callNextAction(cache)
    }

    DBM.Actions.anchorExist = function (id, cache) {
      const anchorIndex = cache.actions.findIndex((a) => a.name === 'Create Anchor' && a.anchor_id === id)
      if (anchorIndex === -1) {
        return false
      }
      return true
    }
  }
}
<|endoftext|>


<commit_before>import React from "react";
import ReactDOM from "react-dom";
import "videojs-contrib-dash";
import "dashjs";
import videojs from "video.js";
import "video.js/dist/video-js.css";
import styled, { injectGlobal } from "styled-components";

injectGlobal`
  html,
  body {
    height: 100%;
  }
`;

const Entry = styled.form``;

const Player = styled.div`
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: space-between;
`;

export default class SPMediaPlayer extends React.Component {
  constructor() {
    super();
    this.state = { url: "" };
  }
  componentDidMount() {
    // instantiate Video.js
    this.player = videojs(this.videoNode, this.props, function onPlayerReady() {
      console.log("onPlayerReady", this);
    });
  }

  // destroy player on unmount
  componentWillUnmount() {
    if (this.player) {
      this.player.dispose();
    }
  }

  onChange(e) {
    this.setState({ url: e.target.value });
  }

  onSubmit(e) {
    e.preventDefault();
    this.player.src(this.state.url);
    this.setState({ url: "" });
    this.player.play();
  }

  // wrap the player in a div with a `data-vjs-player` attribute
  // so videojs won't create additional wrapper in the DOM
  // see https://github.com/videojs/video.js/pull/3856
  render() {
    return (
      <Player>
        <div data-vjs-player>
          <video ref={node => (this.videoNode = node)} className="video-js" />
        </div>
        <Entry onSubmit={e => this.onSubmit(e)}>
          <input value={this.state.url} onChange={e => this.onChange(e)} />
        </Entry>
      </Player>
    );
  }
}

document.addEventListener("DOMContentLoaded", () => {
  for (const node of document.querySelectorAll("Streamplace")) {
    ReactDOM.render(<SPMediaPlayer />, node);
  }
});
<commit_msg>remove console.log<commit_after>import React from "react";
import ReactDOM from "react-dom";
import "videojs-contrib-dash";
import "dashjs";
import videojs from "video.js";
import "video.js/dist/video-js.css";
import styled, { injectGlobal } from "styled-components";

injectGlobal`
  html,
  body {
    height: 100%;
  }
`;

const Entry = styled.form``;

const Player = styled.div`
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: space-between;
`;

export default class SPMediaPlayer extends React.Component {
  constructor() {
    super();
    this.state = { url: "" };
  }
  componentDidMount() {
    // instantiate Video.js
    this.player = videojs(this.videoNode, this.props, function onPlayerReady() {
      // console.log("onPlayerReady", this);
    });
  }

  // destroy player on unmount
  componentWillUnmount() {
    if (this.player) {
      this.player.dispose();
    }
  }

  onChange(e) {
    this.setState({ url: e.target.value });
  }

  onSubmit(e) {
    e.preventDefault();
    this.player.src(this.state.url);
    this.setState({ url: "" });
    this.player.play();
  }

  // wrap the player in a div with a `data-vjs-player` attribute
  // so videojs won't create additional wrapper in the DOM
  // see https://github.com/videojs/video.js/pull/3856
  render() {
    return (
      <Player>
        <div data-vjs-player>
          <video ref={node => (this.videoNode = node)} className="video-js" />
        </div>
        <Entry onSubmit={e => this.onSubmit(e)}>
          <input value={this.state.url} onChange={e => this.onChange(e)} />
        </Entry>
      </Player>
    );
  }
}

document.addEventListener("DOMContentLoaded", () => {
  for (const node of document.querySelectorAll("Streamplace")) {
    ReactDOM.render(<SPMediaPlayer />, node);
  }
});
<|endoftext|>


<commit_before>/**
 * Created by bo on 5/7/16.
 */

var displayMessages = function displayMessages(data) {
    if(data.length == 0) {
        var html = '
Data validation is successful!
';
        $('#feedback-tables').append(html);
    }//if
    else {
        for (var i = 0; i < data.length; i++) {
            var fb = data[i];
            var msg = fb['message'];
            var vals = fb['offendingValues'];
            var msgRow =
                '
' +
                'Message: 	' +
                '  	' +
                '
' +
                '
' +
                '  	' +
                '' + msg + '	' +
                '
';
            var valRows = '
Offending Values:
';

            for (var j = 0; j < vals.length; j++) {
                valRows +=
                    '
' +
                    ' 	' +
                    '' + vals[j] + '	' +
                    '
';
            }
            var html =
                '
' +
                '
' +
                '
' +
                msgRow + '
' +
                valRows +
                '
' +
                '
' +
                '
';
            $('#feedback-tables').append(html);
        }
    }//else
};

function feedbackDataNext() {
    window.location.replace(baseApp + "/views/mapping");
}

$.ajax({
    url: "/validate-data",
    type: "GET",
    cache: false,
    success: displayMessages,
    error: function () {
        console.log("Fetching validation errors from the server failed.");
    }
});
<commit_msg>Fix validation route.<commit_after>/**
 * Created by bo on 5/7/16.
 */

var displayMessages = function displayMessages(data) {
    if(data.length == 0) {
        var html = '
Data validation is successful!
';
        $('#feedback-tables').append(html);
    }//if
    else {
        for (var i = 0; i < data.length; i++) {
            var fb = data[i];
            var msg = fb['message'];
            var vals = fb['offendingValues'];
            var msgRow =
                '
' +
                'Message: 	' +
                '  	' +
                '
' +
                '
' +
                '  	' +
                '' + msg + '	' +
                '
';
            var valRows = '
Offending Values:
';

            for (var j = 0; j < vals.length; j++) {
                valRows +=
                    '
' +
                    ' 	' +
                    '' + vals[j] + '	' +
                    '
';
            }
            var html =
                '
' +
                '
' +
                '
' +
                msgRow + '
' +
                valRows +
                '
' +
                '
' +
                '
';
            $('#feedback-tables').append(html);
        }
    }//else
};

function feedbackDataNext() {
    window.location.replace(baseApp + "/views/mapping");
}

$.ajax({
    url: "/validate/data",
    type: "GET",
    cache: false,
    success: displayMessages,
    error: function () {
        console.log("Fetching validation errors from the server failed.");
    }
});
<|endoftext|>


<commit_before>import React from "react"
import { Modal } from "../../../components/CommonElement"
import ReactTooltip from 'react-tooltip';
import { connect } from "react-redux"
import { getTranslate } from 'react-localize-redux'
import * as limitOrderActions from "../../../actions/limitOrderActions"
import * as accountActions from "../../../actions/accountActions"
import constants from "../../../services/constants"

import {getWallet} from "../../../services/keys"

import {getNonce, submitOrder, getFee} from "../../../services/limit_order"
import * as converters from "../../../utils/converter"
import BLOCKCHAIN_INFO from "../../../../../env"

@connect((store, props) => {
    const account = store.account.account
    const translate = getTranslate(store.locale)
    const tokens = store.tokens.tokens
    const limitOrder = store.limitOrder
    const ethereum = store.connection.ethereum
    const global = store.global;

    return {
        translate, limitOrder, tokens, account, ethereum, global
    }
})

export default class ConfirmModal extends React.Component {

    constructor(){
        super()
        this.state = {
            err: "",
            isConfirming: false,
            isFetchFee : true,
            isFinish: false,
            fee : constants.LIMIT_ORDER_CONFIG.maxFee
        }
        this.onSubmit = this.onSubmit.bind(this);
    }

    componentDidMount = () => {
      this.fetchFee()
    }

    async fetchFee(){
      var userAddr = this.props.account.address
      var src = this.props.tokens[this.props.limitOrder.sourceTokenSymbol].address
      var dest = this.props.tokens[this.props.limitOrder.destTokenSymbol].address
      var srcAmount = this.props.limitOrder.sourceAmount
      var destAmount = this.props.limitOrder.destAmount
      try{
        var fee = await getFee(userAddr, src, dest, srcAmount, destAmount)
        this.setState({isFetchFee : false, fee: fee})
      }catch(err){
        console.log(err)
        this.setState({isFetchFee : false})
      }
    }

    async getUserNonce(){
        //user nonce from server
        try{
            var ethereum = this.props.ethereum
            //nonce from server
            var nonceServer = await getNonce(this.props.account.address, this.props.limitOrder.sourceTokenSymbol, this.props.limitOrder.destTokenSymbol)

            // nonce from contract
            var concatTokenAddresses = converters.concatTokenAddresses(this.props.limitOrder.sourceToken, this.props.limitOrder.destToken)
            console.log(concatTokenAddresses)
            var nonceContract = await ethereum.call("getLimitOrderNonce", this.props.account.address, concatTokenAddresses)
            nonceContract  = converters.sumOfTwoNumber(nonceContract, 1)
            nonceContract = converters.toHex(nonceContract)
            //get minimum nonce
            var minNonce = converters.calculateMinNonce(BLOCKCHAIN_INFO.kyberswapAddress)

            var validNonce = converters.findMaxNumber([nonceServer, nonceContract, minNonce])
            return validNonce
        }catch(err){
            console.log(err)
            throw err
        }
    }

    async onSubmit(){
        if(this.state.isFetchFee) return
        //reset
        var wallet = getWallet(this.props.account.type)
        var password = "";
        this.setState({
          isConfirming: true,
          err: ""
        });

        try{
            //get user nonce
            var ethereum = this.props.ethereum
            var user = this.props.account.address.toLowerCase()
            var nonce = await this.getUserNonce()
            nonce = converters.toHex(nonce)
            var srcToken = this.props.limitOrder.sourceToken.toLowerCase()

            var srcQty = converters.toTWei(this.props.limitOrder.sourceAmount, this.props.tokens[this.props.limitOrder.sourceTokenSymbol].decimals)
            srcQty = converters.toHex(srcQty)

            var destToken = this.props.limitOrder.destToken.toLowerCase()
            var destAddress = this.props.account.address.toLowerCase()
            var minConversionRate = converters.toTWei(this.props.limitOrder.triggerRate, 18)
            minConversionRate = converters.toHex(minConversionRate)

            var feeInPrecision = this.state.fee
            feeInPrecision = converters.toTWei(feeInPrecision, 4)
            feeInPrecision = converters.toHex(feeInPrecision)

            var signData = await ethereum.call("getMessageHash", user, nonce, srcToken, srcQty, destToken, destAddress, minConversionRate, feeInPrecision)
            console.log(signData)

            var signature = await wallet.signSignature(signData, this.props.account)

            // var pramameters = await ethereum.call("getSignatureParameters", signature)

            // console.log(signature)
            // console.log(signData)
            // console.log(pramameters)
            // console.log({user, nonce, srcToken, srcQty, destToken, destAddress, minConversionRate, feeInPrecision})

            var newOrder = await submitOrder({
                address: this.props.account.address,
                nonce: nonce,
                source: this.props.limitOrder.sourceTokenSymbol,
                dest: this.props.limitOrder.destTokenSymbol,
                src_amount: parseFloat(this.props.limitOrder.sourceAmount),
                min_rate: this.props.limitOrder.triggerRate,
                fee: this.props.limitOrder.orderFee,
                signature: signature
            });

            newOrder.id = this.props.limitOrder.listOrder.length + 1;

            //save new order
            this.props.dispatch(limitOrderActions.addNewOrder(newOrder))

            //go to the next step
            // this.props.dispatch(limitOrderActions.forwardOrderPath())
            this.setState({
              isFinish: true,
              isConfirming: false
            });
        }catch(err){
            console.log(err.message);
            this.setState({
              err: err.toString(),
              isConfirming: false,
              isFinish: false
            })
        }
    }

    closeModal = () => {
      if (this.state.isConfirming) return;
      this.props.dispatch(limitOrderActions.resetOrderPath())
    }

    msgHtml = () => {
      if (this.state.isConfirming && this.props.account.type !== 'privateKey') {
          return

          {this.props.translate("modal.waiting_for_confirmation") || "Waiting for confirmation from your wallet"}

      } else {
          return ""
      }
  }

    getFeeInfoTooltip = () => {
      let calculateFee = (this.props.limitOrder.orderFee * this.props.limitOrder.sourceAmount) / 100;
      calculateFee = converters.roundingNumber(calculateFee);
      const sourceAmount = converters.roundingNumber(this.props.limitOrder.sourceAmount)

      return `

          ${`Fee ${calculateFee} ${this.props.limitOrder.sourceTokenSymbol} (${this.props.limitOrder.orderFee}% of ${sourceAmount} ${this.props.limitOrder.sourceTokenSymbol})`}

          ${this.props.translate("limit_order.fee_info_message") || "Don’t worry. You will not be charged now. You pay fees only when transaction is executed (broadcasted & mined)."}

      `
    }

    getFeeInfoComponent = () => {
      return (
        <React.Fragment>

          <ReactTooltip globalEventOff="click" html={true} place="right" type="light" id="fee-info" className="limit-order-modal__fee--info">
            {this.getFeeInfoTooltip()}
          </ReactTooltip>
        </React.Fragment>
      );
    }

    contentModal = () => {
      let calculateFee = (this.props.limitOrder.orderFee * this.props.limitOrder.sourceAmount) / 100;
      // calculateFee = converters.displayNumberWithDot(calculateFee);

      const receiveAmount = (this.props.limitOrder.sourceAmount - (this.props.limitOrder.orderFee * this.props.limitOrder.sourceAmount) / 100) * this.props.limitOrder.triggerRate
      return (

                {this.props.translate("modal.order_confirm") ||
                  "Order Confirm"}

 this.closeModal()}>

                  {this.props.translate("limit_order.confirm_order_message", {
                    srcToken: this.props.limitOrder.sourceTokenSymbol,
                    destToken: this.props.limitOrder.destTokenSymbol,
                    rate: this.props.limitOrder.triggerRate
                  }) ||
                    `Your transaction will be broadcasted when rate of ${this.props.limitOrder.sourceTokenSymbol}/${this.props.limitOrder.destTokenSymbol} >= ${this.props.limitOrder.triggerRate}`
                  }

{this.props.translate("transaction.exchange_from") || "From"}

                            {this.props.limitOrder.sourceAmount}

                            {this.props.limitOrder.sourceTokenSymbol}

{this.props.translate("transaction.exchange_to") || "To"}

                            {this.props.limitOrder.snapshot.isFetchingRate ?  : this.props.limitOrder.destAmount}

                            {this.props.limitOrder.destTokenSymbol}

                        {this.props.translate("limit_order.fee") || "Fee"}

                      {!this.props.global.isOnMobile && this.getFeeInfoComponent()}

                        {converters.displayNumberWithDot(calculateFee)}

                        {this.props.limitOrder.sourceTokenSymbol}

                      {this.props.global.isOnMobile && this.getFeeInfoComponent()}

                  You will receive{' '}
                  {`${converters.displayNumberWithDot(receiveAmount)} ${this.props.limitOrder.destTokenSymbol}`}

                  {this.msgHtml()}
                {this.state.err &&

                  {this.state.err}

}

            {!this.state.isFinish &&

              <button
                className={`btn-cancel ${(this.state.isConfirming || this.state.isFetchFee) ? "btn--disabled" : ""}`}
                onClick={e => this.closeModal()}
              >
                {this.props.translate("modal.cancel") || "Cancel"}
              </button>
              <button className={`btn-confirm ${(this.state.isConfirming || this.state.isFetchFee) ? "btn--disabled" : ""}`}
                onClick={e => this.onSubmit()}>{this.props.translate("modal.confirm") || "Confirm"}</button>

}

            {this.state.isFinish &&

              Success

}

      )
    }

    render() {
        return (
        <Modal className={{
            base: 'reveal medium confirm-modal',
            afterOpen: 'reveal medium confirm-modal'
          }}
            isOpen={true}
            onRequestClose={this.closeModal}
            contentLabel="Confirm modal"
            content={this.contentModal()}
            size="medium"
          />
        )

    }
}
<commit_msg>add console<commit_after>import React from "react"
import { Modal } from "../../../components/CommonElement"
import ReactTooltip from 'react-tooltip';
import { connect } from "react-redux"
import { getTranslate } from 'react-localize-redux'
import * as limitOrderActions from "../../../actions/limitOrderActions"
import * as accountActions from "../../../actions/accountActions"
import constants from "../../../services/constants"

import {getWallet} from "../../../services/keys"

import {getNonce, submitOrder, getFee} from "../../../services/limit_order"
import * as converters from "../../../utils/converter"
import BLOCKCHAIN_INFO from "../../../../../env"

@connect((store, props) => {
    const account = store.account.account
    const translate = getTranslate(store.locale)
    const tokens = store.tokens.tokens
    const limitOrder = store.limitOrder
    const ethereum = store.connection.ethereum
    const global = store.global;

    return {
        translate, limitOrder, tokens, account, ethereum, global
    }
})

export default class ConfirmModal extends React.Component {

    constructor(){
        super()
        this.state = {
            err: "",
            isConfirming: false,
            isFetchFee : true,
            isFinish: false,
            fee : constants.LIMIT_ORDER_CONFIG.maxFee
        }
        this.onSubmit = this.onSubmit.bind(this);
    }

    componentDidMount = () => {
      this.fetchFee()
    }

    async fetchFee(){
      var userAddr = this.props.account.address
      var src = this.props.tokens[this.props.limitOrder.sourceTokenSymbol].address
      var dest = this.props.tokens[this.props.limitOrder.destTokenSymbol].address
      var srcAmount = this.props.limitOrder.sourceAmount
      var destAmount = this.props.limitOrder.destAmount
      try{
        var fee = await getFee(userAddr, src, dest, srcAmount, destAmount)
        this.setState({isFetchFee : false, fee: fee})
      }catch(err){
        console.log(err)
        this.setState({isFetchFee : false})
      }
    }

    async getUserNonce(){
        //user nonce from server
        try{
            var ethereum = this.props.ethereum
            //nonce from server
            var nonceServer = await getNonce(this.props.account.address, this.props.limitOrder.sourceTokenSymbol, this.props.limitOrder.destTokenSymbol)

            // nonce from contract
            var concatTokenAddresses = converters.concatTokenAddresses(this.props.limitOrder.sourceToken, this.props.limitOrder.destToken)
            console.log(concatTokenAddresses)
            var nonceContract = await ethereum.call("getLimitOrderNonce", this.props.account.address, concatTokenAddresses)
            nonceContract  = converters.sumOfTwoNumber(nonceContract, 1)
            nonceContract = converters.toHex(nonceContract)
            //get minimum nonce
            var minNonce = converters.calculateMinNonce(BLOCKCHAIN_INFO.kyberswapAddress)

            var validNonce = converters.findMaxNumber([nonceServer, nonceContract, minNonce])
            return validNonce
        }catch(err){
            console.log(err)
            throw err
        }
    }

    async onSubmit(){
        if(this.state.isFetchFee) return
        //reset
        var wallet = getWallet(this.props.account.type)
        var password = "";
        this.setState({
          isConfirming: true,
          err: ""
        });

        try{
            //get user nonce
            var ethereum = this.props.ethereum
            var user = this.props.account.address.toLowerCase()
            var nonce = await this.getUserNonce()
            nonce = converters.toHex(nonce)
            var srcToken = this.props.limitOrder.sourceToken.toLowerCase()

            var srcQty = converters.toTWei(this.props.limitOrder.sourceAmount, this.props.tokens[this.props.limitOrder.sourceTokenSymbol].decimals)
            srcQty = converters.toHex(srcQty)

            var destToken = this.props.limitOrder.destToken.toLowerCase()
            var destAddress = this.props.account.address.toLowerCase()
            var minConversionRate = converters.toTWei(this.props.limitOrder.triggerRate, 18)
            minConversionRate = converters.toHex(minConversionRate)

            var feeInPrecision = this.state.fee
            feeInPrecision = converters.toTWei(feeInPrecision, 4)
            feeInPrecision = converters.toHex(feeInPrecision)

            var signData = await ethereum.call("getMessageHash", user, nonce, srcToken, srcQty, destToken, destAddress, minConversionRate, feeInPrecision)
            console.log(signData)

            var signature = await wallet.signSignature(signData, this.props.account)

            var pramameters = await ethereum.call("getSignatureParameters", signature)

            console.log(signature)
            console.log(signData)
            console.log(pramameters)
            console.log({user, nonce, srcToken, srcQty, destToken, destAddress, minConversionRate, feeInPrecision})

            var newOrder = await submitOrder({
                address: this.props.account.address,
                nonce: nonce,
                source: this.props.limitOrder.sourceTokenSymbol,
                dest: this.props.limitOrder.destTokenSymbol,
                src_amount: parseFloat(this.props.limitOrder.sourceAmount),
                min_rate: this.props.limitOrder.triggerRate,
                fee: this.props.limitOrder.orderFee,
                signature: signature
            });

            newOrder.id = this.props.limitOrder.listOrder.length + 1;

            //save new order
            this.props.dispatch(limitOrderActions.addNewOrder(newOrder))

            //go to the next step
            // this.props.dispatch(limitOrderActions.forwardOrderPath())
            this.setState({
              isFinish: true,
              isConfirming: false
            });
        }catch(err){
            console.log(err.message);
            this.setState({
              err: err.toString(),
              isConfirming: false,
              isFinish: false
            })
        }
    }

    closeModal = () => {
      if (this.state.isConfirming) return;
      this.props.dispatch(limitOrderActions.resetOrderPath())
    }

    msgHtml = () => {
      if (this.state.isConfirming && this.props.account.type !== 'privateKey') {
          return

          {this.props.translate("modal.waiting_for_confirmation") || "Waiting for confirmation from your wallet"}

      } else {
          return ""
      }
  }

    getFeeInfoTooltip = () => {
      let calculateFee = (this.props.limitOrder.orderFee * this.props.limitOrder.sourceAmount) / 100;
      calculateFee = converters.roundingNumber(calculateFee);
      const sourceAmount = converters.roundingNumber(this.props.limitOrder.sourceAmount)

      return `

          ${`Fee ${calculateFee} ${this.props.limitOrder.sourceTokenSymbol} (${this.props.limitOrder.orderFee}% of ${sourceAmount} ${this.props.limitOrder.sourceTokenSymbol})`}

          ${this.props.translate("limit_order.fee_info_message") || "Don’t worry. You will not be charged now. You pay fees only when transaction is executed (broadcasted & mined)."}

      `
    }

    getFeeInfoComponent = () => {
      return (
        <React.Fragment>

          <ReactTooltip globalEventOff="click" html={true} place="right" type="light" id="fee-info" className="limit-order-modal__fee--info">
            {this.getFeeInfoTooltip()}
          </ReactTooltip>
        </React.Fragment>
      );
    }

    contentModal = () => {
      let calculateFee = (this.props.limitOrder.orderFee * this.props.limitOrder.sourceAmount) / 100;
      // calculateFee = converters.displayNumberWithDot(calculateFee);

      const receiveAmount = (this.props.limitOrder.sourceAmount - (this.props.limitOrder.orderFee * this.props.limitOrder.sourceAmount) / 100) * this.props.limitOrder.triggerRate
      return (

                {this.props.translate("modal.order_confirm") ||
                  "Order Confirm"}

 this.closeModal()}>

                  {this.props.translate("limit_order.confirm_order_message", {
                    srcToken: this.props.limitOrder.sourceTokenSymbol,
                    destToken: this.props.limitOrder.destTokenSymbol,
                    rate: this.props.limitOrder.triggerRate
                  }) ||
                    `Your transaction will be broadcasted when rate of ${this.props.limitOrder.sourceTokenSymbol}/${this.props.limitOrder.destTokenSymbol} >= ${this.props.limitOrder.triggerRate}`
                  }

{this.props.translate("transaction.exchange_from") || "From"}

                            {this.props.limitOrder.sourceAmount}

                            {this.props.limitOrder.sourceTokenSymbol}

{this.props.translate("transaction.exchange_to") || "To"}

                            {this.props.limitOrder.snapshot.isFetchingRate ?  : this.props.limitOrder.destAmount}

                            {this.props.limitOrder.destTokenSymbol}

                        {this.props.translate("limit_order.fee") || "Fee"}

                      {!this.props.global.isOnMobile && this.getFeeInfoComponent()}

                        {converters.displayNumberWithDot(calculateFee)}

                        {this.props.limitOrder.sourceTokenSymbol}

                      {this.props.global.isOnMobile && this.getFeeInfoComponent()}

                  You will receive{' '}
                  {`${converters.displayNumberWithDot(receiveAmount)} ${this.props.limitOrder.destTokenSymbol}`}

                  {this.msgHtml()}
                {this.state.err &&

                  {this.state.err}

}

            {!this.state.isFinish &&

              <button
                className={`btn-cancel ${(this.state.isConfirming || this.state.isFetchFee) ? "btn--disabled" : ""}`}
                onClick={e => this.closeModal()}
              >
                {this.props.translate("modal.cancel") || "Cancel"}
              </button>
              <button className={`btn-confirm ${(this.state.isConfirming || this.state.isFetchFee) ? "btn--disabled" : ""}`}
                onClick={e => this.onSubmit()}>{this.props.translate("modal.confirm") || "Confirm"}</button>

}

            {this.state.isFinish &&

              Success

}

      )
    }

    render() {
        return (
        <Modal className={{
            base: 'reveal medium confirm-modal',
            afterOpen: 'reveal medium confirm-modal'
          }}
            isOpen={true}
            onRequestClose={this.closeModal}
            contentLabel="Confirm modal"
            content={this.contentModal()}
            size="medium"
          />
        )

    }
}
<|endoftext|>