<commit_before>/*
 * Copyright (c) Novedia Group 2012.
 *
 *     This file is part of Hubiquitus.
 *
 *     Hubiquitus is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     Hubiquitus is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with Hubiquitus.  If not, see <http://www.gnu.org/licenses/>.
 */

var should = require("should");
var hClient = require('../hubiquitus.js').hClient;
var conf = require('./testConfig.js');

var channel = 'chan' + Math.floor(Math.random()*10000);
var user = conf.logins[0];

var msgQuantity = 0;

describe('#getLastMessages()', function() {

    var inactiveChannel = 'chan' + Math.floor(Math.random()*10000);
    var notInPartChannel = 'chan' + Math.floor(Math.random()*10000);

    before(conf.connect)

    after(conf.disconnect)

    before(function(done){
        conf.createChannel(channel, user.login, [user.login], true, done);
    })

    before(function(done){
        conf.createChannel(inactiveChannel, user.login, [user.login], false, done);
    })

    before(function(done){
        conf.createChannel(notInPartChannel, user.login, [conf.logins[1].login], true, done);
    })

    it('should return an empty array of messages if nothing has been saved', function(done){
        hClient.getLastMessages(channel, undefined, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.OK);
            hResult.result.should.be.an.instanceof(Array).and.have.lengthOf(msgQuantity);
            done();
        })
    })

    it('should return a hResult with NOT_AUTHORIZED status if user not in participants list', function(done){
        hClient.getLastMessages(notInPartChannel, undefined, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.NOT_AUTHORIZED);
            hResult.result.should.be.a('string');
            done();
        })
    })

    it('should return a hResult with NOT_AUTHORIZED status if channel is inactive', function(done){
        hClient.getLastMessages(inactiveChannel, undefined, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.NOT_AUTHORIZED);
            hResult.result.should.be.a('string');
            done();
        })
    })

    it('should return a hResult with NOT_AVAILABLE status if channel does not exist', function(done){
        hClient.getLastMessages('this chan does not exist', undefined, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.NOT_AVAILABLE);
            done();
        })
    })

    it('should return a hResult with MISSING_ATTR status if channel was not sent', function(done){
        hClient.getLastMessages(undefined, undefined, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.MISSING_ATTR);
            hResult.result.should.be.a('string');
            done();
        })
    })

})

describe('#getLastMessages()', function() {

    before(conf.connect)

    after(conf.disconnect)

    before(function(done){
        hClient.publish(hClient.buildMessage(channel, undefined, undefined, {transient: false}), function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.OK);
            msgQuantity++;
            done();
        })
    })

    it('should return an array of messages with length old+1 after a persistent message is published', function(done){
        hClient.getLastMessages(channel, undefined, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.OK);
            hResult.result.should.be.an.instanceof(Array).and.have.lengthOf(msgQuantity);
            done();
        })
    })

})

describe('#getLastMessages()', function() {

    before(conf.connect)

    after(conf.disconnect)

    before(function(done){
        hClient.publish(hClient.buildMessage(channel, undefined, undefined, {transient: true}), function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.OK);
            done();
        })
    })

    it('should return an array of messages with old length after a transient message is published', function(done){
        hClient.getLastMessages(channel, undefined, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.OK);
            hResult.result.should.be.an.instanceof(Array).and.have.lengthOf(msgQuantity);
            done();
        })
    })

})

describe('#getLastMessages()', function() {

    var chanWithHeader = 'chan' + Math.floor(Math.random()*10000);
    var msgInChanHeader= 0;
    var maxMsgRetrieval = 14;

    before(conf.connect)

    after(conf.disconnect)

    //Create channel with msg quantity in header
    before(function(done){
        hClient.command({
            entity: conf.hNode,
            cmd: 'hcreateupdatechannel',
            params:{
                chid: chanWithHeader,
                host: 'test',
                owner: user.login,
                participants: [user.login],
                active: true,
                headers: [{hK: 'MAX_MSG_RETRIEVAL', hV: ''+maxMsgRetrieval}]
            }
        }, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.OK);
            done();
        })
    })

    before(function(done){
        var counter = 0;
        for(var i = 0; i < 20; i++)
            hClient.publish(hClient.buildMessage(channel, undefined, undefined, {transient: false}), function(hResult){
                hResult.status.should.be.eql(hClient.hResultStatus.OK);
                msgQuantity++;
                if(++counter == 20)
                    done();
            })
    })

    before(function(done){
        var counter = 0;
        for(var i = 0; i < 20; i++)
            hClient.publish(hClient.buildMessage(chanWithHeader, undefined, undefined, {transient: false}), function(hResult){
                hResult.status.should.be.eql(hClient.hResultStatus.OK);
                msgInChanHeader++;
                if(++counter == 20)
                    done();
            })
    })

    it('should return msg quantity specified in headers if not specified in function', function(done){
        hClient.getLastMessages(chanWithHeader, undefined, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.OK);
            hResult.result.should.be.an.instanceof(Array).and.have.lengthOf(maxMsgRetrieval);
            done();
        })
    })

    it('should return msg quantity specified in function even if specified in channel headers', function(done){
        hClient.getLastMessages(chanWithHeader, 5, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.OK);
            hResult.result.should.be.an.instanceof(Array).and.have.lengthOf(5);
            done();
        })
    })

    it('should return msg quantity specified in ref if nothing is defined in function or channel', function(done){
        hClient.getLastMessages(channel, undefined, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.OK);
            hResult.result.should.be.an.instanceof(Array).and.have.lengthOf(10);
            done();
        })
    })

    it('should return msg quantity specified in function if nothing defined in channel (not default from ref)', function(done){
        hClient.getLastMessages(channel, 7, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.OK);
            hResult.result.should.be.an.instanceof(Array).and.have.lengthOf(7);
            done();
        })
    })

})

describe('#getLastMessages()', function() {

    it('should return a hResult status NOT_CONNECTED if trying getLastMessages while not connected', function(done){
        hClient.getLastMessages(channel, undefined, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.NOT_CONNECTED);
            done();
        })
    })

})<commit_msg>Support for new headers format<commit_after>/*
 * Copyright (c) Novedia Group 2012.
 *
 *     This file is part of Hubiquitus.
 *
 *     Hubiquitus is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     Hubiquitus is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with Hubiquitus.  If not, see <http://www.gnu.org/licenses/>.
 */

var should = require("should");
var hClient = require('../hubiquitus.js').hClient;
var conf = require('./testConfig.js');

var channel = 'chan' + Math.floor(Math.random()*10000);
var user = conf.logins[0];

var msgQuantity = 0;

describe('#getLastMessages()', function() {

    var inactiveChannel = 'chan' + Math.floor(Math.random()*10000);
    var notInPartChannel = 'chan' + Math.floor(Math.random()*10000);

    before(conf.connect)

    after(conf.disconnect)

    before(function(done){
        conf.createChannel(channel, user.login, [user.login], true, done);
    })

    before(function(done){
        conf.createChannel(inactiveChannel, user.login, [user.login], false, done);
    })

    before(function(done){
        conf.createChannel(notInPartChannel, user.login, [conf.logins[1].login], true, done);
    })

    it('should return an empty array of messages if nothing has been saved', function(done){
        hClient.getLastMessages(channel, undefined, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.OK);
            hResult.result.should.be.an.instanceof(Array).and.have.lengthOf(msgQuantity);
            done();
        })
    })

    it('should return a hResult with NOT_AUTHORIZED status if user not in participants list', function(done){
        hClient.getLastMessages(notInPartChannel, undefined, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.NOT_AUTHORIZED);
            hResult.result.should.be.a('string');
            done();
        })
    })

    it('should return a hResult with NOT_AUTHORIZED status if channel is inactive', function(done){
        hClient.getLastMessages(inactiveChannel, undefined, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.NOT_AUTHORIZED);
            hResult.result.should.be.a('string');
            done();
        })
    })

    it('should return a hResult with NOT_AVAILABLE status if channel does not exist', function(done){
        hClient.getLastMessages('this chan does not exist', undefined, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.NOT_AVAILABLE);
            done();
        })
    })

    it('should return a hResult with MISSING_ATTR status if channel was not sent', function(done){
        hClient.getLastMessages(undefined, undefined, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.MISSING_ATTR);
            hResult.result.should.be.a('string');
            done();
        })
    })

})

describe('#getLastMessages()', function() {

    before(conf.connect)

    after(conf.disconnect)

    before(function(done){
        hClient.publish(hClient.buildMessage(channel, undefined, undefined, {transient: false}), function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.OK);
            msgQuantity++;
            done();
        })
    })

    it('should return an array of messages with length old+1 after a persistent message is published', function(done){
        hClient.getLastMessages(channel, undefined, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.OK);
            hResult.result.should.be.an.instanceof(Array).and.have.lengthOf(msgQuantity);
            done();
        })
    })

})

describe('#getLastMessages()', function() {

    before(conf.connect)

    after(conf.disconnect)

    before(function(done){
        hClient.publish(hClient.buildMessage(channel, undefined, undefined, {transient: true}), function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.OK);
            done();
        })
    })

    it('should return an array of messages with old length after a transient message is published', function(done){
        hClient.getLastMessages(channel, undefined, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.OK);
            hResult.result.should.be.an.instanceof(Array).and.have.lengthOf(msgQuantity);
            done();
        })
    })

})

describe('#getLastMessages()', function() {

    var chanWithHeader = 'chan' + Math.floor(Math.random()*10000);
    var msgInChanHeader= 0;
    var maxMsgRetrieval = 14;

    before(conf.connect)

    after(conf.disconnect)

    //Create channel with msg quantity in header
    before(function(done){
        hClient.command({
            entity: conf.hNode,
            cmd: 'hcreateupdatechannel',
            params:{
                chid: chanWithHeader,
                host: 'test',
                owner: user.login,
                participants: [user.login],
                active: true,
                headers: {'MAX_MSG_RETRIEVAL': ''+maxMsgRetrieval}
            }
        }, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.OK);
            done();
        })
    })

    before(function(done){
        var counter = 0;
        for(var i = 0; i < 20; i++)
            hClient.publish(hClient.buildMessage(channel, undefined, undefined, {transient: false}), function(hResult){
                hResult.status.should.be.eql(hClient.hResultStatus.OK);
                msgQuantity++;
                if(++counter == 20)
                    done();
            })
    })

    before(function(done){
        var counter = 0;
        for(var i = 0; i < 20; i++)
            hClient.publish(hClient.buildMessage(chanWithHeader, undefined, undefined, {transient: false}), function(hResult){
                hResult.status.should.be.eql(hClient.hResultStatus.OK);
                msgInChanHeader++;
                if(++counter == 20)
                    done();
            })
    })

    it('should return msg quantity specified in headers if not specified in function', function(done){
        hClient.getLastMessages(chanWithHeader, undefined, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.OK);
            hResult.result.should.be.an.instanceof(Array).and.have.lengthOf(maxMsgRetrieval);
            done();
        })
    })

    it('should return msg quantity specified in function even if specified in channel headers', function(done){
        hClient.getLastMessages(chanWithHeader, 5, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.OK);
            hResult.result.should.be.an.instanceof(Array).and.have.lengthOf(5);
            done();
        })
    })

    it('should return msg quantity specified in ref if nothing is defined in function or channel', function(done){
        hClient.getLastMessages(channel, undefined, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.OK);
            hResult.result.should.be.an.instanceof(Array).and.have.lengthOf(10);
            done();
        })
    })

    it('should return msg quantity specified in function if nothing defined in channel (not default from ref)', function(done){
        hClient.getLastMessages(channel, 7, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.OK);
            hResult.result.should.be.an.instanceof(Array).and.have.lengthOf(7);
            done();
        })
    })

})

describe('#getLastMessages()', function() {

    it('should return a hResult status NOT_CONNECTED if trying getLastMessages while not connected', function(done){
        hClient.getLastMessages(channel, undefined, function(hResult){
            hResult.status.should.be.eql(hClient.hResultStatus.NOT_CONNECTED);
            done();
        })
    })

})<|endoftext|>


<commit_before>/* section for outer block start */
function replaceSpeChar(div,d1,searchChar)
{
	var y = d1.innerHTML;
	insno=insno+1;
	var starpos = y.indexOf(searchChar); // pos of 1st `.  ie: No.
	var adstr="";
	var c=0;
	for(c=0;c<starpos;c++)
	{
		adstr = y.replace(searchChar,insno);
		starpos = y.indexOf(searchChar);
		y = adstr;
	}
	addDiv(div,adstr);
}

/* section for outer block end */

function addDiv(div,adstr)
{
	var x = div.innerHTML;
	div.innerHTML = div.innerHTML +adstr;

}

function confirmDisable(action,formField)
{
	if((formField != undefined) && (formField.value == "Disabled"))
	{
		var go = confirm("Are you sure, you want to disable?");
		if (go==true)
		{
			document.forms[0].action = action;
			document.forms[0].submit();
		}
	}
	else
	{
		document.forms[0].action = action;
		document.forms[0].submit();
	}
}

function enableButton(formButton,countElement,checkName)
{
	/** number of rows present    **/
	var counts = countElement.value;
	if(counts == undefined){
		var cnt = document.getElementById(countElement);

	/** number of rows present(counts) when countElement is again element    **/
	counts = cnt.value;
	}
	/** checking whether checkbox is checked or not **/
	var status = false;

	for(var i=1;i <= counts;i++)
	{

		/** creating checkbox name**/
		var itemCheck = checkName+i;
		var chk = document.getElementById(itemCheck);
	        if (chk.checked == true)
	        {

	        	status = true;
	        	break;
	        }
	}
	if(status)
		formButton.disabled = false;
	else
		formButton.disabled = true;
}

function  deleteChecked(subdivtag,action,countElement,checkName,isOuterTable)
{
	var r = new Array();

	/** element of tbody    **/
	var element = document.getElementById(subdivtag);

	/** number of rows present    **/
	var counts = countElement.value;
	if(counts == undefined){
		var cnt = document.getElementById(countElement);

		/** number of rows present(counts) when countElement is again element    **/
		counts = cnt.value;
	}
	/** number if rows deleted**/
	var delCounts = 0;

	/** checking whether checkbox is checked or not **/
	var status = false;
	for(i=1;i <= counts;i++)
	{
		/** creating checkbox name**/
		itemCheck = checkName+i;
		var chk = document.getElementById(itemCheck);

		if(chk.checked==true){
			var pNode = null;
			var k = 0;

			/** condition for checking whether outerTable's delete is clicked or not **/
			if(isOuterTable) {
				tableId = "table_" + i;
				var table = document.getElementById(tableId);
				// md 21 mar start
				var currentRow = table.parentNode.parentNode;
				k = currentRow.rowIndex;
				pNode = element.parentNode;
				pNode.deleteRow(k);
				// md 21 mar end

				/** removing table from tbody tag(div)   **/
				// 21 mar commented by md: element.removeChild(table);

			}
			else {
				/** getting table ref from tbody    **/
				pNode = element.parentNode;

				/** curent row of table ref **/
				var currentRow = chk.parentNode.parentNode;
				k = currentRow.rowIndex;

				/** deleting row from table **/
				pNode.deleteRow(k);
			}

			delCounts++;
			status = true;

		}
	}

	if(countElement.value == undefined){
		/** setting number of rows present in form   **/
		cnt.value = counts - delCounts;
	}
	else
		/** setting number of rows present in form   **/
		countElement.value = (countElement.value - delCounts);

	if(status){
		/** set action when checkbox is clicked **/
		document.forms[0].action = action;
		document.forms[0].submit();
	}

}

	//Mandar: 24-Apr-06 for tooltip
		function showStatus(sMsg)
		{
		    window.status = sMsg ;
		}
		function showTip(objId)
		{

			var obj = document.getElementById(objId);
			var tip="";
			if(obj.selectedIndex == -1)
				tip="";
			else
				tip = obj.options[obj.selectedIndex].text;

			obj.title = tip;

			var browser=navigator.appName;
			if(browser=="Microsoft Internet Explorer")
			{
				showStatus(tip);
			}
		}
		function hideTip(objId)
		{
			var obj = document.getElementById(objId);
			obj.title = "";

			var browser=navigator.appName;
			if(browser=="Microsoft Internet Explorer")
			{
				showStatus(' ');
			}

		}

		function moveToNext(element,value,nextID )
		{
		if (value.length==element.maxLength)
			{
				document.getElementById(nextID).focus();
			}
		}

function rearrangeIdsForDistribution() {
       		var addMore =	document.getElementById("addMore");
			var tableRows = addMore.rows

			for(var i=0;i<tableRows.length;i++) {
			    var row  = tableRows[i];

			   // var childNodeCollection = row.all;
			    var childNodeCollection = row.cells;

				for(var j=0;j<childNodeCollection.length;j++) {

					   if( childNodeCollection[j].firstChild.nodeType == "3" )
						    continue;

						var idName = childNodeCollection[j].firstChild.id;

						if(idName == null || idName == "" ) {
                              idName =  childNodeCollection[j].firstChild.name;
						}

                        var newId = getNewId(idName,i+1);
						childNodeCollection[j].firstChild.name =  newId;
						childNodeCollection[j].firstChild.id =  newId;
				}
			}
		}

function getNewId(oldId,newRowNo) {

	if( oldId == "undefined" || oldId == null || oldId == ""  ) {
	 return oldId;
	}

if( oldId.indexOf(":") == -1) {
    newId =  oldId.substr(0,oldId.indexOf("_")+1) + newRowNo ;

} else {
	var firstPart =  oldId.substr(0,oldId.indexOf(":")) ;
	var thirdPart = oldId.substr(oldId.indexOf("_")) ;
	newId = firstPart + ":"+ newRowNo  + thirdPart ;
}

//alert(oldId + "====>" + newId );

/*	var firstPart = oldId.split(":")[0];
	var thirdPart = oldId.split("_")[1];

   var newId =  firstPart + ":"+ newRowNo + "_" + thirdPart ; */

   return  newId;
}

function disableDistributeOptions() {

	  var distributionForm =  document.forms[0];
	   if (  parseInt(document.forms[0].counter.value) == 0)
	   {

	   			  distributionForm.distributionBasedOn[0].disabled=false
				  distributionForm.distributionBasedOn[1].disabled=false;
				  distributionForm.distributionType[0].disabled = false;
				  distributionForm.distributionType[1].disabled = false;
				  return;
	   }

	 	if (distributionForm.distributionBasedOn[0].checked == true)
		 {
        	    distributionForm.distributionBasedOn[1].disabled=true
		 }

	 	if (distributionForm.distributionBasedOn[1].checked == true)
		 {
        	    distributionForm.distributionBasedOn[0].disabled=true
		 }

	 	if (distributionForm.distributionType[0].checked == true)
		 {
        	    distributionForm.distributionType[1].disabled=true
		 }

	 	if (distributionForm.distributionType[1].checked == true)
		 {
        	    distributionForm.distributionType[0].disabled=true
		 }
}

function checkDistributionBasedOn() {

	 	if (distributionForm.distributionBasedOn[0].checked == false && distributionForm.distributionBasedOn[1].checked == false) {
		 	 alert("Please select 'distribution based on'");
		 	 return false;
        }

        return true;
}

function  deleteCheckedNoSubmit(subdivtag,action,countElement,checkName,isOuterTable) {
	var r = new Array();

	/** element of tbody    **/
	var element = document.getElementById(subdivtag);

	/** number of rows present    **/
	var counts = countElement.value;
	if(counts == undefined){
		var cnt = document.getElementById(countElement);

		/** number of rows present(counts) when countElement is again element    **/
		counts = cnt.value;
	}
	/** number if rows deleted**/
	var delCounts = 0;

	/** checking whether checkbox is checked or not **/
	var status = false;
	for(i=1;i <= counts;i++)
	{
		itemCheck = checkName+i;
		var chk = document.getElementById(itemCheck);

		if(chk.checked==true){
			var pNode = null;
			var k = 0;

			/** condition for checking whether outerTable's delete is clicked or not **/
			if(isOuterTable) {
				tableId = "table_" + i;
				var table = document.getElementById(tableId);
				// md 21 mar start
				var currentRow = table.parentNode.parentNode;
				k = currentRow.rowIndex;
				pNode = element.parentNode;
				pNode.deleteRow(k);
				// md 21 mar end

				/** removing table from tbody tag(div)   **/
				// 21 mar commented by md: element.removeChild(table);

			}
			else {
				/** getting table ref from tbody    **/
				pNode = element.parentNode;

				/** curent row of table ref **/
				var currentRow = chk.parentNode.parentNode;
				k = currentRow.rowIndex;

				/** deleting row from table **/
				pNode.deleteRow(k);
			}

			delCounts++;
			status = true;

		}
	}

	if(countElement.value == undefined){
		/** setting number of rows present in form   **/
		cnt.value = counts - delCounts;
	}
	else
		/** setting number of rows present in form   **/
		countElement.value = (countElement.value - delCounts);

	return status;
}

function showCommentsDialog(operation,key) {
 		 var url ='NewMultipleSpecimenAction.do?method=showCommentsDialog&operation=' + operation+ '&specimenAttributeKey=' + key;
		 var properties = "height = 120; width:100px; Top:300; Left:350; center: Yes; resizable: no;status:no;help:no;toolbar :no";
   		 window.open(url,"caTissuecore", properties);
}

function submitComments()
{
  var form =  document.forms[0];
  form.action =  form.action + "?method=submitComments";
  form.submit();
}

/* --- Start Specimen Array javascript functions ---*/
function changeArrayType()
{
		var confirmArrayChange = confirm("Your entered contents will be lost !! do you really want to continue?");

		if (confirmArrayChange == true)
		{
			var form = document.forms[0];
			//form.operation.value="CreateSpecimenArray";
			form.subOperation.value="ChangeArraytype";
			form.action = "SpecimenArray.do?menuSelected=20";
			form.submit();
		}
}

function doStoreTableData()
{
		var applet = document.applets[0];
		//alert(applet);
		if (applet != null)
		{
			applet.updateSessionData();
		}
}

function doUploadSpecimenArray()
{
		doStoreTableData();
		var form = document.forms[0];
		form.submit();
}

function createSpecimenArrayClicked()
{
		var form = document.forms[0];
		//form.operation.value="CreateSpecimenArray";
		form.subOperation.value="CreateSpecimenArray";
		form.action = "SpecimenArray.do?menuSelected=20";
		form.submit();
}

function doClickEnterSpecimenBy()
{
		var form = document.forms[0];
		var createSpecimenArrayVal = form.createSpecimenArray.value;
		if (createSpecimenArrayVal == "no")
		{
			return;
		}

		var confirmChange = confirm("Your entered Array Contents will be lost !! do you really want to continue?");
		if (confirmChange == true)
		{

			form.subOperation.value="ChangeEnterSpecimenBy";
			form.action = "SpecimenArray.do?menuSelected=20";
			form.submit();
		}
}
/* --- End Specimen Array javascript functions ---*/
<commit_msg>changes related to array function<commit_after>/* section for outer block start */
function replaceSpeChar(div,d1,searchChar)
{
	var y = d1.innerHTML;
	insno=insno+1;
	var starpos = y.indexOf(searchChar); // pos of 1st `.  ie: No.
	var adstr="";
	var c=0;
	for(c=0;c<starpos;c++)
	{
		adstr = y.replace(searchChar,insno);
		starpos = y.indexOf(searchChar);
		y = adstr;
	}
	addDiv(div,adstr);
}

/* section for outer block end */

function addDiv(div,adstr)
{
	var x = div.innerHTML;
	div.innerHTML = div.innerHTML +adstr;

}

function confirmDisable(action,formField)
{
	if((formField != undefined) && (formField.value == "Disabled"))
	{
		var go = confirm("Are you sure, you want to disable?");
		if (go==true)
		{
			document.forms[0].action = action;
			document.forms[0].submit();
		}
	}
	else
	{
		document.forms[0].action = action;
		document.forms[0].submit();
	}
}

function enableButton(formButton,countElement,checkName)
{
	/** number of rows present    **/
	var counts = countElement.value;
	if(counts == undefined){
		var cnt = document.getElementById(countElement);

	/** number of rows present(counts) when countElement is again element    **/
	counts = cnt.value;
	}
	/** checking whether checkbox is checked or not **/
	var status = false;

	for(var i=1;i <= counts;i++)
	{

		/** creating checkbox name**/
		var itemCheck = checkName+i;
		var chk = document.getElementById(itemCheck);
	        if (chk.checked == true)
	        {

	        	status = true;
	        	break;
	        }
	}
	if(status)
		formButton.disabled = false;
	else
		formButton.disabled = true;
}

function  deleteChecked(subdivtag,action,countElement,checkName,isOuterTable)
{
	var r = new Array();

	/** element of tbody    **/
	var element = document.getElementById(subdivtag);

	/** number of rows present    **/
	var counts = countElement.value;
	if(counts == undefined){
		var cnt = document.getElementById(countElement);

		/** number of rows present(counts) when countElement is again element    **/
		counts = cnt.value;
	}
	/** number if rows deleted**/
	var delCounts = 0;

	/** checking whether checkbox is checked or not **/
	var status = false;
	for(i=1;i <= counts;i++)
	{
		/** creating checkbox name**/
		itemCheck = checkName+i;
		var chk = document.getElementById(itemCheck);

		if(chk.checked==true){
			var pNode = null;
			var k = 0;

			/** condition for checking whether outerTable's delete is clicked or not **/
			if(isOuterTable) {
				tableId = "table_" + i;
				var table = document.getElementById(tableId);
				// md 21 mar start
				var currentRow = table.parentNode.parentNode;
				k = currentRow.rowIndex;
				pNode = element.parentNode;
				pNode.deleteRow(k);
				// md 21 mar end

				/** removing table from tbody tag(div)   **/
				// 21 mar commented by md: element.removeChild(table);

			}
			else {
				/** getting table ref from tbody    **/
				pNode = element.parentNode;

				/** curent row of table ref **/
				var currentRow = chk.parentNode.parentNode;
				k = currentRow.rowIndex;

				/** deleting row from table **/
				pNode.deleteRow(k);
			}

			delCounts++;
			status = true;

		}
	}

	if(countElement.value == undefined){
		/** setting number of rows present in form   **/
		cnt.value = counts - delCounts;
	}
	else
		/** setting number of rows present in form   **/
		countElement.value = (countElement.value - delCounts);

	if(status){
		/** set action when checkbox is clicked **/
		document.forms[0].action = action;
		document.forms[0].submit();
	}

}

	//Mandar: 24-Apr-06 for tooltip
		function showStatus(sMsg)
		{
		    window.status = sMsg ;
		}
		function showTip(objId)
		{

			var obj = document.getElementById(objId);
			var tip="";
			if(obj.selectedIndex == -1)
				tip="";
			else
				tip = obj.options[obj.selectedIndex].text;

			obj.title = tip;

			var browser=navigator.appName;
			if(browser=="Microsoft Internet Explorer")
			{
				showStatus(tip);
			}
		}
		function hideTip(objId)
		{
			var obj = document.getElementById(objId);
			obj.title = "";

			var browser=navigator.appName;
			if(browser=="Microsoft Internet Explorer")
			{
				showStatus(' ');
			}

		}

		function moveToNext(element,value,nextID )
		{
		if (value.length==element.maxLength)
			{
				document.getElementById(nextID).focus();
			}
		}

function rearrangeIdsForDistribution() {
       		var addMore =	document.getElementById("addMore");
			var tableRows = addMore.rows

			for(var i=0;i<tableRows.length;i++) {
			    var row  = tableRows[i];

			   // var childNodeCollection = row.all;
			    var childNodeCollection = row.cells;

				for(var j=0;j<childNodeCollection.length;j++) {

					   if( childNodeCollection[j].firstChild.nodeType == "3" )
						    continue;

						var idName = childNodeCollection[j].firstChild.id;

						if(idName == null || idName == "" ) {
                              idName =  childNodeCollection[j].firstChild.name;
						}

                        var newId = getNewId(idName,i+1);
						childNodeCollection[j].firstChild.name =  newId;
						childNodeCollection[j].firstChild.id =  newId;
				}
			}
		}

function getNewId(oldId,newRowNo) {

	if( oldId == "undefined" || oldId == null || oldId == ""  ) {
	 return oldId;
	}

if( oldId.indexOf(":") == -1) {
    newId =  oldId.substr(0,oldId.indexOf("_")+1) + newRowNo ;

} else {
	var firstPart =  oldId.substr(0,oldId.indexOf(":")) ;
	var thirdPart = oldId.substr(oldId.indexOf("_")) ;
	newId = firstPart + ":"+ newRowNo  + thirdPart ;
}

//alert(oldId + "====>" + newId );

/*	var firstPart = oldId.split(":")[0];
	var thirdPart = oldId.split("_")[1];

   var newId =  firstPart + ":"+ newRowNo + "_" + thirdPart ; */

   return  newId;
}

function disableDistributeOptions() {

	  var distributionForm =  document.forms[0];
	   if (  parseInt(document.forms[0].counter.value) == 0)
	   {

	   			  distributionForm.distributionBasedOn[0].disabled=false
				  distributionForm.distributionBasedOn[1].disabled=false;
				  distributionForm.distributionType[0].disabled = false;
				  distributionForm.distributionType[1].disabled = false;
				  return;
	   }

	 	if (distributionForm.distributionBasedOn[0].checked == true)
		 {
        	    distributionForm.distributionBasedOn[1].disabled=true
		 }

	 	if (distributionForm.distributionBasedOn[1].checked == true)
		 {
        	    distributionForm.distributionBasedOn[0].disabled=true
		 }

	 	if (distributionForm.distributionType[0].checked == true)
		 {
        	    distributionForm.distributionType[1].disabled=true
		 }

	 	if (distributionForm.distributionType[1].checked == true)
		 {
        	    distributionForm.distributionType[0].disabled=true
		 }
}

function checkDistributionBasedOn() {

	 	if (distributionForm.distributionBasedOn[0].checked == false && distributionForm.distributionBasedOn[1].checked == false) {
		 	 alert("Please select 'distribution based on'");
		 	 return false;
        }

        return true;
}

function  deleteCheckedNoSubmit(subdivtag,action,countElement,checkName,isOuterTable) {
	var r = new Array();

	/** element of tbody    **/
	var element = document.getElementById(subdivtag);

	/** number of rows present    **/
	var counts = countElement.value;
	if(counts == undefined){
		var cnt = document.getElementById(countElement);

		/** number of rows present(counts) when countElement is again element    **/
		counts = cnt.value;
	}
	/** number if rows deleted**/
	var delCounts = 0;

	/** checking whether checkbox is checked or not **/
	var status = false;
	for(i=1;i <= counts;i++)
	{
		itemCheck = checkName+i;
		var chk = document.getElementById(itemCheck);

		if(chk.checked==true){
			var pNode = null;
			var k = 0;

			/** condition for checking whether outerTable's delete is clicked or not **/
			if(isOuterTable) {
				tableId = "table_" + i;
				var table = document.getElementById(tableId);
				// md 21 mar start
				var currentRow = table.parentNode.parentNode;
				k = currentRow.rowIndex;
				pNode = element.parentNode;
				pNode.deleteRow(k);
				// md 21 mar end

				/** removing table from tbody tag(div)   **/
				// 21 mar commented by md: element.removeChild(table);

			}
			else {
				/** getting table ref from tbody    **/
				pNode = element.parentNode;

				/** curent row of table ref **/
				var currentRow = chk.parentNode.parentNode;
				k = currentRow.rowIndex;

				/** deleting row from table **/
				pNode.deleteRow(k);
			}

			delCounts++;
			status = true;

		}
	}

	if(countElement.value == undefined){
		/** setting number of rows present in form   **/
		cnt.value = counts - delCounts;
	}
	else
		/** setting number of rows present in form   **/
		countElement.value = (countElement.value - delCounts);

	return status;
}

function showCommentsDialog(operation,key) {
 		 var url ='NewMultipleSpecimenAction.do?method=showCommentsDialog&operation=' + operation+ '&specimenAttributeKey=' + key;
		 var properties = "height = 120; width:100px; Top:300; Left:350; center: Yes; resizable: no;status:no;help:no;toolbar :no";
   		 window.open(url,"caTissuecore", properties);
}

function submitComments()
{
  var form =  document.forms[0];
  form.action =  form.action + "?method=submitComments";
  form.submit();
}

/* --- Start Specimen Array javascript functions ---*/
function changeArrayType()
{
		var confirmArrayChange = confirm("Your entered contents will be lost !! do you really want to continue?");

		if (confirmArrayChange == true)
		{
			var form = document.forms[0];
			//form.operation.value="CreateSpecimenArray";
			form.subOperation.value="ChangeArraytype";
			form.action = "SpecimenArray.do?menuSelected=20";
			form.submit();
		}
}

function doStoreTableData()
{
		var applet = document.applets[0];
		//alert(applet);
		if (applet != null)
		{
			applet.updateSessionData();
		}
}

function doUploadSpecimenArray()
{
		doStoreTableData();
		var form = document.forms[0];
		form.submit();
}

function createSpecimenArrayClicked()
{
		var form = document.forms[0];
		var specimenArrayTypeVal = form.specimenArrayTypeId.value;
		if (specimenArrayTypeVal == -1)
		{
			alert("Please select Valid Specimen Array Type !!");
			return;
		}

		//form.operation.value="CreateSpecimenArray";
		form.subOperation.value="CreateSpecimenArray";
		form.action = "SpecimenArray.do?menuSelected=20";
		form.submit();
}

function doClickEnterSpecimenBy()
{
		var form = document.forms[0];
		var createSpecimenArrayVal = form.createSpecimenArray.value;
		if (createSpecimenArrayVal == "no")
		{
			return;
		}

		var confirmChange = confirm("Your entered Array Contents will be lost !! do you really want to continue?");
		if (confirmChange == true)
		{

			form.subOperation.value="ChangeEnterSpecimenBy";
			form.action = "SpecimenArray.do?menuSelected=20";
			form.submit();
		}
}
/* --- End Specimen Array javascript functions ---*/
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Sun Nov 04 2018 16:01:50 GMT+0100 (Mitteleuropäische Zeit)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      '*.js',
      {pattern: 'TestFiles/**/*.*', served: true, included: false}
    ],

    // list of files / patterns to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'trx'],
    trxReporter: {
      outputFile: 'Results.trx',
      shortTestName: true
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['ChromeHeadless'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}
<commit_msg>Use long test names for JS tests to distinguish them from .net tests<commit_after>// Karma configuration
// Generated on Sun Nov 04 2018 16:01:50 GMT+0100 (Mitteleuropäische Zeit)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      '*.js',
      {pattern: 'TestFiles/**/*.*', served: true, included: false}
    ],

    // list of files / patterns to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'trx'],
    trxReporter: {
      outputFile: 'Results.trx',
      shortTestName: false
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['ChromeHeadless'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}
<|endoftext|>


<commit_before>var fs = require("fs");
var path = require("path");
var esprima = require("../process/esprima/index");
var getVariables = require("../process/compile/variables");
var typescript = require("../process/typescript/typescript");
var check = function (root) {
    var rest = [].concat.apply([], arguments);
    var map = {
        "window": true,
        "document": true,
        "location": true,
        "navigator": true,
        "XMLHttpRequest": true,
        "history": true,
        "Image": true,
        "self": true,
        "modules": true,
        "init": true,
        "put": true,
        "state": true
    }, needs = {};
    var list = function () {
        Object.keys(needs).filter(k => !map[k]).forEach(function (k) {
            var key = k;
            if (!global[key]) console.log(key, needs[k]);
        });
    }
    var run = function () {
        if (!rest.length) return list();
        var fullpath = rest.pop();
        fs.access(fullpath, function (error) {
            if (error) return console.error(error);
            fs.stat(fullpath, function (error, stats) {
                if (error) return console.error(error);
                if (stats.isDirectory()) {
                    fs.readdir(fullpath, function (error, names) {
                        if (error) return console.error(error);
                        rest.push.apply(rest, names.map(n => path.join(fullpath, n)));
                        run();
                    });
                    return;
                }
                if (stats.isFile()) {
                    var basename = path.relative(root, fullpath);
                    basename = basename.replace(/[\\\/]/g, '$');
                    if (/\.json$/i.test(basename)) {
                        map[basename.replace(/\.json$/i, "")] = true;
                    }
                    if (/\.(html?|xml)$/i.test(basename)) {
                        map[path.basename(basename).replace(/\.(html?|xml)$/i, "")] = true;
                    }
                    if (!/\.[jt]sx?$/i.test(fullpath)) return run();
                    map[basename.replace(/\.[jt]sx?$/i, "")] = true;
                    fs.readFile(fullpath, function (error, data) {
                        if (error) return console.error(error);
                        try {
                            var jst = esprima.parse(typescript.transpile(String(data)));
                            var {
                                unDeclaredVariables: undeclares
                            } = getVariables(jst);
                            delete undeclares[path.basename(fullpath).replace(/\.[jt]sx?$/i, '')];
                            Object.keys(undeclares).map(k => k).forEach(k => {
                                if (!needs[k]) needs[k] = [];
                                needs[k].push(basename);
                            });
                        } catch (e) {
                            console.error(basename, String(e));
                        }
                        run();
                    });
                    return;
                }
                run();
            });
        });
    }
    run();
}
check('coms/zimoli');<commit_msg>添加screen全局变量<commit_after>var fs = require("fs");
var path = require("path");
var esprima = require("../process/esprima/index");
var getVariables = require("../process/compile/variables");
var typescript = require("../process/typescript/typescript");
var check = function (root) {
    var rest = [].concat.apply([], arguments);
    var map = {
        "screen": true,
        "window": true,
        "document": true,
        "location": true,
        "navigator": true,
        "XMLHttpRequest": true,
        "history": true,
        "Image": true,
        "self": true,
        "modules": true,
        "init": true,
        "put": true,
        "state": true
    }, needs = {};
    var list = function () {
        Object.keys(needs).filter(k => !map[k]).forEach(function (k) {
            var key = k;
            if (!global[key]) console.log(key, needs[k]);
        });
    }
    var run = function () {
        if (!rest.length) return list();
        var fullpath = rest.pop();
        fs.access(fullpath, function (error) {
            if (error) return console.error(error);
            fs.stat(fullpath, function (error, stats) {
                if (error) return console.error(error);
                if (stats.isDirectory()) {
                    fs.readdir(fullpath, function (error, names) {
                        if (error) return console.error(error);
                        rest.push.apply(rest, names.map(n => path.join(fullpath, n)));
                        run();
                    });
                    return;
                }
                if (stats.isFile()) {
                    var basename = path.relative(root, fullpath);
                    basename = basename.replace(/[\\\/]/g, '$');
                    if (/\.json$/i.test(basename)) {
                        map[basename.replace(/\.json$/i, "")] = true;
                    }
                    if (/\.(html?|xml)$/i.test(basename)) {
                        map[path.basename(basename).replace(/\.(html?|xml)$/i, "")] = true;
                    }
                    if (!/\.[jt]sx?$/i.test(fullpath)) return run();
                    map[basename.replace(/\.[jt]sx?$/i, "")] = true;
                    fs.readFile(fullpath, function (error, data) {
                        if (error) return console.error(error);
                        try {
                            var jst = esprima.parse(typescript.transpile(String(data)));
                            var {
                                unDeclaredVariables: undeclares
                            } = getVariables(jst);
                            delete undeclares[path.basename(fullpath).replace(/\.[jt]sx?$/i, '')];
                            Object.keys(undeclares).map(k => k).forEach(k => {
                                if (!needs[k]) needs[k] = [];
                                needs[k].push(basename);
                            });
                        } catch (e) {
                            console.error(basename, String(e));
                        }
                        run();
                    });
                    return;
                }
                run();
            });
        });
    }
    run();
}
check('coms/zimoli');<|endoftext|>


<commit_before>import expect from 'must';
import Action from '../../lib/runtime/action';
import merge from 'lodash/merge';

function mockReqRes(overrides) {
  return merge({
    request: {
      get(headerName) {
        return this.headers && this.headers[headerName.toLowerCase()];
      },
      headers: {
        'content-type': 'application/json'
      },
      query: {},
      body: {}
    },
    response: {
      render() {}
    },
    next() {}
  }, overrides);
}

describe('Denali.Action', function() {
  it('should invoke respond() with params', function() {
    let responded = false;
    class TestAction extends Action {
      respond(params) {
        expect(params.query).to.be.true();
        expect(params.body).to.be.true();
        responded = true;
      }
    }
    let action = new TestAction(mockReqRes({
      request: {
        query: { query: true },
        body: { body: true }
      }
    }));

    return action.run().then(() => {
      expect(responded).to.be.true();
    });
  });

  it('should proxy this.render() to response.render()', function() {
    let rendered = false;
    class TestAction extends Action {
      respond() {
        this.render(true);
      }
    }
    let action = new TestAction(mockReqRes({
      response: {
        render() {
          rendered = true;
        }
      }
    }));

    return action.run().then(() => {
      expect(rendered).to.be.true();
    });
  });

  describe('filters', function() {

    it('should invoke before filters prior to respond()', function() {
      let sequence = [];
      class TestAction extends Action {
        before() {
          sequence.push('before');
        }

        respond() {
          sequence.push('respond');
        }

        after() {
          sequence.push('after');
        }
      }
      let action = new TestAction(mockReqRes());

      return action.run().then(() => {
        expect(sequence).to.eql([ 'before', 'respond', 'after' ]);
      });
    });

    it('should invoke superclass filters before subclass filters', function() {
      let sequence = [];
      class ParentClass extends Action {
        before() {
          sequence.push('parent');
        }

        respond() {}
      }
      class ChildClass extends ParentClass {
        before() {
          sequence.push('child');
        }
      }
      let action = new ChildClass(mockReqRes());

      return action.run().then(() => {
        expect(sequence).to.eql([ 'parent', 'child' ]);
      });
    });

  });

  describe('content negotiation', function() {

    it('should respond with the content-type specific responder', function() {
      let responded = false;
      class TestAction extends Action {
        respond() {}
        respondWithHtml() {
          responded = true;
        }
      }
      let action = new TestAction(mockReqRes({
        request: {
          headers: {
            'Content-type': 'text/html'
          },
          accepts() {
            return 'html';
          }
        }
      }));

      return action.run().then(() => {
        expect(responded).to.be.true();
      });
    });

  });

  describe('when render is not called', function() {

    it('should autorender', function() {
      let rendered;
      class TestAction extends Action {
        respond() {
          return { foo: 'bar' };
        }
      }
      let action = new TestAction(mockReqRes({
        response: {
          render(result) {
            rendered = result;
          }
        }
      }));

      return action.run().then(() => {
        expect(rendered).to.eql({ foo: 'bar' });
      });
    });

  });

});
<commit_msg>noop response.end function for tests<commit_after>import expect from 'must';
import Action from '../../lib/runtime/action';
import merge from 'lodash/merge';

function mockReqRes(overrides) {
  return merge({
    request: {
      get(headerName) {
        return this.headers && this.headers[headerName.toLowerCase()];
      },
      headers: {
        'content-type': 'application/json'
      },
      query: {},
      body: {}
    },
    response: {
      render() {},
      end() {}
    },
    next() {}
  }, overrides);
}

describe('Denali.Action', function() {
  it('should invoke respond() with params', function() {
    let responded = false;
    class TestAction extends Action {
      respond(params) {
        expect(params.query).to.be.true();
        expect(params.body).to.be.true();
        responded = true;
      }
    }
    let action = new TestAction(mockReqRes({
      request: {
        query: { query: true },
        body: { body: true }
      }
    }));

    return action.run().then(() => {
      expect(responded).to.be.true();
    });
  });

  it('should proxy this.render() to response.render()', function() {
    let rendered = false;
    class TestAction extends Action {
      respond() {
        this.render(true);
      }
    }
    let action = new TestAction(mockReqRes({
      response: {
        render() {
          rendered = true;
        }
      }
    }));

    return action.run().then(() => {
      expect(rendered).to.be.true();
    });
  });

  describe('filters', function() {

    it('should invoke before filters prior to respond()', function() {
      let sequence = [];
      class TestAction extends Action {
        before() {
          sequence.push('before');
        }

        respond() {
          sequence.push('respond');
        }

        after() {
          sequence.push('after');
        }
      }
      let action = new TestAction(mockReqRes());

      return action.run().then(() => {
        expect(sequence).to.eql([ 'before', 'respond', 'after' ]);
      });
    });

    it('should invoke superclass filters before subclass filters', function() {
      let sequence = [];
      class ParentClass extends Action {
        before() {
          sequence.push('parent');
        }

        respond() {}
      }
      class ChildClass extends ParentClass {
        before() {
          sequence.push('child');
        }
      }
      let action = new ChildClass(mockReqRes());

      return action.run().then(() => {
        expect(sequence).to.eql([ 'parent', 'child' ]);
      });
    });

  });

  describe('content negotiation', function() {

    it('should respond with the content-type specific responder', function() {
      let responded = false;
      class TestAction extends Action {
        respond() {}
        respondWithHtml() {
          responded = true;
        }
      }
      let action = new TestAction(mockReqRes({
        request: {
          headers: {
            'Content-type': 'text/html'
          },
          accepts() {
            return 'html';
          }
        }
      }));

      return action.run().then(() => {
        expect(responded).to.be.true();
      });
    });

  });

  describe('when render is not called', function() {

    it('should autorender', function() {
      let rendered;
      class TestAction extends Action {
        respond() {
          return { foo: 'bar' };
        }
      }
      let action = new TestAction(mockReqRes({
        response: {
          render(result) {
            rendered = result;
          }
        }
      }));

      return action.run().then(() => {
        expect(rendered).to.eql({ foo: 'bar' });
      });
    });

  });

});
<|endoftext|>


<commit_before>import {
  normalizeControllerQueryParams
} from '../utils';

QUnit.module('Routing query parameter utils - normalizeControllerQueryParams');

QUnit.test('converts array style into verbose object style', function(assert) {
  let paramName = 'foo';
  let params = [paramName];
  let normalized = normalizeControllerQueryParams(params);

  ok(normalized[paramName], 'turns the query param name into key');
  equal(normalized[paramName].as, null, 'includes a blank alias in \'as\' key');
  equal(normalized[paramName].scope, 'model', 'defaults scope to model');
});

QUnit.test('converts object stlye [{foo: \'an_alias\'}]', function(assert) {
  let paramName = 'foo';
  let params = [{ 'foo': 'an_alias' }];
  let normalized = normalizeControllerQueryParams(params);

  ok(normalized[paramName], 'retains the query param name as key');
  equal(normalized[paramName].as, 'an_alias', 'includes the provided alias in \'as\' key');
  equal(normalized[paramName].scope, 'model', 'defaults scope to model');
});

QUnit.test('retains maximally verbose object stlye [{foo: {as: \'foo\'}}]', function(assert) {
  let paramName = 'foo';
  let params = [{ 'foo': { as: 'an_alias' } }];
  let normalized = normalizeControllerQueryParams(params);

  ok(normalized[paramName], 'retains the query param name as key');
  equal(normalized[paramName].as, 'an_alias', 'includes the provided alias in \'as\' key');
  equal(normalized[paramName].scope, 'model', 'defaults scope to model');
});
<commit_msg>fix typo in test description<commit_after>import {
  normalizeControllerQueryParams
} from '../utils';

QUnit.module('Routing query parameter utils - normalizeControllerQueryParams');

QUnit.test('converts array style into verbose object style', function(assert) {
  let paramName = 'foo';
  let params = [paramName];
  let normalized = normalizeControllerQueryParams(params);

  ok(normalized[paramName], 'turns the query param name into key');
  equal(normalized[paramName].as, null, 'includes a blank alias in \'as\' key');
  equal(normalized[paramName].scope, 'model', 'defaults scope to model');
});

QUnit.test('converts object style [{foo: \'an_alias\'}]', function(assert) {
  let paramName = 'foo';
  let params = [{ 'foo': 'an_alias' }];
  let normalized = normalizeControllerQueryParams(params);

  ok(normalized[paramName], 'retains the query param name as key');
  equal(normalized[paramName].as, 'an_alias', 'includes the provided alias in \'as\' key');
  equal(normalized[paramName].scope, 'model', 'defaults scope to model');
});

QUnit.test('retains maximally verbose object style [{foo: {as: \'foo\'}}]', function(assert) {
  let paramName = 'foo';
  let params = [{ 'foo': { as: 'an_alias' } }];
  let normalized = normalizeControllerQueryParams(params);

  ok(normalized[paramName], 'retains the query param name as key');
  equal(normalized[paramName].as, 'an_alias', 'includes the provided alias in \'as\' key');
  equal(normalized[paramName].scope, 'model', 'defaults scope to model');
});
<|endoftext|>


<commit_before>'use strict'
describe('getSpinner()', () => {
  let getSpinner, ora

  beforeEach(() => {
    ({ getSpinner, ora } = require('./helpers').loadLib())
  })

  it('should return the spinner', () => {
    expect(getSpinner()).toBe(ora)
  })
})
<commit_msg>refactor(test): Remove getSpinner() tests<commit_after><|endoftext|>


<commit_before>//  "use strict";
var VERBOSE = "VERBOSE" in process.env;
var TESTS = "TESTS" in process.env ? process.env.TESTS.split(/\|/) : null;

var ShExParser = require("../lib/ShExParser").Parser;
var ShExValidator = require("../lib/ShExValidator");

var N3 = require("n3");
var turtleParser = N3.Parser();
var fs = require("fs");
var path = require("path");
var expect = require("chai").expect;
var assert = require("chai").assert;
var findPath = require("./findPath.js");

var schemasPath = findPath("schemas");
var validationsPath = findPath("validations");
var manifestFile = validationsPath+"manifest.jsonld";
var negSyntaxTestsPath = findPath("negativeSyntax");

describe("A ShEx validator", function () {
  // var b = function () {  };
  // it("is a toy", function () {
  //   expect({a:1, b: b}).to.deep.equal({a:1, b: b});
  // });

  var shexParser = new ShExParser();
  // Ensure the same blank node identifiers are used in every test
  beforeEach(function () {
    shexParser._resetBlanks();
  });

  var tests = parseJSONFile(manifestFile)["@graph"][0]["mf:entries"];

  if (TESTS)
    tests = tests.filter(function (t) {
      return TESTS.indexOf(t["@id"]) !== -1 ||
        TESTS.indexOf(t["@id"].substr(1)) !== -1 ||
        TESTS.indexOf(t.schema) !== -1 ||
        TESTS.indexOf(t.data) !== -1 ||
        TESTS.indexOf(t.result) !== -1;
    });

  tests.forEach(function (test) {
    try {
      var schemaFile = path.join(schemasPath, test.schema);
      var dataFile = path.join(validationsPath, test.data);
      var resultsFile = test.result ? path.join(validationsPath, test.result) : null;
      var schema = shexParser.parse(fs.readFileSync(schemaFile, "utf8"));
      var referenceResult = resultsFile ? parseJSONFile(resultsFile) : null;

      assert(referenceResult !== null || test["@type"] === "sht:ValidationFailure");
      // var start = schema.start;
      // if (start === undefined && Object.keys(schema.shapes).length === 1)
      //   start = Object.keys(schema.shapes)[0];

      it("should validate data '" + (VERBOSE ? dataFile : test.data) + // test title
         "' against schema '" + (VERBOSE ? schemaFile : test.schema) +
         "' and get '" + (VERBOSE ? resultsFile : test.result) + "'." ,
         function (report) {                                             // test action
           var store = N3.Store();
           var validator = ShExValidator(schema);  // @@ Why does a validator fail when constructed outside the call to it()?!
           turtleParser.parse(
             fs.readFileSync(dataFile, "utf8"),
             function (error, triple, prefixes) {
               if (error) {
                 report("error parsing " + dataFile + ": " + error);
               } else if (triple) {
                 store.addTriple(triple)
               } else {
                 try {
                   var validationResult = validator.validate(store, test.focus, test.shape);
                   if (VERBOSE) console.log("result   :" + JSON.stringify(validationResult));
                   if (VERBOSE) console.log("expected :" + JSON.stringify(referenceResult));
                   expect(validationResult).to.deep.equal(referenceResult);
                   report();
                 } catch (e) {
                   report(e);
                 }
               }
             });
         });
    } catch (e) {
      throw new Error("in "+test["@id"]+" "+e);
    }
  });
});

// Parses a JSON object, restoring `undefined` values
function parseJSONFile(filename) {
  try {
    var string = fs.readFileSync(filename, "utf8");
    var object = JSON.parse(string);
    return /"\{undefined\}"/.test(string) ? restoreUndefined(object) : object;
  } catch (e) {
    throw new Error("error reading " + filename + ": " + e);
  }
}

// Recursively replace values of "{undefined}" by `undefined`
function restoreUndefined(object) {
  for (var key in object) {
    var item = object[key];
    if (typeof item === "object")
      object[key] = restoreUndefined(item);
    else if (item === "{undefined}")
      object[key] = undefined;
  }
  return object;
}
<commit_msg>+ adopt shacl test suite<commit_after>//  "use strict";
var VERBOSE = "VERBOSE" in process.env;
var TESTS = "TESTS" in process.env ? process.env.TESTS.split(/\|/) : null;

var ShExParser = require("../lib/ShExParser").Parser;
var ShExValidator = require("../lib/ShExValidator");

var N3 = require("n3");
var turtleParser = N3.Parser();
var fs = require("fs");
var path = require("path");
var expect = require("chai").expect;
var assert = require("chai").assert;
var findPath = require("./findPath.js");

var schemasPath = findPath("schemas");
var validationsPath = findPath("validations");
var manifestFile = validationsPath+"manifest.jsonld";
var negSyntaxTestsPath = findPath("negativeSyntax");

describe("A ShEx validator", function () {
  // var b = function () {  };
  // it("is a toy", function () {
  //   expect({a:1, b: b}).to.deep.equal({a:1, b: b});
  // });

  var shexParser = new ShExParser();
  // Ensure the same blank node identifiers are used in every test
  beforeEach(function () {
    shexParser._resetBlanks();
  });

  var tests = parseJSONFile(manifestFile)["@graph"][0]["mf:entries"];

  if (TESTS)
    tests = tests.filter(function (t) {
      return TESTS.indexOf(t["@id"]) !== -1 ||
        TESTS.indexOf(t["@id"].substr(1)) !== -1 ||
        TESTS.indexOf(t.action.schema) !== -1 ||
        TESTS.indexOf(t.action.data) !== -1 ||
        TESTS.indexOf(t.result) !== -1;
    });

  tests.forEach(function (test) {
    try {
      var schemaFile = path.join(schemasPath, test.action.schema);
      var dataFile = path.join(validationsPath, test.action.data);
      var resultsFile = test.result ? path.join(validationsPath, test.result) : null;
      var schema = shexParser.parse(fs.readFileSync(schemaFile, "utf8"));
      var referenceResult = resultsFile ? parseJSONFile(resultsFile) : null;

      assert(referenceResult !== null || test["@type"] === "sht:ValidationFailure");
      // var start = schema.start;
      // if (start === undefined && Object.keys(schema.action.shapes).length === 1)
      //   start = Object.keys(schema.action.shapes)[0];

      it("should validate data '" + (VERBOSE ? dataFile : test.action.data) + // test title
         "' against schema '" + (VERBOSE ? schemaFile : test.action.schema) +
         "' and get '" + (VERBOSE ? resultsFile : test.result) + "'." ,
         function (report) {                                             // test action
           var store = N3.Store();
           var validator = ShExValidator(schema, {diagnose:true});  // @@ Why does a validator fail when constructed outside the call to it()?!
           turtleParser.parse(
             fs.readFileSync(dataFile, "utf8"),
             function (error, triple, prefixes) {
               if (error) {
                 report("error parsing " + dataFile + ": " + error);
               } else if (triple) {
                 store.addTriple(triple)
               } else {
                 try {
                   var validationResult = validator.validate(store, test.action.focus, test.action.shape);
                   if (VERBOSE) console.log("result   :" + JSON.stringify(validationResult));
                   if (VERBOSE) console.log("expected :" + JSON.stringify(referenceResult));
                   expect(validationResult).to.deep.equal(referenceResult);
                   report();
                 } catch (e) {
                   report(e);
                 }
               }
             });
         });
    } catch (e) {
      throw new Error("in "+test["@id"]+" "+e);
    }
  });
});

// Parses a JSON object, restoring `undefined` values
function parseJSONFile(filename) {
  try {
    var string = fs.readFileSync(filename, "utf8");
    var object = JSON.parse(string);
    return /"\{undefined\}"/.test(string) ? restoreUndefined(object) : object;
  } catch (e) {
    throw new Error("error reading " + filename + ": " + e);
  }
}

// Recursively replace values of "{undefined}" by `undefined`
function restoreUndefined(object) {
  for (var key in object) {
    var item = object[key];
    if (typeof item === "object")
      object[key] = restoreUndefined(item);
    else if (item === "{undefined}")
      object[key] = undefined;
  }
  return object;
}
<|endoftext|>


<commit_before>"use strict";

var request = require("request");
var cheerio = require("cheerio");
var async = require("async");
var applicationStorage = process.require("core/applicationStorage.js");
var mythicDungeonModel = process.require("mythicDungeons/mythicDungeonModel.js");

module.exports.getRuns = function (realm, dungeon, realmsSlugArray, callback) {
    var self = this;
    async.waterfall([
        function (callback) {
            self.getPage(realm.region, realm.bnet.slug, dungeon.slug, function (error, body) {
                callback(error, body);
            });
        }, function (body, callback) {
            self.parsePage(body, realmsSlugArray, dungeon, realm, function (error, runs, affixes) {
                callback(error, runs, affixes);
            });
        }, function (runs, affixes, callback) {
            self.insertRuns(runs, affixes, dungeon, realm, function (error) {
                callback(error);
            });
        }
    ], function (error) {
        callback(error);
    });
};

module.exports.getPage = function (region, realmSlug, dungeonSlug, callback) {
    var logger = applicationStorage.logger;

    var regionSlug = region == "us" ? "en_us" : "en_gb";

    var url = "https://worldofwarcraft.com/" + regionSlug + "/game/pve/leaderboards/" + realmSlug + "/" + dungeonSlug;

    request.get({method: "GET", uri: url, gzip: true}, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            logger.info("Success on " + url);

            callback(null, body);
        } else if (!error) {
            error = new Error("Error HTTP " + response.statusCode + " on fetching bnet site " + url);
            error.statusCode = response.statusCode;
            callback(error);
        }
        else {
            callback(error);
        }
    });
};

module.exports.parsePage = function (body, realmsSlugArray, dungeon, realm, callback) {
    var logger = applicationStorage.logger;

    var $ = cheerio.load(body);

    var affixes = [];
    $('.Box.Box--leather.Box--flush.bordered .List.List--vertical .List-item .font-semp-medium-white').each(function () {
        affixes.push($(this).text());
    });

    if (affixes.length != 3) {
        return callback(new Error("Cannot found 3 affixes"));
    }
    var runs = [];
    $('.Pagination-page .SortTable-body .SortTable-row').each(function () {
        var run = {};
        var count = 0;
        $(this).find(".SortTable-col").each(function () {
            if (count == 1) {
                run.level = parseInt($(this).attr("data-value"), 10);
            }
            if (count == 2) {
                run.time = parseInt($(this).attr("data-value"), 10);
            }
            if (count == 3) {
                run.faction = $(this).attr("data-value") == "alliance" ? 0 : 1;
                run.roster = [];
                var connectedRealms = [];
                $(this).find(".List-item.gutter-tiny").each(function () {
                    var character = {};

                    //FIND CLASS
                    var classe = $(this).find("a").attr("class");
                    if (classe.indexOf("WARRIOR") != -1) {
                        character.class = 1;
                    } else if (classe.indexOf("PALADIN") != -1) {
                        character.class = 2;
                    } else if (classe.indexOf("DEMONHUNTER") != -1) {
                        character.class = 12;
                    } else if (classe.indexOf("HUNTER") != -1) {
                        character.class = 3;
                    } else if (classe.indexOf("ROGUE") != -1) {
                        character.class = 4;
                    } else if (classe.indexOf("PRIEST") != -1) {
                        character.class = 5;
                    } else if (classe.indexOf("DEATHKNIGHT") != -1) {
                        character.class = 6;
                    } else if (classe.indexOf("SHAMAN") != -1) {
                        character.class = 7;
                    } else if (classe.indexOf("MAGE") != -1) {
                        character.class = 8;
                    } else if (classe.indexOf("WARLOCK") != -1) {
                        character.class = 9;
                    } else if (classe.indexOf("MONK") != -1) {
                        character.class = 10;
                    } else if (classe.indexOf("DRUID") != -1) {
                        character.class = 11;
                    } else {
                        logger.error("Character Class not found");
                    }

                    //FIND ROLE
                    var role = $(this).find(".Character-role span").attr("class");
                    if (role) {
                        if (role.indexOf("tank") != -1) {
                            character.role = "tank";
                        } else if (role.indexOf("healer") != -1) {
                            character.role = "healer";
                        }
                    } else {
                        character.role = "dps";
                    }

                    //FIND REALM
                    var slug = $(this).find("a").attr("href").split('/')[6];

                    character.realm = realmsSlugArray[realm.region][slug].name;
                    connectedRealms.push(realmsSlugArray[realm.region][slug].connected_realms);

                    //FIND NAME
                    character.name = $(this).text();
                    run.roster.push(character);
                });

                //Insert realm only when 4 characters are from the same
                var objs = [];
                connectedRealms.forEach(function (connectedRealm) {
                    if (objs[connectedRealm.join("")] == null) {
                        objs[connectedRealm.join("")] = 0;
                    }
                    objs[connectedRealm.join("")]++;
                    if (objs[connectedRealm.join("")] >= 4) {
                        run.realms = connectedRealm;
                    }
                });

            }
            if (count == 4) {
                run.date = Date.parse($(this).attr("data-value"));
            }

            count++;
        });

        if (run.time < dungeon.time) {
            runs.push(run);
        } else {
            logger.verbose("Run not valid " + run.time + ">" + dungeon.time);
        }
    });

    callback(null, runs, affixes);
};

module.exports.insertRuns = function (runs, affixes, dungeon, realm, callback) {
    var logger = applicationStorage.logger;

    async.forEachSeries(runs, function (run, callback) {

        run.dungeon = dungeon.name;
        run.region = realm.region;
        run.affixes = affixes;

        var obj = {dungeon: run.dungeon, level: run.level, region: run.region, time: run.time, date: run.date};
        mythicDungeonModel.findOne("legion", obj, function (error, result) {
            if (result) {
                logger.info("Run for dungeon %s level:%s region:%s time:%s date:%s already exist, skip it", run.dungeon, run.level, run.region, run.time, run.date);
                callback();
            } else {
                logger.info("Insert run for dungeon %s level:%s region:%s time:%s date:%s", run.dungeon, run.level, run.region, realm.name, run.time, run.date);
                mythicDungeonModel.insertOne("legion", run, function (error) {
                    callback(error);
                });

            }
        });

    }, function (error) {
        callback(error);
    })

};
<commit_msg>Remove excesive log<commit_after>"use strict";

var request = require("request");
var cheerio = require("cheerio");
var async = require("async");
var applicationStorage = process.require("core/applicationStorage.js");
var mythicDungeonModel = process.require("mythicDungeons/mythicDungeonModel.js");

module.exports.getRuns = function (realm, dungeon, realmsSlugArray, callback) {
    var self = this;
    async.waterfall([
        function (callback) {
            self.getPage(realm.region, realm.bnet.slug, dungeon.slug, function (error, body) {
                callback(error, body);
            });
        }, function (body, callback) {
            self.parsePage(body, realmsSlugArray, dungeon, realm, function (error, runs, affixes) {
                callback(error, runs, affixes);
            });
        }, function (runs, affixes, callback) {
            self.insertRuns(runs, affixes, dungeon, realm, function (error) {
                callback(error);
            });
        }
    ], function (error) {
        callback(error);
    });
};

module.exports.getPage = function (region, realmSlug, dungeonSlug, callback) {
    var logger = applicationStorage.logger;

    var regionSlug = region == "us" ? "en_us" : "en_gb";

    var url = "https://worldofwarcraft.com/" + regionSlug + "/game/pve/leaderboards/" + realmSlug + "/" + dungeonSlug;

    request.get({method: "GET", uri: url, gzip: true}, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            logger.info("Success on " + url);

            callback(null, body);
        } else if (!error) {
            error = new Error("Error HTTP " + response.statusCode + " on fetching bnet site " + url);
            error.statusCode = response.statusCode;
            callback(error);
        }
        else {
            callback(error);
        }
    });
};

module.exports.parsePage = function (body, realmsSlugArray, dungeon, realm, callback) {
    var logger = applicationStorage.logger;

    var $ = cheerio.load(body);

    var affixes = [];
    $('.Box.Box--leather.Box--flush.bordered .List.List--vertical .List-item .font-semp-medium-white').each(function () {
        affixes.push($(this).text());
    });

    if (affixes.length != 3) {
        return callback(new Error("Cannot found 3 affixes"));
    }
    var runs = [];
    $('.Pagination-page .SortTable-body .SortTable-row').each(function () {
        var run = {};
        var count = 0;
        $(this).find(".SortTable-col").each(function () {
            if (count == 1) {
                run.level = parseInt($(this).attr("data-value"), 10);
            }
            if (count == 2) {
                run.time = parseInt($(this).attr("data-value"), 10);
            }
            if (count == 3) {
                run.faction = $(this).attr("data-value") == "alliance" ? 0 : 1;
                run.roster = [];
                var connectedRealms = [];
                $(this).find(".List-item.gutter-tiny").each(function () {
                    var character = {};

                    //FIND CLASS
                    var classe = $(this).find("a").attr("class");
                    if (classe.indexOf("WARRIOR") != -1) {
                        character.class = 1;
                    } else if (classe.indexOf("PALADIN") != -1) {
                        character.class = 2;
                    } else if (classe.indexOf("DEMONHUNTER") != -1) {
                        character.class = 12;
                    } else if (classe.indexOf("HUNTER") != -1) {
                        character.class = 3;
                    } else if (classe.indexOf("ROGUE") != -1) {
                        character.class = 4;
                    } else if (classe.indexOf("PRIEST") != -1) {
                        character.class = 5;
                    } else if (classe.indexOf("DEATHKNIGHT") != -1) {
                        character.class = 6;
                    } else if (classe.indexOf("SHAMAN") != -1) {
                        character.class = 7;
                    } else if (classe.indexOf("MAGE") != -1) {
                        character.class = 8;
                    } else if (classe.indexOf("WARLOCK") != -1) {
                        character.class = 9;
                    } else if (classe.indexOf("MONK") != -1) {
                        character.class = 10;
                    } else if (classe.indexOf("DRUID") != -1) {
                        character.class = 11;
                    } else {
                        logger.error("Character Class not found");
                    }

                    //FIND ROLE
                    var role = $(this).find(".Character-role span").attr("class");
                    if (role) {
                        if (role.indexOf("tank") != -1) {
                            character.role = "tank";
                        } else if (role.indexOf("healer") != -1) {
                            character.role = "healer";
                        }
                    } else {
                        character.role = "dps";
                    }

                    //FIND REALM
                    var slug = $(this).find("a").attr("href").split('/')[6];

                    character.realm = realmsSlugArray[realm.region][slug].name;
                    connectedRealms.push(realmsSlugArray[realm.region][slug].connected_realms);

                    //FIND NAME
                    character.name = $(this).text();
                    run.roster.push(character);
                });

                //Insert realm only when 4 characters are from the same
                var objs = [];
                connectedRealms.forEach(function (connectedRealm) {
                    if (objs[connectedRealm.join("")] == null) {
                        objs[connectedRealm.join("")] = 0;
                    }
                    objs[connectedRealm.join("")]++;
                    if (objs[connectedRealm.join("")] >= 4) {
                        run.realms = connectedRealm;
                    }
                });

            }
            if (count == 4) {
                run.date = Date.parse($(this).attr("data-value"));
            }

            count++;
        });

        if (run.time < dungeon.time) {
            runs.push(run);
        } else {
            logger.verbose("Run not valid " + run.time + ">" + dungeon.time);
        }
    });

    callback(null, runs, affixes);
};

module.exports.insertRuns = function (runs, affixes, dungeon, realm, callback) {
    var logger = applicationStorage.logger;

    async.forEachSeries(runs, function (run, callback) {

        run.dungeon = dungeon.name;
        run.region = realm.region;
        run.affixes = affixes;

        var obj = {dungeon: run.dungeon, level: run.level, region: run.region, time: run.time, date: run.date};
        mythicDungeonModel.findOne("legion", obj, function (error, result) {
            if (result) {
                logger.verbose("Run for dungeon %s level:%s region:%s time:%s date:%s already exist, skip it", run.dungeon, run.level, run.region, run.time, run.date);
                callback();
            } else {
                logger.info("Insert run for dungeon %s level:%s region:%s time:%s date:%s", run.dungeon, run.level, run.region, realm.name, run.time, run.date);
                mythicDungeonModel.insertOne("legion", run, function (error) {
                    callback(error);
                });

            }
        });

    }, function (error) {
        callback(error);
    })

};
<|endoftext|>


<commit_before>import React from 'react'

import Checkbox from 'src/modules/Checkbox/Checkbox'
import * as common from 'test/specs/commonTests'

describe('Checkbox', () => {
  common.isConformant(Checkbox)
  common.hasUIClassName(Checkbox)
  common.rendersChildren(Checkbox)

  it('can be checked by default', () => {
    deprecatedRender(<Checkbox defaultChecked name='firstName' />)
      .findTag('input')
      .checked.should.equal(true)
  })
  it('should have a semantic ui plugin to handle the check action', () => {
    deprecatedRender(<Checkbox name='firstName' label='Include First' />)
      .first()
      .element.checkbox.called.should.equal(true)
  })
  it('should have a fitted class if no label is given', () => {
    deprecatedRender(<Checkbox name='firstName' />).findClass('fitted')
  })
})
<commit_msg>test(Checkbox): use enzyme<commit_after>import React from 'react'

import Checkbox from 'src/modules/Checkbox/Checkbox'
import * as common from 'test/specs/commonTests'

describe('Checkbox', () => {
  common.isConformant(Checkbox)
  common.hasUIClassName(Checkbox)
  common.rendersChildren(Checkbox)

  it('can be checked by default', () => {
    shallow(<Checkbox defaultChecked name='firstName' />)
      .find('input')
      .should.be.checked()
  })
  it('should init the semantic ui plugin', () => {
    mount(<Checkbox />)
      .instance()
      // the component exposes the jQuery element as 'element'
      // 'checkbox' is the jQuery plugin
      .element.checkbox.called.should.equal(true)
  })
  it('should have a fitted class if no label is given', () => {
    shallow(<Checkbox name='firstName' />)
      .should.have.className('fitted')
  })
})
<|endoftext|>


<commit_before>/**
 * Author: petar bojinov - @pbojinov
 * Date: 04/03/15
 */

'use strict';

/**
 * Get client IP address
 *
 * Will return 127.0.0.1 when testing locally
 * Useful when you need the user ip for geolocation or serving localized content
 *
 * @method getClientIp
 * @param req
 * @returns {string} ip
 */
function getClientIp(req) {

    // the ipAddress we return
    var ipAddress;

    // workaround to get real client IP
    // most likely because our app will be behind a [reverse] proxy or load balancer
    var clientIp = req.headers['x-client-ip'],
        forwardedForAlt = req.headers['x-forwarded-for'],
        realIp = req.headers['x-real-ip'],
        // more obsure ones below
        clusterClientIp = req.headers['x-cluster-client-ip'],
        forwardedAlt = req.headers['x-forwarded'],
        forwardedFor = req.headers['forwarded-for'],
        forwarded = req.headers['forwarded'];

    // x-client-ip
    if (clientIp) {
        ipAddress = clientIp;
    }

    // x-forwarded-for
    else if (forwardedForAlt) {
        // x-forwarded-for header is more common
        // it may return multiple IP addresses in the format:
        // "client IP, proxy 1 IP, proxy 2 IP"
        // we pick the first one
        var forwardedIps = forwardedForAlt.split(',');
        ipAddress = forwardedIps[0];
    }

    // x-real-ip
    // (default nginx proxy/fcgi)
    else if (realIp) {
        // alternative to x-forwarded-for
        // used by some proxies
        ipAddress = realIp;
    }

    // x-cluster-client-ip
    // (Rackspace LB and Riverbed's Stingray)
    // http://www.rackspace.com/knowledge_center/article/controlling-access-to-linux-cloud-sites-based-on-the-client-ip-address
    // https://splash.riverbed.com/docs/DOC-1926
    else if (clusterClientIp) {
        ipAddress = clusterClientIp;
    }

    // x-forwarded
    else if (forwardedAlt) {
        ipAddress = forwardedAlt;
    }

    // forwarded-for
    else if (forwardedFor) {
        ipAddress = forwardedFor;
    }

    // forwarded
    else if (forwarded) {
        ipAddress = forwarded;
    }

    // fallback to something
    if (!ipAddress) {
        // ensure getting client IP address still works in development environment
        // if despite all this we do not find ip, then it returns null
        try {
            ipAddress = req.connection.remoteAddress ||
                req.socket.remoteAddress ||
                req.connection.socket.remoteAddress || // for https
                null;
        } catch(e) {
            ipAddress = null;
        }
    }

    return ipAddress;
}

/**
 * Expose mode public functions
 */
exports.getClientIp = getClientIp;

/**
 * Expose a default implemtation for a connect middleware
 *
 * @options.attributeName - name of attribute to augment request object with
 */
exports.mw = function(options) {
    if (!options) options = {};
    var attr = options.attributeName || "clientIp";
    return function(req, res, next) {
        req[attr] = getClientIp(req); // on localhost > 127.0.0.1
        next();
    }
};
<commit_msg>remove copy-pasted comment<commit_after>/**
 * Author: petar bojinov - @pbojinov
 * Date: 04/03/15
 */

'use strict';

/**
 * Get client IP address
 *
 * Will return 127.0.0.1 when testing locally
 * Useful when you need the user ip for geolocation or serving localized content
 *
 * @method getClientIp
 * @param req
 * @returns {string} ip
 */
function getClientIp(req) {

    // the ipAddress we return
    var ipAddress;

    // workaround to get real client IP
    // most likely because our app will be behind a [reverse] proxy or load balancer
    var clientIp = req.headers['x-client-ip'],
        forwardedForAlt = req.headers['x-forwarded-for'],
        realIp = req.headers['x-real-ip'],
        // more obsure ones below
        clusterClientIp = req.headers['x-cluster-client-ip'],
        forwardedAlt = req.headers['x-forwarded'],
        forwardedFor = req.headers['forwarded-for'],
        forwarded = req.headers['forwarded'];

    // x-client-ip
    if (clientIp) {
        ipAddress = clientIp;
    }

    // x-forwarded-for
    else if (forwardedForAlt) {
        // x-forwarded-for header is more common
        // it may return multiple IP addresses in the format:
        // "client IP, proxy 1 IP, proxy 2 IP"
        // we pick the first one
        var forwardedIps = forwardedForAlt.split(',');
        ipAddress = forwardedIps[0];
    }

    // x-real-ip
    // (default nginx proxy/fcgi)
    else if (realIp) {
        // alternative to x-forwarded-for
        // used by some proxies
        ipAddress = realIp;
    }

    // x-cluster-client-ip
    // (Rackspace LB and Riverbed's Stingray)
    // http://www.rackspace.com/knowledge_center/article/controlling-access-to-linux-cloud-sites-based-on-the-client-ip-address
    // https://splash.riverbed.com/docs/DOC-1926
    else if (clusterClientIp) {
        ipAddress = clusterClientIp;
    }

    // x-forwarded
    else if (forwardedAlt) {
        ipAddress = forwardedAlt;
    }

    // forwarded-for
    else if (forwardedFor) {
        ipAddress = forwardedFor;
    }

    // forwarded
    else if (forwarded) {
        ipAddress = forwarded;
    }

    // fallback to something
    if (!ipAddress) {
        // ensure getting client IP address still works in development environment
        // if despite all this we do not find ip, then it returns null
        try {
            ipAddress = req.connection.remoteAddress ||
                req.socket.remoteAddress ||
                req.connection.socket.remoteAddress || // for https
                null;
        } catch(e) {
            ipAddress = null;
        }
    }

    return ipAddress;
}

/**
 * Expose mode public functions
 */
exports.getClientIp = getClientIp;

/**
 * Expose a default implemtation for a connect middleware
 *
 * @options.attributeName - name of attribute to augment request object with
 */
exports.mw = function(options) {
    if (!options) options = {};
    var attr = options.attributeName || "clientIp";
    return function(req, res, next) {
        req[attr] = getClientIp(req);
        next();
    }
};
<|endoftext|>