<commit_before>
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var readingsArray = [];
var readings = [];
var reading = {};

if (localStorage.getItem("readings") == null) {

	//alert('Reading Empty');

	//readingsArray = [ { 'summary' : 'Test event ', 'begin' : new Date(), 'end' : new Date() } ];

} else {

	//alert('Reading NOT Empty');

	//localStorage.removeItem('readings');

	reading = { 'summary' : 'Today', 'begin' : new Date(y, m, d), 'end' : new Date(y, m, d) };

	readingsArray.push(reading);
	// = [ { "summary" : "Test event", "begin" : new Date(), "end" : new Date() } ];

	readings = JSON.parse(localStorage.getItem("readings"));

	var bdate = date.getDate();
	var edate = date.getDate();
	var bd = date.getDate();
	var bm = date.getMonth();
	var by = date.getFullYear();
	var ed = date.getDate();
	var em = date.getMonth();
	var ey = date.getFullYear();

    for (i = 0; i < readings.length; i++) {

      reading = JSON.parse(readings[i]);

      bd = parseInt(reading.begin.substring(0, 4));
	  bm = parseInt(reading.begin.substring(5, 7));
	  by = parseInt(reading.begin.substring(8, 10));
	  ed = parseInt(reading.end.substring(0, 4));
	  em = parseInt(reading.end.substring(5, 7));
	  ey = parseInt(reading.end.substring(8, 10));

      readingsArray.push( { 'summary' : reading.summary, 'begin' : new Date(y, m, d), 'end' : new Date(y, m, d) } );

    }

    //alert(readings[readings.length - 1]);

}

// Create an array that will contain the events
var events = [];

$(function() {

	setProfile();
	setupCalendar();

	$('#profile_save').click( function() {

		// Store
		saveProfile();
		setProfile();
	});

	$('#reading_save').click( function() {
		//var today = new Date();
		//alert(today.getUTCMonth());
		var date = new Date();
		var d = date.getDate();
		var m = date.getMonth();
		var y = date.getFullYear();
		var type = $('#reading_type').val();
		var value = $('#reading_value').val();
		var units = '';

	   switch (type) {
		    case "Weight":
        		units = "lbs";
        		break;
		}

		date = new Date();
		d = date.getDate();
		m = date.getMonth();
 		y = date.getFullYear();

		reading = { "summary" : type + ":" + value + " " + units, "begin" : new Date(y, m, d), "end": new Date(y, m, d) };
		readingsArray.push(reading);
		$('#calendar').trigger('refresh');
		readings.push(JSON.stringify(reading));
		localStorage.setItem('readings', JSON.stringify(readings));
		//localStorage.setItem("readings", JSON.stringify(readingsArray));

		$('.ui-li-static').each(function() {
		//alert('decoding HTML');
    		$( this ).decHTML();
  			//alert($(this).html());
    	});

		$('#calendar .ui-btn').click(function() {
    	$('.ui-li-static').each(function() {
    		$( this ).decHTML();
  			//alert($(this).html());
    	});
    });

	});

	$('#craving_type').change( function() {

		var values = $(this).val();
		var arrayLength = values.length;
		$('#craving_tip').html('');

		for (var i = 0; i < arrayLength; i++) {

			switch (values[i]) {
			    case 'Bready':
			        $('#craving_tip').append('Sugary: Insecurity, soothes dissatisfaction.

');
        		break;
			    case 'Chewy':
			        $('#craving_tip').append('Chewy: Relieves Tension stress, slowdown so you can unwind.

');
		        break;
			    case 'Creamy':
			        $('#craving_tip').append('Creamy: Helps satisfy need to be nurtured and to receive comfort.

');
		        break;
			    case 'Crunchy':
			        $('#craving_tip').append('Crunchy: Helps release anxiety pressure.

');
		        break;
			    case 'Salty':
			        $('#craving_tip').append('Salty: Redirects anger, frustration and violence.

');
		        break;
			    case 'Sugary':
			        $('#craving_tip').append('Sugary: Substitutes for missing Love, affection ability to give and receive love.

');
		        break;
			}

    		//alert(myStringArray[i]);
    		//Do something
		}
		//var values = $(this).val().split(',');
		//alert('The first value in the array is ' + values[0]);
	});

	$('#journal_save').click( function() {
		//var today = new Date();
		//alert(today.getUTCMonth());
		var date = new Date();
		var d = date.getDate();
		var m = date.getMonth();
		var y = date.getFullYear();
		var mood = $('#journal_mood').val();
		var note = $('#journal_note').val();
		var icon = '';

	   switch (mood) {
		    case "Happy":
        		icon = "img/emoticons/PNG/icontexto-emoticons-03-032x032.png";
        		//alert(icon);
        		break;
        	case "Sad":
        		icon = "img/emoticons/PNG/icontexto-emoticons-13-032x032.png";
        		//alert(icon);
        		break;
        	case "Sick":
        		icon = "img/emoticons/PNG/icontexto-emoticons-11-032x032.png";
        		//alert(icon);
        		break;
		}

		date = new Date();
		d = date.getDate();
		m = date.getMonth();
 		y = date.getFullYear();

		reading = { 'summary' : mood + ' :' + note, 'begin' : new Date(y, m, d), 'end': new Date(y, m, d) };
		readingsArray.push(reading);
		$('#calendar').trigger('refresh');
		readings.push(JSON.stringify(reading));
		localStorage.setItem('readings', JSON.stringify(readings));
		//localStorage.setItem("readings", JSON.stringify(readingsArray));

		$('.ui-li-static').each(function() {
			//alert('decoding html');
    		$( this ).decHTML();
  			//alert($(this).html());
    	});

	});

	$('#calendar .ui-btn').click(function() {

    	$('.ui-li-static').each(function() {
    		$( this ).decHTML();
  			//alert($(this).html());
    	});
    });

});

$(document).on("pagecreate", function(){
    var opts = $("#journal_mood option");
    $( "#journal_mood-listbox-popup" ).on( "popupafteropen", function( event, ui ) {
        $("#journal_mood-menu li").each(function(index){
            if ($(this).find("img").length == 0){
                var imageURL = opts.eq(index).data("image");
                var imgElem = '';
                $(this).find("a").prepend(imgElem);
            }
        });
    });
});

function saveProfile() {
	//alert($('#profile_breakfast').val());
	localStorage.setItem("name", $('#profile_name').val());
	localStorage.setItem("age", $('#profile_age').val() + " years");
	localStorage.setItem("weight", $('#profile_weight').val());
	localStorage.setItem("breakfast", $('#profile_breakfast').val());
	localStorage.setItem("lunch", $('#profile_lunch').val());
	localStorage.setItem("dinner", $('#profile_dinner').val());
	localStorage.setItem("sugar", $('#profile_sugar').val());
	localStorage.setItem("sugar_fasting", $('#profile_sugar_fasting').val());
	calendar_events();

}

function setProfile() {

	//alert('Setting profile field');

	setProfilefield('name');
	setProfilefield('age');
	setProfilefield('breakfast');
	setProfilefield('lunch');
	setProfilefield('dinner');
	//setProfilefield('weight');
	//setProfilefield('sugar');
	//setProfilefield('sugar_fasting');

}

function setProfilefield(fieldName) {

	if (localStorage.getItem(fieldName) === null) {
		//alert('field IS empty');
		$('#profile' + fieldName).html('');
		//$('#profile_' + fieldName).val('');
	} else {
		//alert(fieldName + ' field is NOT empty');
		$('#profile' + fieldName).html(localStorage.getItem(fieldName));
		$('#profile_' + fieldName).val(localStorage.getItem(fieldName));
		//if ($('#profile_' + fieldName).attr('type') == 'range') {
			//$('#profile_' + fieldName).val(localStorage.getItem(fieldName)).slider('disabled', true).slider('refresh');
			//$('#profile_' + fieldName).val(localStorage.getItem(fieldName)).slider("refresh");
		//}
	}

}

function setupCalendar() {

	//alert(JSON.stringify(readingsArray[readingsArray.length - 1]));

    $("#calendar").jqmCalendar({
        events: readingsArray,
        months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
        days: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
        startOfWeek: 0
    });

    $('#calendar').trigger('refresh');

    //alert('setting up calendar');

    $('.ui-li-static').each(function() {
    	$( this ).decHTML();
  		//alert($(this).html());
    });

    $('#calendar .ui-btn').click(function() {
    	$('.ui-li-static').each(function() {
    		$( this ).decHTML();
  			//alert($(this).html());
    	});
    });
}

function createNotifications() {

	/* Set Break Hour in 24hr Notation */
	var breakHour=9;
	/* Set Break Minute */
	var breakMinute=5;
	/* Set Break Message */
	var breakMessage="Reports! Take Your Break!";

	var theDate=new Date();

	if (Math.abs(theDate.getHours())==breakHour&&Math.abs(theDate.getMinutes())==breakMinute) {
		this.focus();
		clearInterval(breakInt);
		alert(breakMessage);
	}

	var breakInt=setInterval("breakTime()",58000);

}

function calendar_events() {

  alert('adding calendar event');
  //alert($('#profile_lunch').val());

  var startDate = new Date();

  startDate.setDate(startDate.getDate() + 1);
  startDate.setHours(parseInt($('#profile_lunch').val().substring(0, 2)));
  startDate.setMinutes(parseInt($('#profile_lunch').val().substring(3, 5)));

  alert(startDate.toString());

  var endDate = startDate;
  endDate.setMinutes(endDate.getMinutes() + 30);
  var title = "Lunch Time";
  var location = "Unknown";
  var notes = 'Please enter your craving';
  var success = function(message) { alert("Success: " + JSON.stringify(message)); };
  var error = function(message) { alert("Error: " + message); };

  var calOptions = window.plugins.calendar.getCalendarOptions();

  calOptions.recurrence = "daily"; // supported are: daily, weekly, monthly, yearly
  eventEnd = startDate;
  eventEnd.setFullYear(startDate.getFullYear() + 1);
  calOptions.recurrenceEndDate = eventEnd;

  //alert(startDate.toString());

  //  window.plugins.calendar.createCalendar(calendarName,success,error);
  window.plugins.calendar.createEventWithOptions(title,location,notes,startDate,endDate,calOptions,success,error);

}

<commit_msg>no reccurence to events<commit_after>
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var readingsArray = [];
var readings = [];
var reading = {};

if (localStorage.getItem("readings") == null) {

	//alert('Reading Empty');

	//readingsArray = [ { 'summary' : 'Test event ', 'begin' : new Date(), 'end' : new Date() } ];

} else {

	//alert('Reading NOT Empty');

	//localStorage.removeItem('readings');

	reading = { 'summary' : 'Today', 'begin' : new Date(y, m, d), 'end' : new Date(y, m, d) };

	readingsArray.push(reading);
	// = [ { "summary" : "Test event", "begin" : new Date(), "end" : new Date() } ];

	readings = JSON.parse(localStorage.getItem("readings"));

	var bdate = date.getDate();
	var edate = date.getDate();
	var bd = date.getDate();
	var bm = date.getMonth();
	var by = date.getFullYear();
	var ed = date.getDate();
	var em = date.getMonth();
	var ey = date.getFullYear();

    for (i = 0; i < readings.length; i++) {

      reading = JSON.parse(readings[i]);

      bd = parseInt(reading.begin.substring(0, 4));
	  bm = parseInt(reading.begin.substring(5, 7));
	  by = parseInt(reading.begin.substring(8, 10));
	  ed = parseInt(reading.end.substring(0, 4));
	  em = parseInt(reading.end.substring(5, 7));
	  ey = parseInt(reading.end.substring(8, 10));

      readingsArray.push( { 'summary' : reading.summary, 'begin' : new Date(y, m, d), 'end' : new Date(y, m, d) } );

    }

    //alert(readings[readings.length - 1]);

}

// Create an array that will contain the events
var events = [];

$(function() {

	setProfile();
	setupCalendar();

	$('#profile_save').click( function() {

		// Store
		saveProfile();
		setProfile();
	});

	$('#reading_save').click( function() {
		//var today = new Date();
		//alert(today.getUTCMonth());
		var date = new Date();
		var d = date.getDate();
		var m = date.getMonth();
		var y = date.getFullYear();
		var type = $('#reading_type').val();
		var value = $('#reading_value').val();
		var units = '';

	   switch (type) {
		    case "Weight":
        		units = "lbs";
        		break;
		}

		date = new Date();
		d = date.getDate();
		m = date.getMonth();
 		y = date.getFullYear();

		reading = { "summary" : type + ":" + value + " " + units, "begin" : new Date(y, m, d), "end": new Date(y, m, d) };
		readingsArray.push(reading);
		$('#calendar').trigger('refresh');
		readings.push(JSON.stringify(reading));
		localStorage.setItem('readings', JSON.stringify(readings));
		//localStorage.setItem("readings", JSON.stringify(readingsArray));

		$('.ui-li-static').each(function() {
		//alert('decoding HTML');
    		$( this ).decHTML();
  			//alert($(this).html());
    	});

		$('#calendar .ui-btn').click(function() {
    	$('.ui-li-static').each(function() {
    		$( this ).decHTML();
  			//alert($(this).html());
    	});
    });

	});

	$('#craving_type').change( function() {

		var values = $(this).val();
		var arrayLength = values.length;
		$('#craving_tip').html('');

		for (var i = 0; i < arrayLength; i++) {

			switch (values[i]) {
			    case 'Bready':
			        $('#craving_tip').append('Sugary: Insecurity, soothes dissatisfaction.

');
        		break;
			    case 'Chewy':
			        $('#craving_tip').append('Chewy: Relieves Tension stress, slowdown so you can unwind.

');
		        break;
			    case 'Creamy':
			        $('#craving_tip').append('Creamy: Helps satisfy need to be nurtured and to receive comfort.

');
		        break;
			    case 'Crunchy':
			        $('#craving_tip').append('Crunchy: Helps release anxiety pressure.

');
		        break;
			    case 'Salty':
			        $('#craving_tip').append('Salty: Redirects anger, frustration and violence.

');
		        break;
			    case 'Sugary':
			        $('#craving_tip').append('Sugary: Substitutes for missing Love, affection ability to give and receive love.

');
		        break;
			}

    		//alert(myStringArray[i]);
    		//Do something
		}
		//var values = $(this).val().split(',');
		//alert('The first value in the array is ' + values[0]);
	});

	$('#journal_save').click( function() {
		//var today = new Date();
		//alert(today.getUTCMonth());
		var date = new Date();
		var d = date.getDate();
		var m = date.getMonth();
		var y = date.getFullYear();
		var mood = $('#journal_mood').val();
		var note = $('#journal_note').val();
		var icon = '';

	   switch (mood) {
		    case "Happy":
        		icon = "img/emoticons/PNG/icontexto-emoticons-03-032x032.png";
        		//alert(icon);
        		break;
        	case "Sad":
        		icon = "img/emoticons/PNG/icontexto-emoticons-13-032x032.png";
        		//alert(icon);
        		break;
        	case "Sick":
        		icon = "img/emoticons/PNG/icontexto-emoticons-11-032x032.png";
        		//alert(icon);
        		break;
		}

		date = new Date();
		d = date.getDate();
		m = date.getMonth();
 		y = date.getFullYear();

		reading = { 'summary' : mood + ' :' + note, 'begin' : new Date(y, m, d), 'end': new Date(y, m, d) };
		readingsArray.push(reading);
		$('#calendar').trigger('refresh');
		readings.push(JSON.stringify(reading));
		localStorage.setItem('readings', JSON.stringify(readings));
		//localStorage.setItem("readings", JSON.stringify(readingsArray));

		$('.ui-li-static').each(function() {
			//alert('decoding html');
    		$( this ).decHTML();
  			//alert($(this).html());
    	});

	});

	$('#calendar .ui-btn').click(function() {

    	$('.ui-li-static').each(function() {
    		$( this ).decHTML();
  			//alert($(this).html());
    	});
    });

});

$(document).on("pagecreate", function(){
    var opts = $("#journal_mood option");
    $( "#journal_mood-listbox-popup" ).on( "popupafteropen", function( event, ui ) {
        $("#journal_mood-menu li").each(function(index){
            if ($(this).find("img").length == 0){
                var imageURL = opts.eq(index).data("image");
                var imgElem = '';
                $(this).find("a").prepend(imgElem);
            }
        });
    });
});

function saveProfile() {
	//alert($('#profile_breakfast').val());
	localStorage.setItem("name", $('#profile_name').val());
	localStorage.setItem("age", $('#profile_age').val() + " years");
	localStorage.setItem("weight", $('#profile_weight').val());
	localStorage.setItem("breakfast", $('#profile_breakfast').val());
	localStorage.setItem("lunch", $('#profile_lunch').val());
	localStorage.setItem("dinner", $('#profile_dinner').val());
	localStorage.setItem("sugar", $('#profile_sugar').val());
	localStorage.setItem("sugar_fasting", $('#profile_sugar_fasting').val());
	calendar_events();

}

function setProfile() {

	//alert('Setting profile field');

	setProfilefield('name');
	setProfilefield('age');
	setProfilefield('breakfast');
	setProfilefield('lunch');
	setProfilefield('dinner');
	//setProfilefield('weight');
	//setProfilefield('sugar');
	//setProfilefield('sugar_fasting');

}

function setProfilefield(fieldName) {

	if (localStorage.getItem(fieldName) === null) {
		//alert('field IS empty');
		$('#profile' + fieldName).html('');
		//$('#profile_' + fieldName).val('');
	} else {
		//alert(fieldName + ' field is NOT empty');
		$('#profile' + fieldName).html(localStorage.getItem(fieldName));
		$('#profile_' + fieldName).val(localStorage.getItem(fieldName));
		//if ($('#profile_' + fieldName).attr('type') == 'range') {
			//$('#profile_' + fieldName).val(localStorage.getItem(fieldName)).slider('disabled', true).slider('refresh');
			//$('#profile_' + fieldName).val(localStorage.getItem(fieldName)).slider("refresh");
		//}
	}

}

function setupCalendar() {

	//alert(JSON.stringify(readingsArray[readingsArray.length - 1]));

    $("#calendar").jqmCalendar({
        events: readingsArray,
        months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
        days: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
        startOfWeek: 0
    });

    $('#calendar').trigger('refresh');

    //alert('setting up calendar');

    $('.ui-li-static').each(function() {
    	$( this ).decHTML();
  		//alert($(this).html());
    });

    $('#calendar .ui-btn').click(function() {
    	$('.ui-li-static').each(function() {
    		$( this ).decHTML();
  			//alert($(this).html());
    	});
    });
}

function createNotifications() {

	/* Set Break Hour in 24hr Notation */
	var breakHour=9;
	/* Set Break Minute */
	var breakMinute=5;
	/* Set Break Message */
	var breakMessage="Reports! Take Your Break!";

	var theDate=new Date();

	if (Math.abs(theDate.getHours())==breakHour&&Math.abs(theDate.getMinutes())==breakMinute) {
		this.focus();
		clearInterval(breakInt);
		alert(breakMessage);
	}

	var breakInt=setInterval("breakTime()",58000);

}

function calendar_events() {

  alert('adding calendar event');
  //alert($('#profile_lunch').val());

  var startDate = new Date();

  startDate.setDate(startDate.getDate() + 1);
  startDate.setHours(parseInt($('#profile_lunch').val().substring(0, 2)));
  startDate.setMinutes(parseInt($('#profile_lunch').val().substring(3, 5)));

  alert(startDate.toString());

  var endDate = startDate;
  endDate.setMinutes(endDate.getMinutes() + 60);
  var title = "Lunch Time";
  var location = "Unknown";
  var notes = 'Please enter your craving';
  var success = function(message) { alert("Success: " + JSON.stringify(message)); };
  var error = function(message) { alert("Error: " + message); };

  var calOptions = window.plugins.calendar.getCalendarOptions();

  calOptions.recurrence = "daily"; // supported are: daily, weekly, monthly, yearly
  eventEnd = startDate;
  eventEnd.setFullYear(startDate.getFullYear() + 1);
  calOptions.recurrenceEndDate = eventEnd;

  //alert(startDate.toString());

  //  window.plugins.calendar.createCalendar(calendarName,success,error);
  window.plugins.calendar.createEvent(title,location,notes,startDate,endDate,success,error);

}

<|endoftext|>


<commit_before>;
// ==UserScript==
// @name        JIRATimeTracker
// @namespace   nickpeirson
// @include     /^https://[a-z]+\.atlassian\.net/browse/[A-Z]+-[0-9]+/
// @version     1
// @grant       GM_addStyle
// @require     Duration.js
// @require     Timer.js
// @require     Worklog.js
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js
// @require     Pubsub.jquery.js
// @require     http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.1.0/moment.min.js
// ==/UserScript==

//token = $("meta#atlassian-token").attr('content');
token = $("input[name='atl_token']").val();
issueId = $("input[name='id']").val();

$.subscribe(Worklog.prototype._EVENT_START, function (){
	$("div#staticpanel button#start").html('Pause').one('click',
		function() {
		    worklog.pause();
		});
});
$.subscribe(Worklog.prototype._EVENT_PAUSE, function (){
	$("div#staticpanel button#start").html('Start').one('click',
		function() {
		    worklog.start();
		});
});

GM_addStyle ( "                                     \
    #staticpanel {                                  \
        bottom:0;                                   \
        padding:2px 0 2px;                          \
        position:fixed;                             \
        width:100%;                                 \
        z-index:100;                                \
        display: none;                            \
    }                                               \
    #stopwatch {                                    \
        border:1px solid #C3702C;                   \
        margin: 0 auto;                             \
        width:180px;                                \
        background: rgba(195, 112, 44, 0.60);       \
    }                                               \
    div#staticpanel div#elapsed {                   \
        color: rgba(255, 255, 255, 0.9);            \
        font-weight: bold;                          \
        padding-right: 2px;                         \
        width: 95px;                                \
        text-align: right;                          \
        float: right;                               \
    }                                               \
" );

startButton = '<button type="button" id="start">Start</button>';
logButton = '<button type="button" id="log">Log</button>';
elapsedDisplay = '
00h 00m 00s';
$("body").append('

' +
    startButton + logButton + elapsedDisplay + '

');

$("div#staticpanel button#log").click(function() {
    try {
		worklog.log();
	    if (confirm('Continue work on this ticket?')) {
	        worklog.start();
	    }
    } catch(e) {
    	alert("Couldn't log timer:\n" + e.message);
    }
});

(function displayElapsed(){
    setTimeout(function(){
          $('div#staticpanel div#elapsed').html(worklog.elapsedSecs().toHHMMSS());
          displayElapsed();
    }, 1000);
})();

worklog = new Worklog(issueId, token, localStorage, jQuery);
worklog.load();
$("div#staticpanel").toggle();<commit_msg>Quick hack to fix a bug where you couldn't start the timer<commit_after>;
// ==UserScript==
// @name        JIRATimeTracker
// @namespace   nickpeirson
// @include     /^https://[a-z]+\.atlassian\.net/browse/[A-Z]+-[0-9]+/
// @version     1
// @grant       GM_addStyle
// @require     Duration.js
// @require     Timer.js
// @require     Worklog.js
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js
// @require     Pubsub.jquery.js
// @require     http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.1.0/moment.min.js
// ==/UserScript==

//token = $("meta#atlassian-token").attr('content');
token = $("input[name='atl_token']").val();
issueId = $("input[name='id']").val();

function togglePause(){
	$("div#staticpanel button#start").html('Pause').one('click',
		function() {
		    worklog.pause();
		});
}
function toggleStart(){
	$("div#staticpanel button#start").html('Start').one('click',
		function() {
		    worklog.start();
		});
}

$.subscribe(Worklog.prototype._EVENT_START, togglePause);
$.subscribe(Worklog.prototype._EVENT_PAUSE, toggleStart);

GM_addStyle ( "                                     \
    #staticpanel {                                  \
        bottom:0;                                   \
        padding:2px 0 2px;                          \
        position:fixed;                             \
        width:100%;                                 \
        z-index:100;                                \
        display: none;                            \
    }                                               \
    #stopwatch {                                    \
        border:1px solid #C3702C;                   \
        margin: 0 auto;                             \
        width:180px;                                \
        background: rgba(195, 112, 44, 0.60);       \
    }                                               \
    div#staticpanel div#elapsed {                   \
        color: rgba(255, 255, 255, 0.9);            \
        font-weight: bold;                          \
        padding-right: 2px;                         \
        width: 95px;                                \
        text-align: right;                          \
        float: right;                               \
    }                                               \
" );

startButton = '<button type="button" id="start">Start</button>';
logButton = '<button type="button" id="log">Log</button>';
elapsedDisplay = '
00h 00m 00s';
$("body").append('

' +
    startButton + logButton + elapsedDisplay + '

');

$("div#staticpanel button#log").click(function() {
    try {
		worklog.log();
	    if (confirm('Continue work on this ticket?')) {
	        worklog.start();
	    }
    } catch(e) {
    	alert("Couldn't log timer:\n" + e.message);
    }
});

(function displayElapsed(){
    setTimeout(function(){
          $('div#staticpanel div#elapsed').html(worklog.elapsedSecs().toHHMMSS());
          displayElapsed();
    }, 1000);
})();

worklog = new Worklog(issueId, token, localStorage, jQuery);
worklog.load();
if (worklog.elapsed() == 0) {
	toggleStart();
}
$("div#staticpanel").toggle();<|endoftext|>


<commit_before>/*
 * content script - Drag'n Download
 *
 * Author : Yuki <paselan@gmail.com>
 * Date   : November 25, 2011
 * License: MIT License
 */

// Path utilities.
var Path = {
  // Get basename.
  basename : function (path) {
    if (path != null && path !== '') {
      var result = path.match(/([^\/\\]*)$/);
      if (result && result[1] !== '') {
        return result[1];
      }
    }
    return null;
  },

  // Strip fragment string.
  stripFragment : function (path) {
    var hash = path.lastIndexOf('#');
    return hash != -1 ? path.substring(0, hash) : path;
  }
};

// Build data for DataTransfer.
function buildTransferData(url, filename, mime) {
  if (url == null || url === '')
    return null;

  if (mime == null)
    mime = 'application/octet-stream';

  if (filename == null)
    filename = Path.basename(Path.stripFragment(url));

  return [mime, filename, url].join(':');
}

function cancelEvent(event) {
  event.preventDefault();
}

// Add drag and drop handler.
function addDragHandler(elm) {
  if (elm.nodeType !== Node.ELEMENT_NODE)
    return false;

  var href = elm.getAttribute('href');
  if (href === null || href === '')
    return false;

  elm.draggable = true;
  elm.addEventListener('dragstart', function (event) {
    event.dataTransfer.setData('DownloadURL', buildTransferData(href));
  }, false);
  elm.addEventListener('dragenter', cancelEvent);
  elm.addEventListener('dragover',  cancelEvent);
  elm.addEventListener('drop',      cancelEvent);

  return true;
}

var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
  addDragHandler(links[i]);
}
<commit_msg>DownloadURL must be an absolute URI.<commit_after>/*
 * content script - Drag'n Download
 *
 * Author : Yuki <paselan@gmail.com>
 * Date   : November 25, 2011
 * License: MIT License
 */

// Path utilities.
var Path = {
  // Get basename.
  basename : function (path) {
    if (path != null && path !== '') {
      var result = path.match(/([^\/\\]*)$/);
      if (result && result[1] !== '') {
        return result[1];
      }
    }
    return null;
  },

  // Strip fragment string.
  stripFragment : function (path) {
    var hash = path.lastIndexOf('#');
    return hash != -1 ? path.substring(0, hash) : path;
  }
};

// Build data for DataTransfer.
function buildTransferData(url, filename, mime) {
  if (url == null || url === '')
    return null;

  if (mime == null)
    mime = 'application/octet-stream';

  if (filename == null)
    filename = Path.basename(Path.stripFragment(url));

  return [mime, filename, url].join(':');
}

function cancelEvent(event) {
  event.preventDefault();
}

// Add drag and drop handler.
function addDragHandler(elm) {
  // Note: Element.getAttribute('href') returns a value as is. and it maybe a relative path.
  //       HTMLAnchorElement.href has an absolute path. (DOM 2)
  if (!(elm instanceof HTMLAnchorElement))
    return false;

  if (elm.href === null || elm.href === '' || elm.href.charAt(0) === '#')
    return false;

  elm.draggable = true;
  elm.addEventListener('dragstart', function (event) {
    event.dataTransfer.setData('DownloadURL', buildTransferData(elm.href));
  }, false);

  return true;
}

var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
  addDragHandler(links[i]);
}
<|endoftext|>


<commit_before>var expect = require('chai').expect,
    sdk = require('../../lib/index.js'),
    Collection = sdk.Collection,

    fixtures = require('../fixtures');

describe('Collection', function () {
    describe('constructor', function () {
        it('should handle all properties', function () {
            var collectionDefinition = {
                    auth: {
                        type: 'basic',
                        basic: [{
                            key: 'username',
                            type: 'string',
                            value: 'postman'
                        }, {
                            key: 'password',
                            type: 'string',
                            value: 'password'
                        }]
                    },
                    event: [{
                        listen: 'test',
                        script: {
                            id: 'my-script-1',
                            type: 'text/javascript',
                            exec: ['console.log("This doesn\'t matter");']
                        }
                    }]
                },
                collection = new Collection(collectionDefinition);

            expect(collection).to.deep.include({
                events: new sdk.EventList({}, collectionDefinition.event),
                auth: new sdk.RequestAuth(collectionDefinition.auth)
            });
            expect(collection).to.have.property('items');
        });

        it('should not create auth if auth is falsy', function () {
            var collectionDefinition = {
                    auth: null
                },
                collection = new Collection(collectionDefinition);

            expect(collection).to.not.have.property('auth');
            expect(collection.toJSON()).to.not.have.property('auth');
        });
    });

    describe('sanity', function () {
        var rawCollection = fixtures.collectionV2,
            collection = new Collection(rawCollection);

        it('initializes successfully', function () {
            expect(collection).to.be.ok;
        });

        describe('has property', function () {
            it('id', function () {
                expect(collection).to.have.property('id', rawCollection.info.id);
            });

            it('items', function () {
                expect(collection).to.have.property('items').that.is.an('object');
                expect(collection.items.all()).to.be.an('array').that.has.lengthOf(3);
                expect(collection.items.all()).to.not.be.empty;
            });

            it('name', function () {
                expect(collection).to.have.property('name', rawCollection.info.name);
            });

            it('events', function () {
                expect(collection).to.have.property('events');
                expect(collection.events.all()).to.be.an('array').that.has.lengthOf(2);
                expect(collection.items.all()).to.not.be.empty;
            });
        });

        describe('has function', function () {
            it('forEachItem', function () {
                expect(collection.forEachItem).to.be.a('function');
            });
        });

        describe('info block parsing', function () {
            it('must parse description', function () {
                var collection = new Collection({
                    info: {
                        name: 'test',
                        description: 'this is test description'
                    }
                });

                expect(collection.description).to.be.ok;
                expect(collection.description.toString()).to.equal('this is test description');
            });

            it('must parse description from outside info block if info is absent', function () {
                var collection = new Collection({
                    name: 'test',
                    description: 'this is test description'
                });

                expect(collection.description).to.be.ok;
                expect(collection.description.toString()).to.equal('this is test description');
            });
        });
    });

    describe('isCollection', function () {
        it('must distinguish between collections and other objects', function () {
            var collection = new Collection(),
                nonCollection = {};

            expect(Collection.isCollection(collection)).to.be.true;
            expect(Collection.isCollection()).to.be.false;
            expect(Collection.isCollection(nonCollection)).to.be.false;
        });
    });

    describe('variables', function () {
        it('must be able to sync variables from an object', function () {
            var collection = new Collection();

            collection.syncVariablesFrom({
                var1: 'value1'
            });

            expect(collection.variables.count()).to.equal(1);
            expect(collection.variables.one('var1')).to.be.ok;
            expect(collection.variables.one('var1').value).to.equal('value1');
        });

        it('must be able to sync variables to a target object', function () {
            var collection = new Collection({
                    variable: [{
                        key: 'var1',
                        value: '1',
                        type: 'number'
                    }]
                }),
                target = {
                    extra: true
                };

            collection.syncVariablesTo(target);

            expect(target).to.have.property('var1', 1);
            expect(target).to.not.have.property('extra');
        });
    });

    describe('events', function () {
        it('should allow adding events with a multitude of script definition format', function () {
            var collection = new Collection(),
                collectionJSON;

            collection.events.add({
                listen: 'test',
                script: {
                    id: 'test-script-1',
                    type: 'text/javascript',
                    exec: ['console.log("Random");']
                }
            });
            collection.events.add({
                listen: 'prerequest',
                script: ['console.log("A little less random");']
            });

            collectionJSON = collection.toJSON();

            expect(collectionJSON.event[0]).to.eql({
                listen: 'test',
                script: {
                    id: 'test-script-1',
                    type: 'text/javascript',
                    exec: ['console.log("Random");']
                }
            });
            expect(collectionJSON.event[1]).to.have.property('listen', 'prerequest');
            expect(collectionJSON.event[1]).to.have.property('script');
            expect(collectionJSON.event[1].script).to.have.property('id');
            expect(collectionJSON.event[1].script).to.have.property('type', 'text/javascript');
            expect(collectionJSON.event[1].script.exec).to.eql(['console.log("A little less random");']);
        });
    });

    describe('.toJSON', function () {
        it('should handle all required properties', function () {
            var collectionDefinition = {
                    info: {
                        id: 'my-collection',
                        name: 'Yay Collection!',
                        description: { content: '__foo__', type: 'markdown' },
                        schema: 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json',
                        version: '2.1.0'
                    },
                    auth: {
                        type: 'basic',
                        basic: [{
                            key: 'username',
                            type: 'string',
                            value: 'postman'
                        }, {
                            key: 'password',
                            type: 'string',
                            value: 'password'
                        }]
                    },
                    event: [{
                        listen: 'test',
                        script: {
                            id: 'my-script-1',
                            type: 'text/javascript',
                            exec: [
                                'console.log("bcoz I am batman!");'
                            ]
                        }
                    }],
                    item: [{
                        event: [],
                        id: 'my-item-1',
                        request: {
                            method: 'GET',
                            url: {
                                host: ['postman-echo', 'com'],
                                path: ['get'],
                                protocol: 'https',
                                query: [],
                                variable: []
                            }
                        },
                        response: []
                    }],
                    variable: [{
                        key: 'foo',
                        value: 'bar',
                        type: 'string'
                    }]
                },
                collection = new Collection(collectionDefinition),
                collectionJSON = collection.toJSON();

            // version info does not exactly have a one to one mapping
            // with the definition and toJSON, hence the hack
            expect(collectionJSON.info.version).to.have.property('string', '2.1.0');
            delete collectionJSON.info.version;
            delete collectionDefinition.info.version;

            // @todo: Remove below conversion to JSON after the description serialization bug has been fixed
            collectionJSON.info.description = collectionJSON.info.description.toJSON();

            expect(collectionJSON).to.eql({
                info: {
                    _postman_id: 'my-collection',
                    name: 'Yay Collection!',
                    description: { content: '__foo__', type: 'markdown' },
                    schema: 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json'
                },
                auth: {
                    type: 'basic',
                    basic: [{
                        key: 'username',
                        type: 'string',
                        value: 'postman'
                    }, {
                        key: 'password',
                        type: 'string',
                        value: 'password'
                    }]
                },
                event: [{
                    listen: 'test',
                    script: {
                        id: 'my-script-1',
                        type: 'text/javascript',
                        exec: [
                            'console.log("bcoz I am batman!");'
                        ]
                    }
                }],
                item: [{
                    event: [],
                    id: 'my-item-1',
                    request: {
                        method: 'GET',
                        url: {
                            host: ['postman-echo', 'com'],
                            path: ['get'],
                            protocol: 'https',
                            query: [],
                            variable: []
                        }
                    },
                    response: []
                }],
                variable: [{
                    key: 'foo',
                    value: 'bar',
                    type: 'string'
                }]
            });

            // check for root level properties moved to info
            expect(collectionJSON).to.not.have.property('id');
            expect(collectionJSON).to.not.have.property('version');
            expect(collectionJSON).to.not.have.property('name');
        });
    });
});
<commit_msg>Update collection test to check for non emptiness<commit_after>var expect = require('chai').expect,
    sdk = require('../../lib/index.js'),
    Collection = sdk.Collection,

    fixtures = require('../fixtures');

describe('Collection', function () {
    describe('constructor', function () {
        it('should handle all properties', function () {
            var collectionDefinition = {
                    auth: {
                        type: 'basic',
                        basic: [{
                            key: 'username',
                            type: 'string',
                            value: 'postman'
                        }, {
                            key: 'password',
                            type: 'string',
                            value: 'password'
                        }]
                    },
                    event: [{
                        listen: 'test',
                        script: {
                            id: 'my-script-1',
                            type: 'text/javascript',
                            exec: ['console.log("This doesn\'t matter");']
                        }
                    }]
                },
                collection = new Collection(collectionDefinition);

            expect(collection).to.deep.include({
                events: new sdk.EventList({}, collectionDefinition.event),
                auth: new sdk.RequestAuth(collectionDefinition.auth)
            });
            expect(collection).to.have.property('items');
        });

        it('should not create auth if auth is falsy', function () {
            var collectionDefinition = {
                    auth: null
                },
                collection = new Collection(collectionDefinition);

            expect(collection).to.not.have.property('auth');
            expect(collection.toJSON()).to.not.have.property('auth');
        });
    });

    describe('sanity', function () {
        var rawCollection = fixtures.collectionV2,
            collection = new Collection(rawCollection);

        it('initializes successfully', function () {
            expect(collection).to.be.ok;
        });

        describe('has property', function () {
            it('id', function () {
                expect(collection).to.have.property('id', rawCollection.info.id);
            });

            it('items', function () {
                expect(collection).to.have.property('items').that.is.an('object');
                expect(collection.items.all()).to.be.an('array');
                expect(collection.items.all()).to.not.be.empty;
            });

            it('name', function () {
                expect(collection).to.have.property('name', rawCollection.info.name);
            });

            it('events', function () {
                expect(collection).to.have.property('events');
                expect(collection.events.all()).to.be.an('array');
                expect(collection.items.all()).to.not.be.empty;
            });
        });

        describe('has function', function () {
            it('forEachItem', function () {
                expect(collection.forEachItem).to.be.a('function');
            });
        });

        describe('info block parsing', function () {
            it('must parse description', function () {
                var collection = new Collection({
                    info: {
                        name: 'test',
                        description: 'this is test description'
                    }
                });

                expect(collection.description).to.be.ok;
                expect(collection.description.toString()).to.equal('this is test description');
            });

            it('must parse description from outside info block if info is absent', function () {
                var collection = new Collection({
                    name: 'test',
                    description: 'this is test description'
                });

                expect(collection.description).to.be.ok;
                expect(collection.description.toString()).to.equal('this is test description');
            });
        });
    });

    describe('isCollection', function () {
        it('must distinguish between collections and other objects', function () {
            var collection = new Collection(),
                nonCollection = {};

            expect(Collection.isCollection(collection)).to.be.true;
            expect(Collection.isCollection()).to.be.false;
            expect(Collection.isCollection(nonCollection)).to.be.false;
        });
    });

    describe('variables', function () {
        it('must be able to sync variables from an object', function () {
            var collection = new Collection();

            collection.syncVariablesFrom({
                var1: 'value1'
            });

            expect(collection.variables.count()).to.equal(1);
            expect(collection.variables.one('var1')).to.be.ok;
            expect(collection.variables.one('var1').value).to.equal('value1');
        });

        it('must be able to sync variables to a target object', function () {
            var collection = new Collection({
                    variable: [{
                        key: 'var1',
                        value: '1',
                        type: 'number'
                    }]
                }),
                target = {
                    extra: true
                };

            collection.syncVariablesTo(target);

            expect(target).to.have.property('var1', 1);
            expect(target).to.not.have.property('extra');
        });
    });

    describe('events', function () {
        it('should allow adding events with a multitude of script definition format', function () {
            var collection = new Collection(),
                collectionJSON;

            collection.events.add({
                listen: 'test',
                script: {
                    id: 'test-script-1',
                    type: 'text/javascript',
                    exec: ['console.log("Random");']
                }
            });
            collection.events.add({
                listen: 'prerequest',
                script: ['console.log("A little less random");']
            });

            collectionJSON = collection.toJSON();

            expect(collectionJSON.event[0]).to.eql({
                listen: 'test',
                script: {
                    id: 'test-script-1',
                    type: 'text/javascript',
                    exec: ['console.log("Random");']
                }
            });
            expect(collectionJSON.event[1]).to.have.property('listen', 'prerequest');
            expect(collectionJSON.event[1]).to.have.property('script');
            expect(collectionJSON.event[1].script).to.have.property('id');
            expect(collectionJSON.event[1].script).to.have.property('type', 'text/javascript');
            expect(collectionJSON.event[1].script.exec).to.eql(['console.log("A little less random");']);
        });
    });

    describe('.toJSON', function () {
        it('should handle all required properties', function () {
            var collectionDefinition = {
                    info: {
                        id: 'my-collection',
                        name: 'Yay Collection!',
                        description: { content: '__foo__', type: 'markdown' },
                        schema: 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json',
                        version: '2.1.0'
                    },
                    auth: {
                        type: 'basic',
                        basic: [{
                            key: 'username',
                            type: 'string',
                            value: 'postman'
                        }, {
                            key: 'password',
                            type: 'string',
                            value: 'password'
                        }]
                    },
                    event: [{
                        listen: 'test',
                        script: {
                            id: 'my-script-1',
                            type: 'text/javascript',
                            exec: [
                                'console.log("bcoz I am batman!");'
                            ]
                        }
                    }],
                    item: [{
                        event: [],
                        id: 'my-item-1',
                        request: {
                            method: 'GET',
                            url: {
                                host: ['postman-echo', 'com'],
                                path: ['get'],
                                protocol: 'https',
                                query: [],
                                variable: []
                            }
                        },
                        response: []
                    }],
                    variable: [{
                        key: 'foo',
                        value: 'bar',
                        type: 'string'
                    }]
                },
                collection = new Collection(collectionDefinition),
                collectionJSON = collection.toJSON();

            // version info does not exactly have a one to one mapping
            // with the definition and toJSON, hence the hack
            expect(collectionJSON.info.version).to.have.property('string', '2.1.0');
            delete collectionJSON.info.version;
            delete collectionDefinition.info.version;

            // @todo: Remove below conversion to JSON after the description serialization bug has been fixed
            collectionJSON.info.description = collectionJSON.info.description.toJSON();

            expect(collectionJSON).to.eql({
                info: {
                    _postman_id: 'my-collection',
                    name: 'Yay Collection!',
                    description: { content: '__foo__', type: 'markdown' },
                    schema: 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json'
                },
                auth: {
                    type: 'basic',
                    basic: [{
                        key: 'username',
                        type: 'string',
                        value: 'postman'
                    }, {
                        key: 'password',
                        type: 'string',
                        value: 'password'
                    }]
                },
                event: [{
                    listen: 'test',
                    script: {
                        id: 'my-script-1',
                        type: 'text/javascript',
                        exec: [
                            'console.log("bcoz I am batman!");'
                        ]
                    }
                }],
                item: [{
                    event: [],
                    id: 'my-item-1',
                    request: {
                        method: 'GET',
                        url: {
                            host: ['postman-echo', 'com'],
                            path: ['get'],
                            protocol: 'https',
                            query: [],
                            variable: []
                        }
                    },
                    response: []
                }],
                variable: [{
                    key: 'foo',
                    value: 'bar',
                    type: 'string'
                }]
            });

            // check for root level properties moved to info
            expect(collectionJSON).to.not.have.property('id');
            expect(collectionJSON).to.not.have.property('version');
            expect(collectionJSON).to.not.have.property('name');
        });
    });
});
<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.9.3
(function() {
  $(function() {
    var emptyInput, randomLetter, random_question, startUp, update_keyHandler, update_question, words;
    $("#question, #answer").hide();
    words = $.getJSON("spellings.json");
    $.when(words).done((function(d) {
      return startUp(d);
    }));
    $.when(words).fail(function(data, status, error) {
      console.log(status + error);
    });
    startUp = function(data) {
      $("#question, #answer").show();
      this.current = "";
      this.fail = 0;
      this.reveal = "";
      this.unfinished = [];
      update_question(data);
      return this.data = data;
    };
    random_question = function(data) {
      var choice, i, j, ref, ref1, results, results1;
      choice = Math.floor(Math.random() * data['words'].length);
      this.current = data['words'][choice]['name'];
      (function() {
        results = [];
        for (var i = 1, ref = this.current.length; 1 <= ref ? i <= ref : i >= ref; 1 <= ref ? i++ : i--){ results.push(i); }
        return results;
      }).apply(this).forEach(function() {
        return this.reveal = this.reveal.concat("_");
      });
      this.unfinished = (function() {
        results1 = [];
        for (var j = 1, ref1 = this.current.length - 1; 1 <= ref1 ? j <= ref1 : j >= ref1; 1 <= ref1 ? j++ : j--){ results1.push(j); }
        return results1;
      }).apply(this);
      return data['words'][choice];
    };
    update_question = function(data) {
      var entry, size;
      entry = random_question(data);
      update_keyHandler();
      size = entry.name.length;
      $("dd#hint_stat").empty().append("This word is " + size + " letters long.");
      $("dd#hint_define").empty().append(entry['hint']);
      return $("dd#hint_sentence").empty().append(entry['example']);
    };
    emptyInput = function() {
      return $("input#input_answer").val("");
    };
    randomLetter = function() {
      var breaking, n;
      if (this.reveal === this.current) {
        return;
      }
      breaking = 0;
      while (breaking < 500) {
        breaking += 1;
        n = Math.floor(Math.random() * this.current.length);
        if (this.reveal[n] === "_") {
          this.reveal = this.reveal.substring(0, n) + this.current[n] + this.reveal.substring(n + 1);
          return;
        }
      }
    };
    return update_keyHandler = function() {
      $("#input_answer").off();
      return $("#input_answer").keydown((function(_this) {
        return function(e) {
          var attempt, last;
          if (e.which === 13) {
            attempt = $("#input_answer").val();
            if (attempt.toLowerCase() === _this.current.toLowerCase()) {
              $(".alert").addClass("alert-success");
              $(".alert").empty().append("You had just spelt the word " + _this.current + " right!");
              update_question(_this.data);
              return emptyInput();
            } else {
              _this.fail += 1;
              $(".alert").addClass("alert-danger");
              if (_this.fail > 1) {
                last = " times.";
              } else {
                last = " time.";
              }
              randomLetter();
              $("#revealed").empty().append(_this.reveal);
              $(".alert").empty().append("You have failed " + _this.fail + last);
              return emptyInput();
            }
          }
        };
      })(this));
    };
  });

}).call(this);
<commit_msg>update output<commit_after>// Generated by CoffeeScript 1.9.3
(function() {
  $(function() {
    var emptyInput, randomLetter, random_question, startUp, update_keyHandler, update_question, words;
    $("#question, #answer").hide();
    words = $.getJSON("spellings.json");
    $.when(words).done((function(d) {
      return startUp(d);
    }));
    $.when(words).fail(function(data, status, error) {
      console.log(status + error);
    });
    startUp = function(data) {
      $("#question, #answer").show();
      this.current = "";
      this.fail = 0;
      this.reveal = "";
      this.unfinished = [];
      update_question(data);
      return this.data = data;
    };
    random_question = function(data) {
      var choice, i, j, ref, ref1, results, results1;
      choice = Math.floor(Math.random() * data['words'].length);
      this.current = data['words'][choice]['name'];
      (function() {
        results = [];
        for (var i = 1, ref = this.current.length; 1 <= ref ? i <= ref : i >= ref; 1 <= ref ? i++ : i--){ results.push(i); }
        return results;
      }).apply(this).forEach(function() {
        return this.reveal = this.reveal.concat("_");
      });
      this.unfinished = (function() {
        results1 = [];
        for (var j = 0, ref1 = this.current.length - 1; 0 <= ref1 ? j <= ref1 : j >= ref1; 0 <= ref1 ? j++ : j--){ results1.push(j); }
        return results1;
      }).apply(this);
      return data['words'][choice];
    };
    update_question = function(data) {
      var entry, i, len, size, word;
      entry = random_question(data);
      update_keyHandler();
      words = entry.name.split(" ").length;
      size = 0;
      for (i = 0, len = words.length; i < len; i++) {
        word = words[i];
        size += word.length;
      }
      $("dd#hint_stat").empty().append("This entry is " + size + " letters long.");
      $("dd#hint_define").empty().append(entry['hint']);
      return $("dd#hint_sentence").empty().append(entry['example']);
    };
    emptyInput = function() {
      return $("input#input_answer").val("");
    };
    randomLetter = function() {
      var decide, n;
      if (this.reveal === this.current) {
        return;
      }
      decide = Math.floor(Math.random() * this.unfinished.length);
      n = this.unfinished[decide];
      this.reveal = this.reveal.substring(0, n) + this.current[n] + this.reveal.substring(n + 1);
      return this.unfinished.splice(decide, 1);
    };
    return update_keyHandler = function() {
      $("#input_answer").off();
      return $("#input_answer").keydown((function(_this) {
        return function(e) {
          var attempt, last;
          if (e.which === 13) {
            attempt = $("#input_answer").val();
            if (attempt.toLowerCase() === _this.current.toLowerCase()) {
              $(".alert").addClass("alert-success");
              $(".alert").empty().append("You had just spelt the word " + _this.current + " right!");
              $("#revealed").empty();
              _this.reveal = "";
              update_question(_this.data);
              return emptyInput();
            } else {
              _this.fail += 1;
              $(".alert").addClass("alert-danger");
              if (_this.fail > 1) {
                last = " times.";
              } else {
                last = " time.";
              }
              randomLetter();
              $("#revealed").empty().append(_this.reveal);
              $(".alert").empty().append("You have failed " + _this.fail + last);
              return emptyInput();
            }
          }
        };
      })(this));
    };
  });

}).call(this);
<|endoftext|>


<commit_before>module("jsAspect.afterReturning", {
  setup: function() {
    this.logged = [];
  }
});

(function() {

  function getAspectWithAfterBeforeMethodsAdvices(self) {
    var afterAdviceBehaviour = function() {
      self.logged.push("joinPoint", "after");
    };
    var beforeAdviceBehaviour = function() {
      self.logged.push("joinPoint", "before");
    };
    var afterAdvice =  new jsAspect.Advice.After(afterAdviceBehaviour, jsAspect.SCOPE.METHODS);
    var beforeAdvice = new jsAspect.Advice.Before(beforeAdviceBehaviour, jsAspect.SCOPE.METHODS);

    return new jsAspect.Aspect(beforeAdvice, afterAdvice);
  }

  test("Setting pointcut to SCOPE.METHODS does not work, method defined inside constructor", function() {
    var aspect = getAspectWithAfterBeforeMethodsAdvices(this);

    function Target() {
      this.method1 = function() {
        return "method1value";
      };
    }

    var target = new Target();

    aspect.applyTo(target);

    target.method1();

    deepEqual(this.logged, ["joinPoint", "before", "joinPoint", "after"], "advices were invoked");
  });

  test("Setting pointcut to SCOPE.METHODS does not work, method defined as object property", function() {
    var aspect = getAspectWithAfterBeforeMethodsAdvices(this);

    var foo = {
      method1: function () {
        return "foobar.";
      }
    };

    aspect.applyTo(foo);

    foo.method1();

    deepEqual(this.logged, ["joinPoint", "before", "joinPoint", "after"], "advices were invoked");
  });
})();<commit_msg>Corrected typo in the name of the test suite<commit_after>module("jsAspect.issues", {
  setup: function() {
    this.logged = [];
  }
});

(function() {

  function getAspectWithAfterBeforeMethodsAdvices(self) {
    var afterAdviceBehaviour = function() {
      self.logged.push("joinPoint", "after");
    };
    var beforeAdviceBehaviour = function() {
      self.logged.push("joinPoint", "before");
    };
    var afterAdvice =  new jsAspect.Advice.After(afterAdviceBehaviour, jsAspect.SCOPE.METHODS);
    var beforeAdvice = new jsAspect.Advice.Before(beforeAdviceBehaviour, jsAspect.SCOPE.METHODS);

    return new jsAspect.Aspect(beforeAdvice, afterAdvice);
  }

  test("Setting pointcut to SCOPE.METHODS does not work, method defined inside constructor", function() {
    var aspect = getAspectWithAfterBeforeMethodsAdvices(this);

    function Target() {
      this.method1 = function() {
        return "method1value";
      };
    }

    var target = new Target();

    aspect.applyTo(target);

    target.method1();

    deepEqual(this.logged, ["joinPoint", "before", "joinPoint", "after"], "advices were invoked");
  });

  test("Setting pointcut to SCOPE.METHODS does not work, method defined as object property", function() {
    var aspect = getAspectWithAfterBeforeMethodsAdvices(this);

    var foo = {
      method1: function () {
        return "foobar.";
      }
    };

    aspect.applyTo(foo);

    foo.method1();

    deepEqual(this.logged, ["joinPoint", "before", "joinPoint", "after"], "advices were invoked");
  });
})();<|endoftext|>


<commit_before>angular.module('ngGoogle', [])
    .provider('$google', function () {
      var config = {};

      return {
        initialize: function (clientId, scopes) {
          config.clientId = clientId;
          config.scope = scopes.join(' ');
        },
        $get: function ($window, $http, $q) {
          function authorize() {
            var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + $.param({
                      client_id: config.clientId,
                      scope: config.scope,
                      redirect_uri: 'http://localhost',
                      response_type: 'code'
                    }),
                authWindow = $window.open(authUrl, '_blank', 'location=no,toolbar=no'),
                deferred = $q.defer();

            $(authWindow).on('loadstart', function (e) {
              var url = e.originalEvent.url;
              var code = /\?code=(.+)$/.exec(url);
              var error = /\?error=(.+)$/.exec(url);

              if (code || error) {
                authWindow.close();
              }

              if (code) {
                $http.post('https://accounts.google.com/o/oauth2/token', {
                  code: code[1],
                  client_id: config.clientId,
                  redirect_uri: 'http://localhost',
                  grant_type: 'authorization_code'
                }, {
                  headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                  },
                  transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj)
                      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    return str.join("&");
                  },
                }).success(function (data) {
                  console.log('successfully obtained authorization code', data);
                  deferred.resolve(data);
                }).error(function (data) {
                  deferred.reject(data);
                  console.log('error obtaining authorization code', data)
                });
              } else if (error) {
                deferred.reject(error[1]);
                console.log('error obtaining access code', error[1]);
              }
            });

            return deferred.promise;
          }

          function createConfig(config, auth) {
            return _.merge({
              headers: {
                Authorization: 'Bearer ' + auth.access_token
              }
            }, config || {})
          }

          return {
            get: function (url, config) {
              return authorize().then(function (auth) {
                return $http.get(url, createConfig(config, auth))
              })
            },
            post: function (url, data, config) {
              return authorize().then(function (auth) {
                return $http.post(url, data, createConfig(config, auth));
              });
            }
          }
        }
      }
    });<commit_msg>Getting google auth to work on desktop too<commit_after>angular.module('ngGoogle', [])
    .provider('$google', function () {
      var config = {},
      // this url does not matter in cordova, while it needs to be the same origin on desktop
          redirectUrl = 'http://localhost:8100';

      return {
        initialize: function (clientId, scopes) {
          config.clientId = clientId;
          config.scope = scopes.join(' ');
        },
        $get: function ($window, $http, $q, $interval) {
          function requestAccessToken(authorizationCode) {
            return $http.post('http://cors.maxogden.com/https://accounts.google.com/o/oauth2/token', {
              code: authorizationCode,
              client_id: config.clientId,
              redirect_uri: redirectUrl,
              grant_type: 'authorization_code'
            }, {
              headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
              transformRequest: function (obj) {
                var str = [];
                for (var p in obj)
                  str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                return str.join("&");
              }
            });
          }

          function handleBrowserAuthorization(authWindow) {
            var deferred = $q.defer(),
                intervalClear = $interval(function () {
                  var url = authWindow.location.href,
                      code = /\?code=([^#]+)/.exec(url),
                      error = /\?error=([^#]+)/.exec(url);

                  if (code || error) {
                    authWindow.close();
                    $interval.cancel(intervalClear);
                  }

                  if (code) {
                    deferred.resolve(requestAccessToken(code[1]));
                  } else if (error) {
                    deferred.reject(error[1]);
                  }
                }, 1000);

            return deferred.promise;
          }

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

            $(authWindow).on('loadstart', function (e) {
              var url = e.originalEvent.url;
              var code = /\?code=(.+)$/.exec(url);
              var error = /\?error=(.+)$/.exec(url);

              if (code || error) {
                authWindow.close();
              }

              if (code) {
                deferred.resolve(requestAccessToken(code[1]));
              } else if (error) {
                return deferred.reject(error[1]);
              }
            });

            return deferred.promise;
          }

          function authorize() {
            var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + $.param({
                      client_id: config.clientId,
                      scope: config.scope,
                      redirect_uri: redirectUrl,
                      response_type: 'code'
                    }),
                authWindow = $window.open(authUrl, '_blank', 'location=no,toolbar=no');

            if (/http/.test($window.location.protocol)) {
              return handleBrowserAuthorization(authWindow);
            } else {
              return handleCordovaAuthorization(authWindow);
            }
          }

          function createConfig(config, authRes) {
            return _.merge({
              headers: { Authorization: 'Bearer ' + authRes.data.access_token }
            }, config || {})
          }

          return {
            get: function (url, config) {
              return authorize().then(function (authRes) {
                return $http.get(url, createConfig(config, authRes))
              });
            },
            post: function (url, data, config) {
              return authorize().then(function (authRes) {
                return $http.post(url, data, createConfig(config, authRes));
              });
            }
          }
        }
      }
    });<|endoftext|>


<commit_before>import { format } from 'd3-format';
import isEmpty from 'lodash/isEmpty';

export const formatUSD = (value, minimize = true) =>
  format('.2s')(value)
    .replace('G', minimize ? 'B' : ' billion')
    .replace('M', minimize ? 'M' : ' million')
    .replace('K', minimize ? 'K' : ' thousand');

export const formatNumber = ({ num, unit }) => {
  let numFormat = unit === '%' ? '.2r' : '.3s';
  if (unit === 'counts') numFormat = ',.0f';
  const thres = unit === '%' ? 0.1 : 1;
  let formattedNum =
    num < thres && num > 0 ? `<${thres}` : format(numFormat)(num);
  if (unit !== '%' && num < thres && num > 0.01) {
    formattedNum = format('.3r')(num);
  } else if (num > 0 && num < 0.01 && unit !== '%') {
    formattedNum = '<0.01';
  }
  return `${formattedNum}${unit && unit !== 'counts' ? unit : ''}`;
};

export const buildGadm36Id = (country, region, subRegion) =>
  `${country}${region ? `.${region}` : ''}${
    subRegion ? `.${subRegion}_1` : '_1'
  }`;

export const parseGadm36Id = gid => {
  if (!gid) return null;
  const ids = gid.split('.');
  const adm0 = (ids && ids[0]) || null;
  const adm1 = ids && ids[1] && ids[1].split('_')[0];
  const adm2 = ids && ids[2] && ids[2].split('_')[0];
  return {
    adm0,
    adm1: adm1 ? parseInt(adm1, 10) : undefined,
    adm2: adm2 ? parseInt(adm2, 10) : undefined
  };
};

export const getLocationFromData = data => {
  let newLocation = {};
  if (data && data.gid_0) {
    newLocation = parseGadm36Id(data[`gid_${data.level}`]);
  }
  return {
    type: 'country',
    ...newLocation
  };
};

export const buildFullLocationName = (
  { adm0, adm1, adm2 },
  { adm0s, adm1s, adm2s }
) => {
  let location = '';
  if (
    (adm0 && isEmpty(adm0s)) ||
    (adm1 && isEmpty(adm1s)) ||
    (adm2 && isEmpty(adm2s))
  ) {
    return '';
  }
  if (adm0) {
    const adm0Obj = adm0s && adm0s.find(a => a.value === adm0);
    location = adm0Obj ? adm0Obj.label : '';
  }
  if (adm1) {
    const adm1Obj = adm1s && adm1s.find(a => a.value === parseInt(adm1, 10));
    location = adm1Obj
      ? `${adm1Obj.label || 'unnamed region'}, ${location}`
      : location;
  }
  if (adm2) {
    const adm2Obj = adm2s && adm2s.find(a => a.value === parseInt(adm2, 10));
    location = adm2Obj
      ? `${adm2Obj.label || 'unnamed region'}, ${location}`
      : location;
  }
  return location;
};

export const buildLocationName = (
  { country, region, subRegion },
  { adms, adm1s, adm2s }
) => {
  let activeLocation = { label: '' };
  if (subRegion) {
    activeLocation =
      adm2s && adm2s.find(a => a.value === parseInt(subRegion, 10));
  } else if (region) {
    activeLocation = adm1s && adm1s.find(a => a.value === parseInt(region, 10));
  } else if (country) {
    activeLocation = adms && adms.find(a => a.value === country);
  }
  return activeLocation && activeLocation.label;
};

export const buildLocationFromNames = (name_0, name_1, name_2) =>
  `${name_2 ? `${name_2}, ` : ''}${name_1 ? `${name_1}, ` : ''}${name_0}`;
<commit_msg>Updated formatnumber function to add special case<commit_after>import { format } from 'd3-format';
import isEmpty from 'lodash/isEmpty';

export const formatUSD = (value, minimize = true) =>
  format('.2s')(value)
    .replace('G', minimize ? 'B' : ' billion')
    .replace('M', minimize ? 'M' : ' million')
    .replace('K', minimize ? 'K' : ' thousand');

export const formatNumber = ({ num, unit }) => {
  let numFormat = unit === '%' ? '.2r' : '.3s';
  if (unit === 'counts') numFormat = ',.0f';
  const thres = unit === '%' ? 0.1 : 1;
  let formattedNum =
    num < thres && num > 0 ? `<${thres}` : format(numFormat)(num);
  if (unit !== '%' && num < thres && num > 0.01) {
    formattedNum = format('.3r')(num);
  } else if (unit === 'ha' && num < 1000) {
    const rounded = Math.round(num);
    formattedNum = format('.3s')(rounded);
  } else if (num > 0 && num < 0.01 && unit !== '%') {
    formattedNum = '<0.01';
  }
  return `${formattedNum}${unit && unit !== 'counts' ? unit : ''}`;
};

export const buildGadm36Id = (country, region, subRegion) =>
  `${country}${region ? `.${region}` : ''}${
    subRegion ? `.${subRegion}_1` : '_1'
  }`;

export const parseGadm36Id = gid => {
  if (!gid) return null;
  const ids = gid.split('.');
  const adm0 = (ids && ids[0]) || null;
  const adm1 = ids && ids[1] && ids[1].split('_')[0];
  const adm2 = ids && ids[2] && ids[2].split('_')[0];
  return {
    adm0,
    adm1: adm1 ? parseInt(adm1, 10) : undefined,
    adm2: adm2 ? parseInt(adm2, 10) : undefined
  };
};

export const getLocationFromData = data => {
  let newLocation = {};
  if (data && data.gid_0) {
    newLocation = parseGadm36Id(data[`gid_${data.level}`]);
  }
  return {
    type: 'country',
    ...newLocation
  };
};

export const buildFullLocationName = (
  { adm0, adm1, adm2 },
  { adm0s, adm1s, adm2s }
) => {
  let location = '';
  if (
    (adm0 && isEmpty(adm0s)) ||
    (adm1 && isEmpty(adm1s)) ||
    (adm2 && isEmpty(adm2s))
  ) {
    return '';
  }
  if (adm0) {
    const adm0Obj = adm0s && adm0s.find(a => a.value === adm0);
    location = adm0Obj ? adm0Obj.label : '';
  }
  if (adm1) {
    const adm1Obj = adm1s && adm1s.find(a => a.value === parseInt(adm1, 10));
    location = adm1Obj
      ? `${adm1Obj.label || 'unnamed region'}, ${location}`
      : location;
  }
  if (adm2) {
    const adm2Obj = adm2s && adm2s.find(a => a.value === parseInt(adm2, 10));
    location = adm2Obj
      ? `${adm2Obj.label || 'unnamed region'}, ${location}`
      : location;
  }
  return location;
};

export const buildLocationName = (
  { country, region, subRegion },
  { adms, adm1s, adm2s }
) => {
  let activeLocation = { label: '' };
  if (subRegion) {
    activeLocation =
      adm2s && adm2s.find(a => a.value === parseInt(subRegion, 10));
  } else if (region) {
    activeLocation = adm1s && adm1s.find(a => a.value === parseInt(region, 10));
  } else if (country) {
    activeLocation = adms && adms.find(a => a.value === country);
  }
  return activeLocation && activeLocation.label;
};

export const buildLocationFromNames = (name_0, name_1, name_2) =>
  `${name_2 ? `${name_2}, ` : ''}${name_1 ? `${name_1}, ` : ''}${name_0}`;
<|endoftext|>


<commit_before>describe('accordion:', function() {
  beforeEach(function() {
    this.addMatchers({
      // Place accordion-specific matchers here...
    });

    var origFunc = $.fn.foundation;
    spyOn($.fn, 'foundation').andCallFake(function() {
      var result = origFunc.apply(this, arguments);
      jasmine.Clock.tick(1000); // Let things settle...
      return result;
    });
  });

  describe('basic accordion with tab child', function() {
    beforeEach(function() {
      document.body.innerHTML = __html__['spec/accordion/basic.html'];
    });

    it('should default to the active tab', function() {
      $(document).foundation();

      expect($('#panel1')).toBeVisible();
      expect($('#panel2-1')).toBeVisible();
      expect($('#panel2-2')).toBeHidden();
      expect($('#panel2')).toBeHidden();
      expect($('#panel3')).toBeHidden();
    });

    it('should switch to the clicked section', function() {
      $(document).foundation();

      $('#panel2').prev().click();

      expect($('#panel1')).toBeHidden();
      expect($('#panel2-1')).toBeHidden();
      expect($('#panel2-2')).toBeHidden();
      expect($('#panel2')).toBeVisible();
      expect($('#panel3')).toBeHidden();
    });
  });

  describe('embedded grid accordion', function() {
    beforeEach(function() {
      document.body.innerHTML = __html__['spec/accordion/grid.html'];
    });

    it('should switch to the clicked section', function() {
      $(document).foundation();

      $('#panel1c').prev().click();

      expect($('#panel1c')).toBeVisible();
      expect($('#panel2c')).toBeHidden();
      expect($('#panel3c')).toBeHidden();
      expect($('#panel4c')).toBeHidden();
      expect($('#panel5c')).toBeHidden();
      expect($('#panel6c')).toBeHidden();

      $('#panel4c').prev().click();

      expect($('#panel1c')).toBeHidden();
      expect($('#panel2c')).toBeHidden();
      expect($('#panel3c')).toBeHidden();
      expect($('#panel4c')).toBeVisible();
      expect($('#panel5c')).toBeHidden();
      expect($('#panel6c')).toBeHidden();
    });
  });

  describe('multi-expand accordion', function() {
    beforeEach(function() {
      document.body.innerHTML = __html__['spec/accordion/multiexpand.html'];
    });

    it('should default to the active panel', function() {
      $(document).foundation({ multi_expand: true });

      expect($('#panel1')).toBeHidden();
      expect($('#panel2')).toBeVisible();
      expect($('#panel3')).toBeHidden();
    });

    it('should open the clicked section, leaving previous active panels open', function() {
      $(document).foundation({ multi_expand: true });

      $('#panel3').prev().click();

      expect($('#panel1')).toBeHidden();
      expect($('#panel2')).toBeVisible();
      expect($('#panel3')).toBeVisible();
    });
  });
});
<commit_msg>Update accordion tests to use proper Foundation initialization<commit_after>describe('accordion:', function() {
  beforeEach(function() {
    this.addMatchers({
      // Place accordion-specific matchers here...
    });

    var origFunc = $.fn.foundation;
    spyOn($.fn, 'foundation').andCallFake(function() {
      var result = origFunc.apply(this, arguments);
      jasmine.Clock.tick(1000); // Let things settle...
      return result;
    });
  });

  describe('basic accordion with tab child', function() {
    beforeEach(function() {
      document.body.innerHTML = __html__['spec/accordion/basic.html'];
    });

    it('should default to the active tab', function() {
      $(document).foundation();

      expect($('#panel1')).toBeVisible();
      expect($('#panel2-1')).toBeVisible();
      expect($('#panel2-2')).toBeHidden();
      expect($('#panel2')).toBeHidden();
      expect($('#panel3')).toBeHidden();
    });

    it('should switch to the clicked section', function() {
      $(document).foundation();

      $('#panel2').prev().click();

      expect($('#panel1')).toBeHidden();
      expect($('#panel2-1')).toBeHidden();
      expect($('#panel2-2')).toBeHidden();
      expect($('#panel2')).toBeVisible();
      expect($('#panel3')).toBeHidden();
    });
  });

  describe('embedded grid accordion', function() {
    beforeEach(function() {
      document.body.innerHTML = __html__['spec/accordion/grid.html'];
    });

    it('should switch to the clicked section', function() {
      $(document).foundation();

      $('#panel1c').prev().click();

      expect($('#panel1c')).toBeVisible();
      expect($('#panel2c')).toBeHidden();
      expect($('#panel3c')).toBeHidden();
      expect($('#panel4c')).toBeHidden();
      expect($('#panel5c')).toBeHidden();
      expect($('#panel6c')).toBeHidden();

      $('#panel4c').prev().click();

      expect($('#panel1c')).toBeHidden();
      expect($('#panel2c')).toBeHidden();
      expect($('#panel3c')).toBeHidden();
      expect($('#panel4c')).toBeVisible();
      expect($('#panel5c')).toBeHidden();
      expect($('#panel6c')).toBeHidden();
    });
  });

  describe('multi-expand accordion', function() {
    beforeEach(function() {
      document.body.innerHTML = __html__['spec/accordion/multiexpand.html'];
    });

    it('should default to the active panel', function() {
      $(document).foundation('accordion', { multi_expand: true });

      expect($('#panel1')).toBeHidden();
      expect($('#panel2')).toBeVisible();
      expect($('#panel3')).toBeHidden();
    });

    it('should open the clicked section, leaving previous active panels open', function() {
      $(document).foundation('accordion', { multi_expand: true });

      $('#panel3').prev().click();

      expect($('#panel1')).toBeHidden();
      expect($('#panel2')).toBeVisible();
      expect($('#panel3')).toBeVisible();
    });
  });
});
<|endoftext|>


<commit_before>const client = require('prom-client');
const Promise = require('bluebird');
const dhtSensor = require('node-dht-sensor');
const sensors = require('./sensorconfig.json')

Promise.promisifyAll(dhtSensor, { multiArgs: true });

const airTempGauge = new client.Gauge('air_temperature', 'Air Temperature in a room', ['sensorId', 'sensorDescription']);
const relHumidityGauge = new client.Gauge('humidity_relative', 'Relative humidity in a room', ['sensorId', 'sensorDescription']);

function readSensorData(sensor) {
  return dhtSensor.readAsync(sensor.type, sensor.gpioPin)
  .then((reading) => {
    if (!Array.isArray(reading) || reading.length !== 2) {
      console.warn('Reading does not have required format. Skipping');
    }
    const temperature = reading[0];
    const humidity = reading[1];
    if (!temperature || !humidity) {
      console.warn('Data returned, but temp and/or humidity value undefined');
      return;
    }
    airTempGauge.set({
      sensorId: sensor.id,
      sensorDescription: sensor.description,
    }, temperature);
    relHumidityGauge.set({
      sensorId: sensor.id,
      sensorDescription: sensor.description,
    }, humidity);
  })
  .catch((err) => {
    console.warn(err);
  });
}

function readSensors() {
  Promise.mapSeries(sensors, sensor => readSensorData(sensor))
  .delay(3000)
  .then(readSensors);
}

readSensors();
<commit_msg>Calculate absolute humidity<commit_after>const client = require('prom-client');
const Promise = require('bluebird');
const dhtSensor = require('node-dht-sensor');
const sensors = require('./sensorconfig.json')

Promise.promisifyAll(dhtSensor, { multiArgs: true });

const airTempGauge = new client.Gauge('air_temperature', 'Air Temperature', ['sensorId', 'sensorDescription']);
const relHumidityGauge = new client.Gauge('humidity_relative', 'Humidity (relative)', ['sensorId', 'sensorDescription']);
const absHumidityGauge = new client.Gauge('humidity_absolute', 'Humidity (absolute)', ['sensorId', 'sensorDescription']);

function calcAbsoluteHumidity(relHumidity, temperature) {
  return 6.112 * Math.exp((17.67 * temperature) / (temperature + 243.5)) * relHumidity * 2.1674;
}

function readSensorData(sensor) {
  return dhtSensor.readAsync(sensor.type, sensor.gpioPin)
  .then((reading) => {
    if (!Array.isArray(reading) || reading.length !== 2) {
      console.warn('Reading does not have required format. Skipping');
    }
    const temperature = reading[0];
    const relHumidity = reading[1];
    const absHumidity = calcAbsoluteHumidity(relHumidity, temperature);

    airTempGauge.set({
      sensorId: sensor.id,
      sensorDescription: sensor.description,
    }, temperature);
    relHumidityGauge.set({
      sensorId: sensor.id,
      sensorDescription: sensor.description,
    }, relHumidity);
    absHumidityGauge.set({
      sensorId: sensor.id,
      sensorDescription: sensor.description,
    }, absHumidity);
  })
  .catch((err) => {
    console.warn(err);
  });
}

function readSensors() {
  Promise.mapSeries(sensors, sensor => readSensorData(sensor))
  .delay(3000)
  .then(readSensors);
}

readSensors();
<|endoftext|>


<commit_before>import { text } from '@storybook/addon-knobs';
import React, { useState } from 'react';
import { action } from '@storybook/addon-actions';
import { State, Store } from '@sambego/storybook-state';
import countriesList from '../../../../demo/data/countries';
import Button from '../../button';
import MultiActionButton from '../../multi-action-button';
import {
  Table,
  TableCell,
  TableHeader,
  TableRow
} from '..';
import TextArea from '../../../__experimental__/components/textarea';
import TextBox from '../../../__experimental__/components/textbox';
import DateInput from '../../../__experimental__/components/date';
import getTextboxStoryProps from '../../../__experimental__/components/textbox/textbox.stories';
import OptionsHelper from '../../../utils/helpers/options-helper/options-helper';

const store = new Store({
  sortOrder: 'asc',
  sortedColumn: 'name',
  currentPage: '1',
  children: undefined
});

const handleChange = (e, tableOptions) => {
  const { sortOrder, sortedColumn, currentPage } = tableOptions;

  store.set({ sortOrder, sortedColumn, currentPage });
  action('change')(e, tableOptions);
};

const handleToolbarAction = () => {
  action('toolbar action')();
};

const recordsForActivePage = (start, end) => {
  let records = countriesList;
  if (store.get('sortOrder') === 'desc' && store.get('sortedColumn').length) {
    records = records.reverse();
  }
  return records.slice(start, end).toJS();
};

const getActiveRows = (pageSize, totalRecords) => {
  const currentPage = store.get('currentPage');
  const candidateIndex = pageSize * currentPage;
  const endIndex = (candidateIndex <= totalRecords) ? candidateIndex : totalRecords;
  const remainder = endIndex % pageSize;
  const currentPageSize = (endIndex === totalRecords && remainder !== 0) ? (endIndex % pageSize) : pageSize;
  const startIndex = endIndex - currentPageSize;

  return recordsForActivePage(startIndex, endIndex);
};

const pickInput = (name) => {
  const { inputTypes } = OptionsHelper;
  switch (name) {
    case inputTypes[1]:
      return <TextArea { ...getTextboxStoryProps } />;
    case inputTypes[2]:
      return <DateInput { ...getTextboxStoryProps } />;
    default:
      return <TextBox { ...getTextboxStoryProps } />;
  }
};

const buildRows = ({
  pageSize, totalRecords, inputType, size
}) => {
  const rowsCountries = getActiveRows(pageSize, totalRecords);

  return (
    <>
      <TableRow
        key='header'
        as='header'
        uniqueID='header'
      >
        <TableHeader
          sortable
          name='name'
          scope='col'
        >
          Country
        </TableHeader>
        <TableHeader
          sortable
          scope='col'
          name='code'
          width='200'
        >
          Code
        </TableHeader>
      </TableRow>
      {rowsCountries.map((row) => {
        let cellContent = (<TableCell>{ row.name }</TableCell>);
        if (inputType) {
          cellContent = (
            <TableCell size={ size }>
              { pickInput(inputType) }
            </TableCell>
          );
        }
        return (
          <TableRow
            key={ row.id }
            uniqueID={ row.id }
          >
            { cellContent }
            <TableCell>{ row.value }</TableCell>
          </TableRow>
        );
      })}
    </>
  );
};

const calculateCurrentPage = ({ totalRecords, pageSize, paginate }) => {
  const pages = totalRecords / pageSize;
  const maxValidPage = (pageSize && paginate) ? Math.max(Math.ceil(pages), 1) : '1';
  const isCurrentPageValid = store.get('currentPage') <= pages;

  return isCurrentPageValid ? store.get('currentPage') : maxValidPage;
};

const Wrapper = (props) => {
  const [pageSize, setPageSize] = useState('10');

  const tableProps = { ...props };
  tableProps.pageSize = tableProps.showPageSizeSelection ? pageSize : text('pageSize', '5');

  store.set({ currentPage: calculateCurrentPage(tableProps) });
  store.set({ sortOrder: tableProps.sortOrder });
  store.set({ sortedColumn: tableProps.sortColumn });

  return (
    <State
      store={ store }
      parseState={ state => ({ ...state, children: buildRows(tableProps) }) }
    >
      <Table
        actionToolbarChildren={ (context) => {
          return [
            <Button
              disabled={ context.disabled }
              key='single-action'
              onClick={ handleToolbarAction }
              size='medium'
            >
              Test Action
            </Button>,
            <MultiActionButton
              text='Actions'
              disabled={ context.disabled }
              key='multi-actions'
              size='medium'
            >
              <Button onClick={ handleToolbarAction }>foo</Button>
              <Button onClick={ handleToolbarAction }>bar</Button>
              <Button onClick={ handleToolbarAction }>qux</Button>
            </MultiActionButton>
          ];
        } }
        path='/countries'
        actions={ {
          delete: {
            icon: 'bin',
            onClick: handleToolbarAction
          },
          settings: {
            icon: 'settings',
            onClick: handleToolbarAction
          }
        } }
        { ...tableProps }
        onChange={ handleChange }
        sortOrder={ store.sortOrder }
        sortedColumn={ store.sortedColumn }
        onPageSizeChange={ size => setPageSize(size) }
      />
    </State>
  );
};

export default Wrapper;
<commit_msg>remove prop size<commit_after>import { text } from '@storybook/addon-knobs';
import React, { useState } from 'react';
import { action } from '@storybook/addon-actions';
import { State, Store } from '@sambego/storybook-state';
import countriesList from '../../../../demo/data/countries';
import Button from '../../button';
import MultiActionButton from '../../multi-action-button';
import {
  Table,
  TableCell,
  TableHeader,
  TableRow
} from '..';
import TextArea from '../../../__experimental__/components/textarea';
import TextBox from '../../../__experimental__/components/textbox';
import DateInput from '../../../__experimental__/components/date';
import getTextboxStoryProps from '../../../__experimental__/components/textbox/textbox.stories';
import OptionsHelper from '../../../utils/helpers/options-helper/options-helper';

const store = new Store({
  sortOrder: 'asc',
  sortedColumn: 'name',
  currentPage: '1',
  children: undefined
});

const handleChange = (e, tableOptions) => {
  const { sortOrder, sortedColumn, currentPage } = tableOptions;

  store.set({ sortOrder, sortedColumn, currentPage });
  action('change')(e, tableOptions);
};

const handleToolbarAction = () => {
  action('toolbar action')();
};

const recordsForActivePage = (start, end) => {
  let records = countriesList;
  if (store.get('sortOrder') === 'desc' && store.get('sortedColumn').length) {
    records = records.reverse();
  }
  return records.slice(start, end).toJS();
};

const getActiveRows = (pageSize, totalRecords) => {
  const currentPage = store.get('currentPage');
  const candidateIndex = pageSize * currentPage;
  const endIndex = (candidateIndex <= totalRecords) ? candidateIndex : totalRecords;
  const remainder = endIndex % pageSize;
  const currentPageSize = (endIndex === totalRecords && remainder !== 0) ? (endIndex % pageSize) : pageSize;
  const startIndex = endIndex - currentPageSize;

  return recordsForActivePage(startIndex, endIndex);
};

const pickInput = (name) => {
  const { inputTypes } = OptionsHelper;
  switch (name) {
    case inputTypes[1]:
      return <TextArea { ...getTextboxStoryProps } />;
    case inputTypes[2]:
      return <DateInput { ...getTextboxStoryProps } />;
    default:
      return <TextBox { ...getTextboxStoryProps } />;
  }
};

const buildRows = ({
  pageSize, totalRecords, inputType, size
}) => {
  const rowsCountries = getActiveRows(pageSize, totalRecords);

  return (
    <>
      <TableRow
        key='header'
        as='header'
        uniqueID='header'
      >
        <TableHeader
          sortable
          name='name'
          scope='col'
        >
          Country
        </TableHeader>
        <TableHeader
          sortable
          scope='col'
          name='code'
          width='200'
        >
          Code
        </TableHeader>
      </TableRow>
      {rowsCountries.map((row) => {
        let cellContent = (<TableCell>{ row.name }</TableCell>);
        if (inputType) {
          cellContent = (
            <TableCell size={ size }>
              { pickInput(inputType) }
            </TableCell>
          );
        }
        return (
          <TableRow
            key={ row.id }
            uniqueID={ row.id }
          >
            { cellContent }
            <TableCell>{ row.value }</TableCell>
          </TableRow>
        );
      })}
    </>
  );
};

const calculateCurrentPage = ({ totalRecords, pageSize, paginate }) => {
  const pages = totalRecords / pageSize;
  const maxValidPage = (pageSize && paginate) ? Math.max(Math.ceil(pages), 1) : '1';
  const isCurrentPageValid = store.get('currentPage') <= pages;

  return isCurrentPageValid ? store.get('currentPage') : maxValidPage;
};

const Wrapper = (props) => {
  const [pageSize, setPageSize] = useState('10');

  const tableProps = { ...props };
  tableProps.pageSize = tableProps.showPageSizeSelection ? pageSize : text('pageSize', '5');

  store.set({ currentPage: calculateCurrentPage(tableProps) });
  store.set({ sortOrder: tableProps.sortOrder });
  store.set({ sortedColumn: tableProps.sortColumn });

  return (
    <State
      store={ store }
      parseState={ state => ({ ...state, children: buildRows(tableProps) }) }
    >
      <Table
        actionToolbarChildren={ (context) => {
          return [
            <Button
              disabled={ context.disabled }
              key='single-action'
              onClick={ handleToolbarAction }
            >
              Test Action
            </Button>,
            <MultiActionButton
              text='Actions'
              disabled={ context.disabled }
              key='multi-actions'
            >
              <Button onClick={ handleToolbarAction }>foo</Button>
              <Button onClick={ handleToolbarAction }>bar</Button>
              <Button onClick={ handleToolbarAction }>qux</Button>
            </MultiActionButton>
          ];
        } }
        path='/countries'
        actions={ {
          delete: {
            icon: 'bin',
            onClick: handleToolbarAction
          },
          settings: {
            icon: 'settings',
            onClick: handleToolbarAction
          }
        } }
        { ...tableProps }
        onChange={ handleChange }
        sortOrder={ store.sortOrder }
        sortedColumn={ store.sortedColumn }
        onPageSizeChange={ size => setPageSize(size) }
      />
    </State>
  );
};

export default Wrapper;
<|endoftext|>


<commit_before>(function() {

  function comparePasswords(password, comparate, invalidmsg) {
    if (password.value !== comparate.value) {
      password.setCustomValidity(invalidmsg);
    } else {
      password.setCustomValidity('');
    }
  }

  var inputs = document.getElementsByTagName('input');
  for (var i = 0; i < inputs.length; i++) {
    var input = inputs[i];
    if (!input.hasAttribute('compareTo')) continue;
    var comparateName = input.getAttribute('compareTo');
    var comparates = document.getElementsByName(comparateName);
    if (comparates.length !== 1) continue;
    var comparate = comparates[0];

    var defaultValidateError = 'These passwords don\'t match.';  //default validation error message
    if (input.hasAttribute('compareToMsg')) { defaultValidateError = input.getAttribute('compareToMsg'); }  //set the validation error if attribute present

    input.addEventListener("change", (function(input, comparate, invalidmsg) {
      return function() {
        comparePasswords(input, comparate, invalidmsg);
      }
    })(input, comparate, defaultValidateError));

    comparate.addEventListener("change", (function(input, comparate, invalidmsg) {
      return function() {
        comparePasswords(input, comparate, invalidmsg);
      }
    })(input, comparate, defaultValidateError));
  }

}());
<commit_msg>closes #4 We may want to put in some extra work to make sure two compareTo elements are linked to the same password field.<commit_after>(function() {

  function comparePasswords(password, comparate, invalidmsg) {
    if (password.value !== comparate.value) {
      password.setCustomValidity(invalidmsg);
    } else {
      password.setCustomValidity('');
    }
  }

  var inputs = document.getElementsByTagName('input');
  for (var i = 0; i < inputs.length; i++) {
    var input = inputs[i];
    if (!input.hasAttribute('compareTo')) continue;
    var comparateName = input.getAttribute('compareTo');
    var comparates = document.getElementsByName(comparateName);
    if (comparates.length === 0) {
        console.log('Error:  The element named by the compareTo attribute, "'.concat(comparateName ,'" ,could not be found!'));
        continue;
     } else if (comparates.length > 1) {
        console.log('Error:  More than one('.concat(comparates.length ,') element referenced by the compareTo attribute were found, compareTo element could not be used.'));
        continue;
     }
    var comparate = comparates[0];

    var defaultValidateError = 'These passwords don\'t match.';  //default validation error message
    if (input.hasAttribute('compareToMsg')) { defaultValidateError = input.getAttribute('compareToMsg'); }  //set the validation error if attribute present

    input.addEventListener("change", (function(input, comparate, invalidmsg) {
      return function() {
        comparePasswords(input, comparate, invalidmsg);
      }
    })(input, comparate, defaultValidateError));

    comparate.addEventListener("change", (function(input, comparate, invalidmsg) {
      return function() {
        comparePasswords(input, comparate, invalidmsg);
      }
    })(input, comparate, defaultValidateError));
  }

}());
<|endoftext|>