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

/**
 * @fileoverview Blocks for basic ZR C++ API.
 * @author dininno@mit.edu (Ethan DiNinno)
 */
'use strict';

goog.provide('Blockly.Blocks.zrms14');

goog.require('Blockly.Blocks');

Blockly.Blocks['zrms14_getDebrisLocation'] = {
	init: function() {
		var DEBRIS =
			[['1', '1'],
			 ['2', '2'],
			 ['3', '3'],
			 ['4', '4'],
			 ['5', '5'],
			 ['6', '6'],
			 ['7', '7'],
			 ['8', '8']];
		this.setHelpUrl('');
		this.setColour(20);
		this.appendValueInput('debrisId')
			.appendField('location of debris:')
			.appendField(new Blockly.FieldDropdown(DEBRIS), 'debrisId');
		this.appendValueInput('loc')
			.appendField('array:')
			.setCheck('array');
		this.setPreviousStatement(true, 'statement');
		this.setNextStatement(true, 'statement');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_haveDebris'] = {
	init: function() {
		var PLAYERS =
			[['Me', 'ME'],
			 ['Opponent', 'OTHER']];
		var DEBRIS =
			[['1', '1'],
			 ['2', '2'],
			 ['3', '3'],
			 ['4', '4'],
			 ['5', '5'],
			 ['6', '6'],
			 ['7', '7'],
			 ['8', '8']];
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('player:')
			.appendField(new Blockly.FieldDropdown(PLAYERS), 'player');
		this.appendDummyInput()
			.appendField('has debris:')
			.appendField(new Blockly.FieldDropdown(DEBRIS), 'debrisId');
		this.setOutput(true, 'number');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_startLasso'] = {
	init: function() {
		var DEBRIS =
			[['1', '1'],
			 ['2', '2'],
			 ['3', '3'],
			 ['4', '4'],
			 ['5', '5'],
			 ['6', '6'],
			 ['7', '7'],
			 ['8', '8']];
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('start lasso on debris:');
			.appendField(new Blockly.FieldDropdown(DEBRIS), 'debrisId');
		this.setPreviousStatement(true, 'statement');
		this.setNextStatement(true, 'statement');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_havePack'] = {
	init: function() {
		var PLAYERS =
			[['Me', 'ME'],
			 ['Opponent', 'OTHER']];
		var ITEMS =
			[['0', '0'],
			 ['1', '1']];
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('player:')
			.appendField(new Blockly.FieldDropdown(PLAYERS), 'player');
		this.appendDummyInput()
			.appendField('has item:')
			.appendField(new Blockly.FieldDropdown(ITEMS), 'objectNum');
		this.setOutput(true, 'number');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_predictCometState'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('predictCometState');
		this.appendValueInput('dtSteps')
			.appendField('steps:')
			.setCheck('number');
		this.appendValueInput('initState')
			.appendField('initial state:')
			.setCheck('array');
		this.appendValueInput('finalState')
			.appendField('final state:')
			.setCheck('array');
		this.setPreviousStatement(true, 'statement');
		this.setNextStatement(true, 'statement');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_getCometState'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('getCometState');
		this.appendValueInput('state')
			.appendField('array:')
			.setCheck('array');
		this.setPreviousStatement(true, 'statement');
		this.setNextStatement(true, 'statement');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_faceTarget'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('faceTarget');
		this.appendValueInput('target')
			.appendField('target:')
			.setCheck('array');
		this.setPreviousStatement(true, 'statement');
		this.setNextStatement(true, 'statement');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_isFacingTarget'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('I am facing my comet')
		this.setOutput(true, 'number');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_shootLaserBool'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('shoot laser')
		this.setOutput(true, 'number');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_shootLaserVoid'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('shoot laser');
		this.setPreviousStatement(true, 'statement');
		this.setNextStatement(true, 'statement');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_laserShotsRemaining'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('laser shots remaining')
		this.setOutput(true, 'number');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_getMass'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('my mass')
		this.setOutput(true, 'number');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_getFuelRemaining'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('my remaining fuel')
		this.setOutput(true, 'number');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_getScore'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('my score')
		this.setOutput(true, 'number');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_getOtherScore'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('opponent\'s score')
		this.setOutput(true, 'number');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_isSlowDownActive'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('slowdown is active')
		this.setOutput(true, 'number');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_isBounceActive'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('bounce is active')
		this.setOutput(true, 'number');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};<commit_msg>Blocks for ZRMS14<commit_after>/**
 * Visual Blocks Editor
 *
 * Copyright 2014 Massachusetts Institute of Technology
 * http://zerorobotics.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Blocks for basic ZR C++ API.
 * @author dininno@mit.edu (Ethan DiNinno)
 */
'use strict';

goog.provide('Blockly.Blocks.zrms14');

goog.require('Blockly.Blocks');

Blockly.Blocks['zrms14_getDebrisLocation'] = {
	init: function() {
		var DEBRIS =
			[['1', '1'],
			 ['2', '2'],
			 ['3', '3'],
			 ['4', '4'],
			 ['5', '5'],
			 ['6', '6'],
			 ['7', '7'],
			 ['8', '8']];
		this.setHelpUrl('');
		this.setColour(20);
		this.appendValueInput('debrisId')
			.appendField('location of debris:')
			.appendField(new Blockly.FieldDropdown(DEBRIS), 'debrisId');
		this.appendValueInput('loc')
			.appendField('array:')
			.setCheck('array');
		this.setPreviousStatement(true, 'statement');
		this.setNextStatement(true, 'statement');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_haveDebris'] = {
	init: function() {
		var PLAYERS =
			[['Me', 'ME'],
			 ['Opponent', 'OTHER']];
		var DEBRIS =
			[['1', '1'],
			 ['2', '2'],
			 ['3', '3'],
			 ['4', '4'],
			 ['5', '5'],
			 ['6', '6'],
			 ['7', '7'],
			 ['8', '8']];
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('player:')
			.appendField(new Blockly.FieldDropdown(PLAYERS), 'player');
		this.appendDummyInput()
			.appendField('has debris:')
			.appendField(new Blockly.FieldDropdown(DEBRIS), 'debrisId');
		this.setOutput(true, 'number');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_startLasso'] = {
	init: function() {
		var DEBRIS =
			[['1', '1'],
			 ['2', '2'],
			 ['3', '3'],
			 ['4', '4'],
			 ['5', '5'],
			 ['6', '6'],
			 ['7', '7'],
			 ['8', '8']];
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('start lasso on debris:')
			.appendField(new Blockly.FieldDropdown(DEBRIS), 'debrisId');
		this.setPreviousStatement(true, 'statement');
		this.setNextStatement(true, 'statement');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_havePack'] = {
	init: function() {
		var PLAYERS =
			[['Me', 'ME'],
			 ['Opponent', 'OTHER']];
		var ITEMS =
			[['0', '0'],
			 ['1', '1']];
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('player:')
			.appendField(new Blockly.FieldDropdown(PLAYERS), 'player');
		this.appendDummyInput()
			.appendField('has item:')
			.appendField(new Blockly.FieldDropdown(ITEMS), 'objectNum');
		this.setOutput(true, 'number');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_predictCometState'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('predictCometState');
		this.appendValueInput('dtSteps')
			.appendField('steps:')
			.setCheck('number');
		this.appendValueInput('initState')
			.appendField('initial state:')
			.setCheck('array');
		this.appendValueInput('finalState')
			.appendField('final state:')
			.setCheck('array');
		this.setPreviousStatement(true, 'statement');
		this.setNextStatement(true, 'statement');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_getCometState'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('getCometState');
		this.appendValueInput('state')
			.appendField('array:')
			.setCheck('array');
		this.setPreviousStatement(true, 'statement');
		this.setNextStatement(true, 'statement');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_faceTarget'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('faceTarget');
		this.appendValueInput('target')
			.appendField('target:')
			.setCheck('array');
		this.setPreviousStatement(true, 'statement');
		this.setNextStatement(true, 'statement');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_isFacingTarget'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('I am facing my comet')
		this.setOutput(true, 'number');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_shootLaserBool'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('shoot laser')
		this.setOutput(true, 'number');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_shootLaserVoid'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('shoot laser');
		this.setPreviousStatement(true, 'statement');
		this.setNextStatement(true, 'statement');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_laserShotsRemaining'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('laser shots remaining')
		this.setOutput(true, 'number');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_getMass'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('my mass')
		this.setOutput(true, 'number');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_getFuelRemaining'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('my remaining fuel')
		this.setOutput(true, 'number');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_getScore'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('my score')
		this.setOutput(true, 'number');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_getOtherScore'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('opponent\'s score')
		this.setOutput(true, 'number');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_isSlowDownActive'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('slowdown is active')
		this.setOutput(true, 'number');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};

Blockly.Blocks['zrms14_isBounceActive'] = {
	init: function() {
		this.setHelpUrl('');
		this.setColour(20);
		this.appendDummyInput()
			.appendField('bounce is active')
		this.setOutput(true, 'number');
		this.setTooltip('');
		this.setInputsInline(true);
	},
	onchange: Blockly.Blocks.requireInFunction,
};<|endoftext|>


<commit_before>//
// charts_update.js
// Will De Freitas
//
// Displays error messages based on xml files
//
//

//-------------------------------------------------------------------------------
// Pads a number with zeros
//-------------------------------------------------------------------------------
function pad(num, size) {
    var s = "000" + num;
    return s.substr(s.length-size);
}

//-------------------------------------------------------------------------------
// Grab error.json data
//-------------------------------------------------------------------------------
function grabErrorData(functionCall){

	$.getJSON('weather_data/error.json', function(json) {
		functionCall(json);
	});

}

//-------------------------------------------------------------------------------
// Grab error.json data
//-------------------------------------------------------------------------------
function clearErrors(){

	$.get('php/clear_errors.php', function(data) {
	  	alert(data);
	});

}

//-------------------------------------------------------------------------------
// Manages error messages depending on passed error code
//-------------------------------------------------------------------------------
function displayErrorMessage(error_data) {

	errorValue = 0;
	errorMessage = '';

	for (var error in error_data) {
		if(error_data[error].time != 0) {
			errorValue = error;
			errorMessage = error_data[error].msg;
		}
	};

	if(errorValue != 0){

		var displayErrorType = "   Error E"+ pad(errorValue, 4) + ": ";

		var formattedErrorMsg 	= HTMLerrorMSG.replace("%error_type%", displayErrorType);
		formattedErrorMsg 		= formattedErrorMsg.replace("%error_msg%", errorMessage);

		$('#error_display').append(formattedErrorMsg);
	}
}

//-------------------------------------------------------------------------------
// Parses error messages to error table
//-------------------------------------------------------------------------------
function parseErrorMsgTable(error_data) {

	for (var error in error_data) {
		if(error_data[error].time != 0) {

			var datetime = new Date(error_data[error].time);
			datetime = datetime.toUTCString();

			var formattedError 	= HTMLerrorTable.replace("%date%", datetime);
			formattedError 		= formattedError.replace("%errornumber%", error);
			formattedError 		= formattedError.replace("%message%", error_data[error].msg);
			formattedError 		= formattedError.replace("%count%", error_data[error].count);

			var notified = 'No';

			if(error_data[error].notified === '1') { notified = 'YES' }
			formattedError 		= formattedError.replace("%notified%", notified);

			$('#error_table').append(formattedError);
		}
	}
}

//-------------------------------------------------------------------------------
// Prepares data and displays it
//-------------------------------------------------------------------------------
function main() {

	grabErrorData(displayErrorMessage);

	$('#modal_errors').on('shown.bs.modal', function (e) {
    	grabErrorData(parseErrorMsgTable);
	});

	$('#modal_errors').on('hidden.bs.modal', function (e) {
    	$('#error_table').empty()
	});
}

//===============================================================================
// Main
//===============================================================================
main();

<commit_msg>Fix date issue in error log<commit_after>//
// charts_update.js
// Will De Freitas
//
// Displays error messages based on xml files
//
//

//-------------------------------------------------------------------------------
// Pads a number with zeros
//-------------------------------------------------------------------------------
function pad(num, size) {
    var s = "000" + num;
    return s.substr(s.length-size);
}

//-------------------------------------------------------------------------------
// Grab error.json data
//-------------------------------------------------------------------------------
function grabErrorData(functionCall){

	$.getJSON('weather_data/error.json', function(json) {
		functionCall(json);
	});

}

//-------------------------------------------------------------------------------
// Grab error.json data
//-------------------------------------------------------------------------------
function clearErrors(){

	$.get('php/clear_errors.php', function(data) {
	  	alert(data);
	});

}

//-------------------------------------------------------------------------------
// Manages error messages depending on passed error code
//-------------------------------------------------------------------------------
function displayErrorMessage(error_data) {

	errorValue = 0;
	errorMessage = '';

	for (var error in error_data) {
		if(error_data[error].time != 0) {
			errorValue = error;
			errorMessage = error_data[error].msg;
		}
	};

	if(errorValue != 0){

		var displayErrorType = "   Error E"+ pad(errorValue, 4) + ": ";

		var formattedErrorMsg 	= HTMLerrorMSG.replace("%error_type%", displayErrorType);
		formattedErrorMsg 		= formattedErrorMsg.replace("%error_msg%", errorMessage);

		$('#error_display').append(formattedErrorMsg);
	}
}

//-------------------------------------------------------------------------------
// Parses error messages to error table
//-------------------------------------------------------------------------------
function parseErrorMsgTable(error_data) {

	for (var error in error_data) {
		if(error_data[error].time != 0) {

			var datetime = new Date(error_data[error].time * 1000);
			datetime = datetime.toUTCString();

			var formattedError 	= HTMLerrorTable.replace("%date%", datetime);
			formattedError 		= formattedError.replace("%errornumber%", error);
			formattedError 		= formattedError.replace("%message%", error_data[error].msg);
			formattedError 		= formattedError.replace("%count%", error_data[error].count);

			var notified = 'No';

			if(error_data[error].notified === '1') { notified = 'YES' }
			formattedError 		= formattedError.replace("%notified%", notified);

			$('#error_table').append(formattedError);
		}
	}
}

//-------------------------------------------------------------------------------
// Prepares data and displays it
//-------------------------------------------------------------------------------
function main() {

	grabErrorData(displayErrorMessage);

	$('#modal_errors').on('shown.bs.modal', function (e) {
    	grabErrorData(parseErrorMsgTable);
	});

	$('#modal_errors').on('hidden.bs.modal', function (e) {
    	$('#error_table').empty()
	});
}

//===============================================================================
// Main
//===============================================================================
main();

<|endoftext|>


<commit_before>
// run the currently selected effect
function runEffect(togglerWindow) {
        $(togglerWindow ).show( "slide",{direction: "left"}, 1500);
};

$(document).ready(function()
{
    $.ajaxSetup ({
        cache: false
    });

    setupCSS();

    // hide toggle windows
    hideToggleWindows();

    // hover effects
    $('#requestInviteButton, #loginButton, #submitRequestInvite, #submitLogin').hover(
        function() {$(this).addClass('ui-state-hover');},
        function() {$(this).removeClass('ui-state-hover');}
     );

    $("#loginForm").ajaxSuccess(function(){
        //alert("Success");
    });

    $("#loginForm").ajaxComplete(function(){
        //alert("Complete");
    });

    $("#loginForm").ajaxError(function(){
        alert("Fail");
    });
    $("#loginForm").submit(function(e){
        // validate user via ajax call
        e.preventDefault();
        var url = $(this).attr('action');

        $.post( url, {email: $("#login_email_addr").val(), password: $("#password").val()}, function(data){

            $dataArray = data.split(",");

            if($dataArray[0].toLowerCase() == "continue")
            {
                // redirect to home page
                redirectToHomePage();
            }
            else
            {
                displayMessage($dataArray[0]);
            }
        });
    });

    $('#requestInviteForm').submit(function(e) {
        e.preventDefault();

        $.post('/frontpage/requestInvite', {email: $("#email_addr").val()}, function(data){
            displayMessage(data);
        });
    });

    // set effect from log in or request invite buttons
    $("#requestInviteButton, #loginButton, #loginLink").click(function() {
        var thisId = $(this).attr('id');
        var activeToggler_SelectorId = "";
        var hiddenToggler_SelectorId = "";

        if(thisId == "requestInviteButton")
        {
            activeToggler_SelectorId = "#requestInviteToggleWindow";
            hiddenToggler_SelectorId = "#loginToggleWindow";
        }
        else{
            activeToggler_SelectorId = "#loginToggleWindow";
            hiddenToggler_SelectorId = "#requestInviteToggleWindow";
        }

        $(hiddenToggler_SelectorId).hide();
        runEffect(activeToggler_SelectorId);
    });

    // a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
    $( "#dialog:ui-dialog" ).dialog( "destroy" );

});

function displayMessage(message)
{
    $('#dialog-message').html(message);
    $( "#dialog-message" ).dialog({
        modal: true,
        buttons: {
                Ok: function() {
                        $( this ).dialog( "close" );
                }
        }
    });
}

function redirectToHomePage()
{
    // redirect to the logged in user's home page
    window.location = "/app_dev.php/Homepage";
}

// run the currently selected effect
function runEffect(togglerWindow) {
    $(togglerWindow ).show( "slide",{direction: "left"}, 1500);
}

function setupCSS()
{
    $(':input').addClass("ui-state-default");
    $(':input').addClass("ui-corner-all");

    $('#requestInviteButton, #loginButton').addClass("ui-state-default");
    $('#requestInviteButton, #loginButton').addClass("ui-corner-all");
}

// hide the toggle windows
function hideToggleWindows()
{
    $('#requestInviteToggleWindow').hide();
    $('#loginToggleWindow').hide();
}

<commit_msg>starting to add the info for the About link on the front page<commit_after>
// run the currently selected effect
function runEffect(togglerWindow) {
        $(togglerWindow ).show( "slide",{direction: "left"}, 1500);
};

$(document).ready(function()
{
    $.ajaxSetup ({
        cache: false
    });

    setupCSS();

    // hide toggle windows
    hideToggleWindows();

    // hover effects
    $('#requestInviteButton, #loginButton, #submitRequestInvite, #submitLogin').hover(
        function() {$(this).addClass('ui-state-hover');},
        function() {$(this).removeClass('ui-state-hover');}
     );

    $("#loginForm").ajaxSuccess(function(){
        //alert("Success");
    });

    $("#loginForm").ajaxComplete(function(){
        //alert("Complete");
    });

    $("#loginForm").ajaxError(function(){
        alert("Fail");
    });
    $("#loginForm").submit(function(e){
        // validate user via ajax call
        e.preventDefault();
        var url = $(this).attr('action');

        $.post( url, {email: $("#login_email_addr").val(), password: $("#password").val()}, function(data){

            $dataArray = data.split(",");

            if($dataArray[0].toLowerCase() == "continue")
            {
                // redirect to home page
                redirectToHomePage();
            }
            else
            {
                displayMessage($dataArray[0]);
            }
        });
    });

    $('#requestInviteForm').submit(function(e) {
        e.preventDefault();

        $.post('/frontpage/requestInvite', {email: $("#email_addr").val()}, function(data){
            displayMessage(data);
        });
    });

    // set effect from log in or request invite buttons
    $("#requestInviteButton, #loginButton, #loginLink").click(function() {
        var thisId = $(this).attr('id');
        var activeToggler_SelectorId = "";
        var hiddenToggler_SelectorId = "";

        if(thisId == "requestInviteButton")
        {
            activeToggler_SelectorId = "#requestInviteToggleWindow";
            hiddenToggler_SelectorId = "#loginToggleWindow";
        }
        else{
            activeToggler_SelectorId = "#loginToggleWindow";
            hiddenToggler_SelectorId = "#requestInviteToggleWindow";
        }

        $(hiddenToggler_SelectorId).hide();
        runEffect(activeToggler_SelectorId);
    });

    $("#aboutLink").click(displayAboutDialog);

    // a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
    $( "#dialog:ui-dialog" ).dialog( "destroy" );

});

function displayAboutDialog()
{
    var aboutMessage = "Wishlist lets you keep track of all of your wishes in one location and lets you share your list with friends!
\n\
     Your friends can see when your birthday or anniversary is coming up and get a present from your list without you knowing!

\n\
     Our Goal is to make life easier by providing a central location where everyone can bookmark their wishes and their friends can easily see what they want!

\n\
     Request an invite to create your wishlist today!";

    $( "#dialog-message" ).attr('title','What is Wishlist?');
    $( "#dialog-message" ).css('width','300px');

    displayMessage(aboutMessage);
}

function displayMessage(message)
{
    $('#dialog-message').html(message);
    $( "#dialog-message" ).dialog({
        modal: true,
        buttons: {
                Ok: function() {
                        $( this ).dialog( "close" );
                }
        }
    });
}

function redirectToHomePage()
{
    // redirect to the logged in user's home page
    window.location = "/app_dev.php/Homepage";
}

// run the currently selected effect
function runEffect(togglerWindow) {
    $(togglerWindow ).show( "slide",{direction: "left"}, 1500);
}

function setupCSS()
{
    $(':input').addClass("ui-state-default");
    $(':input').addClass("ui-corner-all");

    $('#requestInviteButton, #loginButton').addClass("ui-state-default");
    $('#requestInviteButton, #loginButton').addClass("ui-corner-all");
}

// hide the toggle windows
function hideToggleWindows()
{
    $('#requestInviteToggleWindow').hide();
    $('#loginToggleWindow').hide();
}

<|endoftext|>


<commit_before>const path = require('path')
const server = require('local-web-server')
const childprocess = require('child_process')

const runCypress = () => {
  const winExt = /^win/.test(process.platform) ? '.cmd' : ''
  const cypressBin = 'cypress' + winExt

  const cypressArgs = ['run']
  if (process.argv.slice(2).length > 0) {
    process.argv.slice(2).forEach(arg => cypressArgs.push(arg))
  }

  childprocess.spawn(cypressBin, cypressArgs, { stdio: 'inherit' })
    .on('close', (code) => {
      ws.server.close()
      process.exit(code)
    })
}

const ws = server.create({
  port: 3000,
  directory: path.join(__dirname, 'wwwroot')
})

runCypress()
<commit_msg>Log web server errors.<commit_after>const path = require('path')
const server = require('local-web-server')
const childprocess = require('child_process')

const runCypress = () => {
  const winExt = /^win/.test(process.platform) ? '.cmd' : ''
  const cypressBin = 'cypress' + winExt

  const cypressArgs = ['run']
  if (process.argv.slice(2).length > 0) {
    process.argv.slice(2).forEach(arg => cypressArgs.push(arg))
  }

  childprocess.spawn(cypressBin, cypressArgs, { stdio: 'inherit' })
    .on('close', (code) => {
      ws.server.close()
      process.exit(code)
    })
}

const ws = server.create({
  port: 3000,
  directory: path.join(__dirname, 'wwwroot')
})

ws.server.on('error', (error) => {
  console.log(error)
})

runCypress()
<|endoftext|>


<commit_before>'use strict';

require('babel/polyfill');
var React = require('react/addons');
var Vue = require('vue');

var LandingPage      = require('view/LandingPage.jsx');
var DashboardBuilder = require('view/dashboard-builder/DashboardBuilder.jsx');
var ChartBuilder     = require('view/chart-builder/ChartBuilder.jsx');
var Navigation       = require('component/Navigation.jsx');
var AdminApp         = require('./ufadmin');

Vue.config.debug = true;

Vue.component('vue-dropdown', require('./component/dropdown'));
Vue.component('vue-table', require('./component/table'));
Vue.component('vue-table-editable', require('./component/table-editable'));
Vue.component('vue-pagination', require('./component/pagination'));
Vue.component('vue-tooltip', require('./component/tooltip'));
Vue.component('vue-menu', require('./component/menu'));

Vue.filter('num', require('./filter/num'));

Vue.partial('tooltip-stacked-bar', require('./partial/tooltip-stacked-bar.html'));
Vue.partial('tooltip-heatmap', require('./partial/tooltip-heatmap.html'));
Vue.partial('tooltip-indicator', require('./partial/tooltip-indicator.html'));

React.render(
	React.createElement(Navigation),
	document.getElementById('main-nav')
);

module.exports = {
	Explorer: function (el) {
		new Vue({
			el: el,
			components: { 'uf-explorer': require('./view/explorer') }
		});
	},
	Dashboard: function (el) {
		new Vue({
			el: el,
			components: { 'uf-dashboard': require('./view/dashboard') }
		});
	},
	DataEntry: function (el) {
		new Vue({
			el: el,
			components: { 'uf-entry-form': require('./view/entry-form') }
		});
	},
	FieldMapping: function (el,document_id) {
		new Vue({
			el: el,
			components: { 'uf-field-mapping': require('./view/field-mapping') },
			data:{'document_id':document_id}
		});
	},
	UserAccount: function (el,user_id) {
		new Vue({
			el: el,
			components: { 'uf-user-account': require('./view/user-account') },
			data:{'user_id':user_id}
		});
	},
	LandingPage: function (el) {
		React.render(React.createElement(LandingPage), el);
	},
	DashboardBuilder: function (el) {
		React.render(React.createElement(DashboardBuilder), el);
	},
	ChartBuilder: function (el) {
		React.render(React.createElement(ChartBuilder), el);
	},
	UFAdmin: function(el) {
		AdminApp.render(document.getElementById('main'));
	}
};
<commit_msg>Fix the extraneous API calls on each page<commit_after>'use strict';

require('babel/polyfill');
var React = require('react/addons');
var Vue = require('vue');

var LandingPage      = require('view/LandingPage.jsx');
var DashboardBuilder = require('view/dashboard-builder/DashboardBuilder.jsx');
var Navigation       = require('component/Navigation.jsx');
var AdminApp         = require('./ufadmin');

Vue.config.debug = true;

Vue.component('vue-dropdown', require('./component/dropdown'));
Vue.component('vue-table', require('./component/table'));
Vue.component('vue-table-editable', require('./component/table-editable'));
Vue.component('vue-pagination', require('./component/pagination'));
Vue.component('vue-tooltip', require('./component/tooltip'));
Vue.component('vue-menu', require('./component/menu'));

Vue.filter('num', require('./filter/num'));

Vue.partial('tooltip-stacked-bar', require('./partial/tooltip-stacked-bar.html'));
Vue.partial('tooltip-heatmap', require('./partial/tooltip-heatmap.html'));
Vue.partial('tooltip-indicator', require('./partial/tooltip-indicator.html'));

React.render(
	React.createElement(Navigation),
	document.getElementById('main-nav')
);

module.exports = {
	Explorer: function (el) {
		new Vue({
			el: el,
			components: { 'uf-explorer': require('./view/explorer') }
		});
	},
	Dashboard: function (el) {
		new Vue({
			el: el,
			components: { 'uf-dashboard': require('./view/dashboard') }
		});
	},
	DataEntry: function (el) {
		new Vue({
			el: el,
			components: { 'uf-entry-form': require('./view/entry-form') }
		});
	},
	FieldMapping: function (el,document_id) {
		new Vue({
			el: el,
			components: { 'uf-field-mapping': require('./view/field-mapping') },
			data:{'document_id':document_id}
		});
	},
	UserAccount: function (el,user_id) {
		new Vue({
			el: el,
			components: { 'uf-user-account': require('./view/user-account') },
			data:{'user_id':user_id}
		});
	},
	LandingPage: function (el) {
		React.render(React.createElement(LandingPage), el);
	},
	DashboardBuilder: function (el) {
		React.render(React.createElement(DashboardBuilder), el);
	},
	ChartBuilder: function (el) {
		var ChartBuilder = require('view/chart-builder/ChartBuilder.jsx');
		React.render(React.createElement(ChartBuilder), el);
	},
	UFAdmin: function(el) {
		AdminApp.render(document.getElementById('main'));
	}
};
<|endoftext|>


<commit_before>var stages = require('./stage/list');

module.exports = {
  onComplete: function(data, stage) {
    var categ = stages.categs[stages.stageIdToCategId(stage.id)];
    var complete = categ.stages.every(function(s) {
      return !!data.stages[s.key];
    });
    if (complete) dataLayer.push({
      'event': 'VirtualPageview',
      'virtualPageURL': '/learn-' + categ.key + '-completed',
      'virtualPageTitle': categ.name
    });
  }
};
<commit_msg>add user id to /learn GTM<commit_after>var stages = require('./stage/list');

module.exports = {
  onComplete: function(data, stage) {
    var categ = stages.categs[stages.stageIdToCategId(stage.id)];
    var complete = categ.stages.every(function(s) {
      return !!data.stages[s.key];
    });
    if (complete) dataLayer.push({
      'uid': data._id,
      'event': 'VirtualPageview',
      'virtualPageURL': '/learn-' + categ.key + '-completed',
      'virtualPageTitle': categ.name
    });
  }
};
<|endoftext|>


<commit_before>// run grunt --help for help on how to run
// Learn more about configuring this file at <https://github.com/theintern/intern/wiki/Configuring-Intern>.
// These default settings work OK for most people. The options that *must* be changed below are the
// packages, suites, excludeInstrumentation, and (if you want functional tests) functionalSuites.
define({
	// The port on which the instrumenting proxy will listen
	proxyPort: 9000,

	proxyUrl: "http://127.0.0.1:9000/",

	// Browsers to run integration testing against. Note that version numbers must be strings if used with Sauce
	// OnDemand. Options that will be permutated are browserName, version, platform, and platformVersion; any other
	// capabilities options specified for an environment will be copied as-is
	environments: [
		// It seems that specifying version="" or leaving version unspecified
		// does not default to the latest version of the browser.

		// Desktop.
		// Not running on IE9 since Widget-attr test depends on domClass methods only available in IE10_
		{ browserName: "internet explorer", version: "11", platform: "Windows 8.1", requireWindowFocus: "true",
			name : "deliteful"},
		{ browserName: "internet explorer", version: "10", platform: "Windows 8", requireWindowFocus: "true",
			name : "deliteful"},
		// { browserName: "internet explorer", version: "9", platform: "Windows 7" },
		{ browserName: "firefox", version: "25", platform: [ /*"OS X 10.6", "Linux", */ "Windows 7" ],
			name : "deliteful"},
		{ browserName: "chrome", version: "32", platform: [ /*"OS X 10.6", "Linux", */ "Windows 7" ],
			name : "deliteful"},
		{ browserName: "safari", version: "7", platform: [ "OS X 10.9" ], name : "deliteful"},

		// Mobile
		{ browserName: "iphone 7.1 simulator", platform: "OS X 10.9", version: "7.1", deviceName: "iPhone",
			app: "safari", device: "iPhone Simulator", name: "deliteful" },
		{ browserName: "ipad 7.1 simulator", platform: "OS X 10.9", version: "7.1", deviceName: "iPad",
			app: "safari", device: "iPad Simulator", name: "deliteful" },
		{ browserName: "iphone 7.0 simulator", platform: "OS X 10.9", version: "7.0", deviceName: "iPhone",
			app: "safari", device: "iPhone Simulator", name: "deliteful" },
		{ browserName: "ipad 7.0 simulator", platform: "OS X 10.9", version: "7.0", deviceName: "iPad",
			app: "safari", device: "iPad Simulator", name: "deliteful" }
//		{ browserName: "", platform: "OS X 10.8", version: "6", deviceName: "iPhone",
//			app: "safari", device: "iPhone Simulator", name: "deliteful" },
//		{ browserName: "", platform: "OS X 10.8", version: "6", deviceName: "iPad",
//			app: "safari", device: "iPad Simulator", name: "deliteful" },
//		{ browserName: "android", platform: "Linux", version: "4.1", name : "deliteful"},
//		{ browserName: "android", platform: "Linux", "device-type": "tablet", version: "4.1", name : "deliteful"},
//		{ browserName: "android", platform: "Linux", version: "4.1", name : "deliteful"},
//		{ browserName: "android", platform: "Linux", "device-type": "tablet", version: "4.0", name : "deliteful"},
//		{ browserName: "android", platform: "Linux", version: "4.0", name : "deliteful"},
	],

	// Maximum number of simultaneous integration tests that should be executed on the remote WebDriver service
	maxConcurrency: 3,

	// Whether or not to start Sauce Connect before running tests
	useSauceConnect: true,

	// Connection information for the remote WebDriver service. If using Sauce Labs, keep your username and password
	// in the SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables unless you are sure you will NEVER be
	// publishing this configuration file somewhere
	webdriver: {
		host: "localhost",
		port: 4444
	},

	loader: {
		baseUrl: typeof window !== "undefined" ? "../../.." : "..",
		config: {
			"ecma402/locales": "en-US"
		}
	},

	useLoader: {
		"host-node": "requirejs",
		"host-browser": "../../../requirejs/require.js"
	},

	// Non-functional test suite(s) to run in each browser
	suites: [ "deliteful/tests/unit/all" ],

	// Functional test suite(s) to run in each browser once non-functional tests are completed
	functionalSuites: [ "deliteful/tests/functional/all" ],

	// A regular expression matching URLs to files that should not be included in code coverage analysis
	excludeInstrumentation: /^(requirejs.*|dcl|dojo|dstore|dpointer|decor|delite\/|deliteful\/tests|.*themes|.*transitions)/
});
<commit_msg>excludeInstrumentation: avoid too long line (jshint error)<commit_after>// run grunt --help for help on how to run
// Learn more about configuring this file at <https://github.com/theintern/intern/wiki/Configuring-Intern>.
// These default settings work OK for most people. The options that *must* be changed below are the
// packages, suites, excludeInstrumentation, and (if you want functional tests) functionalSuites.
define({
	// The port on which the instrumenting proxy will listen
	proxyPort: 9000,

	proxyUrl: "http://127.0.0.1:9000/",

	// Browsers to run integration testing against. Note that version numbers must be strings if used with Sauce
	// OnDemand. Options that will be permutated are browserName, version, platform, and platformVersion; any other
	// capabilities options specified for an environment will be copied as-is
	environments: [
		// It seems that specifying version="" or leaving version unspecified
		// does not default to the latest version of the browser.

		// Desktop.
		// Not running on IE9 since Widget-attr test depends on domClass methods only available in IE10_
		{ browserName: "internet explorer", version: "11", platform: "Windows 8.1", requireWindowFocus: "true",
			name : "deliteful"},
		{ browserName: "internet explorer", version: "10", platform: "Windows 8", requireWindowFocus: "true",
			name : "deliteful"},
		// { browserName: "internet explorer", version: "9", platform: "Windows 7" },
		{ browserName: "firefox", version: "25", platform: [ /*"OS X 10.6", "Linux", */ "Windows 7" ],
			name : "deliteful"},
		{ browserName: "chrome", version: "32", platform: [ /*"OS X 10.6", "Linux", */ "Windows 7" ],
			name : "deliteful"},
		{ browserName: "safari", version: "7", platform: [ "OS X 10.9" ], name : "deliteful"},

		// Mobile
		{ browserName: "iphone 7.1 simulator", platform: "OS X 10.9", version: "7.1", deviceName: "iPhone",
			app: "safari", device: "iPhone Simulator", name: "deliteful" },
		{ browserName: "ipad 7.1 simulator", platform: "OS X 10.9", version: "7.1", deviceName: "iPad",
			app: "safari", device: "iPad Simulator", name: "deliteful" },
		{ browserName: "iphone 7.0 simulator", platform: "OS X 10.9", version: "7.0", deviceName: "iPhone",
			app: "safari", device: "iPhone Simulator", name: "deliteful" },
		{ browserName: "ipad 7.0 simulator", platform: "OS X 10.9", version: "7.0", deviceName: "iPad",
			app: "safari", device: "iPad Simulator", name: "deliteful" }
//		{ browserName: "", platform: "OS X 10.8", version: "6", deviceName: "iPhone",
//			app: "safari", device: "iPhone Simulator", name: "deliteful" },
//		{ browserName: "", platform: "OS X 10.8", version: "6", deviceName: "iPad",
//			app: "safari", device: "iPad Simulator", name: "deliteful" },
//		{ browserName: "android", platform: "Linux", version: "4.1", name : "deliteful"},
//		{ browserName: "android", platform: "Linux", "device-type": "tablet", version: "4.1", name : "deliteful"},
//		{ browserName: "android", platform: "Linux", version: "4.1", name : "deliteful"},
//		{ browserName: "android", platform: "Linux", "device-type": "tablet", version: "4.0", name : "deliteful"},
//		{ browserName: "android", platform: "Linux", version: "4.0", name : "deliteful"},
	],

	// Maximum number of simultaneous integration tests that should be executed on the remote WebDriver service
	maxConcurrency: 3,

	// Whether or not to start Sauce Connect before running tests
	useSauceConnect: true,

	// Connection information for the remote WebDriver service. If using Sauce Labs, keep your username and password
	// in the SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables unless you are sure you will NEVER be
	// publishing this configuration file somewhere
	webdriver: {
		host: "localhost",
		port: 4444
	},

	loader: {
		baseUrl: typeof window !== "undefined" ? "../../.." : "..",
		config: {
			"ecma402/locales": "en-US"
		}
	},

	useLoader: {
		"host-node": "requirejs",
		"host-browser": "../../../requirejs/require.js"
	},

	// Non-functional test suite(s) to run in each browser
	suites: [ "deliteful/tests/unit/all" ],

	// Functional test suite(s) to run in each browser once non-functional tests are completed
	functionalSuites: [ "deliteful/tests/functional/all" ],

	// A regular expression matching URLs to files that should not be included in code coverage analysis
	excludeInstrumentation:
		/^(requirejs.*|dcl|dojo|dstore|dpointer|decor|delite\/|deliteful\/tests|.*themes|.*transitions)/
});
<|endoftext|>


<commit_before>// run grunt --help for help on how to run
// Learn more about configuring this file at <https://github.com/theintern/intern/wiki/Configuring-Intern>.
// These default settings work OK for most people. The options that *must* be changed below are the
// packages, suites, excludeInstrumentation, and (if you want functional tests) functionalSuites.
define({
	// The port on which the instrumenting proxy will listen
	proxyPort: 9000,

	// Browsers to run integration testing against. Note that version numbers must be strings if used with Sauce
	// OnDemand. Options that will be permutated are browserName, version, platform, and platformVersion; any other
	// capabilities options specified for an environment will be copied as-is
	environments: [
		// It seems that specifying version="" or leaving version unspecified
		// does not default to the latest version of the browser.

		// Mobile
		{ browserName: "iphone", platform: "OS X 10.10", version: "9.0", deviceName: "iPad Retina", name: "deliteful" },

		// Desktop.
		{ browserName: "internet explorer", version: "11", platform: "Windows 8.1", requireWindowFocus: "true",
			name : "deliteful"},
		{ browserName: "firefox", version: "31", platform: [ /*"OS X 10.6", "Linux", */ "Windows 7" ],
			// default selenium-version is currently 2.40.0; some Combobox functional tests fail with
			// 2.40.0, while they pass with 2.41.0.
			"selenium-version": "2.41.0",
			name : "deliteful"},
		{ browserName: "chrome", version: "51", platform: [ /*"OS X 10.6", "Linux", */ "Windows 7" ],
			name : "deliteful"},
		{ browserName: "safari", version: "9", name : "deliteful"}
	],

	// Maximum number of simultaneous integration tests that should be executed on the remote WebDriver service
	maxConcurrency: 3,

	// Whether or not to start Sauce Connect before running tests
	tunnel: "SauceLabsTunnel",

	// Maximum duration of a test, in milliseconds
	defaultTimeout: 300000, // 5 minutes

	// Maximum time to wait for someting (pollUntil, etc...)
	WAIT_TIMEOUT: 180000, // 3 minutes

	// Interval between two polling request, in milliseconds (for pollUntil)
	POLL_INTERVAL: 500, // 0.5 seconds

	basePath: "..",

	loaders: {
		"host-node": "requirejs",
		"host-browser": "../../requirejs/require.js"
	},

	// Non-functional test suite(s) to run in each browser
	suites: [ "deliteful/tests/unit/all" ],

	// Functional test suite(s) to run in each browser once non-functional tests are completed
	functionalSuites: [ "deliteful/tests/functional/all" ],

	// A regular expression matching URLs to files that should not be included in code coverage analysis
	excludeInstrumentation:
		/*jshint -W101*/
		/^(requirejs.*|dcl|dojo|dstore|dpointer|decor|jquery|lie|delite\/|deliteful\/tests|ecma402|.*themes|.*transitions|.*node_modules)/
});
<commit_msg>Update selenium server for Firefox to v2.53.0 instead of v2.41.0.<commit_after>// run grunt --help for help on how to run
// Learn more about configuring this file at <https://github.com/theintern/intern/wiki/Configuring-Intern>.
// These default settings work OK for most people. The options that *must* be changed below are the
// packages, suites, excludeInstrumentation, and (if you want functional tests) functionalSuites.
define({
	// The port on which the instrumenting proxy will listen
	proxyPort: 9000,

	// Browsers to run integration testing against. Note that version numbers must be strings if used with Sauce
	// OnDemand. Options that will be permutated are browserName, version, platform, and platformVersion; any other
	// capabilities options specified for an environment will be copied as-is
	environments: [
		// It seems that specifying version="" or leaving version unspecified
		// does not default to the latest version of the browser.

		// Mobile
		{ browserName: "iphone", platform: "OS X 10.10", version: "9.0", deviceName: "iPad Retina", name: "deliteful" },

		// Desktop.
		{ browserName: "internet explorer", version: "11", platform: "Windows 8.1", requireWindowFocus: "true",
			name : "deliteful"},
		{ browserName: "firefox", version: "31", platform: [ /*"OS X 10.6", "Linux", */ "Windows 7" ],
			"selenium-version": "2.53.0",
			name : "deliteful"},
		{ browserName: "chrome", version: "51", platform: [ /*"OS X 10.6", "Linux", */ "Windows 7" ],
			name : "deliteful"},
		{ browserName: "safari", version: "9", name : "deliteful"}
	],

	// Maximum number of simultaneous integration tests that should be executed on the remote WebDriver service
	maxConcurrency: 3,

	// Whether or not to start Sauce Connect before running tests
	tunnel: "SauceLabsTunnel",

	// Maximum duration of a test, in milliseconds
	defaultTimeout: 300000, // 5 minutes

	// Maximum time to wait for someting (pollUntil, etc...)
	WAIT_TIMEOUT: 180000, // 3 minutes

	// Interval between two polling request, in milliseconds (for pollUntil)
	POLL_INTERVAL: 500, // 0.5 seconds

	basePath: "..",

	loaders: {
		"host-node": "requirejs",
		"host-browser": "../../requirejs/require.js"
	},

	// Non-functional test suite(s) to run in each browser
	suites: [ "deliteful/tests/unit/all" ],

	// Functional test suite(s) to run in each browser once non-functional tests are completed
	functionalSuites: [ "deliteful/tests/functional/all" ],

	// A regular expression matching URLs to files that should not be included in code coverage analysis
	excludeInstrumentation:
		/*jshint -W101*/
		/^(requirejs.*|dcl|dojo|dstore|dpointer|decor|jquery|lie|delite\/|deliteful\/tests|ecma402|.*themes|.*transitions|.*node_modules)/
});
<|endoftext|>


<commit_before>var buildConfig = require('../../../config/build.config');
var q = require('q');
var exec = require('child_process').exec;

module.exports = function buildConfigProcessor(log) {
  return {
    $runBefore: ['rendering-docs'],
    $unAfter: ['indexPageProcessor'],
    $process: process
  };

  function process(docs) {

    docs.push({
      template: 'build-config.js',
      outputPath: 'js/build-config.js',
      buildConfig: buildConfig
    });

    return q.all([
        getSHA(q.defer()),
        getCommitDate(q.defer())
    ]).then(function(){
        return docs;
    });

  }

  /**
   * Git the SHA associated with the most recent commit on origin/master
   * @param deferred
   * @returns {*}
   */
  function getSHA(deferred) {
    exec('git rev-parse HEAD', function(error, stdout, stderr) {
      buildConfig.commit = stdout && stdout.toString().trim();
      deferred.resolve(buildConfig.commit);
    });

    return deferred.promise;
  }

  /**
   * Get the commit date for the most recent commit on origin/master
   * @param deferred
   * @returns {*}
   */
  function getCommitDate(deferred) {
    exec('git show -s --format=%ci HEAD', function(error, stdout, stderr) {
      buildConfig.date = stdout && stdout.toString().trim();
      deferred.resolve(buildConfig.date);
    });

    return deferred.promise;
  }

};
<commit_msg>enhance(docs): improve use of promises in buildConfig.js<commit_after>var buildConfig = require('../../../config/build.config');
var q = require('q');
var exec = require('child_process').exec;

module.exports = function buildConfigProcessor(log) {
  return {
    $runBefore: ['rendering-docs'],
    $unAfter: ['indexPageProcessor'],
    $process: process
  };

  function process(docs) {

    docs.push({
      template: 'build-config.js',
      outputPath: 'js/build-config.js',
      buildConfig: buildConfig
    });

    return q.all([ getSHA(), getCommitDate() ])
            .then( function(){
              return docs;
          });
  }

  /**
   * Git the SHA associated with the most recent commit on origin/master
   * @param deferred
   * @returns {*}
   */
  function getSHA() {
    var deferred = q.defer();

    exec('git rev-parse HEAD', function(error, stdout, stderr) {
      buildConfig.commit = stdout && stdout.toString().trim();
      deferred.resolve(buildConfig.commit);
    });

    return deferred.promise;
  }

  /**
   * Get the commit date for the most recent commit on origin/master
   * @param deferred
   * @returns {*}
   */
  function getCommitDate() {
    var deferred = q.defer();

    exec('git show -s --format=%ci HEAD', function(error, stdout, stderr) {
      buildConfig.date = stdout && stdout.toString().trim();
      deferred.resolve(buildConfig.date);
    });

    return deferred.promise;
  }

};
<|endoftext|>


<commit_before>'use strict'

let Promise = require('bluebird')
let fs = Promise.promisifyAll(require('fs'))
let chalk = require('chalk')
let dateFormat = require('dateformat')
let sass = require('node-sass')
let bs = require('browser-sync').create()

// console.log for 1337 h4X0r
let log = console.log.bind(console)

// ISO date format to use for debuging
// let now = new Date()

// add a / at the end
let appPath = {
  appFolderPath: 'app/',
  cssFolderName: 'css/',
  sassFolderName: 'sass/',
  jsFolderName: 'js/',
  imgFolderName: 'css/'
}

let catchError = function (err) { log(err) }

// Greeting Message
var greetingMessage = function () {
  log(chalk.red('  #####   '))
  log(chalk.red(' #######  '))
  log(chalk.red('#  ###  # ') + chalk.grey(' The mighty Skull is starting your project.'))
  log(chalk.red('#   #   # '))
  log(chalk.red('######### ') + chalk.grey(' Happy coding !'))
  log(chalk.red(' ### ###  '))
  log(chalk.red('  #####   '))
  log(chalk.red('  # # #   ') + chalk.grey(' Play more, care less, be an heartless'))
}

greetingMessage()

// Reload all browser on HTML change
bs.watch(appPath.appFolderPath + '*.html').on('change', function () {
  bs.notify("HTML Reloaded", 2000)
  bs.reload()
})

// Reload all browser on JS change
bs.watch(appPath.appFolderPath + appPath.jsFolderName + '**.js').on('change', function () {
  bs.notify("JS Reloaded", 2000)
  bs.reload()
})

// Specific compilation for SASS file
bs.watch(appPath.appFolderPath + appPath.sassFolderName + '**.scss', function (event, file) {
  if (event === 'change') {
    sass.render({
      file: appPath.appFolderPath + appPath.sassFolderName + 'style.scss',
      outputStyle: 'expanded',
      outFile: appPath.appFolderPath + appPath.cssFolderName + 'style.css',
      sourceMap: true
    }, function (error, result) {
      if (error) {
        // Pretty Debug Message on sass error

        let nowFormat = dateFormat(new Date(), 'HH:MM:ss')

        log(chalk.red('[SASS ERROR ' + nowFormat + '] ') + error.file)
        log(chalk.red('[SASS ERROR ' + nowFormat + '] ') + 'On line ' + chalk.red(error.line) + ' at column ' + chalk.red(error.column))
        log(chalk.red('[SASS ERROR ' + nowFormat + '] ') + error.message)
      } else {
        // Creating css style files
        fs.writeFile(appPath.appFolderPath + appPath.cssFolderName + 'style.css', result.css, function (err) {
          if (!err) {
            // Creating css map file
            fs.writeFile(appPath.appFolderPath + appPath.cssFolderName + 'style.map.css', result.map, function (err) {
              if (!err) {
                let nowFormat = dateFormat(new Date(), '[HH:MM:ss]')
                log(nowFormat + chalk.green(' CSS Reloaded'))
                bs.notify("CSS Reloaded", 2000)
              } else {
                log(err)
              }
            })
          } else {
            log('error there')
            log(err)
          }
        })
        // Injecting the CSS change in BrowserSync
        bs.reload(appPath.appFolderPath + 'css/style.css')
      }
    })
  }
})

// Now init the Browsersync server
bs.init({
  server: './' + appPath.appFolderPath
})
<commit_msg>Fix sourcemap<commit_after>'use strict'

let Promise = require('bluebird')
let fs = Promise.promisifyAll(require('fs'))
let chalk = require('chalk')
let dateFormat = require('dateformat')
let sass = require('node-sass')
let bs = require('browser-sync').create()

// console.log for 1337 h4X0r
let log = console.log.bind(console)

// ISO date format to use for debuging
// let now = new Date()

// add a / at the end
let appPath = {
  appFolderPath: 'app/',
  cssFolderName: 'css/',
  sassFolderName: 'sass/',
  jsFolderName: 'js/',
  imgFolderName: 'css/'
}

let catchError = function (err) { log(err) }

// Greeting Message
var greetingMessage = function () {
  log(chalk.red('  #####   '))
  log(chalk.red(' #######  '))
  log(chalk.red('#  ###  # ') + chalk.grey(' The mighty Skull is starting your project.'))
  log(chalk.red('#   #   # '))
  log(chalk.red('######### ') + chalk.grey(' Happy coding !'))
  log(chalk.red(' ### ###  '))
  log(chalk.red('  #####   '))
  log(chalk.red('  # # #   ') + chalk.grey(' Play more, care less, be an heartless'))
}

greetingMessage()

// Reload all browser on HTML change
bs.watch(appPath.appFolderPath + '*.html').on('change', function () {
  bs.notify("HTML Reloaded", 2000)
  bs.reload()
})

// Reload all browser on JS change
bs.watch(appPath.appFolderPath + appPath.jsFolderName + '**.js').on('change', function () {
  bs.notify("JS Reloaded", 2000)
  bs.reload()
})

// Specific compilation for SASS file
bs.watch(appPath.appFolderPath + appPath.sassFolderName + '**.scss', function (event, file) {
  if (event === 'change') {
    sass.render({
      file: appPath.appFolderPath + appPath.sassFolderName + 'style.scss',
      outputStyle: 'expanded',
      outFile: appPath.appFolderPath + appPath.cssFolderName + 'style.css',
      sourceMap: 'style.map.css'
    }, function (error, result) {
      if (error) {
        // Pretty Debug Message on sass error

        let nowFormat = dateFormat(new Date(), 'HH:MM:ss')

        log(chalk.red('[SASS ERROR ' + nowFormat + '] ') + error.file)
        log(chalk.red('[SASS ERROR ' + nowFormat + '] ') + 'On line ' + chalk.red(error.line) + ' at column ' + chalk.red(error.column))
        log(chalk.red('[SASS ERROR ' + nowFormat + '] ') + error.message)
      } else {
        // Creating css style files
        fs.writeFile(appPath.appFolderPath + appPath.cssFolderName + 'style.css', result.css, function (err) {
          if (!err) {
            // Creating css map file
            fs.writeFile(appPath.appFolderPath + appPath.cssFolderName + 'style.map.css', result.map, function (err) {
              if (!err) {
                let nowFormat = dateFormat(new Date(), '[HH:MM:ss]')
                log(nowFormat + chalk.green(' CSS Reloaded'))
                bs.notify("CSS Reloaded", 2000)
              } else {
                log(err)
              }
            })
          } else {
            log('error there')
            log(err)
          }
        })
        // Injecting the CSS change in BrowserSync
        bs.reload(appPath.appFolderPath + 'css/style.css')
      }
    })
  }
})

// Now init the Browsersync server
bs.init({
  server: './' + appPath.appFolderPath
})
<|endoftext|>


<commit_before>"use strict";

var child_process = require("child_process");
var fs = require("fs");

// for use with child_process.exec/execFile
function execCallback(task) {
  return function (error, stdout, stderr) {
    if (stdout) console.log(stdout.toString());
    if (stderr) console.error(stderr.toString());
    if (error) {
      console.error(error);
      task.fail(error);
    }
    else task.complete();
  }
}

function catFiles(files, out) {
  fs.writeFileSync(out, files.map(f => fs.readFileSync(f, "utf8")).join(""))
}

function cmdIn(task, dir, cmd) {
  console.log(`[${dir}] ${cmd}`)
  child_process.exec(cmd, { cwd: dir }, execCallback(task))
}

function tscIn(task, dir) {
  cmdIn(task, dir, 'node ../node_modules/typescript/bin/tsc')
}

task('default', ['runprj'])

task('clean', function() {
  jake.rmRf("built")
})

task('runprj', ['buildprj', 'sim'], {async:true, parallelLimit: 10}, function() {
  cmdIn(this, "mbitprj", 'node ../built/sim.js')
})

task('buildprj', ['tsm'], {async:true}, function() {
  let f = fs.readdirSync("mbitprj").filter(f => /\.ts$/.test(f)).join(" ")
  cmdIn(this, "mbitprj", 'node ../built/tsm.js ' + f)
})

task('tsm', ['tsmbit'], function () {
  catFiles([ "node_modules/typescript/lib/typescript.js",
             "built/tsmbit.js"], "built/tsm.js")
})

task('tsmbit', {async : true}, function () { tscIn(this, "src") })
task('sim', {async: true}, function () { tscIn(this, "mbitsim") })

<commit_msg>Fix deps in build<commit_after>"use strict";

var child_process = require("child_process");
var fs = require("fs");

// for use with child_process.exec/execFile
function execCallback(task) {
  return function (error, stdout, stderr) {
    if (stdout) console.log(stdout.toString());
    if (stderr) console.error(stderr.toString());
    if (error) {
      console.error(error);
      task.fail(error);
    }
    else task.complete();
  }
}

function expand(dir) {
  if (Array.isArray(dir)) {
    let r = []
    dir.forEach(f => expand(dir).forEach(f => r.push(f)))
    return r
  }
  if (fs.existsSync(dir) && fs.statSync(dir).isDirectory())
    return fs.readdirSync(dir).map(f => dir + "/" + f)
  else return [dir]
}

function catFiles(files, out) {
  fs.writeFileSync(out, files.map(f => fs.readFileSync(f, "utf8")).join(""))
}

function cmdIn(task, dir, cmd) {
  console.log(`[${dir}] ${cmd}`)
  child_process.exec(cmd, { cwd: dir }, execCallback(task))
}

function tscIn(task, dir) {
  cmdIn(task, dir, 'node ../node_modules/typescript/bin/tsc')
}

task('default', ['runprj'])

task('clean', function() {
  jake.rmRf("built")
})

task('runprj', ['built/microbit.js', 'built/sim.js'], {async:true, parallelLimit: 10}, function() {
  cmdIn(this, "mbitprj", 'node ../built/sim.js')
})

file('built/microbit.js', ['built/tsm.js'], {async:true}, function() {
  let f = fs.readdirSync("mbitprj").filter(f => /\.ts$/.test(f)).join(" ")
  cmdIn(this, "mbitprj", 'node ../built/tsm.js ' + f)
})

file('built/tsm.js', ['built/tsmbit.js'], function () {
  catFiles([ "node_modules/typescript/lib/typescript.js",
             "built/tsmbit.js"], "built/tsm.js")
})

file('built/tsmbit.js', expand("src"), {async : true}, function () { tscIn(this, "src") })
file('built/sim.js', expand("mbitsim"), {async: true}, function () { tscIn(this, "mbitsim") })

<|endoftext|>


<commit_before>(function() {
	"use strict";

	angular
		.module('VinculacionApp')
		.factory('TbUtils', TbUtils);

    TbUtils.$inject = ['toaster'];

	function TbUtils (toaster) {
        var service = {
            fillList: fillList,
            displayNotification: displayNotification
        };

        return service;

        function fillList(response, list) {
            console.log(response);
            for(let obj in response.data) {
                list.push(response.data[obj]);
            }

            console.log(list);
        };

        function displayNotification(type, title, body) {
            toaster.pop(
                {
                    type: type,
                    title: title,
                    body: body
                }
            );
        }
	}
})();<commit_msg>Remove logs<commit_after>(function() {
	"use strict";

	angular
		.module('VinculacionApp')
		.factory('TbUtils', TbUtils);

    TbUtils.$inject = ['toaster'];

	function TbUtils (toaster) {
        var service = {
            fillList: fillList,
            displayNotification: displayNotification
        };

        return service;

        function fillList(response, list) {
            for(let obj in response.data) {
                list.push(response.data[obj]);
            }
        };

        function displayNotification(type, title, body) {
            toaster.pop(
                {
                    type: type,
                    title: title,
                    body: body
                }
            );
        }
	}
})();<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var EventEmitter = require('./lib/event_emitter');
var stat = require('./lib/stat');
var inherits = require('util').inherits;

var errors = require('./errors');
var States = require('./reqres_states');

function TChannelOutResponse(id, options) {
    options = options || {};
    var self = this;
    EventEmitter.call(self);
    self.errorEvent = self.defineEvent('error');
    self.spanEvent = self.defineEvent('span');
    self.finishEvent = self.defineEvent('finish');

    self.channel = options.channel;
    self.inreq = options.inreq;
    self.logger = options.logger;
    self.random = options.random;
    self.timers = options.timers;

    self.start = 0;
    self.end = 0;
    self.state = States.Initial;
    self.id = id || 0;
    self.code = options.code || 0;
    self.tracing = options.tracing || null;
    self.headers = options.headers || {};
    self.checksumType = options.checksumType || 0;
    self.checksum = options.checksum || null;
    self.ok = self.code === 0;
    self.span = options.span || null;
    self.streamed = false;
    self._argstream = null;
    self.arg1 = null;
    self.arg2 = null;
    self.arg3 = null;

    self.codeString = null;
    self.message = null;
}

inherits(TChannelOutResponse, EventEmitter);

TChannelOutResponse.prototype.type = 'tchannel.outgoing-response';

TChannelOutResponse.prototype.extendLogInfo = function extendLogInfo(info) {
    var self = this;

    info.responseId = self.id;
    info.responseType = self.type;
    info.responseState = States.describe(self.state);
    info.responseOk = self.ok;
    info.responseCode = self.code;
    info.responseCodeString = self.codeString;
    info.responseErrorMessage = self.message;
    info.responseStart = self.start;
    info.responseEnd = self.end;
    info.responseHasArg3 = self.arg3 !== null && self.arg3 !== undefined;

    if (self.inreq) {
        info = self.inreq.extendLogInfo(info);
    }

    return info;
};

TChannelOutResponse.prototype._sendCallResponse = function _sendCallResponse(args, isLast) {
    var self = this;
    throw errors.UnimplementedMethod({
        className: self.constructor.name,
        methodName: '_sendCallResponse'
    });
};

TChannelOutResponse.prototype._sendCallResponseCont = function _sendCallResponseCont(args, isLast) {
    var self = this;
    throw errors.UnimplementedMethod({
        className: self.constructor.name,
        methodName: '_sendCallResponseCont'
    });
};

TChannelOutResponse.prototype._sendError = function _sendError(codeString, message) {
    var self = this;
    throw errors.UnimplementedMethod({
        className: self.constructor.name,
        methodName: '_sendError'
    });
};

TChannelOutResponse.prototype.sendParts = function sendParts(parts, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.sendCallResponseFrame(parts, isLast);
            break;
        case States.Streaming:
            self.sendCallResponseContFrame(parts, isLast);
            break;
        case States.Done:
            self.errorEvent.emit(self, errors.ResponseFrameState({
                attempted: 'arg parts',
                state: 'Done'
            }));
            break;
        case States.Error:
            // TODO: log warn
            break;
        default:
            self.channel.logger.error('TChannelOutResponse is in a wrong state', self.extendLogInfo({}));
            break;
    }
};

TChannelOutResponse.prototype.sendCallResponseFrame = function sendCallResponseFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.start = self.timers.now();
            self._sendCallResponse(args, isLast);
            if (self.span) {
                self.span.annotate('ss');
            }
            if (isLast) self.state = States.Done;
            else self.state = States.Streaming;
            break;
        case States.Streaming:
            self.errorEvent.emit(self, errors.ResponseFrameState({
                attempted: 'call response',
                state: 'Streaming'
            }));
            break;
        case States.Done:
        case States.Error:
            var arg2 = args[1] || '';
            var arg3 = args[2] || '';

            self.errorEvent.emit(self, errors.ResponseAlreadyDone({
                attempted: 'call response',
                state: self.state,
                method: 'sendCallResponseFrame',
                bufArg2: arg2.slice(0, 50),
                arg2: String(arg2).slice(0, 50),
                bufArg3: arg3.slice(0, 50),
                arg3: String(arg3).slice(0, 50)
            }));
    }
};

TChannelOutResponse.prototype.sendCallResponseContFrame = function sendCallResponseContFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.errorEvent.emit(self, errors.ResponseFrameState({
                attempted: 'call response continuation',
                state: 'Initial'
            }));
            break;
        case States.Streaming:
            self._sendCallResponseCont(args, isLast);
            if (isLast) self.state = States.Done;
            break;
        case States.Done:
        case States.Error:
            self.errorEvent.emit(self, errors.ResponseAlreadyDone({
                attempted: 'call response continuation',
                state: self.state,
                method: 'sendCallResponseContFrame'
            }));
    }
};

TChannelOutResponse.prototype.sendError = function sendError(codeString, message) {
    var self = this;
    if (self.state === States.Done || self.state === States.Error) {
        self.errorEvent.emit(self, errors.ResponseAlreadyDone({
            attempted: 'error frame',
            currentState: self.state,
            method: 'sendError',
            codeString: codeString,
            errMessage: message
        }));
    } else {
        if (self.span) {
            self.span.annotate('ss');
        }
        self.state = States.Error;

        self.codeString = codeString;
        self.message = message;
        self.channel.inboundCallsSystemErrorsStat.increment(1, {
            'calling-service': self.inreq.headers.cn,
            'service': self.inreq.serviceName,
            'endpoint': String(self.inreq.arg1),
            'type': self.codeString
        });
        self._sendError(codeString, message);
        self.emitFinish();
    }
};

TChannelOutResponse.prototype.emitFinish = function emitFinish() {
    var self = this;
    var now = self.timers.now();

    if (self.end) {
        self.logger.warn('out response double emitFinish', self.extendLogInfo({
            now: now
        }));
        return;
    }

    self.end = now;

    var latency = self.end - self.inreq.start;

    self.channel.emitFastStat(self.channel.buildStat(
        'tchannel.inbound.calls.latency',
        'timing',
        latency,
        new stat.InboundCallsLatencyTags(
            self.inreq.headers.cn,
            self.inreq.serviceName,
            self.inreq.endpoint
        )
    ));

    if (self.span) {
        self.spanEvent.emit(self, self.span);
    }

    self.finishEvent.emit(self);
};

TChannelOutResponse.prototype.setOk = function setOk(ok) {
    var self = this;
    if (self.state !== States.Initial) {
        self.errorEvent.emit(self, errors.ResponseAlreadyStarted({
            state: self.state,
            method: 'setOk',
            ok: ok
        }));
        return false;
    }
    self.ok = ok;
    self.code = ok ? 0 : 1; // TODO: too coupled to v2 specifics?
    return true;
};

TChannelOutResponse.prototype.sendOk = function sendOk(res1, res2) {
    var self = this;
    self.setOk(true);
    self.send(res1, res2);
};

TChannelOutResponse.prototype.sendNotOk = function sendNotOk(res1, res2) {
    var self = this;
    if (self.state === States.Error) {
        self.logger.error('cannot send application error, already sent error frame', self.extendLogInfo({
            res1: res1,
            res2: res2
        }));
    } else {
        self.setOk(false);
        self.send(res1, res2);
    }
};

TChannelOutResponse.prototype.send = function send(res1, res2) {
    var self = this;

    /* send calls after finish() should be swallowed */
    if (self.end) {
        var inreqErrClass = self.inreq &&
                            self.inreq.err &&
                            errors.classify(self.inreq.err);

        switch (inreqErrClass) {
            case 'Timeout':
                self.logger.info('OutResponse.send() after inreq timed out', self.extendLogInfo({}));
                break;
            default:
                self.logger.warn('OutResponse called send() after end', self.extendLogInfo({}));
        }
        return;
    }

    self.arg2 = res1;
    self.arg3 = res2;

    if (self.ok) {
        self.channel.emitFastStat(self.channel.buildStat(
            'tchannel.inbound.calls.success',
            'counter',
            1,
            new stat.InboundCallsSuccessTags(
                self.inreq.headers.cn,
                self.inreq.serviceName,
                self.inreq.endpoint
            )
        ));
    } else {
        // TODO: add outResponse.setErrorType()
        self.channel.emitFastStat(self.channel.buildStat(
            'tchannel.inbound.calls.app-errors',
            'counter',
            1,
            new stat.InboundCallsAppErrorsTags(
                self.inreq.headers.cn,
                self.inreq.serviceName,
                self.inreq.endpoint,
                'unknown'
            )
        ));
    }

    self.sendCallResponseFrame([self.arg1, res1, res2], true);
    self.emitFinish();

    return self;
};

module.exports = TChannelOutResponse;
<commit_msg>TChannelOutResponse: fix early return bug in .send<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var EventEmitter = require('./lib/event_emitter');
var stat = require('./lib/stat');
var inherits = require('util').inherits;

var errors = require('./errors');
var States = require('./reqres_states');

function TChannelOutResponse(id, options) {
    options = options || {};
    var self = this;
    EventEmitter.call(self);
    self.errorEvent = self.defineEvent('error');
    self.spanEvent = self.defineEvent('span');
    self.finishEvent = self.defineEvent('finish');

    self.channel = options.channel;
    self.inreq = options.inreq;
    self.logger = options.logger;
    self.random = options.random;
    self.timers = options.timers;

    self.start = 0;
    self.end = 0;
    self.state = States.Initial;
    self.id = id || 0;
    self.code = options.code || 0;
    self.tracing = options.tracing || null;
    self.headers = options.headers || {};
    self.checksumType = options.checksumType || 0;
    self.checksum = options.checksum || null;
    self.ok = self.code === 0;
    self.span = options.span || null;
    self.streamed = false;
    self._argstream = null;
    self.arg1 = null;
    self.arg2 = null;
    self.arg3 = null;

    self.codeString = null;
    self.message = null;
}

inherits(TChannelOutResponse, EventEmitter);

TChannelOutResponse.prototype.type = 'tchannel.outgoing-response';

TChannelOutResponse.prototype.extendLogInfo = function extendLogInfo(info) {
    var self = this;

    info.responseId = self.id;
    info.responseType = self.type;
    info.responseState = States.describe(self.state);
    info.responseOk = self.ok;
    info.responseCode = self.code;
    info.responseCodeString = self.codeString;
    info.responseErrorMessage = self.message;
    info.responseStart = self.start;
    info.responseEnd = self.end;
    info.responseHasArg3 = self.arg3 !== null && self.arg3 !== undefined;

    if (self.inreq) {
        info = self.inreq.extendLogInfo(info);
    }

    return info;
};

TChannelOutResponse.prototype._sendCallResponse = function _sendCallResponse(args, isLast) {
    var self = this;
    throw errors.UnimplementedMethod({
        className: self.constructor.name,
        methodName: '_sendCallResponse'
    });
};

TChannelOutResponse.prototype._sendCallResponseCont = function _sendCallResponseCont(args, isLast) {
    var self = this;
    throw errors.UnimplementedMethod({
        className: self.constructor.name,
        methodName: '_sendCallResponseCont'
    });
};

TChannelOutResponse.prototype._sendError = function _sendError(codeString, message) {
    var self = this;
    throw errors.UnimplementedMethod({
        className: self.constructor.name,
        methodName: '_sendError'
    });
};

TChannelOutResponse.prototype.sendParts = function sendParts(parts, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.sendCallResponseFrame(parts, isLast);
            break;
        case States.Streaming:
            self.sendCallResponseContFrame(parts, isLast);
            break;
        case States.Done:
            self.errorEvent.emit(self, errors.ResponseFrameState({
                attempted: 'arg parts',
                state: 'Done'
            }));
            break;
        case States.Error:
            // TODO: log warn
            break;
        default:
            self.channel.logger.error('TChannelOutResponse is in a wrong state', self.extendLogInfo({}));
            break;
    }
};

TChannelOutResponse.prototype.sendCallResponseFrame = function sendCallResponseFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.start = self.timers.now();
            self._sendCallResponse(args, isLast);
            if (self.span) {
                self.span.annotate('ss');
            }
            if (isLast) self.state = States.Done;
            else self.state = States.Streaming;
            break;
        case States.Streaming:
            self.errorEvent.emit(self, errors.ResponseFrameState({
                attempted: 'call response',
                state: 'Streaming'
            }));
            break;
        case States.Done:
        case States.Error:
            var arg2 = args[1] || '';
            var arg3 = args[2] || '';

            self.errorEvent.emit(self, errors.ResponseAlreadyDone({
                attempted: 'call response',
                state: self.state,
                method: 'sendCallResponseFrame',
                bufArg2: arg2.slice(0, 50),
                arg2: String(arg2).slice(0, 50),
                bufArg3: arg3.slice(0, 50),
                arg3: String(arg3).slice(0, 50)
            }));
    }
};

TChannelOutResponse.prototype.sendCallResponseContFrame = function sendCallResponseContFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.errorEvent.emit(self, errors.ResponseFrameState({
                attempted: 'call response continuation',
                state: 'Initial'
            }));
            break;
        case States.Streaming:
            self._sendCallResponseCont(args, isLast);
            if (isLast) self.state = States.Done;
            break;
        case States.Done:
        case States.Error:
            self.errorEvent.emit(self, errors.ResponseAlreadyDone({
                attempted: 'call response continuation',
                state: self.state,
                method: 'sendCallResponseContFrame'
            }));
    }
};

TChannelOutResponse.prototype.sendError = function sendError(codeString, message) {
    var self = this;
    if (self.state === States.Done || self.state === States.Error) {
        self.errorEvent.emit(self, errors.ResponseAlreadyDone({
            attempted: 'error frame',
            currentState: self.state,
            method: 'sendError',
            codeString: codeString,
            errMessage: message
        }));
    } else {
        if (self.span) {
            self.span.annotate('ss');
        }
        self.state = States.Error;

        self.codeString = codeString;
        self.message = message;
        self.channel.inboundCallsSystemErrorsStat.increment(1, {
            'calling-service': self.inreq.headers.cn,
            'service': self.inreq.serviceName,
            'endpoint': String(self.inreq.arg1),
            'type': self.codeString
        });
        self._sendError(codeString, message);
        self.emitFinish();
    }
};

TChannelOutResponse.prototype.emitFinish = function emitFinish() {
    var self = this;
    var now = self.timers.now();

    if (self.end) {
        self.logger.warn('out response double emitFinish', self.extendLogInfo({
            now: now
        }));
        return;
    }

    self.end = now;

    var latency = self.end - self.inreq.start;

    self.channel.emitFastStat(self.channel.buildStat(
        'tchannel.inbound.calls.latency',
        'timing',
        latency,
        new stat.InboundCallsLatencyTags(
            self.inreq.headers.cn,
            self.inreq.serviceName,
            self.inreq.endpoint
        )
    ));

    if (self.span) {
        self.spanEvent.emit(self, self.span);
    }

    self.finishEvent.emit(self);
};

TChannelOutResponse.prototype.setOk = function setOk(ok) {
    var self = this;
    if (self.state !== States.Initial) {
        self.errorEvent.emit(self, errors.ResponseAlreadyStarted({
            state: self.state,
            method: 'setOk',
            ok: ok
        }));
        return false;
    }
    self.ok = ok;
    self.code = ok ? 0 : 1; // TODO: too coupled to v2 specifics?
    return true;
};

TChannelOutResponse.prototype.sendOk = function sendOk(res1, res2) {
    var self = this;
    self.setOk(true);
    self.send(res1, res2);
};

TChannelOutResponse.prototype.sendNotOk = function sendNotOk(res1, res2) {
    var self = this;
    if (self.state === States.Error) {
        self.logger.error('cannot send application error, already sent error frame', self.extendLogInfo({
            res1: res1,
            res2: res2
        }));
    } else {
        self.setOk(false);
        self.send(res1, res2);
    }
};

TChannelOutResponse.prototype.send = function send(res1, res2) {
    var self = this;

    /* send calls after finish() should be swallowed */
    if (self.end) {
        var inreqErrClass = self.inreq &&
                            self.inreq.err &&
                            errors.classify(self.inreq.err);

        switch (inreqErrClass) {
            case 'Timeout':
                self.logger.info('OutResponse.send() after inreq timed out', self.extendLogInfo({}));
                break;
            default:
                self.logger.warn('OutResponse called send() after end', self.extendLogInfo({}));
        }
        return self;
    }

    self.arg2 = res1;
    self.arg3 = res2;

    if (self.ok) {
        self.channel.emitFastStat(self.channel.buildStat(
            'tchannel.inbound.calls.success',
            'counter',
            1,
            new stat.InboundCallsSuccessTags(
                self.inreq.headers.cn,
                self.inreq.serviceName,
                self.inreq.endpoint
            )
        ));
    } else {
        // TODO: add outResponse.setErrorType()
        self.channel.emitFastStat(self.channel.buildStat(
            'tchannel.inbound.calls.app-errors',
            'counter',
            1,
            new stat.InboundCallsAppErrorsTags(
                self.inreq.headers.cn,
                self.inreq.serviceName,
                self.inreq.endpoint,
                'unknown'
            )
        ));
    }

    self.sendCallResponseFrame([self.arg1, res1, res2], true);
    self.emitFinish();

    return self;
};

module.exports = TChannelOutResponse;
<|endoftext|>


<commit_before>require('babel-register');
const Joi = require('joi');
const util = require('util');
const _ = require('lodash');
const hashAString = require('string-hash');

const schema = Joi.object().keys({
    a: Joi.boolean().valid(true),
    b: Joi.alternatives().try([
        Joi.string().regex(/^a/),
        Joi.string().valid('boom')
    ]),
    c: Joi.number().valid(5),
    d: Joi.string().valid('key'),
    e: Joi.object().keys({
        hi:    Joi.string(),
        hello: Joi.number()
    })
});

// Cache of validated values for each model
const validatedValues = {};

export default function JoiModelFactory(schema, defaults) {

    // Check if schema is a Joi schema
    if (!schema.isJoi && !(schema._type === 'object')) {
        throw new Error('Schema passed to joi-model2 must be a Joi schema.');
    }

    // Check if default object is valid itself
    const validation = Joi.validate(schema, defaults);
    if (validation.error) {
        throw new Error('JoiModel default values do not validate against given schema \n' + validation.error);
    }

    // Create a shadow object that
    const shadowObj = _.cloneDeep(defaults);

    // TODO make real random UUIDs
    const modelUUID = '12345';
    let JoiModel = {
        _UUID: modelUUID,
        _shadowObj: shadowObj
    };

    // Create an object to store cached values
    validatedValues[ modelUUID ] = {};

    const keys = Object.keys(schema.children);

    for (let key of keys) {
        Object.defineProperty(JoiModel, key, {
            enumerable: true,
            writable: true,
            get() {
                return this[key];
            },
            set(val) {
                const _this = this;
                const hash = hashAString(JSON.stringify(val));

                // If this value has already been validated for this key before, then just set the value
                if (validatedValues[ modelUUID ][hash]) {
                    return _this[ key ] = val;
                }

                // Do the validation against the shadow object
                const oldVal = _this[key];
                JoiModel._shadowObj[key] = val;
                const validation = Joi.validate(schema, JoiModel._shadowObj);
                if (validation.error) {
                    JoiModel._shadowObj[ key ] = oldVal;
                    throw new Error('Attempted to change a property to an invalid value: \n' + validation.error);
                }
                else {
                    // Cache the validated value
                    validatedValues[ modelUUID ][hash] = true;
                    return _this[ key ] = val;

                }
            }
        });
    }

    JoiModel.toJSON = function() {

    };

    return JoiModel;
}<commit_msg>Extract factory function from export default<commit_after>require('babel-register');
const Joi = require('joi');
const util = require('util');
const _ = require('lodash');
const hashAString = require('string-hash');

const schema = Joi.object().keys({
    a: Joi.boolean().valid(true),
    b: Joi.alternatives().try([
        Joi.string().regex(/^a/),
        Joi.string().valid('boom')
    ]),
    c: Joi.number().valid(5),
    d: Joi.string().valid('key'),
    e: Joi.object().keys({
        hi:    Joi.string(),
        hello: Joi.number()
    })
});

// Cache of validated values for each model
const validatedValues = {};

function createJoiModel(schema, defaults) {

    // Check if schema is a Joi schema
    if (!schema.isJoi && !(schema._type === 'object')) {
        throw new Error('Schema passed to joi-model2 must be a Joi schema.');
    }

    // Check if default object is valid itself
    const validation = Joi.validate(schema, defaults);
    if (validation.error) {
        throw new Error('JoiModel default values do not validate against given schema \n' + validation.error);
    }

    // Create a shadow object that
    const shadowObj = _.cloneDeep(defaults);

    // TODO make real random UUIDs
    const modelUUID = '12345';
    let JoiModel = {
        _UUID: modelUUID,
        _shadowObj: shadowObj
    };

    // Create an object to store cached values
    validatedValues[ modelUUID ] = {};

    const keys = Object.keys(schema.children);

    for (let key of keys) {
        Object.defineProperty(JoiModel, key, {
            enumerable: true,
            writable: true,
            get() {
                return this[key];
            },
            set(val) {
                const _this = this;
                const hash = hashAString(JSON.stringify(val));

                // If this value has already been validated for this key before, then just set the value
                if (validatedValues[ modelUUID ][hash]) {
                    return _this[ key ] = val;
                }

                // Do the validation against the shadow object
                const oldVal = _this[key];
                JoiModel._shadowObj[key] = val;
                const validation = Joi.validate(schema, JoiModel._shadowObj);
                if (validation.error) {
                    JoiModel._shadowObj[ key ] = oldVal;
                    throw new Error('Attempted to change a property to an invalid value: \n' + validation.error);
                }
                else {
                    // Cache the validated value
                    validatedValues[ modelUUID ][hash] = true;
                    return _this[ key ] = val;

                }
            }
        });
    }

    JoiModel.toJSON = function() {

    };

    return JoiModel;
}

export default createJoiModel;<|endoftext|>