<commit_before>'use strict';
const test = require('tape');
const path = require('path');
const proxyquire = require('proxyquire');
const noop = () => {
};

test('extractPbo', t => {
  t.plan(4);
  const pboFile = path.join(__dirname, 'test_folder.pbo');
  const pboFolder = path.join(__dirname, 'test_folder');

  const err = new Error('test');
  const stub = {child_process: {exec: (path, cb) => cb(err)}};
  const {extractPbo} = proxyquire.noCallThru().load('../lib/pbo-tools', stub);

  extractPbo(pboFile, (e, res) => {
    t.equals(err, e, 'returns error from exec');
  });

  stub.child_process.exec = (path, cb) => cb(null);
  extractPbo(pboFile, (e, res) => {
    t.error(e, 'no error');
    t.ok(res.ok, 'callback is ok');
    t.equals(res.folder, pboFolder, 'provides folder');
  });
});

test('lintPbo', t => {
  const pboFile = path.join(__dirname, 'test_folder.pbo');
  const pboFolder = path.join(__dirname, 'test_folder');

  const stub = {
    child_process: {exec: (cmd, cb) => cb(new Error('test'))},
    fs: {
      constants: {R_OK: null},
      access: (p, c, cb) => cb()
    }
  };
  const {lintPboFolder} = proxyquire.noCallThru().load('../lib/pbo-tools', stub);

  lintPboFolder(pboFolder, (e, res) => {
    t.ok(e instanceof Error, 'callbacks with error');
    t.ok(e.message.includes('Makepbo fail'), 'makepbo failed');
  })

  const err = new Error('Test');
  err.code = 87;
  const stdout = [
    'removed',
    pboFolder + ' lint fail'
  ].join('\n');

  stub.child_process.exec = (p, cb) => cb(err, stdout);
  lintPboFolder(pboFolder, (e, res) => {
    t.error(e, 'no error');
    t.false(res.ok, 'was not ok');
    const msg = res.message;
    t.false(msg.includes('removed'), 'does not print removed');
    t.false(msg.includes(pboFolder), 'path removed');
    t.ok(msg.includes('lint fail'), 'err msg included');
  });

  stub.child_process.exec = cmd => t.equals(cmd, 'makepbo -PQ ' + pboFolder + ' bla.pbo', 'exec called with folder');
  lintPboFolder(pboFolder, (e, res) => {
    t.error(e, 'no error');
    t.ok(res.ok, 'was ok');
  });

  t.end();
});
<commit_msg>Fix tests<commit_after>'use strict';
const test = require('tape');
const path = require('path');
const proxyquire = require('proxyquire');
const noop = () => {
};

test('extractPbo', t => {
  t.plan(4);
  const pboFile = path.join(__dirname, 'test_folder.pbo');
  const pboFolder = path.join(__dirname, 'test_folder');

  const err = new Error('test');
  const stub = {child_process: {exec: (path, cb) => cb(err)}};
  const {extractPbo} = proxyquire.noCallThru().load('../lib/pbo-tools', stub);

  extractPbo(pboFile, (e, res) => {
    t.equals(err, e, 'returns error from exec');
  });

  stub.child_process.exec = (path, cb) => cb(null);
  extractPbo(pboFile, (e, res) => {
    t.error(e, 'no error');
    t.ok(res.ok, 'callback is ok');
    t.equals(res.folder, pboFolder, 'provides folder');
  });
});

test('lintPbo', t => {
  const pboFile = path.join(__dirname, 'test_folder.pbo');
  const pboFolder = path.join(__dirname, 'test_folder');

  const stub = {
    child_process: {exec: (cmd, cb) => cb(new Error('test'))},
    fs: {
      constants: {R_OK: null},
      access: (p, c, cb) => cb()
    }
  };
  const {lintPboFolder} = proxyquire.noCallThru().load('../lib/pbo-tools', stub);

  lintPboFolder(pboFolder, (e, res) => {
    t.ok(e instanceof Error, 'callbacks with error');
    t.ok(e.message.includes('Makepbo fail'), 'makepbo failed');
  })

  const err = new Error('Test');
  err.code = 87;
  const stdout = [
    'removed',
    pboFolder + ' lint fail'
  ].join('\n');

  stub.child_process.exec = (p, cb) => cb(err, stdout);
  lintPboFolder(pboFolder, (e, res) => {
    t.error(e, 'no error');
    t.false(res.ok, 'was not ok');
    const msg = res.message;
    t.false(msg.includes('removed'), 'does not print removed');
    t.false(msg.includes(pboFolder), 'path removed');
    t.ok(msg.includes('lint fail'), 'err msg included');
  });

  stub.child_process.exec = cmd => t.equals(cmd, 'makepbo -W ' + pboFolder + ' bla.pbo', 'exec called with folder');
  lintPboFolder(pboFolder, (e, res) => {
    t.error(e, 'no error');
    t.ok(res.ok, 'was ok');
  });

  t.end();
});
<|endoftext|>


<commit_before>
var http = require("http");

exports.get = function(yql, callback){

	yql = yql.replace(/\s/g, "%20").replace(/\=/g, '%3D');

	var client 	= http.createClient(80, "query.yahooapis.com");
	var url 	= "http://query.yahooapis.com/v1/public/yql?q=" + yql + "&format=json";
	var request = client.request("GET", url, {"host": "search.twitter.com", "User-Agent": "NodeJS HTTP Client"});

	request.addListener('response', function (response) {

		var responseBody = '';

		response.addListener("data", function (chunk) {
			responseBody += chunk;
		});

		response.addListener("end", function () {
			callback(JSON.parse(responseBody));
		});

	});

	request.close();

}<commit_msg>Commentary, host value update<commit_after>
var http = require("http");

exports.get = function(yql, callback){

	// Some pretty basic encoding.  Will need more testing
	yql = yql.replace(/\s/g, "%20").replace(/\=/g, '%3D');

	var client 	= http.createClient(80, "query.yahooapis.com");
	var url 	= "http://query.yahooapis.com/v1/public/yql?q=" + yql + "&format=json";
	var request = client.request("GET", url, {"host": "query.yahooapis.com", "User-Agent": "NodeJS HTTP Client"});

	request.addListener('response', function (response) {

		var responseBody = '';

		response.addListener("data", function (chunk) {
			responseBody += chunk;
		});

		response.addListener("end", function () {
			callback(JSON.parse(responseBody));
		});

	});

	request.close();

}<|endoftext|>


<commit_before>/**
 * Sets the cookie for contests page (GRID/LIST)
 *
 * @param viewType type of the view (GRID/LIST)
 */
function setContestsViewTypeCookie(viewType) {
	jQuery.cookie("cc_contests_viewType", null, {expires: -1});
	jQuery.cookie("cc_contests_viewType", viewType, {expires: 365, path: '/'});
}

/**
 *
 *
 */
function filterContests() {
	jQuery("#filterContestsForm").submit();
}

jQuery(function() {
    //Try to initialize client-side code first time
    initializeJavaScript();
    //Try to initiliaze after timeout since portlet doesn't sometimes load
    setTimeout(function(){
        initializeJavaScript();
    }, 10000);
});

function initializeJavaScript(){
    initTooltips();
    initializeTextEditors();
    evaluateTime();
    jQuery(".addpropform .helpTrigger").click(function() {
        var trigger = jQuery(this);
        trigger.parent().parent().find(".addprophelp").slideToggle("fast");
    });

    jQuery("#contestFilterInput").change(filterContests).keypress(function (e) {
        if (e.keyCode == 13) {
            filterContests();
            return false;
        }
    });
    jQuery("#contestsFilterClear").click(function() {
        jQuery("#contestFilterInput").val("");
        jQuery("#filterContestsForm").submit();
    });
}

function evaluateTime() {
    $(".dateInfo").each(function() {
        var adjustedDate = new Date(Date.parse($(this).html()));
        //add +1 to month since the enumeration starts with 0
        $(this).html((adjustedDate.getMonth()+1)+"/"+adjustedDate.getDate()+"/"+adjustedDate.getFullYear()+" UTC"+(adjustedDate.getTimezoneOffset()/(-60)));
        $(this).removeClass("dateInfo");
    });
}

/**
 * Counts characters
 * @param input
 * @param editor
 * @returns
 */
function countCharacters(input, editor) {
    if (editor) {
    	if (editor == null || editor.document == null) return 0;
        if (editor.document['$'].body.textContent) {
            return jQuery.trim(editor.document['$'].body.textContent).length;

        }
        if (editor.document['$'].body.innerText) {
            return jQuery.trim(editor.document['$'].body.innerText).length;
        }
    }
    return jQuery.trim(input.val().replace(/<[^>]*>/g, "").replace(/\s+/g, " ").length);

}

/**
 * Returns true if input is allowed to contain more characters
 * @param input
 * @returns
 */
function shouldAllowMoreCharacters(input) {
    if (typeof(input.attr('validateLength')) == 'undefined' ||
    		typeof(input.attr('maxCharacters')) == 'undefined' ||
    		input.attr('maxCharacters') + 0 <= 0) {
        return true;
    }
    return input.attr('maxCharacters') > input.val().length;
}

/**
 * Updates character counter for given input
 * @param input
 * @param editor
 * @returns
 */
function updateCharacterCounter(input, editor) {
	var parent = input.parents('.addpropbox');
    var elem = input.get(0);
    var max = input.attr('maxCharacters');
    if (elem && elem.limitCharacterCounter) {
        var count = countCharacters(input, editor);
        if (count > 1 * max) {
            elem.limitCharacterCounter.parent().addClass('overflow');
            input.addClass('invalid');
        }
        else {
            elem.limitCharacterCounter.parent().removeClass('overflow');
            input.removeClass('invalid');
        }
        elem.limitCharacterCounter.text(count);
        if (count > 0) {
        	parent.removeClass('empty').addClass('notempty');
        }
        else {
        	parent.removeClass('notempty').addClass('empty');
        }
    }
}

function markEditorDirty(editor) {
	editor.addClass('editorDirty');
}

function initializeTextEditors() {
	jQuery("input[type='text'], textarea").each(function() {
		if (jQuery(this).hasClass('rteInitialized') || jQuery(this).parent().parent().attr('class') == "login_popup_box") {
			return;
		}

		var tmp = this;
		var thiz = jQuery(this);

		var limitCharactersMax = thiz.parent().find(".limit_charactersMax");
		var limitCharacterCount = thiz.parent().find(".limit_characterCount");

		if (limitCharactersMax.length > 0) {
			thiz.attr({maxCharacters: limitCharactersMax.text(), validateLength: true});
			this.limitCharacterCounter = limitCharacterCount;
			updateCharacterCounter(thiz);
		}
		else {
			thiz.attr({validateLength: false});
		}

		if (thiz.hasClass("rte")) {

			var editor = CKEDITOR.replace(thiz.attr("id"));

			thiz.get(0)["ckeditor"] = editor;
			editor.updatedCharCount = false;

			function updateEditorCharCount() {
				try{
					if (editor == null) return;

					if (editor &&  editor.document && editor.document['$'] && (editor.checkDirty() || editor.updatedCharCount)) {
						markEditorDirty(thiz);
						updateCharacterCounter(thiz, editor);
						editor.updatedCharCount = true;
						editor.resetDirty();
					}

					setTimeout(updateEditorCharCount, 1000);
				} catch (e) {
					if (typeof(console) != 'undefined' && typeof(console.log) != 'undefined') {
						console.log(e);
					}
				}
			}
			if (! jQuery.browser.ie || jQuery.browser.version.number >= 9) {
				updateEditorCharCount();
			}

			editor.on("blur", function() {
				updateCharacterCounter(thiz, editor);
			});

			// initiate char counters
			setTimeout(function() { updateCharacterCounter(thiz, editor); }, 2000);
        }
		else {
			eventsToBind = {
					keypress: function(event) {
	                    if (thiz.attr('validateLength') && tmp.limitCharacterCounter) {
	                        updateCharacterCounter(thiz);
	                    }
	                },
	                keyup: function(event) {
	                    if (thiz.attr('validateLength') && tmp.limitCharacterCounter) {
	                        updateCharacterCounter(thiz);
	                    }
	                },
	                change: function(event) {
	                	markEditorDirty(thiz);
	                }
	        };
			thiz.bind(eventsToBind);
		}
		jQuery(this).addClass('rteInitialized');
	});

};

function validatePlanEditForm() {
    for (var ckInstanceId in CKEDITOR.instances) {
        if (document.getElementById(ckInstanceId)) {
        	var ckInstance = CKEDITOR.instances[ckInstanceId];
            ckInstance.element['$'].value = ckInstance.getData();
        }
    }
    var invalidFieldsList = jQuery("#invalidFieldsList");
    invalidFieldsList.html("");

    var isValid = true;
    jQuery("input[type='text'].invalid, textarea.invalid").each(function() {
        var x = jQuery(this).parents(".addpropbox");
        invalidFieldsList.append("
" + jQuery(this).parents(".addpropbox").find("strong").text() + "
");

        isValid = false;
    });
    if (!isValid) {
        jQuery("#invalidFieldsPopupContainer").show();
    }
    for (var ckInstanceId in CKEDITOR.instances) {
        if (document.getElementById(ckInstanceId)) {
        	// remove all instances
        	//ckInstance.destroy();
        }
    }
    //delete CKEDITOR;

    return isValid;
};

function enableDirtyCheck() {
	window.oldOnBeforeUnload = window.onbeforeunload;

	window.onbeforeunload = function() {
        var dirtyEditors = $(".editorDirty").filter(function(index){
            return !($(this).attr("name") === "login");
        });
        console.log(dirtyEditors);
		if (dirtyEditors.length > 0) {
			return 'You have modified this page but have not saved your changes.';
		}
		return null;
	};
}

function disableDirtyCheck() {
	if ('oldOnBeforeUnload' in window) {
		window.onbeforeunload = window.oldOnBeforeUnload;
	}
	delete window.onbeforeunload;
}

/* Request membership form logic */
function clearContents(element) {
    element.value = '';
};

function requestMembership() {
    $('#requestComment').slideDown('slow');
    $('.prop-butt-popover:first').css('background', 'url(/climatecolab-theme/images/search-bg.png)');
    $('#requestButtons').empty();
    $('#requestButtons').append('
Cancel
');
    $('#requestButtons').append('
Send
');
}
function hideRequestForm(animate) {
    var speed = animate ? 600 : 1;
    $('#requestComment').slideUp('slow', function () {
        $('.prop-butt-popover:first').css('background', 'none');
        $('#requestButtons').empty();
        $('#requestButtons').append('
Request membership
');
    });
}
/* End of request membership form logic */

/* Membership invite logic */
function inviteMember() {
    $('#invite-comment').slideDown('slow');
    $('#invite-recipient').slideDown('slow');
    $('.prop-butt-popover:first').css('background', 'url(/climatecolab-theme/images/search-bg.png)');
    $('#requestButtons').empty();
    $('#requestButtons').append('
Cancel
');
    $('#requestButtons').append('
Send
');
}

function hideInviteForm(animate) {
    var speed = animate ? 600 : 1;
    $('#invite-comment').slideUp('slow', function () {
        $('.prop-butt-popover:first').css('background', 'none');
        $('#requestButtons').empty();
        $('#requestButtons').append('
Invite team member
');
    });
    $('#invite-recipient').slideUp('slow');

function validateRecipients() {
    var input = $("#recipient-input").val();
    var list = split(input);
    console.log("list: " + list);

    $.each(list, function(k, v) {
        console.log("item " + v);
    });
    var json = new Object();
    json.params = list;
    console.log("json: " + JSON.stringify(json));

    $.ajax
    ({
        type: "POST",
        //the url where you want to sent the userName and password to
        url: validationURL,
        dataType: 'json',
        async: false,
        //json object to sent to the authentication url
        data: {screenNames : list},
        success: function (data) {
            if (data.success) {
                $('#send-button').removeAttr('disabled');

            } else {
                var error = "";
                var list = data.message;
                if (list.length > 0) {
                    error += "The following recipients could not be resolved:<ul>";

                    $.each(list, function(k, v) {
                        error += "<li>" + v + "</li>";
                    });

                    error += "<ul>";
                }

                $('.recipient-error').html(error);
                console.log(error);
                $('#send-button').attr('disabled', 'disabled');
            }
        }
    });
}}

// jQuery autocomplete
$(function() {
    var cache = {};
    $( "#invite-recipient" ).autocomplete({
        minLength: 3,
        source: function( request, response ) {
            var term = request.term;
            if ( term in cache ) {
                response( cache[ term ] );
                return;
            }

            $.getJSON( $('#invite-member-validation-url').text(), request, function( data, status, xhr ) {
                cache[ term ] = data;
                response( data );
            });
        }
    });
    $( "#invite-recipient" ).bind("autocompleteselect", "select", function(event) {

    });

    $("#invite-recipient").focusout(function(event) {
        validateRecipients();
    });
});

function setModelSetRadiosState(enabled) {
    var modelSetRadios = document.getElementsByName("modelSet");
    var len = modelSetRadios.length;
    for (var i = 0; i < len; i++) {
        modelSetRadios[i].disabled = enabled;
    }
}

function checkModelSetRadioWithId(id) {
    var modelSetRadios = document.getElementsByName("modelSet");
    var len = modelSetRadios.length;
    for (var i = 0; i < len; i++) {
        if (modelSetRadios[i].id == id) {
            modelSetRadios[i].checked = true;
        }
        else {
            modelSetRadios[i].checked = false;
        }
    }
}

var selectModelForFetchedScenario = function(event){
    checkModelSetRadioWithId(event.scenario.modelId);
};
<commit_msg>changed timeformat in contest-phases to local  standard timezone<commit_after>/**
 * Sets the cookie for contests page (GRID/LIST)
 *
 * @param viewType type of the view (GRID/LIST)
 */
function setContestsViewTypeCookie(viewType) {
	jQuery.cookie("cc_contests_viewType", null, {expires: -1});
	jQuery.cookie("cc_contests_viewType", viewType, {expires: 365, path: '/'});
}

/**
 *
 *
 */
function filterContests() {
	jQuery("#filterContestsForm").submit();
}

jQuery(function() {
    //Try to initialize client-side code first time
    initializeJavaScript();
    //Try to initiliaze after timeout since portlet doesn't sometimes load
    setTimeout(function(){
        initializeJavaScript();
    }, 10000);
});

function initializeJavaScript(){
    initTooltips();
    initializeTextEditors();
    evaluateTime();
    jQuery(".addpropform .helpTrigger").click(function() {
        var trigger = jQuery(this);
        trigger.parent().parent().find(".addprophelp").slideToggle("fast");
    });

    jQuery("#contestFilterInput").change(filterContests).keypress(function (e) {
        if (e.keyCode == 13) {
            filterContests();
            return false;
        }
    });
    jQuery("#contestsFilterClear").click(function() {
        jQuery("#contestFilterInput").val("");
        jQuery("#filterContestsForm").submit();
    });
}

function evaluateTime() {
    $(".dateInfo").each(function() {
        var adjustedDate = new Date(Date.parse($(this).html()));
        var timeZoneIdentifier = String(String(new Date).split("(")[1]).split(")")[0];  //get the timezone abbreviation
        //add +1 to month since the enumeration starts with 0
        $(this).html((adjustedDate.getMonth()+1)+"/"+adjustedDate.getDate()+"/"+adjustedDate.getFullYear()+" "+timeZoneIdentifier);
        $(this).removeClass("dateInfo");
    });
}

/**
 * Counts characters
 * @param input
 * @param editor
 * @returns
 */
function countCharacters(input, editor) {
    if (editor) {
    	if (editor == null || editor.document == null) return 0;
        if (editor.document['$'].body.textContent) {
            return jQuery.trim(editor.document['$'].body.textContent).length;

        }
        if (editor.document['$'].body.innerText) {
            return jQuery.trim(editor.document['$'].body.innerText).length;
        }
    }
    return jQuery.trim(input.val().replace(/<[^>]*>/g, "").replace(/\s+/g, " ").length);

}

/**
 * Returns true if input is allowed to contain more characters
 * @param input
 * @returns
 */
function shouldAllowMoreCharacters(input) {
    if (typeof(input.attr('validateLength')) == 'undefined' ||
    		typeof(input.attr('maxCharacters')) == 'undefined' ||
    		input.attr('maxCharacters') + 0 <= 0) {
        return true;
    }
    return input.attr('maxCharacters') > input.val().length;
}

/**
 * Updates character counter for given input
 * @param input
 * @param editor
 * @returns
 */
function updateCharacterCounter(input, editor) {
	var parent = input.parents('.addpropbox');
    var elem = input.get(0);
    var max = input.attr('maxCharacters');
    if (elem && elem.limitCharacterCounter) {
        var count = countCharacters(input, editor);
        if (count > 1 * max) {
            elem.limitCharacterCounter.parent().addClass('overflow');
            input.addClass('invalid');
        }
        else {
            elem.limitCharacterCounter.parent().removeClass('overflow');
            input.removeClass('invalid');
        }
        elem.limitCharacterCounter.text(count);
        if (count > 0) {
        	parent.removeClass('empty').addClass('notempty');
        }
        else {
        	parent.removeClass('notempty').addClass('empty');
        }
    }
}

function markEditorDirty(editor) {
	editor.addClass('editorDirty');
}

function initializeTextEditors() {
	jQuery("input[type='text'], textarea").each(function() {
		if (jQuery(this).hasClass('rteInitialized') || jQuery(this).parent().parent().attr('class') == "login_popup_box") {
			return;
		}

		var tmp = this;
		var thiz = jQuery(this);

		var limitCharactersMax = thiz.parent().find(".limit_charactersMax");
		var limitCharacterCount = thiz.parent().find(".limit_characterCount");

		if (limitCharactersMax.length > 0) {
			thiz.attr({maxCharacters: limitCharactersMax.text(), validateLength: true});
			this.limitCharacterCounter = limitCharacterCount;
			updateCharacterCounter(thiz);
		}
		else {
			thiz.attr({validateLength: false});
		}

		if (thiz.hasClass("rte")) {

			var editor = CKEDITOR.replace(thiz.attr("id"));

			thiz.get(0)["ckeditor"] = editor;
			editor.updatedCharCount = false;

			function updateEditorCharCount() {
				try{
					if (editor == null) return;

					if (editor &&  editor.document && editor.document['$'] && (editor.checkDirty() || editor.updatedCharCount)) {
						markEditorDirty(thiz);
						updateCharacterCounter(thiz, editor);
						editor.updatedCharCount = true;
						editor.resetDirty();
					}

					setTimeout(updateEditorCharCount, 1000);
				} catch (e) {
					if (typeof(console) != 'undefined' && typeof(console.log) != 'undefined') {
						console.log(e);
					}
				}
			}
			if (! jQuery.browser.ie || jQuery.browser.version.number >= 9) {
				updateEditorCharCount();
			}

			editor.on("blur", function() {
				updateCharacterCounter(thiz, editor);
			});

			// initiate char counters
			setTimeout(function() { updateCharacterCounter(thiz, editor); }, 2000);
        }
		else {
			eventsToBind = {
					keypress: function(event) {
	                    if (thiz.attr('validateLength') && tmp.limitCharacterCounter) {
	                        updateCharacterCounter(thiz);
	                    }
	                },
	                keyup: function(event) {
	                    if (thiz.attr('validateLength') && tmp.limitCharacterCounter) {
	                        updateCharacterCounter(thiz);
	                    }
	                },
	                change: function(event) {
	                	markEditorDirty(thiz);
	                }
	        };
			thiz.bind(eventsToBind);
		}
		jQuery(this).addClass('rteInitialized');
	});

};

function validatePlanEditForm() {
    for (var ckInstanceId in CKEDITOR.instances) {
        if (document.getElementById(ckInstanceId)) {
        	var ckInstance = CKEDITOR.instances[ckInstanceId];
            ckInstance.element['$'].value = ckInstance.getData();
        }
    }
    var invalidFieldsList = jQuery("#invalidFieldsList");
    invalidFieldsList.html("");

    var isValid = true;
    jQuery("input[type='text'].invalid, textarea.invalid").each(function() {
        var x = jQuery(this).parents(".addpropbox");
        invalidFieldsList.append("
" + jQuery(this).parents(".addpropbox").find("strong").text() + "
");

        isValid = false;
    });
    if (!isValid) {
        jQuery("#invalidFieldsPopupContainer").show();
    }
    for (var ckInstanceId in CKEDITOR.instances) {
        if (document.getElementById(ckInstanceId)) {
        	// remove all instances
        	//ckInstance.destroy();
        }
    }
    //delete CKEDITOR;

    return isValid;
};

function enableDirtyCheck() {
	window.oldOnBeforeUnload = window.onbeforeunload;

	window.onbeforeunload = function() {
        var dirtyEditors = $(".editorDirty").filter(function(index){
            return !($(this).attr("name") === "login");
        });
        console.log(dirtyEditors);
		if (dirtyEditors.length > 0) {
			return 'You have modified this page but have not saved your changes.';
		}
		return null;
	};
}

function disableDirtyCheck() {
	if ('oldOnBeforeUnload' in window) {
		window.onbeforeunload = window.oldOnBeforeUnload;
	}
	delete window.onbeforeunload;
}

/* Request membership form logic */
function clearContents(element) {
    element.value = '';
};

function requestMembership() {
    $('#requestComment').slideDown('slow');
    $('.prop-butt-popover:first').css('background', 'url(/climatecolab-theme/images/search-bg.png)');
    $('#requestButtons').empty();
    $('#requestButtons').append('
Cancel
');
    $('#requestButtons').append('
Send
');
}
function hideRequestForm(animate) {
    var speed = animate ? 600 : 1;
    $('#requestComment').slideUp('slow', function () {
        $('.prop-butt-popover:first').css('background', 'none');
        $('#requestButtons').empty();
        $('#requestButtons').append('
Request membership
');
    });
}
/* End of request membership form logic */

/* Membership invite logic */
function inviteMember() {
    $('#invite-comment').slideDown('slow');
    $('#invite-recipient').slideDown('slow');
    $('.prop-butt-popover:first').css('background', 'url(/climatecolab-theme/images/search-bg.png)');
    $('#requestButtons').empty();
    $('#requestButtons').append('
Cancel
');
    $('#requestButtons').append('
Send
');
}

function hideInviteForm(animate) {
    var speed = animate ? 600 : 1;
    $('#invite-comment').slideUp('slow', function () {
        $('.prop-butt-popover:first').css('background', 'none');
        $('#requestButtons').empty();
        $('#requestButtons').append('
Invite team member
');
    });
    $('#invite-recipient').slideUp('slow');

function validateRecipients() {
    var input = $("#recipient-input").val();
    var list = split(input);
    console.log("list: " + list);

    $.each(list, function(k, v) {
        console.log("item " + v);
    });
    var json = new Object();
    json.params = list;
    console.log("json: " + JSON.stringify(json));

    $.ajax
    ({
        type: "POST",
        //the url where you want to sent the userName and password to
        url: validationURL,
        dataType: 'json',
        async: false,
        //json object to sent to the authentication url
        data: {screenNames : list},
        success: function (data) {
            if (data.success) {
                $('#send-button').removeAttr('disabled');

            } else {
                var error = "";
                var list = data.message;
                if (list.length > 0) {
                    error += "The following recipients could not be resolved:<ul>";

                    $.each(list, function(k, v) {
                        error += "<li>" + v + "</li>";
                    });

                    error += "<ul>";
                }

                $('.recipient-error').html(error);
                console.log(error);
                $('#send-button').attr('disabled', 'disabled');
            }
        }
    });
}}

// jQuery autocomplete
$(function() {
    var cache = {};
    $( "#invite-recipient" ).autocomplete({
        minLength: 3,
        source: function( request, response ) {
            var term = request.term;
            if ( term in cache ) {
                response( cache[ term ] );
                return;
            }

            $.getJSON( $('#invite-member-validation-url').text(), request, function( data, status, xhr ) {
                cache[ term ] = data;
                response( data );
            });
        }
    });
    $( "#invite-recipient" ).bind("autocompleteselect", "select", function(event) {

    });

    $("#invite-recipient").focusout(function(event) {
        validateRecipients();
    });
});

function setModelSetRadiosState(enabled) {
    var modelSetRadios = document.getElementsByName("modelSet");
    var len = modelSetRadios.length;
    for (var i = 0; i < len; i++) {
        modelSetRadios[i].disabled = enabled;
    }
}

function checkModelSetRadioWithId(id) {
    var modelSetRadios = document.getElementsByName("modelSet");
    var len = modelSetRadios.length;
    for (var i = 0; i < len; i++) {
        if (modelSetRadios[i].id == id) {
            modelSetRadios[i].checked = true;
        }
        else {
            modelSetRadios[i].checked = false;
        }
    }
}

var selectModelForFetchedScenario = function(event){
    checkModelSetRadioWithId(event.scenario.modelId);
};
<|endoftext|>


<commit_before>const assert = require('assert');
const http = require('http');
const https = require('https');
const url = require('url');

const withV4 = require('../support/withV4');
const BucketUtility = require('../../lib/utility/bucket-util');
const conf = require('../../../../../lib/Config').config;
const jsutil = require('arsenal').jsutil;

const transport = conf.https ? https : http;
const ipAddress = process.env.IP ? process.env.IP : '127.0.0.1';
const hostname = process.env.AWS_ON_AIR ? 's3.amazonaws.com' : ipAddress;
const port = process.env.AWS_ON_AIR ? 80 : 8000;
const bucket = 'foo-bucket';
const key = 'foo-key';
const body = Buffer.alloc(1024 * 1024);

class ContinueRequestHandler {
    constructor(path) {
        this.path = path;
        return this;
    }

    setRequestPath(path) {
        this.path = path;
        return this;
    }

    setExpectHeader(header) {
        this.expectHeader = header;
        return this;
    }

    getRequestOptions() {
        return {
            path: this.path,
            hostname,
            port,
            method: 'PUT',
            headers: {
                'content-length': body.length,
                'Expect': this.expectHeader || '100-continue',
            },
        };
    }

    hasStatusCode(statusCode, cb) {
        const options = this.getRequestOptions();
        process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
        const req = transport.request(options, res => {
            assert.strictEqual(res.statusCode, statusCode);
            return cb();
        });
        // Send the body either on the continue event, or immediately.
        if (this.expectHeader === '100-continue') {
            req.on('continue', () => req.end(body));
        } else {
            req.end(body);
        }
    }

    sendsBodyOnContinue(cb) {
        const cbOnce = jsutil.once(cb);
        const options = this.getRequestOptions();
        process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
        const req = transport.request(options);
        // At this point we have only sent the header.
        assert(req.output.length === 1);
        const headerLen = req.output[0].length;
        req.on('continue', () => {
            // Has only the header been sent?
            assert.strictEqual(req.socket.bytesWritten, headerLen);
            // Send the body since the continue event has been emitted.
            return req.end(body);
        });
        req.on('close', () => {
            const expected = body.length + headerLen;
            // Has the entire body been sent?
            assert.strictEqual(req.socket.bytesWritten, expected);
            return cbOnce();
        });
        req.on('error', err => cbOnce(err));
    }
}

describe('PUT public object with 100-continue header', () => {
    withV4(sigCfg => {
        let bucketUtil;
        let s3;
        let continueRequest;
        const invalidSignedURL = `/${bucket}/${key}`;

        beforeEach(() => {
            bucketUtil = new BucketUtility('default', sigCfg);
            s3 = bucketUtil.s3;
            const params = {
                Bucket: bucket,
                Key: key,
            };
            const signedUrl = s3.getSignedUrl('putObject', params);
            const { path } = url.parse(signedUrl);
            continueRequest = new ContinueRequestHandler(path);
            return s3.createBucketAsync({ Bucket: bucket });
        });

        afterEach(() =>
            bucketUtil.empty(bucket)
            .then(() => bucketUtil.deleteOne(bucket)));

        it('should return 200 status code', done =>
            continueRequest.hasStatusCode(200, done));

        it('should return 200 status code with upper case value', done =>
            continueRequest.setExpectHeader('100-CONTINUE')
                .hasStatusCode(200, done));

        it('should return 200 status code if incorrect value', done =>
            continueRequest.setExpectHeader('101-continue')
                .hasStatusCode(200, done));

        it('should return 403 status code if cannot authenticate', done =>
            continueRequest.setRequestPath(invalidSignedURL)
                .hasStatusCode(403, done));

        it('should wait for continue event before sending body', done =>
            continueRequest.sendsBodyOnContinue(done));

        it('should continue if a public user', done =>
            continueRequest.setRequestPath(invalidSignedURL)
                .sendsBodyOnContinue(done));
    });
});
<commit_msg>added retuen in cb<commit_after>const assert = require('assert');
const http = require('http');
const https = require('https');
const url = require('url');

const withV4 = require('../support/withV4');
const BucketUtility = require('../../lib/utility/bucket-util');
const conf = require('../../../../../lib/Config').config;
const jsutil = require('arsenal').jsutil;

const transport = conf.https ? https : http;
const ipAddress = process.env.IP ? process.env.IP : '127.0.0.1';
const hostname = process.env.AWS_ON_AIR ? 's3.amazonaws.com' : ipAddress;
const port = process.env.AWS_ON_AIR ? 80 : 8000;
const bucket = 'foo-bucket';
const key = 'foo-key';
const body = Buffer.alloc(1024 * 1024);

class ContinueRequestHandler {
    constructor(path) {
        this.path = path;
        return this;
    }

    setRequestPath(path) {
        this.path = path;
        return this;
    }

    setExpectHeader(header) {
        this.expectHeader = header;
        return this;
    }

    getRequestOptions() {
        return {
            path: this.path,
            hostname,
            port,
            method: 'PUT',
            headers: {
                'content-length': body.length,
                'Expect': this.expectHeader || '100-continue',
            },
        };
    }

    hasStatusCode(statusCode, cb) {
        const options = this.getRequestOptions();
        process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
        const req = transport.request(options, res => {
            assert.strictEqual(res.statusCode, statusCode);
            return cb();
        });
        // Send the body either on the continue event, or immediately.
        if (this.expectHeader === '100-continue') {
            req.on('continue', () => req.end(body));
        } else {
            req.end(body);
        }
    }

    sendsBodyOnContinue(cb) {
        const cbOnce = jsutil.once(cb);
        const options = this.getRequestOptions();
        process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
        const req = transport.request(options);
        // At this point we have only sent the header.
        assert(req.output.length === 1);
        const headerLen = req.output[0].length;
        req.on('continue', () => {
            // Has only the header been sent?
            assert.strictEqual(req.socket.bytesWritten, headerLen);
            // Send the body since the continue event has been emitted.
            return req.end(body);
        });
        req.on('close', () => {
            const expected = body.length + headerLen;
            // Has the entire body been sent?
            assert.strictEqual(req.socket.bytesWritten, expected);
            return cbOnce();
        });
        req.on('error', err => {
            return cbOnce(err)
        });
    }
}

describe('PUT public object with 100-continue header', () => {
    withV4(sigCfg => {
        let bucketUtil;
        let s3;
        let continueRequest;
        const invalidSignedURL = `/${bucket}/${key}`;

        beforeEach(() => {
            bucketUtil = new BucketUtility('default', sigCfg);
            s3 = bucketUtil.s3;
            const params = {
                Bucket: bucket,
                Key: key,
            };
            const signedUrl = s3.getSignedUrl('putObject', params);
            const { path } = url.parse(signedUrl);
            continueRequest = new ContinueRequestHandler(path);
            return s3.createBucketAsync({ Bucket: bucket });
        });

        afterEach(() =>
            bucketUtil.empty(bucket)
            .then(() => bucketUtil.deleteOne(bucket)));

        it('should return 200 status code', done =>
            continueRequest.hasStatusCode(200, done));

        it('should return 200 status code with upper case value', done =>
            continueRequest.setExpectHeader('100-CONTINUE')
                .hasStatusCode(200, done));

        it('should return 200 status code if incorrect value', done =>
            continueRequest.setExpectHeader('101-continue')
                .hasStatusCode(200, done));

        it('should return 403 status code if cannot authenticate', done =>
            continueRequest.setRequestPath(invalidSignedURL)
                .hasStatusCode(403, done));

        it('should wait for continue event before sending body', done =>
            continueRequest.sendsBodyOnContinue(done));

        it.only('should continue if a public user', done =>
            continueRequest.setRequestPath(invalidSignedURL)
                .sendsBodyOnContinue(done));
    });
});
<|endoftext|>


<commit_before>var animals = [{
    name: "Mooney",
    common_name: "Blue monkey",
    species: "Cercopithecus mitis",
    location: "Smith Jungle",
    age: 2,
    image: "Blue_monkey.jpg"
}, {
    name: "Sami",
    common_name: "Common squirrel monkey",
    species: "Saimiri scirureus",
    location: "Smith Jungle",
    age: 2,
    image: "Common_squirrel_monkey.jpg"
}, {
    name: "Chester",
    common_name: "Black howler monkey",
    species: "Alouatta caraya",
    location: "Smith Jungle",
    age: 5,
    image: "Black_howler_monkey.jpg"
}, {
    name: "Scarborough",
    common_name: "Scarlet macaw",
    species: "Ara macao",
    location: "Smith Jungle",
    age: 3,
    image: "Scarlet_macaw.jpg"
}, {
    name: "Maverick",
    common_name: "Tufted puffin",
    species: "Fratercula cirrhata",
    location: "Birai Aquarium",
    age: 2,
    image: "Tufted_puffin.jpg"
}, {
    name: "Puck",
    common_name: "Little penguin",
    species: "Eudyptula minor",
    location: "Birai Aquarium",
    age: 4,
    image: "Little_penguin.jpg"
}, {
    name: "Tweed",
    common_name: "Leafy sea dragon",
    species: "Phycodurus eques",
    location: "Birai Aquarium",
    age: 1,
    image: "Leafy_seadragon.jpg"
}, {
    name: "Taylor",
    common_name: "Swift fox",
    species: "Vulpes velox",
    location: "Rodeheaver Desert",
    age: 9,
    image: "Swift_fox.jpg"
}, {
    name: "Trip",
    common_name: "Cap thick-knee",
    species: "Burhinus capensus",
    location: "Rodeheaver Desert",
    age: 5,
    image: "Cape_thick-knee.jpg"
}, {
    name: "Helios",
    common_name: "Mantled guereza",
    species: "Colobus guereza",
    location: "Fagan Valley",
    age: 11,
    image: "Mantled_guereza.jpg"
}, {
    name: "Asteria",
    common_name: "Western lowland gorilla",
    species: "Gorilla gorilla gorilla",
    location: "Fagain Valley",
    age: 5,
    image: "Western_lowland_gorilla.jpg"
}, {
    name: "Perses",
    common_name: "Wolf's mona monkey",
    species: "Cercopithecus wolfi",
    location: "Fagan Valley",
    age: 10,
    image: "Wolfs_mana_monkey.jpg"
}, {
    name: "Pip",
    common_name: "Red river hog",
    species: "Potamochoerus porcus",
    location: "Fagan Valley",
    age: 4,
    image: "Red_river_hog.jpg"
}, {
    name: "Skrytnaya",
    common_name: "Amur leopard",
    species: "Panthera pardus orientalis",
    location: "Kond Cat Complex",
    age: 8,
    image: "Amur_leopard.jpg"
}, {
    name: "Matadi",
    common_name: "African lion",
    species: "Panthera leo",
    location: "Kond Cat Complex",
    age: 6,
    image: "African_lion.jpg"
}, {
    name: "Kimani",
    common_name: "Siberian tiger",
    species: "Panthera tigris altaica",
    location: "Kond Cat Complex",
    age: 2,
    image: ".jpg"
}, {
    name: "Antipode",
    common_name: "Polar bear",
    species: "Ursus maritimus",
    location: "Moser Canyon",
    age: 11,
    image: "Polar_bear.jpg"
}];

displayAnimalGallery(animals.sort(
    function(a, b) {
        var A = a.name.toLowerCase();
        var B = b.name.toLowerCase();
        if (A < B) {
            return -1;
        }
        else if (A > B) {
            return 1;
        }
        else {
            return 0;
        }
    }));

var featured = animals.filter(function(value) {
    if (value.name === "Taylor")
        return 1;
    else
        return 0;
})

displayFeaturedAnimal(featured[0]);

var ages = animals.map(function(value) {
    return {
        name: value.name,
        common_name: value.common_name,
        age: value.age
    };
})

displayAnimalAges(ages.sort(function(a, b) {
    return a.age - b.age;
}))
<commit_msg>fixed links to images<commit_after>var animals = [{
    name: "Mooney",
    common_name: "Blue monkey",
    species: "Cercopithecus mitis",
    location: "Smith Jungle",
    age: 2,
    image: "Blue_monkey.jpg"
}, {
    name: "Sami",
    common_name: "Common squirrel monkey",
    species: "Saimiri scirureus",
    location: "Smith Jungle",
    age: 2,
    image: "Common_squirrel_monkey.jpg"
}, {
    name: "Chester",
    common_name: "Black howler monkey",
    species: "Alouatta caraya",
    location: "Smith Jungle",
    age: 5,
    image: "Black_howler_monkey.jpg"
}, {
    name: "Scarborough",
    common_name: "Scarlet macaw",
    species: "Ara macao",
    location: "Smith Jungle",
    age: 3,
    image: "Scarlet_macaw.jpg"
}, {
    name: "Maverick",
    common_name: "Tufted puffin",
    species: "Fratercula cirrhata",
    location: "Birai Aquarium",
    age: 2,
    image: "Tufted_puffin.jpg"
}, {
    name: "Puck",
    common_name: "Little penguin",
    species: "Eudyptula minor",
    location: "Birai Aquarium",
    age: 4,
    image: "Little_penguin.jpg"
}, {
    name: "Tweed",
    common_name: "Leafy sea dragon",
    species: "Phycodurus eques",
    location: "Birai Aquarium",
    age: 1,
    image: "Leafy_seadragon.jpg"
}, {
    name: "Taylor",
    common_name: "Swift fox",
    species: "Vulpes velox",
    location: "Rodeheaver Desert",
    age: 9,
    image: "Swift_fox.jpg"
}, {
    name: "Trip",
    common_name: "Cap thick-knee",
    species: "Burhinus capensus",
    location: "Rodeheaver Desert",
    age: 5,
    image: "Cape_thick-knee.jpg"
}, {
    name: "Helios",
    common_name: "Mantled guereza",
    species: "Colobus guereza",
    location: "Fagan Valley",
    age: 11,
    image: "Mantled_guereza.jpg"
}, {
    name: "Asteria",
    common_name: "Western lowland gorilla",
    species: "Gorilla gorilla gorilla",
    location: "Fagain Valley",
    age: 5,
    image: "Western_lowland_gorilla.jpg"
}, {
    name: "Perses",
    common_name: "Wolf's mona monkey",
    species: "Cercopithecus wolfi",
    location: "Fagan Valley",
    age: 10,
    image: "Wolfs_mona_monkey.jpg"
}, {
    name: "Pip",
    common_name: "Red river hog",
    species: "Potamochoerus porcus",
    location: "Fagan Valley",
    age: 4,
    image: "Red_river_hog.jpg"
}, {
    name: "Skrytnaya",
    common_name: "Amur leopard",
    species: "Panthera pardus orientalis",
    location: "Kond Cat Complex",
    age: 8,
    image: "Amur_leopard.jpg"
}, {
    name: "Matadi",
    common_name: "African lion",
    species: "Panthera leo",
    location: "Kond Cat Complex",
    age: 6,
    image: "African_lion.jpg"
}, {
    name: "Kimani",
    common_name: "Siberian tiger",
    species: "Panthera tigris altaica",
    location: "Kond Cat Complex",
    age: 2,
    image: "Siberian_tiger.jpg"
}, {
    name: "Antipode",
    common_name: "Polar bear",
    species: "Ursus maritimus",
    location: "Moser Canyon",
    age: 11,
    image: "Polar_bear.jpg"
}];

displayAnimalGallery(animals.sort(
    function(a, b) {
        var A = a.name.toLowerCase();
        var B = b.name.toLowerCase();
        if (A < B) {
            return -1;
        }
        else if (A > B) {
            return 1;
        }
        else {
            return 0;
        }
    }));

var featured = animals.filter(function(value) {
    if (value.name === "Taylor")
        return 1;
    else
        return 0;
})

displayFeaturedAnimal(featured[0]);

var ages = animals.map(function(value) {
    return {
        name: value.name,
        common_name: value.common_name,
        age: value.age
    };
})

displayAnimalAges(ages.sort(function(a, b) {
    return a.age - b.age;
}))
<|endoftext|>


<commit_before>/*
 * Copyright 2014 Basho Technologies, Inc.
 *
 * 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.
 */

var RiakConnection = require('../lib/core/riakconnection');
var RpbErrorResp = require('../lib/protobuf/riakprotobuf').getProtoFor('RpbErrorResp');
var responseCode = require('../lib/protobuf/riakprotobuf').getCodeFor('RpbErrorResp');
var assert = require('assert');

describe('RiakConnection', function() {
    describe('#_receiveData', function() {

        var conn = new RiakConnection({ remoteAddress : "172.16.1.8",
                                            remotePort : 8087,
                                            connectionTimeout : 30000
                                          });
        var resp = new RpbErrorResp();
        var msg = new Buffer('some error message');
        resp.setErrmsg(msg);
        resp.setErrcode(5);
        var header = new Buffer(5);
        header.writeUInt8(responseCode, 4);
        var encoded = resp.encode().toBuffer();
        header.writeInt32BE(encoded.length + 1, 0);

        it('should emit responseReceived', function(done) {

            var errTimeout = setTimeout(function () {
                assert(false, 'Event never fired');
                done();
            }, 1000);

            conn.on('responseReceived', function(conn, command, code, decoded) {
                clearTimeout(errTimeout);
                assert(code === responseCode);
                assert(decoded.getErrmsg().toBuffer().toString() === msg.toString());
                assert(true);
                conn.removeAllListeners();
                done();
            });

            conn._receiveData(header);
            conn._receiveData(encoded);

        });

        it('should emit responseReceived twice', function(done) {

            var errTimeout = setTimeout(function () {
                assert(false, 'Event never fired twice');
                done();
            }, 1000);

            var count = 0;
            conn.on('responseReceived', function(conn, command, code, decoded) {
                count++;
                assert(code === responseCode);
                assert(decoded.getErrmsg().toBuffer().toString() === msg.toString());
                if (count === 2) {
                    clearTimeout(errTimeout);
                    assert(true);
                    conn.removeAllListeners();
                    done();
                }
            });

            for (var i = 0; i < 2; i++) {
                conn._receiveData(header);
                conn._receiveData(encoded);
            }
        });

        it('should buffer a partial write', function() {

            conn._receiveData(header);

            assert(conn._buffer.flip().remaining() === 5);

        });

        it('should emit then buffer partial second write', function(done) {

            var errTimeout = setTimeout(function () {
                assert(false, 'Event never fired twice');
                done();
            }, 1000);

            conn.on('responseReceived', function(conn, command, code, decoded) {
                clearTimeout(errTimeout);
                assert(code === responseCode);
                assert(decoded.getErrmsg().toBuffer().toString() === msg.toString());
                assert(conn._buffer.flip().remaining() === 5);
                assert(conn._buffer.offset === 0);
                conn.removeAllListeners();
                done();
            });

            var combined = Buffer.concat([header, encoded, header]);

            conn._receiveData(combined);

        });

    });

});

<commit_msg>clear buffer after partial write tests<commit_after>/*
 * Copyright 2014 Basho Technologies, Inc.
 *
 * 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.
 */

var RiakConnection = require('../lib/core/riakconnection');
var RpbErrorResp = require('../lib/protobuf/riakprotobuf').getProtoFor('RpbErrorResp');
var responseCode = require('../lib/protobuf/riakprotobuf').getCodeFor('RpbErrorResp');
var assert = require('assert');

describe('RiakConnection', function() {
    describe('#_receiveData', function() {

        var conn = new RiakConnection({ remoteAddress : "172.16.1.8",
                                            remotePort : 8087,
                                            connectionTimeout : 30000
                                          });
        var resp = new RpbErrorResp();
        var msg = new Buffer('some error message');
        resp.setErrmsg(msg);
        resp.setErrcode(5);
        var header = new Buffer(5);
        header.writeUInt8(responseCode, 4);
        var encoded = resp.encode().toBuffer();
        header.writeInt32BE(encoded.length + 1, 0);

        it('should emit responseReceived', function(done) {

            var errTimeout = setTimeout(function () {
                assert(false, 'Event never fired');
                done();
            }, 1000);

            conn.on('responseReceived', function(conn, command, code, decoded) {
                clearTimeout(errTimeout);
                assert(code === responseCode);
                assert(decoded.getErrmsg().toBuffer().toString() === msg.toString());
                assert(true);
                conn.removeAllListeners();
                done();
            });

            conn._receiveData(header);
            conn._receiveData(encoded);

        });

        it('should emit responseReceived twice', function(done) {

            var errTimeout = setTimeout(function () {
                assert(false, 'Event never fired twice');
                done();
            }, 1000);

            var count = 0;
            conn.on('responseReceived', function(conn, command, code, decoded) {
                count++;
                assert(code === responseCode);
                assert(decoded.getErrmsg().toBuffer().toString() === msg.toString());
                if (count === 2) {
                    clearTimeout(errTimeout);
                    assert(true);
                    conn.removeAllListeners();
                    done();
                }
            });

            for (var i = 0; i < 2; i++) {
                conn._receiveData(header);
                conn._receiveData(encoded);
            }
        });

        it('should buffer a partial write', function() {

            conn._receiveData(header);

            assert(conn._buffer.flip().remaining() === 5);
            conn._buffer.clear();

        });

        it('should emit then buffer partial second write', function(done) {

            var errTimeout = setTimeout(function () {
                assert(false, 'Event never fired');
                done();
            }, 1000);

            conn.on('responseReceived', function(conn, command, code, decoded) {
                clearTimeout(errTimeout);
                assert(code === responseCode);
                assert(decoded.getErrmsg().toBuffer().toString() === msg.toString());
                assert(conn._buffer.flip().remaining() === 5);
                assert(conn._buffer.offset === 0);
                conn.removeAllListeners();
                conn._buffer.clear();
                done();
            });

            var combined = Buffer.concat([header, encoded, header]);

            conn._receiveData(combined);

        });

    });

});

<|endoftext|>


<commit_before>/// <reference path="../typings/node/node.d.ts"/>
/// <reference path="../typings/mocha/mocha.d.ts"/>
"use strict";

var expect = require('chai').expect;
var fs = require('fs');
var request = require('request');
var _ = require('lodash');

var bbcms = require("../index");

var testoOn = function (infile, outfile, goldfile, done) {
    var istream = fs.createReadStream(infile, 'utf-8');
    istream
        .pipe(new bbcms.C32ParserStream("test"))
        .on('data', function (data) {
            expect(data).to.exist;
            fs.writeFile(outfile, JSON.stringify(data, null, '  '), function (err2) {
                if (err2) {
                    return done(err2);
                }
                fs.readFile(goldfile, function (err, data2) {
                    if (err) {
                        return done(); // Not an error, just skip comparison
                    }
                    try {
                        expect(JSON.parse(data2.toString())).to.be.eql(data);
                        //return done(err);
                        if (_.isEqual(JSON.parse(data2.toString()), data)) {
                            return done(err);
                        } else {
                            return done(new Error("Compare fails"));
                        }
                    } catch (ee) {
                        return done(ee);
                    }
                });
            });
        })
        .on('error', function (error) {
            done(error);
        });
};

describe('C32 parser test', function () {

    it('"VA_CCD_Sample_File_Version_12_5_1.xml" as input', function (done) {

        var request = require('request');
        var data = request.get('https://raw.githubusercontent.com/amida-tech/blue-button/master/test/fixtures/parser-c32/VA_CCD_Sample_File_Version_12_5_1.xml');

        data
            .pipe(new bbcms.C32ParserStream('test'))
            .on('data', function (data) {
                expect(data).to.exist;
                /*fs.writeFile(__dirname + '/artifacts/VA_CCD_Sample_File_Version_12_5_1.json', JSON.stringify(data, null, '  '), function (err2) {
                    done(err2);
                });*/
            })
            .on('error', function (error) {
                done(error);
            });

    });

    /*it('"mhv_VA_CCD_WATSON_20140909_1002" as input', function (done) {

        testoOn(__dirname + '/../../private-records/blue-button/tests/proprietary/watson/mhv_VA_CCD_WATSON_20140909_1002.xml',
            __dirname + '/artifacts/mhv_VA_CCD_WATSON_20140909_1002.json',
            __dirname + '/artifacts/mhv_VA_CCD_WATSON_20140909_1002-gold.json',
            done);

    });*/

});
<commit_msg>test: fix<commit_after>/// <reference path="../typings/node/node.d.ts"/>
/// <reference path="../typings/mocha/mocha.d.ts"/>
"use strict";

var expect = require('chai').expect;
var fs = require('fs');
var request = require('request');
var _ = require('lodash');

var bbcms = require("../index");

var testoOn = function (infile, outfile, goldfile, done) {
    var istream = fs.createReadStream(infile, 'utf-8');
    istream
        .pipe(new bbcms.C32ParserStream("test"))
        .on('data', function (data) {
            expect(data).to.exist;
            fs.writeFile(outfile, JSON.stringify(data, null, '  '), function (err2) {
                if (err2) {
                    return done(err2);
                }
                fs.readFile(goldfile, function (err, data2) {
                    if (err) {
                        return done(); // Not an error, just skip comparison
                    }
                    try {
                        expect(JSON.parse(data2.toString())).to.be.eql(data);
                        //return done(err);
                        if (_.isEqual(JSON.parse(data2.toString()), data)) {
                            return done(err);
                        } else {
                            return done(new Error("Compare fails"));
                        }
                    } catch (ee) {
                        return done(ee);
                    }
                });
            });
        })
        .on('error', function (error) {
            done(error);
        });
};

describe('C32 parser test', function () {

    it('"VA_CCD_Sample_File_Version_12_5_1.xml" as input', function (done) {

        var request = require('request');
        var data = request.get('https://raw.githubusercontent.com/amida-tech/blue-button/master/test/fixtures/parser-c32/VA_CCD_Sample_File_Version_12_5_1.xml');

        data
            .pipe(new bbcms.C32ParserStream('test'))
            .on('data', function (data) {
                expect(data).to.exist;
                /*fs.writeFile(__dirname + '/artifacts/VA_CCD_Sample_File_Version_12_5_1.json', JSON.stringify(data, null, '  '), function (err2) {
                    done(err2);
                });*/
                done();
            })
            .on('error', function (error) {
                done(error);
            });

    });

    /*it('"mhv_VA_CCD_WATSON_20140909_1002" as input', function (done) {

        testoOn(__dirname + '/../../private-records/blue-button/tests/proprietary/watson/mhv_VA_CCD_WATSON_20140909_1002.xml',
            __dirname + '/artifacts/mhv_VA_CCD_WATSON_20140909_1002.json',
            __dirname + '/artifacts/mhv_VA_CCD_WATSON_20140909_1002-gold.json',
            done);

    });*/

});
<|endoftext|>


<commit_before>/* global describe:false, it:false, assert:false, expect:false */
/* eslint-disable no-magic-numbers */

const semLib = require("../");

describe("schedule", function() {
    // eslint-disable-next-line no-invalid-this
    this.timeout(300 * 1000);
    const ms = Math.pow(2, 5);
    const hasProp = Object.prototype.hasOwnProperty;

    function actualPush(actual, count, timerDiff) {
        const key = "t" + Math.round( timerDiff / ms );
        if (!hasProp.call(actual, key)) {
            actual[key] = [];
        }
        actual[key].push(count);
    }

    function assertSchedule(actual, expected) {
        expect(Object.keys(actual)).to.deep.equal(Object.keys(expected));
        // eslint-disable-next-line guard-for-in
        for (const key in actual) {
            expect(actual[key].sort()).to.deep.equal(expected[key].sort());
        }
    }

    it("should schedule array", (done) => {
        const actual = {};
        const semID = semLib.semCreate(3, true); // 3 tokens full capacity
        let count = 0;

        semID.schedule([
            schedule(++count, 2 * ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms)
        ], () => {
            const expected = {};
            expected.t1 = [2, 3];
            expected.t2 = [1, 4, 5];
            expected.t3 = [6];

            assertSchedule(actual, expected);
            done();
        });

        const timerInit = new Date().getTime();
        assert.strictEqual(semID.getNumTokens(), 0);

        function schedule(count, timeout) {
            return (next) => {
                setTimeout(() => {
                    actualPush(actual, count, new Date().getTime() - timerInit);
                    next();
                }, timeout);
            };
        }
    });

    it("should schedule array with iteratee", (done) => {
        const actual = {};
        const semID = semLib.semCreate(3, true); // 3 tokens full capacity
        let count = 0;

        semID.schedule([
            [++count, 2 * ms],
            [++count, ms],
            [++count, ms],
            [++count, ms],
            [++count, ms],
            [++count, ms]
        ], (args, key, next) => {
            return schedule.apply(null, args)(next);
        }, () => {
            const expected = {};
            expected.t1 = [2, 3];
            expected.t2 = [1, 4, 5];
            expected.t3 = [6];

            assertSchedule(actual, expected);
            done();
        });

        const timerInit = new Date().getTime();
        assert.strictEqual(semID.getNumTokens(), 0);

        function schedule(count, timeout) {
            return (next) => {
                setTimeout(() => {
                    actualPush(actual, count, new Date().getTime() - timerInit);
                    next();
                }, timeout);
            };
        }
    });

    it("should schedule object", (done) => {
        const actual = {};
        const semID = semLib.semCreate(3, true); // 3 tokens full capacity
        let count = 0;

        semID.schedule({
            s1: schedule(++count, 2 * ms),
            s2: schedule(++count, ms),
            s3: schedule(++count, ms),
            s4: schedule(++count, ms),
            s5: schedule(++count, ms),
            s6: schedule(++count, ms)
        }, () => {
            const expected = {};
            expected.t1 = [2, 3];
            expected.t2 = [1, 4, 5];
            expected.t3 = [6];

            assertSchedule(actual, expected);
            done();
        });

        const timerInit = new Date().getTime();
        assert.strictEqual(semID.getNumTokens(), 0);

        function schedule(count, timeout) {
            return (next) => {
                setTimeout(() => {
                    actualPush(actual, count, new Date().getTime() - timerInit);
                    next();
                }, timeout);
            };
        }
    });

    it("should schedule object with iteratee", (done) => {
        const actual = {};
        const semID = semLib.semCreate(3, true); // 3 tokens full capacity
        let count = 0;

        semID.schedule({
            s1: [++count, 2 * ms],
            s2: [++count, ms],
            s3: [++count, ms],
            s4: [++count, ms],
            s5: [++count, ms],
            s6: [++count, ms]
        }, (args, key, next) => {
            return schedule.apply(null, args)(next);
        }, () => {
            const expected = {};
            expected.t1 = [2, 3];
            expected.t2 = [1, 4, 5];
            expected.t3 = [6];

            assertSchedule(actual, expected);
            done();
        });

        const timerInit = new Date().getTime();
        assert.strictEqual(semID.getNumTokens(), 0);

        function schedule(count, timeout) {
            return (next) => {
                setTimeout(() => {
                    actualPush(actual, count, new Date().getTime() - timerInit);
                    next();
                }, timeout);
            };
        }
    });

    it("should cancel schedule before start", (done) => {
        const actual = {};
        const semID = semLib.semCreate(3, true); // 3 tokens full capacity
        let count = 0;
        let waiting = 0;
        let canceled = false;

        const item = semID.schedule([
            schedule(++count, 2 * ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms)
        ], err => {
            canceled = true;
            expect(err).not.to.be.an("undefined");
            assert.strictEqual(err.code, "CANCELED");
        });

        const timerInit = new Date().getTime();
        assert.strictEqual(waiting, 0);
        assert.strictEqual(semID.getNumTokens(), 0);
        item.cancel();
        assert.strictEqual(waiting, 0);
        assert.strictEqual(semID.getNumTokens(), 3);

        setTimeout(() => {
            const expected = {};
            assert.strictEqual(waiting, 0);
            assert.strictEqual(canceled, true);
            assertSchedule(actual, expected);
            done();
        }, 3.2 * ms);

        function schedule(count, timeout) {
            return (next) => {
                waiting++;
                setTimeout(() => {
                    waiting--;
                    actualPush(actual, count, new Date().getTime() - timerInit);
                    next();
                }, timeout);
            };
        }
    });

    it("should cancel schedule after callback and before done", (done) => {
        const actual = {};
        const semID = semLib.semCreate(3, true); // 3 tokens full capacity
        let count = 0;
        let waiting = 0;
        let canceled = false;

        const item = semID.schedule([
            schedule(++count, 2 * ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms)
        ], err => {
            canceled = true;
            expect(err).not.to.be.an("undefined");
            assert.strictEqual(err.code, "CANCELED");
        });

        const timerInit = new Date().getTime();
        assert.strictEqual(semID.getNumTokens(), 0);

        setTimeout(() => {
            item.cancel();
            assert.strictEqual(waiting, 3);
            assert.strictEqual(semID.getNumTokens(), 3);
        }, ms / 2);

        setTimeout(() => {
            const expected = {};
            assert.strictEqual(canceled, true);
            assertSchedule(actual, expected);
            done();
        }, 3.2 * ms);

        function schedule(count, timeout) {
            return (next) => {
                waiting++;
                const timerID = setTimeout(() => {
                    waiting--;
                    actualPush(actual, count, new Date().getTime() - timerInit);
                    next();
                }, timeout);

                return () => {
                    // should be synchronous
                    clearTimeout(timerID);
                    next();
                };
            };
        }
    });

    it("should change priority on the fly", (done) => {
        const actual = {};
        const semID = semLib.semCreate(3, true); // 3 tokens full capacity
        let count = 0;
        let waiting = 0;

        semID.schedule([
            schedule(++count, 2 * ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms)
        ], 15);

        const group2 = semID.schedule([
            schedule(++count, 2 * ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms)
        ], 15);

        const timerInit = new Date().getTime();
        assert.strictEqual(semID.getNumTokens(), 0);

        setTimeout(() => {
            group2.setPriority(14);
            assert.strictEqual(waiting, 3);
            assert.strictEqual(semID.getNumTokens(), 0);
        }, ms / 2);

        setTimeout(() => {
            const expected = {
                t1: [2, 3],
                t2: [1, 8],
                t3: [7, 9, 10],
                t4: [11, 12, 4],
                t5: [5, 6]
            };

            assertSchedule(actual, expected);
            done();
        }, 5.2 * ms);

        function schedule(count, timeout) {
            return (next) => {
                waiting++;
                const timerID = setTimeout(() => {
                    waiting--;
                    actualPush(actual, count, new Date().getTime() - timerInit);
                    next();
                }, timeout);

                return () => {
                    // should be synchronous
                    clearTimeout(timerID);
                    next();
                };
            };
        }
    });

});
<commit_msg>fix scheduler test<commit_after>/* global describe:false, it:false, assert:false, expect:false */
/* eslint-disable no-magic-numbers */

const semLib = require("../");

describe("schedule", function() {
    // eslint-disable-next-line no-invalid-this
    this.timeout(300 * 1000);
    const ms = Math.pow(2, 5);
    const hasProp = Object.prototype.hasOwnProperty;

    function actualPush(actual, count, timerDiff) {
        // timerDiff may not be exact
        const key = "t" + (timerDiff / ms >> 0);
        if (!hasProp.call(actual, key)) {
            actual[key] = [];
        }
        actual[key].push(count);
    }

    function assertSchedule(actual, expected) {
        expect(Object.keys(actual)).to.deep.equal(Object.keys(expected));
        // eslint-disable-next-line guard-for-in
        for (const key in actual) {
            expect(actual[key].sort()).to.deep.equal(expected[key].sort());
        }
    }

    it("should schedule array", done => {
        const actual = {};
        const semID = semLib.semCreate(3, true); // 3 tokens full capacity
        let count = 0;

        semID.schedule([
            schedule(++count, 2 * ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms)
        ], () => {
            const expected = {};
            expected.t1 = [2, 3];
            expected.t2 = [1, 4, 5];
            expected.t3 = [6];

            assertSchedule(actual, expected);
            done();
        });

        const timerInit = Date.now();
        assert.strictEqual(semID.getNumTokens(), 0);

        function schedule(count, timeout) {
            return (next) => {
                setTimeout(() => {
                    actualPush(actual, count, Date.now() - timerInit);
                    next();
                }, timeout);
            };
        }
    });

    it("should schedule array with iteratee", done => {
        const actual = {};
        const semID = semLib.semCreate(3, true); // 3 tokens full capacity
        let count = 0;

        semID.schedule([
            [++count, 2 * ms],
            [++count, ms],
            [++count, ms],
            [++count, ms],
            [++count, ms],
            [++count, ms]
        ], (args, key, next) => {
            return schedule.apply(null, args)(next);
        }, () => {
            const expected = {};
            expected.t1 = [2, 3];
            expected.t2 = [1, 4, 5];
            expected.t3 = [6];

            assertSchedule(actual, expected);
            done();
        });

        const timerInit = Date.now();
        assert.strictEqual(semID.getNumTokens(), 0);

        function schedule(count, timeout) {
            return (next) => {
                setTimeout(() => {
                    actualPush(actual, count, new Date().getTime() - timerInit);
                    next();
                }, timeout);
            };
        }
    });

    it("should schedule object", done => {
        const actual = {};
        const semID = semLib.semCreate(3, true); // 3 tokens full capacity
        let count = 0;

        semID.schedule({
            s1: schedule(++count, 2 * ms),
            s2: schedule(++count, ms),
            s3: schedule(++count, ms),
            s4: schedule(++count, ms),
            s5: schedule(++count, ms),
            s6: schedule(++count, ms)
        }, () => {
            const expected = {};
            expected.t1 = [2, 3];
            expected.t2 = [1, 4, 5];
            expected.t3 = [6];

            assertSchedule(actual, expected);
            done();
        });

        const timerInit = new Date().getTime();
        assert.strictEqual(semID.getNumTokens(), 0);

        function schedule(count, timeout) {
            return (next) => {
                setTimeout(() => {
                    actualPush(actual, count, new Date().getTime() - timerInit);
                    next();
                }, timeout);
            };
        }
    });

    it("should schedule object with iteratee", done => {
        const actual = {};
        const semID = semLib.semCreate(3, true); // 3 tokens full capacity
        let count = 0;

        semID.schedule({
            s1: [++count, 2 * ms],
            s2: [++count, ms],
            s3: [++count, ms],
            s4: [++count, ms],
            s5: [++count, ms],
            s6: [++count, ms]
        }, (args, key, next) => {
            return schedule.apply(null, args)(next);
        }, () => {
            const expected = {};
            expected.t1 = [2, 3];
            expected.t2 = [1, 4, 5];
            expected.t3 = [6];

            assertSchedule(actual, expected);
            done();
        });

        const timerInit = new Date().getTime();
        assert.strictEqual(semID.getNumTokens(), 0);

        function schedule(count, timeout) {
            return (next) => {
                setTimeout(() => {
                    actualPush(actual, count, new Date().getTime() - timerInit);
                    next();
                }, timeout);
            };
        }
    });

    it("should cancel schedule before start", done => {
        const actual = {};
        const semID = semLib.semCreate(3, true); // 3 tokens full capacity
        let count = 0;
        let waiting = 0;
        let canceled = false;

        const item = semID.schedule([
            schedule(++count, 2 * ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms)
        ], err => {
            canceled = true;
            expect(err).not.to.be.an("undefined");
            assert.strictEqual(err.code, "CANCELED");
        });

        const timerInit = new Date().getTime();
        assert.strictEqual(waiting, 0);
        assert.strictEqual(semID.getNumTokens(), 0);
        item.cancel();
        assert.strictEqual(waiting, 0);
        assert.strictEqual(semID.getNumTokens(), 3);

        setTimeout(() => {
            const expected = {};
            assert.strictEqual(waiting, 0);
            assert.strictEqual(canceled, true);
            assertSchedule(actual, expected);
            done();
        }, 3.2 * ms);

        function schedule(count, timeout) {
            return (next) => {
                waiting++;
                setTimeout(() => {
                    waiting--;
                    actualPush(actual, count, new Date().getTime() - timerInit);
                    next();
                }, timeout);
            };
        }
    });

    it("should cancel schedule after callback and before done", done => {
        const actual = {};
        const semID = semLib.semCreate(3, true); // 3 tokens full capacity
        let count = 0;
        let waiting = 0;
        let canceled = false;

        const item = semID.schedule([
            schedule(++count, 2 * ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms)
        ], err => {
            canceled = true;
            expect(err).not.to.be.an("undefined");
            assert.strictEqual(err.code, "CANCELED");
        });

        const timerInit = new Date().getTime();
        assert.strictEqual(semID.getNumTokens(), 0);

        setTimeout(() => {
            item.cancel();
            assert.strictEqual(waiting, 3);
            assert.strictEqual(semID.getNumTokens(), 3);
        }, ms / 2);

        setTimeout(() => {
            const expected = {};
            assert.strictEqual(canceled, true);
            assertSchedule(actual, expected);
            done();
        }, 3.2 * ms);

        function schedule(count, timeout) {
            return (next) => {
                waiting++;
                const timerID = setTimeout(() => {
                    waiting--;
                    actualPush(actual, count, new Date().getTime() - timerInit);
                    next();
                }, timeout);

                return () => {
                    // cancel should be synchronous
                    clearTimeout(timerID);
                    next();
                };
            };
        }
    });

    it("should change priority on the fly", done => {
        const actual = {};
        const semID = semLib.semCreate(3, true); // 3 tokens full capacity
        let count = 0;
        let waiting = 0;

        semID.schedule([
            schedule(++count, 2 * ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms)
        ], 15);

        const group2 = semID.schedule([
            schedule(++count, 2 * ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms),
            schedule(++count, ms)
        ], 15);

        const timerInit = Date.now();
        assert.strictEqual(semID.getNumTokens(), 0);

        setTimeout(() => {
            group2.setPriority(14);
            assert.strictEqual(waiting, 3);
            assert.strictEqual(semID.getNumTokens(), 0);
        }, ms / 2);

        setTimeout(() => {
            const expected = {
                t1: [2, 3],
                t2: [1, 8],
                t3: [7, 9, 10],
                t4: [11, 12, 4],
                t5: [5, 6]
            };

            assertSchedule(actual, expected);
            done();
        }, 6 * ms);

        function schedule(count, timeout) {
            return next => {
                waiting++;
                const timerID = setTimeout(() => {
                    waiting--;
                    actualPush(actual, count, Date.now() - timerInit);
                    next();
                }, timeout);

                return () => {
                    // cancel should be synchronous
                    clearTimeout(timerID);
                    next();
                };
            };
        }
    });

});
<|endoftext|>


<commit_before>'use strict';

var assert    = require('assert');
var grunt     = require('grunt');

grunt.task.init = function() {};

// Init config
grunt.initConfig({
  sequelize: {
    options: {
      dialect: 'sqlite',
      storage: 'test/tmp.sqlite',
      migrationsPath: __dirname + '/migrations'
    }
  }
});

grunt.loadTasks('tasks');

describe('grunt-sequelize', function() {

  describe('sequelize:migrate', function() {
    describe('without any arguments', function() {
      it('should migrate to the top migration', function(done) {

        grunt.util.spawn({ grunt: true, args: ['sequelize:migrate'] }, function(error, result) {
          console.log(result);
          assert.equal(result.code, 0);
          done();
        });

      });
    });
    describe('with a migration argument', function() {
    });
  });

  describe('sequelize:undo', function() {
    it('should undo the last migration', function(done) {
      grunt.util.spawn({ grunt: true, args: ['sequelize:undo'] }, function(error, result) {
        console.log(result);
        assert.equal(result.code, 0);
        done();
      });
    });
  });

});
<commit_msg>Setup test definitions for new features<commit_after>'use strict';

var assert    = require('assert');
var grunt     = require('grunt');

grunt.task.init = function() {};

// Init config
grunt.initConfig({
  sequelize: {
    options: {
      dialect: 'sqlite',
      storage: 'test/tmp.sqlite',
      migrationsPath: __dirname + '/migrations'
    }
  }
});

grunt.loadTasks('tasks');

describe('grunt-sequelize', function() {

  describe('sequelize:migrate', function() {
    describe('without any arguments', function() {
      it('should migrate to the top migration', function(done) {

        grunt.util.spawn({ grunt: true, args: ['sequelize:migrate'] }, function(error, result) {
          console.log(result);
          assert.equal(result.code, 0);
          done();
        });

      });
    });
    describe('with a migration argument', function() {
      describe('where the migration is the same as the current state of the database', function() {
        it('should just inform the user');
      });
      describe('where the migration is higher than the current state of the database', function(){
        it('should migrate to the specified migration');
      });
      describe('where the migration is lower than the current state of the database', function(){
        it('should migrate to the specified migration');
      });
    });
  });

  describe('sequelize:undo', function() {
    describe('without any arguments', function() {
      it('should undo the last migration', function(done) {
        grunt.util.spawn({ grunt: true, args: ['sequelize:undo'] }, function(error, result) {
          console.log(result);
          assert.equal(result.code, 0);
          // TODO assert migration ID === last ID
          done();
        });
      });
    });
    describe('with a set number to undo', function() {
      it('should migrate downwards by the given number of migrations');
    })
  });

});
<|endoftext|>


<commit_before>import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import { actividadMock } from '../../helpers/mocks'
import { xmlBloqueEmpezarAEjecutar } from 'pilasbloques/models/desafio'
import sinon from 'sinon'

let ctrl
let version
let actividad = actividadMock.nombre
let solucion = "PHhtbCB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94aHRtbCI+PHZhcmlhYmxlcz48L3ZhcmlhYmxlcz48YmxvY2sgdHlwZT0iYWxfZW1wZXphcl9hX2VqZWN1dGFyIiBpZD0idX4vczBQV1BEWkQ1aFEtLFFnPXQiIGRlbGV0YWJsZT0iZmFsc2UiIG1vdmFibGU9ImZhbHNlIiBlZGl0YWJsZT0iZmFsc2UiIHg9IjIyNyIgeT0iMTUiPjwvYmxvY2s+PC94bWw+"

module('Unit | Components | challenge-workspace-buttons', function (hooks) {
  setupTest(hooks);

  hooks.beforeEach(function () {
    ctrl = this.owner.factoryFor('component:challenge-workspace-buttons').create()
    ctrl.set('actividad', actividadMock)
    ctrl.descargar = sinon.stub()
    version = ctrl.version()
    sinon.resetHistory()
  });

  test("Al guardar solución crea el archivo correctamente", function (assert) {
    let contenido = JSON.stringify({
      version,
      actividad,
      solucion: "bnVsbA=="
    })
    let archivo = `${actividad}.spbq`
    let tipo = 'application/octet-stream'

    ctrl.send("guardarSolucion")
    assert.ok(ctrl.descargar.calledWith(contenido, archivo, tipo))
  })

  let solucionCompleta = {
    version,
    actividad,
    solucion
  }

  test("Al borrar una solucion con un workspace inicial se deberia volver al workspace incial", function (assert) {
    const actividadConWorkspaceInicial = this.owner.lookup('service:store').createRecord('desafio', { solucionInicial: solucion })
    ctrl.set('actividad', actividadConWorkspaceInicial)
    ctrl.set('workspace', 'algoDistinto')
    ctrl.send('borrarSolucion')
    assert.equal(ctrl.get('workspace'), solucion)
  })

  test("Al borrar una solucion sin un workspace inicial se deberia volver al wokspace inicial base", function (assert) {
    const actividadSinWorkspaceInicial = this.owner.lookup('service:store').createRecord('desafio')
    ctrl.set('actividad', actividadSinWorkspaceInicial)
    ctrl.set('workspace', 'algoDistinto')
    ctrl.send('borrarSolucion')
    assert.equal(ctrl.get('workspace'), xmlBloqueEmpezarAEjecutar)
  })

  goodFileTest("Carga un archivo de solución correctamente", solucionCompleta)

  let solucionCompletaConVersionPosterior = {
    version: 999,
    actividad,
    solucion
  }

  goodFileTest("Carga un archivo de solución aunque tenga una versión posterior", solucionCompletaConVersionPosterior)

  let solucionCompletaConVersionAnterior = {
    version: -1,
    actividad,
    solucion
  }

  failFileTest("Verifica que se está cargando una versión anterior", solucionCompletaConVersionAnterior, function (assert, err) {
    assert.equal(err, "Cuidado, el archivo indica que es de una versión anterior. Se cargará de todas formas, pero te sugerimos que resuelvas nuevamente el ejercicio y guardes un nuevo archivo.")
  })

  failFileTest("Aunque no tenga una versión actual se carga al workspace", solucionCompletaConVersionAnterior, function (assert) {
    assert.ok(ctrl.get("workspace"))
  })

  let solucionCompletaSinVersion = {
    actividad,
    solucion
  }

  goodFileTest("Carga un archivo de solución aunque no tenga versión", solucionCompletaSinVersion)

  let solucionParaOtraActividad = {
    version,
    actividad: "Otra_Actividad",
    solucion
  }

  failFileTest("Verifica que sea para la actividad que se está cargando", solucionParaOtraActividad, function (assert, err) {
    assert.equal(err, "Cuidado, el archivo indica que es para otra actividad (Otra_Actividad). Se cargará de todas formas, pero puede fallar.")
  })

  failFileTest("Aunque no sea una solución para la actividad se carga al workspace", solucionParaOtraActividad, function (assert) {
    assert.ok(ctrl.get("workspace"))
  })

  let solucionCompletaConVersionAnteriorParaOtraActividad = {
    version: -1,
    actividad: "Otra_Actividad",
    solucion
  }

  failFileTest("Acumula las validaciones con soluciones", solucionCompletaConVersionAnteriorParaOtraActividad, function (assert, err) {
    assert.equal(err,
      `Cuidado, el archivo indica que es para otra actividad (Otra_Actividad). Se cargará de todas formas, pero puede fallar.
Cuidado, el archivo indica que es de una versión anterior. Se cargará de todas formas, pero te sugerimos que resuelvas nuevamente el ejercicio y guardes un nuevo archivo.`)
  })

  failFileTest("Aunque no tenga versión actual y sea una solución para la actividad se carga al workspace", solucionCompletaConVersionAnteriorParaOtraActividad, function (assert) {
    assert.ok(ctrl.get("workspace"))
  })

  let archivoSinSolucion = {
    version,
    actividad,
  }

  failFileTest("Verifica que tenga una solucion", archivoSinSolucion, function (assert, err) {
    assert.equal(err, "Lo siento, este archivo no tiene una solución de Pilas Bloques.")
  })

  failFileTest("Verifica que tenga una solucion", archivoSinSolucion, function (assert) {
    assert.notOk(ctrl.get("workspace"))
  })

  function goodFileTest(mensaje, contenido) {
    fileTest(mensaje, contenido, (assert) => { assert.ok(ctrl.get("workspace")) }, () => { })
  }

  function failFileTest(mensaje, contenido, cb) {
    fileTest(mensaje, contenido, () => { }, cb)
  }

  function fileTest(mensaje, contenido, cbGood, cbFail) {
    test(mensaje, function (assert) {
      let done = assert.async()
      let archivo = new Blob([JSON.stringify(contenido)])

      ctrl
        .leerSolucionWeb(archivo)
        .then(() => {
          cbGood(assert)
          done()
        })
        .catch((err) => {
          cbFail(assert, err)
          done()
        })
    })
  }
});

<commit_msg>Fixing loading solution error tests<commit_after>import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import { actividadMock } from '../../helpers/mocks'
import { xmlBloqueEmpezarAEjecutar } from 'pilasbloques/models/desafio'
import sinon from 'sinon'
import { setUpTestLocale } from '../../helpers/utils'

let ctrl
let version
let actividad = actividadMock.nombre
let solucion = "PHhtbCB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94aHRtbCI+PHZhcmlhYmxlcz48L3ZhcmlhYmxlcz48YmxvY2sgdHlwZT0iYWxfZW1wZXphcl9hX2VqZWN1dGFyIiBpZD0idX4vczBQV1BEWkQ1aFEtLFFnPXQiIGRlbGV0YWJsZT0iZmFsc2UiIG1vdmFibGU9ImZhbHNlIiBlZGl0YWJsZT0iZmFsc2UiIHg9IjIyNyIgeT0iMTUiPjwvYmxvY2s+PC94bWw+"

module('Unit | Components | challenge-workspace-buttons', function (hooks) {
  setupTest(hooks);

  hooks.beforeEach(function () {
    ctrl = this.owner.factoryFor('component:challenge-workspace-buttons').create()
    ctrl.set('actividad', actividadMock)
    ctrl.descargar = sinon.stub()
    version = ctrl.version()
    sinon.resetHistory()
    setUpTestLocale(hooks)
  });

  test("Al guardar solución crea el archivo correctamente", function (assert) {
    let contenido = JSON.stringify({
      version,
      actividad,
      solucion: "bnVsbA=="
    })
    let archivo = `${actividad}.spbq`
    let tipo = 'application/octet-stream'

    ctrl.send("guardarSolucion")
    assert.ok(ctrl.descargar.calledWith(contenido, archivo, tipo))
  })

  let solucionCompleta = {
    version,
    actividad,
    solucion
  }

  test("Al borrar una solucion con un workspace inicial se deberia volver al workspace incial", function (assert) {
    const actividadConWorkspaceInicial = this.owner.lookup('service:store').createRecord('desafio', { solucionInicial: solucion })
    ctrl.set('actividad', actividadConWorkspaceInicial)
    ctrl.set('workspace', 'algoDistinto')
    ctrl.send('borrarSolucion')
    assert.equal(ctrl.get('workspace'), solucion)
  })

  test("Al borrar una solucion sin un workspace inicial se deberia volver al wokspace inicial base", function (assert) {
    const actividadSinWorkspaceInicial = this.owner.lookup('service:store').createRecord('desafio')
    ctrl.set('actividad', actividadSinWorkspaceInicial)
    ctrl.set('workspace', 'algoDistinto')
    ctrl.send('borrarSolucion')
    assert.equal(ctrl.get('workspace'), xmlBloqueEmpezarAEjecutar)
  })

  goodFileTest("Carga un archivo de solución correctamente", solucionCompleta)

  let solucionCompletaConVersionPosterior = {
    version: 999,
    actividad,
    solucion
  }

  goodFileTest("Carga un archivo de solución aunque tenga una versión posterior", solucionCompletaConVersionPosterior)

  let solucionCompletaConVersionAnterior = {
    version: -1,
    actividad,
    solucion
  }

  failFileTest("Verifica que se está cargando una versión anterior", solucionCompletaConVersionAnterior, function (assert, err) {
    assert.equal(err, "Cuidado! El archivo indica que es de una versión anterior. Se cargará de todas formas, pero te sugerimos que resuelvas nuevamente el ejercicio y guardes un nuevo archivo.")
  })

  failFileTest("Aunque no tenga una versión actual se carga al workspace", solucionCompletaConVersionAnterior, function (assert) {
    assert.ok(ctrl.get("workspace"))
  })

  let solucionCompletaSinVersion = {
    actividad,
    solucion
  }

  goodFileTest("Carga un archivo de solución aunque no tenga versión", solucionCompletaSinVersion)

  let solucionParaOtraActividad = {
    version,
    actividad: "Otra_Actividad",
    solucion
  }

  failFileTest("Verifica que sea para la actividad que se está cargando", solucionParaOtraActividad, function (assert, err) {
    assert.equal(err, "Cuidado! El archivo indica que es para otra actividad (Otra_Actividad). Se cargará de todas formas, pero puede fallar.")
  })

  failFileTest("Aunque no sea una solución para la actividad se carga al workspace", solucionParaOtraActividad, function (assert) {
    assert.ok(ctrl.get("workspace"))
  })

  let solucionCompletaConVersionAnteriorParaOtraActividad = {
    version: -1,
    actividad: "Otra_Actividad",
    solucion
  }

  failFileTest("Acumula las validaciones con soluciones", solucionCompletaConVersionAnteriorParaOtraActividad, function (assert, err) {
    assert.equal(err,
      `Cuidado! El archivo indica que es para otra actividad (Otra_Actividad). Se cargará de todas formas, pero puede fallar.
Cuidado! El archivo indica que es de una versión anterior. Se cargará de todas formas, pero te sugerimos que resuelvas nuevamente el ejercicio y guardes un nuevo archivo.`)
  })

  failFileTest("Aunque no tenga versión actual y sea una solución para la actividad se carga al workspace", solucionCompletaConVersionAnteriorParaOtraActividad, function (assert) {
    assert.ok(ctrl.get("workspace"))
  })

  let archivoSinSolucion = {
    version,
    actividad,
  }

  failFileTest("Verifica que tenga una solucion", archivoSinSolucion, function (assert, err) {
    assert.equal(err, "Este archivo no tiene una solución de Pilas Bloques.")
  })

  failFileTest("Verifica que tenga una solucion", archivoSinSolucion, function (assert) {
    assert.notOk(ctrl.get("workspace"))
  })

  function goodFileTest(mensaje, contenido) {
    fileTest(mensaje, contenido, (assert) => { assert.ok(ctrl.get("workspace")) }, () => { })
  }

  function failFileTest(mensaje, contenido, cb) {
    fileTest(mensaje, contenido, () => { }, cb)
  }

  function fileTest(mensaje, contenido, cbGood, cbFail) {
    test(mensaje, function (assert) {
      let done = assert.async()
      let archivo = new Blob([JSON.stringify(contenido)])

      ctrl
        .leerSolucionWeb(archivo)
        .then(() => {
          cbGood(assert)
          done()
        })
        .catch((err) => {
          cbFail(assert, err)
          done()
        })
    })
  }
});

<|endoftext|>