<commit_before>$(document).ready(function(){

	// bubble popup for brief panel documentation
	$.fn.qTip({
		'pageName': 'gene',
		'tip': 'top right',
		'corner' : 'right top'
	});

    //function to fire off a refresh of a table and it's dropdown filters

	var selectedFilters = "";
	var dropdownsList = new Array();
        initGenePhenotypesTable();
	/* var oDataTable = $('table#phenotypes').dataTable();
						oDataTable.fnDestroy();  */
	// use jquery DataTable for table searching/sorting/pagination
        function initGenePhenotypesTable(){
	var aDataTblCols = [0,1,2,3,4,5,6,7,8];
	var oDataTable = $.fn.initDataTable($('table#phenotypes'), {
		"aoColumns": [
		              { "sType": "html", "mRender":function( data, type, full ) {
		            	  return (type === "filter") ? $(data).text() : data;
		              }},
		              { "sType": "html", "mRender":function( data, type, full ) {
		            	  return (type === "filter") ? $(data).text() : data;
		              }},
		              { "sType": "string"},
		              { "sType": "string"},
		              { "sType": "string"},
		              { "sType": "string"},
		              { "sType": "html"},
                      { "sType": "allnumeric"},
		              { "sType": "string", "bSortable" : false }

		              ],
                              "aaSorting": [[ 7, 'asc' ]],//sort on pValue first
		              "bDestroy": true,
		              "bFilter":false
	});
    }

	// Sort the individual table containing p-values
	$.fn.dataTableExt.oSort['pvalues-asc']  = function(a,b) {
		var x = 0;
		var y = 0;
		if (!a || !a.length) { a = 10; }
		if (!b || !b.length) { b = 10; }
		x = parseFloat( a );
		y = parseFloat( b );
		return ((x < y) ? -1 : ((x > y) ?  1 : 0));
	};

	$.fn.dataTableExt.oSort['pvalues-desc']  = function(a,b) {
		var x = 0;
		var y = 0;
		if (!a || !a.length) { a = 10; }
		if (!b || !b.length) { b = 10; }
		x = parseFloat( a );
		y = parseFloat( b );
		return ((x < y) ?  1 : ((x > y) ? -1 : 0));
	};

	// the number of columns should be kept in sync in the JSP
	var oDataTable = $.fn.initDataTable($('table#strainPhenome'), {
		"aoColumns": [
		              { "sType": "string" },
		              { "sType": "string" },
		              { "sType": "string" },
		              { "sType": "string" },
		              { "sType": "string" },
		             // { "sType": "string" }, // Statistical Method
		              { "sType": "pvalues" }, // or numeric
		              { "sType": "string" },
		              { "sType": "string", "bSortable" : false }

		              ],
		              "bDestroy": true,
		              "bFilter":false
	});

	// the number of columns should be kept in sync in the JSP
	var oDataTable = $.fn.initDataTable($('table#strainPvalues'), {
		"aoColumns": [
		              { "sType": "string" },
		              { "sType": "string" },
		              { "sType": "string" },
		              { "sType": "string" },
		              { "sType": "string" }, // Statistical Method
		              { "sType": "pvalues" }, // or numeric
		              { "sType": "string" },
		              { "sType": "string", "bSortable" : false }

		              ],
		              "bDestroy": true,
		              "bFilter":false
	});

	//$('[rel=tooltip]').tooltip();
	//$.fn.dataTableshowAllShowLess(oDataTable, aDataTblCols, null);

	$('div#exportIconsDiv').append($.fn.loadFileExporterUI({
		label: 'Export table as:',
		textPos : "textright",
		formatSelector: {
			TSV: 'tsv_phenoAssoc',
			XLS: 'xls_phenoAssoc'
		},
		class: 'fileIcon exportButton'
	}));

	var mgiGeneId = window.location.href.split("/")[window.location.href.split("/").length-1];
	mgiGeneId = mgiGeneId.split("#")[0];
	var windowLocation = window.location;

	initFileExporter();                                                     // Initialize the exportUrl. the fileType parameter will be empty.

	function initFileExporter(){
            var conf = {
               mgiGeneId: mgiGeneId,
               externalDbId: 3,
               fileName: 'phenotype_associations_for_'+mgiGeneId.replace(/:/g,'_'),
               solrCoreName: 'genotype-phenotype',
               dumpMode: 'all',
               baseUrl: windowLocation,
               page:"gene",
               gridFields: 'marker_symbol,allele_symbol,zygosity,sex,procedure_name,resource_name,parameter_stable_id,phenotyping_center,marker_accession_id, parameter_name,parameter_name,mp_term_name',
               params: "qf=auto_suggest&defType=edismax&wt=json&rows=100000&q=*:*&fq=marker_accession_id:\"" + mgiGeneId +"\""
            };

            var exportObj = buildExportUrl(conf);                                   // Build the export url, page url, and form strings.
            $('div#exportIconsDiv').attr("data-exporturl", exportObj.exportUrl);    // Initialize the url.
// WARNING NOTE: FILTER CHANGES DO NOT UPDATE data-exporturl; THUS, THE data-exporturl VALUE WILL BE OUT-OF-SYNC SHOULD
// THE USER CHANGE FILTERS. THIS WILL LIKELY RESULT IN A HARD-TO-FIND BUG.
// RECOMMENDATION: ANY FILTER CHANGES SHOULD TRIGGER AN UPDATE OF THE data-exporturl.

            $('button.fileIcon').click(function() {
                var exportObj = buildExportUrl(conf, $(this).text());                       // Build the export url, page url, and form strings.
                $('div#exportIconsDiv').attr("data-exporturl", exportObj.exportUrl);        // Update the url in case the filters changed.
                _doDataExport(exportObj.url, exportObj.form);
            });
	}

        function buildExportUrl(conf, fileType) {
            if (fileType === undefined)
                fileType = '';
            var url = baseUrl + '/export';
            var sInputs = '';
            for ( var k in conf ){
                    if (k === "params"){
                            sInputs += "<input type='text' name='" + k + "' value='" + conf[k] + selectedFilters + "'>";
                            alert("here " + selectedFilters);
            		}
                    else {
                           sInputs += "<input type='text' name='" + k + "' value='" + conf[k] + "'>";
                    }
            }
            sInputs += "<input type='text' name='fileType' value='" + fileType.toLowerCase() + "'>";
            var form = $("<form action='"+ url + "' method=get>" + sInputs + "</form>");
            var exportUrl = url + '?' + $(form).serialize();

            var retVal = new Object();
            retVal.url = url;
            retVal.form = form;
            retVal.exportUrl = exportUrl;
            return retVal;
        }

	function _doDataExport(url, form){
		$.ajax({
			type: 'GET',
			url: url,
			cache: false,
			data: $(form).serialize(),
			success:function(data){
				$(form).appendTo('body').submit();
			},
			error:function(){
				//alert("Oops, there is error during data export..");
			}
		});
	}

	function refreshPhenoTable(newUrl){
		$.ajax({
			url: newUrl,
			cache: false
		}).done(function( html ) {
			$("#phenotypes_wrapper").html(html);//phenotypes wrapper div has been created by the original datatable so we need to replace this div with the new table and content
			initGenePhenotypesTable();
			//alert('calling new table in genes.jsp');
		});
	}
	//http://stackoverflow.com/questions/5990386/datatables-search-box-outside-datatable
	//to move the input text or reassign the div that does it and hide the other one??
	//put filtering in another text field than the default so we can position it with the other controls like dropdown ajax filters for project etc

	//stuff for dropdown tick boxes here
	var allDropdowns = new Array();
	allDropdowns[0] = $('#top_level_mp_term_name');
	allDropdowns[1] = $('#resource_fullname');
	createDropdown(allDropdowns[0],"Top level MP: All", allDropdowns);
	createDropdown(allDropdowns[1], "Source: All", allDropdowns);

	function createDropdown(multipleSel, emptyText,  allDd){
		$(multipleSel).dropdownchecklist( { firstItemChecksAll: false, emptyText: emptyText, icon: {},
			minWidth: 150, onItemClick: function(checkbox, selector){
				var justChecked = checkbox.prop("checked");
//				console.log("justChecked="+justChecked);
//				console.log("checked="+ checkbox.val());
				var values = [];
				for(var  i=0; i < selector.options.length; i++ ) {
					if (selector.options[i].selected && (selector.options[i].value != "")) {
						values .push(selector.options[i].value);
					}
				}

				if(justChecked){
					values.push( checkbox.val());
				}else{//just unchecked value is in the array so we remove it as already ticked
					var index = $.inArray(checkbox.val(), values);
					values.splice(index, 1);
				}

				console.log("values="+values );
				// add current one and create dropdown object
				dd1 = new Object();
				dd1.name = multipleSel.attr('id');
				dd1.array = values; // selected values

				dropdownsList[0] = dd1;

				var ddI  = 1;
				for (var ii=0; ii<allDd.length; ii++) {
					if ($(allDd[ii]).attr('id') != multipleSel.attr('id')) {
//						console.log ("here " + allDd[ii].val() + " " + allDd[ii].attr('id'));
						dd = new Object();
						dd.name = allDd[ii].attr('id');
						dd.array = allDd[ii].val() || [];
						dropdownsList[ddI++] = dd;
					}
				}
//				console.log("call with " + dropdownsList.length);
				refreshGenesPhenoFrag(dropdownsList);
			}, textFormatFunction: function(options) {
				var selectedOptions = options.filter(":selected");
		        var countOfSelected = selectedOptions.size();
		        var size = options.size();
		        var text = "";
		        if (size > 1){
		        	options.each(function() {
	                    if ($(this).prop("selected")) {
	                        if ( text != "" ) { text += ", "; }
	                        /* NOTE use of .html versus .text, which can screw up ampersands for IE */
	                        var optCss = $(this).attr('style');
	                        var tempspan = $('<span/>');
	                        tempspan.html( $(this).html() );
	                        if ( optCss == null ) {
	                                text += tempspan.html();
	                        } else {
	                                tempspan.attr('style',optCss);
	                                text += $("<span/>").append(tempspan).html();
	                        }
	                    }
	                });
		        }
		        switch(countOfSelected) {
		           case 0: return emptyText;
		           case 1: return selectedOptions.text();
		           case options.size(): return emptyText;
		           default: return text;
		        }
			}
		} );
	}

	//if filter parameters are already set then we need to set them as selected in the dropdowns
	var previousParams = $("#filterParams").html();

	function refreshGenesPhenoFrag(dropdownsList) {
		var rootUrl=window.location.href;
		var newUrl=rootUrl.replace("genes", "genesPhenoFrag");
		var output ='?';
		selectedFilters = "";
		for (var it = 0; it < dropdownsList.length; it++){
//			console.log(dropdownsList[it].array);
			if(dropdownsList[it].array.length == 1){//if only one entry for this parameter then don't use brackets and or
				output += '&fq=' + dropdownsList[it].name + ':"' + dropdownsList[it].array+'"';
				selectedFilters += '+AND+' + dropdownsList[it].name + ':"' + dropdownsList[it].array+'"';
			}
			if(dropdownsList[it].array.length > 1)	{
				output += '&fq='+dropdownsList[it].name+':(\"' + dropdownsList[it].array.join("\"OR\"") + '\")';
				selectedFilters += '+AND+'+dropdownsList[it].name+':(\"' + dropdownsList[it].array.join("\"OR\"") + '\")';
			}
		}
		newUrl+=output;
		refreshPhenoTable(newUrl);
		return false;
	}

	$(".filterTrigger").click(function() {
		//Do stuff when clicked
		//the id is set as the field to be filtered on
		//set the value of the current id of the trigger

		var filter=$(this).attr("id").replace("phenIconsBox_", "");
		var values = filter.split(" or ");
//		console.log ("filterTrigger" + values);
		$(allDropdowns[0]).val(values);
		$(allDropdowns[0]).dropdownchecklist("refresh");
		$(allDropdowns[1]).val([]);
		$(allDropdowns[1]).dropdownchecklist("refresh");
		var dropdownsList = new Array();

		var dd1 = new Object();
		dd1.name = allDropdowns[0].attr("id");
		dd1.array = new Array; // selected values
		dd1.array = values;
		dropdownsList[0] = dd1;

		var dd2 = new Object();
		dd2.name = allDropdowns[1].attr("id");
		dd2.array = []; //set array for second dropdown to empty so we get the same
		dropdownsList[1] = dd2;

		refreshGenesPhenoFrag(dropdownsList);
	});

});

 /* new sorting functions */
//http://datatables.net/forums/discussion/5894/datatable-sorting-scientific-notation
jQuery.fn.dataTableExt.oSort['allnumeric-asc']  = function(a,b) {
          var x = parseFloat(a);
          var y = parseFloat(b);
          return ((x < y) ? -1 : ((x > y) ?  1 : 0));
        };

jQuery.fn.dataTableExt.oSort['allnumeric-desc']  = function(a,b) {
          var x = parseFloat(a);
          var y = parseFloat(b);
          return ((x < y) ? 1 : ((x > y) ?  -1 : 0));
        };
<commit_msg>removed alert<commit_after>$(document).ready(function(){

	// bubble popup for brief panel documentation
	$.fn.qTip({
		'pageName': 'gene',
		'tip': 'top right',
		'corner' : 'right top'
	});

    //function to fire off a refresh of a table and it's dropdown filters

	var selectedFilters = "";
	var dropdownsList = new Array();
        initGenePhenotypesTable();
	/* var oDataTable = $('table#phenotypes').dataTable();
						oDataTable.fnDestroy();  */
	// use jquery DataTable for table searching/sorting/pagination
        function initGenePhenotypesTable(){
	var aDataTblCols = [0,1,2,3,4,5,6,7,8];
	var oDataTable = $.fn.initDataTable($('table#phenotypes'), {
		"aoColumns": [
		              { "sType": "html", "mRender":function( data, type, full ) {
		            	  return (type === "filter") ? $(data).text() : data;
		              }},
		              { "sType": "html", "mRender":function( data, type, full ) {
		            	  return (type === "filter") ? $(data).text() : data;
		              }},
		              { "sType": "string"},
		              { "sType": "string"},
		              { "sType": "string"},
		              { "sType": "string"},
		              { "sType": "html"},
                      { "sType": "allnumeric"},
		              { "sType": "string", "bSortable" : false }

		              ],
                              "aaSorting": [[ 7, 'asc' ]],//sort on pValue first
		              "bDestroy": true,
		              "bFilter":false
	});
    }

	// Sort the individual table containing p-values
	$.fn.dataTableExt.oSort['pvalues-asc']  = function(a,b) {
		var x = 0;
		var y = 0;
		if (!a || !a.length) { a = 10; }
		if (!b || !b.length) { b = 10; }
		x = parseFloat( a );
		y = parseFloat( b );
		return ((x < y) ? -1 : ((x > y) ?  1 : 0));
	};

	$.fn.dataTableExt.oSort['pvalues-desc']  = function(a,b) {
		var x = 0;
		var y = 0;
		if (!a || !a.length) { a = 10; }
		if (!b || !b.length) { b = 10; }
		x = parseFloat( a );
		y = parseFloat( b );
		return ((x < y) ?  1 : ((x > y) ? -1 : 0));
	};

	// the number of columns should be kept in sync in the JSP
	var oDataTable = $.fn.initDataTable($('table#strainPhenome'), {
		"aoColumns": [
		              { "sType": "string" },
		              { "sType": "string" },
		              { "sType": "string" },
		              { "sType": "string" },
		              { "sType": "string" },
		             // { "sType": "string" }, // Statistical Method
		              { "sType": "pvalues" }, // or numeric
		              { "sType": "string" },
		              { "sType": "string", "bSortable" : false }

		              ],
		              "bDestroy": true,
		              "bFilter":false
	});

	// the number of columns should be kept in sync in the JSP
	var oDataTable = $.fn.initDataTable($('table#strainPvalues'), {
		"aoColumns": [
		              { "sType": "string" },
		              { "sType": "string" },
		              { "sType": "string" },
		              { "sType": "string" },
		              { "sType": "string" }, // Statistical Method
		              { "sType": "pvalues" }, // or numeric
		              { "sType": "string" },
		              { "sType": "string", "bSortable" : false }

		              ],
		              "bDestroy": true,
		              "bFilter":false
	});

	//$('[rel=tooltip]').tooltip();
	//$.fn.dataTableshowAllShowLess(oDataTable, aDataTblCols, null);

	$('div#exportIconsDiv').append($.fn.loadFileExporterUI({
		label: 'Export table as:',
		textPos : "textright",
		formatSelector: {
			TSV: 'tsv_phenoAssoc',
			XLS: 'xls_phenoAssoc'
		},
		class: 'fileIcon exportButton'
	}));

	var mgiGeneId = window.location.href.split("/")[window.location.href.split("/").length-1];
	mgiGeneId = mgiGeneId.split("#")[0];
	var windowLocation = window.location;

	initFileExporter();                                                     // Initialize the exportUrl. the fileType parameter will be empty.

	function initFileExporter(){
            var conf = {
               mgiGeneId: mgiGeneId,
               externalDbId: 3,
               fileName: 'phenotype_associations_for_'+mgiGeneId.replace(/:/g,'_'),
               solrCoreName: 'genotype-phenotype',
               dumpMode: 'all',
               baseUrl: windowLocation,
               page:"gene",
               gridFields: 'marker_symbol,allele_symbol,zygosity,sex,procedure_name,resource_name,parameter_stable_id,phenotyping_center,marker_accession_id, parameter_name,parameter_name,mp_term_name',
               params: "qf=auto_suggest&defType=edismax&wt=json&rows=100000&q=*:*&fq=marker_accession_id:\"" + mgiGeneId +"\""
            };

            var exportObj = buildExportUrl(conf);                                   // Build the export url, page url, and form strings.
            $('div#exportIconsDiv').attr("data-exporturl", exportObj.exportUrl);    // Initialize the url.
// WARNING NOTE: FILTER CHANGES DO NOT UPDATE data-exporturl; THUS, THE data-exporturl VALUE WILL BE OUT-OF-SYNC SHOULD
// THE USER CHANGE FILTERS. THIS WILL LIKELY RESULT IN A HARD-TO-FIND BUG.
// RECOMMENDATION: ANY FILTER CHANGES SHOULD TRIGGER AN UPDATE OF THE data-exporturl.

            $('button.fileIcon').click(function() {
                var exportObj = buildExportUrl(conf, $(this).text());                       // Build the export url, page url, and form strings.
                $('div#exportIconsDiv').attr("data-exporturl", exportObj.exportUrl);        // Update the url in case the filters changed.
                _doDataExport(exportObj.url, exportObj.form);
            });
	}

        function buildExportUrl(conf, fileType) {
            if (fileType === undefined)
                fileType = '';
            var url = baseUrl + '/export';
            var sInputs = '';
            for ( var k in conf ){
                    if (k === "params"){
                            sInputs += "<input type='text' name='" + k + "' value='" + conf[k] + selectedFilters + "'>";
            		}
                    else {
                           sInputs += "<input type='text' name='" + k + "' value='" + conf[k] + "'>";
                    }
            }
            sInputs += "<input type='text' name='fileType' value='" + fileType.toLowerCase() + "'>";
            var form = $("<form action='"+ url + "' method=get>" + sInputs + "</form>");
            var exportUrl = url + '?' + $(form).serialize();

            var retVal = new Object();
            retVal.url = url;
            retVal.form = form;
            retVal.exportUrl = exportUrl;
            return retVal;
        }

	function _doDataExport(url, form){
		$.ajax({
			type: 'GET',
			url: url,
			cache: false,
			data: $(form).serialize(),
			success:function(data){
				$(form).appendTo('body').submit();
			},
			error:function(){
				//alert("Oops, there is error during data export..");
			}
		});
	}

	function refreshPhenoTable(newUrl){
		$.ajax({
			url: newUrl,
			cache: false
		}).done(function( html ) {
			$("#phenotypes_wrapper").html(html);//phenotypes wrapper div has been created by the original datatable so we need to replace this div with the new table and content
			initGenePhenotypesTable();
			//alert('calling new table in genes.jsp');
		});
	}
	//http://stackoverflow.com/questions/5990386/datatables-search-box-outside-datatable
	//to move the input text or reassign the div that does it and hide the other one??
	//put filtering in another text field than the default so we can position it with the other controls like dropdown ajax filters for project etc

	//stuff for dropdown tick boxes here
	var allDropdowns = new Array();
	allDropdowns[0] = $('#top_level_mp_term_name');
	allDropdowns[1] = $('#resource_fullname');
	createDropdown(allDropdowns[0],"Top level MP: All", allDropdowns);
	createDropdown(allDropdowns[1], "Source: All", allDropdowns);

	function createDropdown(multipleSel, emptyText,  allDd){
		$(multipleSel).dropdownchecklist( { firstItemChecksAll: false, emptyText: emptyText, icon: {},
			minWidth: 150, onItemClick: function(checkbox, selector){
				var justChecked = checkbox.prop("checked");
//				console.log("justChecked="+justChecked);
//				console.log("checked="+ checkbox.val());
				var values = [];
				for(var  i=0; i < selector.options.length; i++ ) {
					if (selector.options[i].selected && (selector.options[i].value != "")) {
						values .push(selector.options[i].value);
					}
				}

				if(justChecked){
					values.push( checkbox.val());
				}else{//just unchecked value is in the array so we remove it as already ticked
					var index = $.inArray(checkbox.val(), values);
					values.splice(index, 1);
				}

				console.log("values="+values );
				// add current one and create dropdown object
				dd1 = new Object();
				dd1.name = multipleSel.attr('id');
				dd1.array = values; // selected values

				dropdownsList[0] = dd1;

				var ddI  = 1;
				for (var ii=0; ii<allDd.length; ii++) {
					if ($(allDd[ii]).attr('id') != multipleSel.attr('id')) {
//						console.log ("here " + allDd[ii].val() + " " + allDd[ii].attr('id'));
						dd = new Object();
						dd.name = allDd[ii].attr('id');
						dd.array = allDd[ii].val() || [];
						dropdownsList[ddI++] = dd;
					}
				}
//				console.log("call with " + dropdownsList.length);
				refreshGenesPhenoFrag(dropdownsList);
			}, textFormatFunction: function(options) {
				var selectedOptions = options.filter(":selected");
		        var countOfSelected = selectedOptions.size();
		        var size = options.size();
		        var text = "";
		        if (size > 1){
		        	options.each(function() {
	                    if ($(this).prop("selected")) {
	                        if ( text != "" ) { text += ", "; }
	                        /* NOTE use of .html versus .text, which can screw up ampersands for IE */
	                        var optCss = $(this).attr('style');
	                        var tempspan = $('<span/>');
	                        tempspan.html( $(this).html() );
	                        if ( optCss == null ) {
	                                text += tempspan.html();
	                        } else {
	                                tempspan.attr('style',optCss);
	                                text += $("<span/>").append(tempspan).html();
	                        }
	                    }
	                });
		        }
		        switch(countOfSelected) {
		           case 0: return emptyText;
		           case 1: return selectedOptions.text();
		           case options.size(): return emptyText;
		           default: return text;
		        }
			}
		} );
	}

	//if filter parameters are already set then we need to set them as selected in the dropdowns
	var previousParams = $("#filterParams").html();

	function refreshGenesPhenoFrag(dropdownsList) {
		var rootUrl=window.location.href;
		var newUrl=rootUrl.replace("genes", "genesPhenoFrag");
		var output ='?';
		selectedFilters = "";
		for (var it = 0; it < dropdownsList.length; it++){
//			console.log(dropdownsList[it].array);
			if(dropdownsList[it].array.length == 1){//if only one entry for this parameter then don't use brackets and or
				output += '&fq=' + dropdownsList[it].name + ':"' + dropdownsList[it].array+'"';
				selectedFilters += '+AND+' + dropdownsList[it].name + ':"' + dropdownsList[it].array+'"';
			}
			if(dropdownsList[it].array.length > 1)	{
				output += '&fq='+dropdownsList[it].name+':(\"' + dropdownsList[it].array.join("\"OR\"") + '\")';
				selectedFilters += '+AND+'+dropdownsList[it].name+':(\"' + dropdownsList[it].array.join("\"OR\"") + '\")';
			}
		}
		newUrl+=output;
		refreshPhenoTable(newUrl);
		return false;
	}

	$(".filterTrigger").click(function() {
		//Do stuff when clicked
		//the id is set as the field to be filtered on
		//set the value of the current id of the trigger

		var filter=$(this).attr("id").replace("phenIconsBox_", "");
		var values = filter.split(" or ");
//		console.log ("filterTrigger" + values);
		$(allDropdowns[0]).val(values);
		$(allDropdowns[0]).dropdownchecklist("refresh");
		$(allDropdowns[1]).val([]);
		$(allDropdowns[1]).dropdownchecklist("refresh");
		var dropdownsList = new Array();

		var dd1 = new Object();
		dd1.name = allDropdowns[0].attr("id");
		dd1.array = new Array; // selected values
		dd1.array = values;
		dropdownsList[0] = dd1;

		var dd2 = new Object();
		dd2.name = allDropdowns[1].attr("id");
		dd2.array = []; //set array for second dropdown to empty so we get the same
		dropdownsList[1] = dd2;

		refreshGenesPhenoFrag(dropdownsList);
	});

});

 /* new sorting functions */
//http://datatables.net/forums/discussion/5894/datatable-sorting-scientific-notation
jQuery.fn.dataTableExt.oSort['allnumeric-asc']  = function(a,b) {
          var x = parseFloat(a);
          var y = parseFloat(b);
          return ((x < y) ? -1 : ((x > y) ?  1 : 0));
        };

jQuery.fn.dataTableExt.oSort['allnumeric-desc']  = function(a,b) {
          var x = parseFloat(a);
          var y = parseFloat(b);
          return ((x < y) ? 1 : ((x > y) ?  -1 : 0));
        };
<|endoftext|>


<commit_before>var common = require('../common-tap')
  , test = require('tap').test
  , path = require('path')
  , rimraf = require('rimraf')
  , mkdirp = require('mkdirp')
  , pkg = __dirname + '/ls-depth'
  , cache = pkg + '/cache'
  , tmp = pkg + '/tmp'
  , node = process.execPath
  , npm = path.resolve(__dirname, '../../cli.js')
  , mr = require('npm-registry-mock')
  , opts = {cwd: pkg}

function cleanup () {
  rimraf.sync(pkg + '/cache')
  rimraf.sync(pkg + '/tmp')
  rimraf.sync(pkg + '/node_modules')
}

test('setup', function (t) {
  cleanup()
  mkdirp.sync(pkg + '/cache')
  mkdirp.sync(pkg + '/tmp')
  mr(common.port, function (s) {
    common.run([
      npm
    , 'install'
    , '--registry=' + common.registry
    ], t, opts
    , function (t, c) {
      s.close()
      t.end()
    })
  })
})

test('npm ls --depth=0', function (t) {
  common.run([npm, 'ls', '--depth=0'], t, opts, function (t, c) {
    t.has(c, /test-package-with-one-dep@0\.0\.0/
      , "output contains test-package-with-one-dep@0.0.0")
    t.doesNotHave(c, /test-package@0\.0\.0/
      , "output not contains test-package@0.0.0")
    t.end()
  })
})

test('npm ls --depth=1', function (t) {
  common.run([npm, 'ls', '--depth=1'], t, opts, function (t, c) {
    t.has(c, /test-package-with-one-dep@0\.0\.0/
      , "output contains test-package-with-one-dep@0.0.0")
    t.has(c, /test-package@0\.0\.0/
      , "output contains test-package@0.0.0")
    t.end()
  })
})

test('npm ls (no depth defined)', function (t) {
  common.run([npm, 'ls'], t, opts, function (t, c) {
    t.has(c, /test-package-with-one-dep@0\.0\.0/
      , "output contains test-package-with-one-dep@0.0.0")
    t.has(c, /test-package@0\.0\.0/
      , "output contains test-package@0.0.0")
    t.end()
  })
})

test('cleanup', function (t) {
  cleanup()
  t.end()
})
<commit_msg>Fix ls-depth-cli test on Windows.<commit_after>var common = require('../common-tap')
  , test = require('tap').test
  , path = require('path')
  , rimraf = require('rimraf')
  , osenv = require('osenv')
  , mkdirp = require('mkdirp')
  , pkg = __dirname + '/ls-depth'
  , cache = pkg + '/cache'
  , tmp = pkg + '/tmp'
  , node = process.execPath
  , npm = path.resolve(__dirname, '../../cli.js')
  , mr = require('npm-registry-mock')
  , opts = {cwd: pkg}

function cleanup () {
  process.chdir(osenv.tmpdir())
  rimraf.sync(pkg + '/cache')
  rimraf.sync(pkg + '/tmp')
  rimraf.sync(pkg + '/node_modules')
}

test('setup', function (t) {
  cleanup()
  mkdirp.sync(pkg + '/cache')
  mkdirp.sync(pkg + '/tmp')
  mr(common.port, function (s) {
    common.run([
      npm
    , 'install'
    , '--registry=' + common.registry
    ], t, opts
    , function (t, c) {
      s.close()
      t.end()
    })
  })
})

test('npm ls --depth=0', function (t) {
  common.run([npm, 'ls', '--depth=0'], t, opts, function (t, c) {
    t.has(c, /test-package-with-one-dep@0\.0\.0/
      , "output contains test-package-with-one-dep@0.0.0")
    t.doesNotHave(c, /test-package@0\.0\.0/
      , "output not contains test-package@0.0.0")
    t.end()
  })
})

test('npm ls --depth=1', function (t) {
  common.run([npm, 'ls', '--depth=1'], t, opts, function (t, c) {
    t.has(c, /test-package-with-one-dep@0\.0\.0/
      , "output contains test-package-with-one-dep@0.0.0")
    t.has(c, /test-package@0\.0\.0/
      , "output contains test-package@0.0.0")
    t.end()
  })
})

test('npm ls (no depth defined)', function (t) {
  common.run([npm, 'ls'], t, opts, function (t, c) {
    t.has(c, /test-package-with-one-dep@0\.0\.0/
      , "output contains test-package-with-one-dep@0.0.0")
    t.has(c, /test-package@0\.0\.0/
      , "output contains test-package@0.0.0")
    t.end()
  })
})

test('cleanup', function (t) {
  cleanup()
  t.end()
})
<|endoftext|>


<commit_before>import fs from "fs";

import {
  getTimeObj,
  getTimeStr,
  clamp,
  parseViscolors,
  parseIni,
  normalize,
  denormalize,
  segment,
  moveSelected,
  spliceIn
} from "./utils";

const fixture = filename =>
  fs.readFileSync(`./js/__tests__/fixtures/${filename}`, "utf8");

describe("getTimeObj", () => {
  it("expresses seconds as an object", () => {
    const actual = getTimeObj(1234);
    const expected = {
      minutesFirstDigit: 2,
      minutesSecondDigit: 0,
      secondsFirstDigit: 3,
      secondsSecondDigit: 4
    };
    expect(actual).toEqual(expected);
  });
});

describe("getTimeStr", () => {
  it("expresses seconds as string", () => {
    const actual = getTimeStr(1234);
    const expected = "20:34";
    expect(actual).toEqual(expected);
  });
  it("pads with only one zero", () => {
    const actual = getTimeStr(5);
    const expected = "0:05";
    expect(actual).toEqual(expected);
  });
  it("truncates extra minutes", () => {
    const actual = getTimeStr(540000);
    const expected = "9000:00";
    expect(actual).toEqual(expected);
  });
});

describe("clamp", () => {
  it("respects the max value", () => {
    const actual = clamp(101, 0, 100);
    const expected = 100;
    expect(actual).toEqual(expected);
  });
  it("respects the min value", () => {
    const actual = clamp(0, 1, 100);
    const expected = 1;
    expect(actual).toEqual(expected);
  });
  it("respects the given value if in range", () => {
    const actual = clamp(50, 0, 100);
    const expected = 50;
    expect(actual).toEqual(expected);
  });
});

describe("parseViscolors", () => {
  it("can parse the default viscolors file", () => {
    const viscolors = fixture("VISCOLOR.TXT");
    const actual = parseViscolors(viscolors);
    const expected = [
      "rgb(0,0,0)",
      "rgb(24,33,41)",
      "rgb(239,49,16)",
      "rgb(206,41,16)",
      "rgb(214,90,0)",
      "rgb(214,102,0)",
      "rgb(214,115,0)",
      "rgb(198,123,8)",
      "rgb(222,165,24)",
      "rgb(214,181,33)",
      "rgb(189,222,41)",
      "rgb(148,222,33)",
      "rgb(41,206,16)",
      "rgb(50,190,16)",
      "rgb(57,181,16)",
      "rgb(49,156,8)",
      "rgb(41,148,0)",
      "rgb(24,132,8)",
      "rgb(255,255,255)",
      "rgb(214,214,222)",
      "rgb(181,189,189)",
      "rgb(160,170,175)",
      "rgb(148,156,165)",
      "rgb(150,150,150)"
    ];
    expect(actual).toEqual(expected);
  });
});

describe("parseIni", () => {
  it("can parse the default pledit.txt file", () => {
    const pledit = fixture("PLEDIT.TXT");
    const actual = parseIni(pledit);
    const expected = {
      text: {
        normal: "#00FF00",
        current: "#FFFFFF",
        normalbg: "#000000",
        selectedbg: "#0000FF",
        font: "Arial"
      }
    };
    expect(actual).toEqual(expected);
  });

  it("can parse TopazAmp's pledit.txt file", () => {
    const pledit = fixture("PLEDIT_TOPAZ.TXT");
    const actual = parseIni(pledit);
    const expected = {
      text: {
        normal: "#319593",
        current: "#89D8D1",
        normalbg: "#000000",
        selectedbg: "#2B4242",
        font: "Arial",
        mbbg: "#000000",
        mbfg: "#89D8D1"
      }
    };
    expect(actual).toEqual(expected);
  });

  it("allows space around =", () => {
    const actual = parseIni(`
[foo]
bar = baz
`);
    const expected = {
      foo: {
        bar: "baz"
      }
    };
    expect(actual).toEqual(expected);
  });
});

test("normalize", () => {
  expect(normalize(1)).toBe(1);
  expect(normalize(64)).toBe(100);
});
test("denormalize", () => {
  expect(denormalize(1)).toBe(1);
  expect(denormalize(100)).toBe(64);
});

describe("segment", () => {
  it("can handle min", () => {
    expect(segment(0, 100, 0, [0, 1, 2])).toBe(0);
    expect(segment(1, 100, 1, [0, 1, 2])).toBe(0);
    expect(segment(-1, 100, -1, [0, 1, 2])).toBe(0);
  });
  it("can handle max", () => {
    //expect(segment(0, 100, 100, [0, 1, 2])).toBe(2);
    //expect(segment(1, 100, 100, [0, 1, 2])).toBe(2);
    expect(segment(-1, 100, 100, [0, 1, 2])).toBe(2);
  });
  it("can handle mid", () => {
    expect(segment(0, 2, 1, [0, 1, 2])).toBe(1);
    expect(segment(0, 2, 1.5, [0, 1, 2])).toBe(2);
    expect(segment(1, 3, 2.5, [0, 1, 2])).toBe(2);
    expect(segment(-1, 2, 0.5, [0, 1, 2])).toBe(1);
  });
  it("can handle various real wold cases", () => {
    expect(segment(-100, 100, -100, ["left", "center", "right"])).toBe("left");
    expect(segment(0, 100, 88, ["left", "center", "right"])).toBe("right");
    expect(segment(0, 100, 50, ["left", "center", "right"])).toBe("center");
  });
});

describe("moveSelected", () => {
  it("can drag a single item 1", () => {
    expect(
      moveSelected(
        ["a", "b", "c", "d", "e", "f", "g", "h"],
        i => new Set([1]).has(i),
        1
      )
    ).toEqual(["a", "c", "b", "d", "e", "f", "g", "h"]);
  });
  it("can drag a single item", () => {
    expect(
      moveSelected(
        ["a", "b", "c", "d", "e", "f", "g", "h"],
        i => new Set([1]).has(i),
        3
      )
    ).toEqual(["a", "c", "d", "e", "b", "f", "g", "h"]);
  });
  it("can drag consecutive items", () => {
    expect(
      moveSelected(
        ["a", "b", "c", "d", "e", "f", "g", "h"],
        i => new Set([1, 2]).has(i),
        3
      )
    ).toEqual(["a", "d", "e", "f", "b", "c", "g", "h"]);
  });
  it("works for a simple example", () => {
    const arr = [true, false, false];
    expect(moveSelected(arr, i => arr[i], 1)).toEqual([false, true, false]);
  });
  it("works for a simple negative example", () => {
    const arr = [false, false, true];
    expect(moveSelected(arr, i => arr[i], -1)).toEqual([false, true, false]);
  });
});

describe("spliceIn", () => {
  it("is immutable", () => {
    const original = [1, 2, 3];
    const spliced = spliceIn(original, 1, [200]);
    expect(spliced).not.toBe(original);
    expect(original).toEqual([1, 2, 3]);
  });
  it("adds values at the given index", () => {
    const spliced = spliceIn([1, 2, 3], 1, [200]);
    expect(spliced).toEqual([1, 200, 2, 3]);
  });
});
<commit_msg>Add test<commit_after>import fs from "fs";

import {
  getTimeObj,
  getTimeStr,
  clamp,
  parseViscolors,
  parseIni,
  normalize,
  denormalize,
  segment,
  moveSelected,
  spliceIn
} from "./utils";

const fixture = filename =>
  fs.readFileSync(`./js/__tests__/fixtures/${filename}`, "utf8");

describe("getTimeObj", () => {
  it("expresses seconds as an object", () => {
    const actual = getTimeObj(1234);
    const expected = {
      minutesFirstDigit: 2,
      minutesSecondDigit: 0,
      secondsFirstDigit: 3,
      secondsSecondDigit: 4
    };
    expect(actual).toEqual(expected);
  });
});

describe("getTimeStr", () => {
  it("expresses seconds as string", () => {
    const actual = getTimeStr(1234);
    const expected = "20:34";
    expect(actual).toEqual(expected);
  });
  it("pads with only one zero", () => {
    const actual = getTimeStr(5);
    const expected = "0:05";
    expect(actual).toEqual(expected);
  });
  it("truncates extra minutes", () => {
    const actual = getTimeStr(540000);
    const expected = "9000:00";
    expect(actual).toEqual(expected);
  });
});

describe("clamp", () => {
  it("respects the max value", () => {
    const actual = clamp(101, 0, 100);
    const expected = 100;
    expect(actual).toEqual(expected);
  });
  it("respects the min value", () => {
    const actual = clamp(0, 1, 100);
    const expected = 1;
    expect(actual).toEqual(expected);
  });
  it("respects the given value if in range", () => {
    const actual = clamp(50, 0, 100);
    const expected = 50;
    expect(actual).toEqual(expected);
  });
});

describe("parseViscolors", () => {
  it("can parse the default viscolors file", () => {
    const viscolors = fixture("VISCOLOR.TXT");
    const actual = parseViscolors(viscolors);
    const expected = [
      "rgb(0,0,0)",
      "rgb(24,33,41)",
      "rgb(239,49,16)",
      "rgb(206,41,16)",
      "rgb(214,90,0)",
      "rgb(214,102,0)",
      "rgb(214,115,0)",
      "rgb(198,123,8)",
      "rgb(222,165,24)",
      "rgb(214,181,33)",
      "rgb(189,222,41)",
      "rgb(148,222,33)",
      "rgb(41,206,16)",
      "rgb(50,190,16)",
      "rgb(57,181,16)",
      "rgb(49,156,8)",
      "rgb(41,148,0)",
      "rgb(24,132,8)",
      "rgb(255,255,255)",
      "rgb(214,214,222)",
      "rgb(181,189,189)",
      "rgb(160,170,175)",
      "rgb(148,156,165)",
      "rgb(150,150,150)"
    ];
    expect(actual).toEqual(expected);
  });
});

describe("parseIni", () => {
  it("can parse the default pledit.txt file", () => {
    const pledit = fixture("PLEDIT.TXT");
    const actual = parseIni(pledit);
    const expected = {
      text: {
        normal: "#00FF00",
        current: "#FFFFFF",
        normalbg: "#000000",
        selectedbg: "#0000FF",
        font: "Arial"
      }
    };
    expect(actual).toEqual(expected);
  });

  it("can parse TopazAmp's pledit.txt file", () => {
    const pledit = fixture("PLEDIT_TOPAZ.TXT");
    const actual = parseIni(pledit);
    const expected = {
      text: {
        normal: "#319593",
        current: "#89D8D1",
        normalbg: "#000000",
        selectedbg: "#2B4242",
        font: "Arial",
        mbbg: "#000000",
        mbfg: "#89D8D1"
      }
    };
    expect(actual).toEqual(expected);
  });

  it("allows space around =", () => {
    const actual = parseIni(`
[foo]
bar = baz
`);
    const expected = {
      foo: {
        bar: "baz"
      }
    };
    expect(actual).toEqual(expected);
  });

  it("allows quotes around values", () => {
    const actual = parseIni(`
[foo]
bar = "baz"
  `);
    const expected = {
      foo: {
        bar: "baz"
      }
    };
    expect(actual).toEqual(expected);
  });
});

test("normalize", () => {
  expect(normalize(1)).toBe(1);
  expect(normalize(64)).toBe(100);
});
test("denormalize", () => {
  expect(denormalize(1)).toBe(1);
  expect(denormalize(100)).toBe(64);
});

describe("segment", () => {
  it("can handle min", () => {
    expect(segment(0, 100, 0, [0, 1, 2])).toBe(0);
    expect(segment(1, 100, 1, [0, 1, 2])).toBe(0);
    expect(segment(-1, 100, -1, [0, 1, 2])).toBe(0);
  });
  it("can handle max", () => {
    //expect(segment(0, 100, 100, [0, 1, 2])).toBe(2);
    //expect(segment(1, 100, 100, [0, 1, 2])).toBe(2);
    expect(segment(-1, 100, 100, [0, 1, 2])).toBe(2);
  });
  it("can handle mid", () => {
    expect(segment(0, 2, 1, [0, 1, 2])).toBe(1);
    expect(segment(0, 2, 1.5, [0, 1, 2])).toBe(2);
    expect(segment(1, 3, 2.5, [0, 1, 2])).toBe(2);
    expect(segment(-1, 2, 0.5, [0, 1, 2])).toBe(1);
  });
  it("can handle various real wold cases", () => {
    expect(segment(-100, 100, -100, ["left", "center", "right"])).toBe("left");
    expect(segment(0, 100, 88, ["left", "center", "right"])).toBe("right");
    expect(segment(0, 100, 50, ["left", "center", "right"])).toBe("center");
  });
});

describe("moveSelected", () => {
  it("can drag a single item 1", () => {
    expect(
      moveSelected(
        ["a", "b", "c", "d", "e", "f", "g", "h"],
        i => new Set([1]).has(i),
        1
      )
    ).toEqual(["a", "c", "b", "d", "e", "f", "g", "h"]);
  });
  it("can drag a single item", () => {
    expect(
      moveSelected(
        ["a", "b", "c", "d", "e", "f", "g", "h"],
        i => new Set([1]).has(i),
        3
      )
    ).toEqual(["a", "c", "d", "e", "b", "f", "g", "h"]);
  });
  it("can drag consecutive items", () => {
    expect(
      moveSelected(
        ["a", "b", "c", "d", "e", "f", "g", "h"],
        i => new Set([1, 2]).has(i),
        3
      )
    ).toEqual(["a", "d", "e", "f", "b", "c", "g", "h"]);
  });
  it("works for a simple example", () => {
    const arr = [true, false, false];
    expect(moveSelected(arr, i => arr[i], 1)).toEqual([false, true, false]);
  });
  it("works for a simple negative example", () => {
    const arr = [false, false, true];
    expect(moveSelected(arr, i => arr[i], -1)).toEqual([false, true, false]);
  });
});

describe("spliceIn", () => {
  it("is immutable", () => {
    const original = [1, 2, 3];
    const spliced = spliceIn(original, 1, [200]);
    expect(spliced).not.toBe(original);
    expect(original).toEqual([1, 2, 3]);
  });
  it("adds values at the given index", () => {
    const spliced = spliceIn([1, 2, 3], 1, [200]);
    expect(spliced).toEqual([1, 200, 2, 3]);
  });
});
<|endoftext|>


<commit_before>/**
 * Copyright 2018 The AMP HTML Authors. All Rights Reserved.
 *
 * 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.
 */

import {BrowserController} from '../../../../../testing/test-helper';

const TIMEOUT = 15000;

describe('amp-list (integration)', function() {
  this.timeout(TIMEOUT);

  const basicBody =
    `<amp-list width=300 height=100 src="http://localhost:9876/list/fruit-data/get?cors=0">
      <template type="amp-mustache">
        {{name}} : {{quantity}} @ {{unitPrice}}
      </template>
    '</amp-list>`;

  const basicTests = env => {

    let browser;
    let doc;
    let win;

    beforeEach(() => {
      win = env.win;
      browser = new BrowserController(win);
      doc = win.document;
    });

    it('should build', function*() {
      const list = doc.querySelector('amp-list');
      expect(list).to.exist;
      yield browser.waitForElementBuild('amp-list', TIMEOUT);
      const container = list.querySelector('div[role="list"]');
      expect(container).to.exist;
    });

    // TODO(choumx): Frequent 10s timeout on Chrome 72.0.3626 (Linux 0.0.0).
    it.skip('should render items', function*() {
      const list = doc.querySelector('amp-list');
      expect(list).to.exist;

      yield browser.waitForElementLayout('amp-list', TIMEOUT);

      const children = list.querySelectorAll('div[role=list] > div');
      expect(children.length).to.equal(3);
      expect(children[0].textContent.trim()).to.equal('apple : 47 @ 0.33');
      expect(children[1].textContent.trim()).to.equal('pear : 538 @ 0.54');
      expect(children[2].textContent.trim()).to.equal('tomato : 0 @ 0.23');
    });
  };

  describes.integration('basic (mustache-0.1)', {
    body: basicBody,
    extensions: ['amp-list', 'amp-mustache:0.1'],
  }, basicTests);

  describes.integration('basic (mustache-0.2)', {
    body: basicBody,
    extensions: ['amp-list', 'amp-mustache:0.2'],
  }, basicTests);
});
<commit_msg>amp-list script template integration test (#22095)<commit_after>/**
 * Copyright 2018 The AMP HTML Authors. All Rights Reserved.
 *
 * 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.
 */

import {BrowserController} from '../../../../../testing/test-helper';

const TIMEOUT = 15000;

describe('amp-list (integration)', function() {
  this.timeout(TIMEOUT);

  const basicBody =
    `<amp-list width=300 height=100 src="http://localhost:9876/list/fruit-data/get?cors=0">
      <template type="amp-mustache">
        {{name}} : {{quantity}} @ {{unitPrice}}
      </template>
    '</amp-list>`;

  const scriptTemplateBody =
  `<amp-list width=300 height=100 src="http://localhost:9876/list/fruit-data/get?cors=0">
    <script type="text/plain" template="amp-mustache">
      {{name}} : {{quantity}} @ {{unitPrice}}
    </script>
  '</amp-list>`;

  const basicTests = env => {

    let browser;
    let doc;
    let win;

    beforeEach(() => {
      win = env.win;
      browser = new BrowserController(win);
      doc = win.document;
    });

    it('should build', function*() {
      const list = doc.querySelector('amp-list');
      expect(list).to.exist;
      yield browser.waitForElementBuild('amp-list', TIMEOUT);
      const container = list.querySelector('div[role="list"]');
      expect(container).to.exist;
    });

    // TODO(choumx): Frequent 10s timeout on Chrome 72.0.3626 (Linux 0.0.0).
    it.skip('should render items', function*() {
      const list = doc.querySelector('amp-list');
      expect(list).to.exist;

      yield browser.waitForElementLayout('amp-list', TIMEOUT);

      const children = list.querySelectorAll('div[role=list] > div');
      expect(children.length).to.equal(3);
      expect(children[0].textContent.trim()).to.equal('apple : 47 @ 0.33');
      expect(children[1].textContent.trim()).to.equal('pear : 538 @ 0.54');
      expect(children[2].textContent.trim()).to.equal('tomato : 0 @ 0.23');
    });
  };

  describes.integration('basic (mustache-0.1)', {
    body: basicBody,
    extensions: ['amp-list', 'amp-mustache:0.1'],
  }, basicTests);

  describes.integration('basic (mustache-0.2)', {
    body: basicBody,
    extensions: ['amp-list', 'amp-mustache:0.2'],
  }, basicTests);

  describes.integration('basic (mustache-0.1) script template', {
    body: scriptTemplateBody,
    extensions: ['amp-list', 'amp-mustache:0.1'],
  }, basicTests);

  describes.integration('basic (mustache-0.2) script template', {
    body: scriptTemplateBody,
    extensions: ['amp-list', 'amp-mustache:0.2'],
  }, basicTests);
});
<|endoftext|>


<commit_before>var path   = require('path'),
    fs     = require('fs'),
    log4js = require('log4js');

log4js.configure(path.join(__dirname, "log4js.json"));

var config = {
  DNODE_PORT: 0xC5EA,
  SEARCH_REPO: path.join(__dirname, "../../linux"),
  SEARCH_REF:  "v3.0",
  SEARCH_ARGS: [],
  BACKEND_CONNECTIONS: 8,
  BACKENDS: [
    ["localhost", 0xC5EA]
  ]
};

try {
  fs.statSync(path.join(__dirname, 'config.local.js'));
  var local = require('./config.local.js');
  Object.keys(local).forEach(
    function (k){
      config[k] = local[k]
    })
} catch (e) {
}

module.exports = config;
<commit_msg>Allow config.local to override log4js configuration.<commit_after>var path   = require('path'),
    fs     = require('fs'),
    log4js = require('log4js');

var config = {
  DNODE_PORT: 0xC5EA,
  SEARCH_REPO: path.join(__dirname, "../../linux"),
  SEARCH_REF:  "v3.0",
  SEARCH_ARGS: [],
  BACKEND_CONNECTIONS: 8,
  BACKENDS: [
    ["localhost", 0xC5EA]
  ],
  LOG4JS_CONFIG: path.join(__dirname, "log4js.json")
};

try {
  fs.statSync(path.join(__dirname, 'config.local.js'));
  var local = require('./config.local.js');
  Object.keys(local).forEach(
    function (k){
      config[k] = local[k]
    })
} catch (e) {
}

log4js.configure(config.LOG4JS_CONFIG);

module.exports = config;
<|endoftext|>


<commit_before>var assert = require('assert'),
    ltsv = require('../');

suite('ltsvのテスト', function() {

  suite('parse関数のテスト', function() {

    test('パースできること', function() {
      var result = ltsv.parse('aaa:bbb\tccc:ddd\teee:fff');

      assert.deepEqual(result, {
        aaa: 'bbb',
        ccc: 'ddd',
        eee: 'fff'
      }, 'result has any records');
    });

  });

});
<commit_msg>テストコードを若干見やすくした<commit_after>var assert = require('assert'),
    ltsv = require('../');

suite('ltsvのテスト', function() {

  suite('parse関数のテスト', function() {

    test('パースできること', function() {
      var result = ltsv.parse([
        'aaa:bbb',
        'ccc:ddd',
        'eee:fff'
      ].join('\t'));

      assert.deepEqual(result, {
        aaa: 'bbb',
        ccc: 'ddd',
        eee: 'fff'
      }, 'result has any records');
    });

  });

});
<|endoftext|>


<commit_before>(function(){
    var depth = parseInt(window.location.search.substring(1));

    if(isNaN(depth)
      || depth < 0){
        depth = 1;
    }

    var display = [];

    Object.getOwnPropertyNames(window).forEach(
      function(property){
          display.push(
            '
'
            + property
            + ''
            + window[property]
          );
          fetchInfo(
            window[property],
            property,
            0
          );
      }
    );

    function fetchInfo(object, name, depthcounter){
        if(depthcounter >= depth
          || object == window){
            return;
        }

        for(property in object){
            if(object.hasOwnProperty(property)){
                display.push(
                  '
'
                  + name
                  + '.'
                  + property
                  + ''
                  + object[property]
                );
                fetchInfo(
                  object[property],
                  name + '.' + property,
                  depthcounter + 1
                );
            }
        }
    }

    document.getElementById('property-list').innerHTML =
      '
window.WindowInfo.htm (Depth: '
      + depth
      + ')'
      + display.sort().join('');
}());
<commit_msg>added default depth parameter<commit_after>(function(){
    var depth = parseInt(window.location.search.substring(1));

    if(isNaN(depth)
      || depth < 0){
        depth = 1;
        location.replace('?1');
    }

    var display = [];

    Object.getOwnPropertyNames(window).forEach(
      function(property){
          display.push(
            '
'
            + property
            + ''
            + window[property]
          );
          fetchInfo(
            window[property],
            property,
            0
          );
      }
    );

    function fetchInfo(object, name, depthcounter){
        if(depthcounter >= depth
          || object == window){
            return;
        }

        for(property in object){
            if(object.hasOwnProperty(property)){
                display.push(
                  '
'
                  + name
                  + '.'
                  + property
                  + ''
                  + object[property]
                );
                fetchInfo(
                  object[property],
                  name + '.' + property,
                  depthcounter + 1
                );
            }
        }
    }

    document.getElementById('property-list').innerHTML =
      '
window.WindowInfo.htm (Depth: '
      + depth
      + ')'
      + display.sort().join('');
}());
<|endoftext|>


<commit_before>describes.endtoend(
  'bento-sidebar',
  {
    version: '1.0',
    fixture: 'bento/sidebar.html',
    environments: ['single'],
  },
  (env) => {
    let controller;

    beforeEach(() => {
      controller = env.controller;
    });

    it('should be able to open and close', async () => {
      // check if sidebar content is not visibile
      const navLinkInSidebar = await controller.findElement('nav');
      await expect(controller.isElementDisplayed(navLinkInSidebar)).to.be.false;

      // Open sidebar
      const openButton = await controller.findElement('#open-sidebar');
      controller.click(openButton);

      // check if sidebar content is visible
      await expect(controller.isElementDisplayed(navLinkInSidebar)).to.be.true;

      // Close sidebar
      const closeButton = await controller.findElement('#close-sidebar');
      controller.click(closeButton);

      // check if sidebar content is not visible
      await expect(controller.isElementDisplayed(navLinkInSidebar)).to.be.false;
    });
  }
);
<commit_msg>[bento-sidebar] refactor e2e test to hopefully be less flaky (#36974)<commit_after>describes.endtoend(
  'bento-sidebar',
  {
    version: '1.0',
    fixture: 'bento/sidebar.html',
    environments: ['single'],
  },
  (env) => {
    let controller;

    beforeEach(() => {
      controller = env.controller;
    });

    it('should be able to open and close', async () => {
      // check if sidebar content is not visibile
      const navInLightDom = await controller.findElement('nav');
      await expect(controller.isElementDisplayed(navInLightDom)).to.be.false;

      // Open sidebar
      const openButton = await controller.findElement('#open-sidebar');
      controller.click(openButton);

      // wait for sidebar to finish open animation
      const element = await controller.findElement('bento-sidebar');
      await controller.switchToShadowRoot(element);
      const navInShadowDom = await controller.findElement('[part="sidebar"]');

      // check if sidebar content is visible
      await expect(controller.isElementDisplayed(navInShadowDom)).to.be.true;
      await expect(controller.getElementRect(navInShadowDom)).to.include({
        width: 128,
        right: 128,
      });

      await controller.switchToLight();
      // Close sidebar
      const closeButton = await controller.findElement('#close-sidebar');
      controller.click(closeButton);

      // check if sidebar content is not visible
      await expect(controller.isElementDisplayed(navInShadowDom)).to.be.false;
    });
  }
);
<|endoftext|>


<commit_before>/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version).to.exist;
        expect(npmPackage.version).to.exist;

        if (!expect(ioPackage.common.version).to.be.equal(npmPackage.version)) {
            console.log('ERROR: Version numbers in package.json and io-package.json differ!!');
        }

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
        }

        expect(ioPackage.common.authors).to.exist;
        if (ioPackage.common.name.indexOf('template') !== 0) {
            if (Array.isArray(ioPackage.common.authors)) {
                expect(ioPackage.common.authors.length).to.not.be.equal(0);
                if (ioPackage.common.authors.length === 1) {
                    expect(ioPackage.common.authors[0]).to.not.be.equal('my Name <my@email.com>');
                }
            }
            else {
                expect(ioPackage.common.authors).to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            console.log('Testing for set authors field in io-package skipped because template adapter');
        }
        done();
    });
});
<commit_msg>update basic package-file testing<commit_after>/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        console.log();

        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json', 'utf8');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json', 'utf8');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version, 'ERROR: Version number in io-package.json needs to exist').to.exist;
        expect(npmPackage.version, 'ERROR: Version number in package.json needs to exist').to.exist;

        expect(ioPackage.common.version, 'ERROR: Version numbers in package.json and io-package.json needs to match').to.be.equal(npmPackage.version);

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
            console.log();
        }

        expect(npmPackage.author, 'ERROR: Author in package.json needs to exist').to.exist;
        expect(ioPackage.common.authors, 'ERROR: Authors in io-package.json needs to exist').to.exist;

        if (ioPackage.common.name.indexOf('template') !== 0) {
            if (Array.isArray(ioPackage.common.authors)) {
                expect(ioPackage.common.authors.length, 'ERROR: Author in io-package.json needs to be set').to.not.be.equal(0);
                if (ioPackage.common.authors.length === 1) {
                    expect(ioPackage.common.authors[0], 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
                }
            }
            else {
                expect(ioPackage.common.authors, 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            console.log('WARNING: Testing for set authors field in io-package skipped because template adapter');
            console.log();
        }
        expect(fs.existsSync(__dirname + '/../README.md'), 'ERROR: README.md needs to exist! Please create one with description, detail information and changelog. English is mandatory.').to.be.true;
        if (!ioPackage.common.titleLang || typeof ioPackage.common.titleLang !== 'object') {
            console.log('WARNING: titleLang is not existing in io-package.json. Please add');
            console.log();
        }
        if (
            ioPackage.common.title.indexOf('iobroker') !== -1 ||
            ioPackage.common.title.indexOf('ioBroker') !== -1 ||
            ioPackage.common.title.indexOf('adapter') !== -1 ||
            ioPackage.common.title.indexOf('Adapter') !== -1
        ) {
            console.log('WARNING: title contains Adapter or ioBroker. It is clear anyway, that it is adapter for ioBroker.');
            console.log();
        }

        if (ioPackage.common.name.indexOf('vis-') !== 0) {
            if (!ioPackage.common.materialize || !fs.existsSync(__dirname + '/../admin/index_m.html') || !fs.existsSync(__dirname + '/../gulpfile.js')) {
                console.log('WARNING: Admin3 support is missing! Please add it');
                console.log();
            }
            if (ioPackage.common.materialize) {
                expect(fs.existsSync(__dirname + '/../admin/index_m.html'), 'Admin3 support is enabled in io-package.json, but index_m.html is missing!').to.be.true;
            }
        }

        var licenseFileExists = fs.existsSync(__dirname + '/../LICENSE');
        var fileContentReadme = fs.readFileSync(__dirname + '/../README.md', 'utf8');
        if (fileContentReadme.indexOf('## Changelog') === -1) {
            console.log('Warning: The README.md should have a section ## Changelog');
            console.log();
        }
        expect((licenseFileExists || fileContentReadme.indexOf('## License') !== -1), 'A LICENSE must exist as LICENSE file or as part of the README.md').to.be.true;
        if (!licenseFileExists) {
            console.log('Warning: The License should also exist as LICENSE file');
            console.log();
        }
        if (fileContentReadme.indexOf('## License') === -1) {
            console.log('Warning: The README.md should also have a section ## License to be shown in Admin3');
            console.log();
        }
        done();
    });
});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import update from 'react-addons-update';
import KanbanBoard from './KanbanBoard';

const API_URL = 'http://kanbanapi.pro-react.com';
const API_HEADERS = {
  'Content-Type': 'application/json',
  Authorization: 'adg29-react'
};

class KanbanBoardContainer extends Component {
  constructor() {
    super(...arguments);
    this.state = {
      cards: [],
    };
  }

  addTask(cardId, taskName) {}
  deleteTask(cardId, taskId, taskIndex) {
    // Find the index of the card
    let cardIndex = this.state.cards.findIndex((card) => card.id == cardId);
    // Create a new object without the task
    let nextState = update(this.state.cards, {
      [cardIndex]: {
        tasks: {
          $splice: [[taskIndex, 1]]
        }
      }
    });
    // set the component state to the mutated object
    this.setState({
      cards: nextState
    });
    // Call the API to remove the task on the server
    fetch(`${API_URL}/cards/${cardId}/tasks/${taskId}`, {
      method: 'delete',
      headers: API_HEADERS
    });

  }
  toggleTask(cardId, taskId, taskIndex) {}

  componentDidMount() {
    fetch(API_URL + '/cards', {
      headers: API_HEADERS
    })
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          cards: responseData
        });
      })
      .catch((error) => {
        console.log('Error fetching and parsing data', error);
      });
  }

  render() {
    return <KanbanBoard cards={ this.state.cards } taskCallbacks={ { toggle: this.toggleTask.bind(this), delete: this.deleteTask.bind(this), add: this.addTask.bind(this) } } />
  }
}
export default KanbanBoardContainer;

<commit_msg>Toggling a task by splicing the array, walk the object hierarchy up to the done property of the task and directly manipulate its value using a function with the immutability helper. when adding tasks since all tasks need an ID,  generate a temporary ID for the task until it’s persisted to the server and it returns the definitive ID. Then update the task ID<commit_after>import React, { Component } from 'react';
import update from 'react-addons-update';
import KanbanBoard from './KanbanBoard';

const API_URL = 'http://kanbanapi.pro-react.com';
const API_HEADERS = {
  'Content-Type': 'application/json',
  Authorization: 'adg29-react'
};

class KanbanBoardContainer extends Component {
  constructor() {
    super(...arguments);
    this.state = {
      cards: [],
    };
  }

  addTask(cardId, taskName) {
    // Find the index of the card
    let cardIndex = this.state.cards.findIndex((card) => card.id == cardId);
    // Create a new task with the given name and a temporary ID
    let newTask = {
      id: Date.now(),
      name: taskName,
      done: false
    };

    // Create a new object and push the new task to the array of tasks
    let nextState = update(this.state.cards, {
      [cardIndex]: {
        tasks: {
          $push: [newTask]
        }
      }
    });
    // set the component state to the mutated object
    this.setState({
      cards: nextState
    });
    // Call the API to add the task on the server
    fetch(`${API_URL}/cards/${cardId}/tasks`, {
      method: 'post',
      headers: API_HEADERS,
      body: JSON.stringify(newTask)
    })
      .then((response) => response.json())
      .then((responseData) => {
        // When the server returns the definitive ID
        // used for the new Task on the server, update it on React
        newTask.id = responseData.id;
        this.setState({
          cards: nextState
        });
      });
  }

  deleteTask(cardId, taskId, taskIndex) {
    // Find the index of the card
    let cardIndex = this.state.cards.findIndex((card) => card.id == cardId);
    // Create a new object without the task
    let nextState = update(this.state.cards, {
      [cardIndex]: {
        tasks: {
          $splice: [[taskIndex, 1]]
        }
      }
    });
    // set the component state to the mutated object
    this.setState({
      cards: nextState
    });
    // Call the API to remove the task on the server
    fetch(`${API_URL}/cards/${cardId}/tasks/${taskId}`, {
      method: 'delete',
      headers: API_HEADERS
    });

  }
  toggleTask(cardId, taskId, taskIndex) {
    // Find the index of the card
    let cardIndex = this.state.cards.findIndex((card) => card.id == cardId);
    // Save a reference to the task's 'done' value
    let newDoneValue;
    // Using the $apply command, you will change the done value to its opposite
    let nextState = update(this.state.cards, {
      [cardIndex]: {
        tasks: {
          [taskIndex]: {
            done: {
              $apply: (done) => {
                newDoneValue = !done
                return newDoneValue;
              }
            }
          }
        }
      }
    });
    // set the component state to the mutated object
    this.setState({
      cards: nextState
    });
    // Call the API to toggle the task on the server
    fetch(`${API_URL}/cards/${cardId}/tasks/${taskId}`, {
      method: 'put',
      headers: API_HEADERS,
      body: JSON.stringify({
        done: newDoneValue
      })
    });
  }
  componentDidMount() {
    fetch(API_URL + '/cards', {
      headers: API_HEADERS
    })
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          cards: responseData
        });
      })
      .catch((error) => {
        console.log('Error fetching and parsing data', error);
      });
  }

  render() {
    return <KanbanBoard cards={ this.state.cards } taskCallbacks={ { toggle: this.toggleTask.bind(this), delete: this.deleteTask.bind(this), add: this.addTask.bind(this) } } />
  }
}
export default KanbanBoardContainer;

<|endoftext|>


<commit_before>/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        console.log();

        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json', 'utf8');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json', 'utf8');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version, 'ERROR: Version number in io-package.json needs to exist').to.exist;
        expect(npmPackage.version, 'ERROR: Version number in package.json needs to exist').to.exist;

        expect(ioPackage.common.version, 'ERROR: Version numbers in package.json and io-package.json needs to match').to.be.equal(npmPackage.version);

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
            console.log();
        }

        expect(npmPackage.author, 'ERROR: Author in package.json needs to exist').to.exist;
        expect(ioPackage.common.authors, 'ERROR: Authors in io-package.json needs to exist').to.exist;

        if (ioPackage.common.name.indexOf('template') !== 0) {
            if (Array.isArray(ioPackage.common.authors)) {
                expect(ioPackage.common.authors.length, 'ERROR: Author in io-package.json needs to be set').to.not.be.equal(0);
                if (ioPackage.common.authors.length === 1) {
                    expect(ioPackage.common.authors[0], 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
                }
            }
            else {
                expect(ioPackage.common.authors, 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            console.log('WARNING: Testing for set authors field in io-package skipped because template adapter');
            console.log();
        }
        expect(fs.existsSync(__dirname + '/../README.md'), 'ERROR: README.md needs to exist! Please create one with description, detail information and changelog. English is mandatory.').to.be.true;
        expect(fs.existsSync(__dirname + '/../LICENSE'), 'ERROR: LICENSE needs to exist! Please create one.').to.be.true;
        if (!ioPackage.common.titleLang || typeof ioPackage.common.titleLang !== 'object') {
            console.log('WARNING: titleLang is not existing in io-package.json. Please add');
            console.log();
        }
        if (
            ioPackage.common.title.indexOf('iobroker') !== -1 ||
            ioPackage.common.title.indexOf('ioBroker') !== -1 ||
            ioPackage.common.title.indexOf('adapter') !== -1 ||
            ioPackage.common.title.indexOf('Adapter') !== -1
        ) {
            console.log('WARNING: title contains Adapter or ioBroker. It is clear anyway, that it is adapter for ioBroker.');
            console.log();
        }

        if (ioPackage.common.name.indexOf('vis-') !== 0) {
            if (!ioPackage.common.materialize || !fs.existsSync(__dirname + '/../admin/index_m.html') || !fs.existsSync(__dirname + '/../gulpfile.js')) {
                console.log('WARNING: Admin3 support is missing! Please add it');
                console.log();
            }
            if (ioPackage.common.materialize) {
                expect(fs.existsSync(__dirname + '/../admin/index_m.html'), 'Admin3 support is enabled in io-package.json, but index_m.html is missing!').to.be.true;
            }
        }

        expect(fs.existsSync(__dirname + '/../LICENSE'), 'A LICENSE must exist');
        var fileContentReadme = fs.readFileSync(__dirname + '/../README.md', 'utf8');
        if (fileContentReadme.indexOf('## License') === -1) {
            console.log('Warning: The README.md should have a section ## License');
            console.log();
        }
        if (fileContentReadme.indexOf('## Changelog') === -1) {
            console.log('Warning: The README.md should have a section ## Changelog');
            console.log();
        }
        done();
    });
});
<commit_msg>update basic package-file testing<commit_after>/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        console.log();

        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json', 'utf8');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json', 'utf8');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version, 'ERROR: Version number in io-package.json needs to exist').to.exist;
        expect(npmPackage.version, 'ERROR: Version number in package.json needs to exist').to.exist;

        expect(ioPackage.common.version, 'ERROR: Version numbers in package.json and io-package.json needs to match').to.be.equal(npmPackage.version);

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
            console.log();
        }

        expect(npmPackage.author, 'ERROR: Author in package.json needs to exist').to.exist;
        expect(ioPackage.common.authors, 'ERROR: Authors in io-package.json needs to exist').to.exist;

        if (ioPackage.common.name.indexOf('template') !== 0) {
            if (Array.isArray(ioPackage.common.authors)) {
                expect(ioPackage.common.authors.length, 'ERROR: Author in io-package.json needs to be set').to.not.be.equal(0);
                if (ioPackage.common.authors.length === 1) {
                    expect(ioPackage.common.authors[0], 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
                }
            }
            else {
                expect(ioPackage.common.authors, 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            console.log('WARNING: Testing for set authors field in io-package skipped because template adapter');
            console.log();
        }
        expect(fs.existsSync(__dirname + '/../README.md'), 'ERROR: README.md needs to exist! Please create one with description, detail information and changelog. English is mandatory.').to.be.true;
        expect(fs.existsSync(__dirname + '/../LICENSE'), 'ERROR: LICENSE needs to exist! Please create one.').to.be.true;
        if (!ioPackage.common.titleLang || typeof ioPackage.common.titleLang !== 'object') {
            console.log('WARNING: titleLang is not existing in io-package.json. Please add');
            console.log();
        }
        if (
            ioPackage.common.title.indexOf('iobroker') !== -1 ||
            ioPackage.common.title.indexOf('ioBroker') !== -1 ||
            ioPackage.common.title.indexOf('adapter') !== -1 ||
            ioPackage.common.title.indexOf('Adapter') !== -1
        ) {
            console.log('WARNING: title contains Adapter or ioBroker. It is clear anyway, that it is adapter for ioBroker.');
            console.log();
        }

        if (ioPackage.common.name.indexOf('vis-') !== 0) {
            if (!ioPackage.common.materialize || !fs.existsSync(__dirname + '/../admin/index_m.html') || !fs.existsSync(__dirname + '/../gulpfile.js')) {
                console.log('WARNING: Admin3 support is missing! Please add it');
                console.log();
            }
            if (ioPackage.common.materialize) {
                expect(fs.existsSync(__dirname + '/../admin/index_m.html'), 'Admin3 support is enabled in io-package.json, but index_m.html is missing!').to.be.true;
            }
        }

        var licenseFileExists = fs.existsSync(__dirname + '/../LICENSE');
        var fileContentReadme = fs.readFileSync(__dirname + '/../README.md', 'utf8');
        if (fileContentReadme.indexOf('## Changelog') === -1) {
            console.log('Warning: The README.md should have a section ## Changelog');
            console.log();
        }
        expect((licenseFileExists || fileContentReadme.indexOf('## License') !== -1), 'A LICENSE must exist as LICENSE file or as part of the README.md').to.be.true;
        if (!licenseFileExists) {
            console.log('Warning: The License should also exist as LICENSE file');
            console.log();
        }
        if (fileContentReadme.indexOf('## License') === -1) {
            console.log('Warning: The README.md should also have a section ## License to be shown in Admin3');
            console.log();
        }
        done();
    });
});
<|endoftext|>


<commit_before>// this file is the entrypoint for building a browser file with browserify

colorConvert = require("./index");<commit_msg>Delete browser.js<commit_after><|endoftext|>


<commit_before>"use strict"
var chevrotain = require("chevrotain")

// ----------------- lexer -----------------
var Token = chevrotain.Token
var Lexer = chevrotain.Lexer
var Parser = chevrotain.Parser

// With ES6 we can define Tokens using the class keywords.

// Unfortunately no support for static class properties in ES2015, only in ES2016...
// so the PATTERN/GROUP static props are defined outside the class declarations.
// see: https://github.com/jeffmo/es-class-fields-and-static-properties
class True extends Token {}
True.PATTERN = /true/

class False extends Token {}
False.PATTERN = /false/

class Null extends Token {}
Null.PATTERN = /null/

class LCurly extends Token {}
LCurly.PATTERN = /{/

class RCurly extends Token {}
RCurly.PATTERN = /}/

class LSquare extends Token {}
LSquare.PATTERN = /\[/

class RSquare extends Token {}
RSquare.PATTERN = /]/

class Comma extends Token {}
Comma.PATTERN = /,/

class Colon extends Token {}
Colon.PATTERN = /:/

class StringLiteral extends Token {}
StringLiteral.PATTERN = /"(?:[^\\"]+|\\(?:[bfnrtv"\\/]|u[0-9a-fA-F]{4}))*"/

class NumberLiteral extends Token {}
NumberLiteral.PATTERN = /-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?/

class WhiteSpace extends Token {}
WhiteSpace.PATTERN = /\s+/
WhiteSpace.GROUP = Lexer.SKIPPED // marking WhiteSpace as 'SKIPPED' makes the lexer skip it.

var allTokens = [WhiteSpace, NumberLiteral, StringLiteral, LCurly, RCurly, LSquare, RSquare, Comma, Colon, True, False, Null]
var JsonLexer = new Lexer(allTokens)

// ----------------- parser -----------------
// Using ES6 the parser too can be defined as a class
class JsonParserES6 extends chevrotain.Parser {

    constructor(input) {
        super(input, allTokens)

        // not mandatory, using $ (or any other sign) to reduce verbosity (this. this. this. this. .......)
        var $ = this

        $.RULE("json", () => {
            $.OR([
                // using ES6 Arrow functions to reduce verbosity.
                {ALT: () => { $.SUBRULE($.object) }},
                {ALT: () => { $.SUBRULE($.array) }}
            ])
        })

        // the parsing methods
        $.RULE("object", () => {
            $.CONSUME(LCurly)
            $.OPTION(() => {
                $.SUBRULE($.objectItem)
                $.MANY(() => {
                    $.CONSUME(Comma)
                    $.SUBRULE2($.objectItem)
                })
            })
            $.CONSUME(RCurly)
        })

        $.RULE("objectItem", () => {
            $.CONSUME(StringLiteral)
            $.CONSUME(Colon)
            $.SUBRULE($.value)
        })

        $.RULE("array", () => {
            $.CONSUME(LSquare)
            $.OPTION(() => {
                $.SUBRULE($.value)
                $.MANY(() => {
                    $.CONSUME(Comma)
                    $.SUBRULE2($.value)
                })
            })
            $.CONSUME(RSquare)
        })

        $.RULE("value", () => {
            $.OR([
                {ALT: () => { $.CONSUME(StringLiteral) }},
                {ALT: () => { $.CONSUME(NumberLiteral) }},
                {ALT: () => { $.SUBRULE($.object) }},
                {ALT: () => { $.SUBRULE($.array) }},
                {ALT: () => { $.CONSUME(True) }},
                {ALT: () => { $.CONSUME(False) }},
                {ALT: () => { $.CONSUME(Null) }}
            ])
        })

        // very important to call this after all the rules have been defined.
        // otherwise the parser may not work correctly as it will lack information
        // derived during the self analysis phase.
        Parser.performSelfAnalysis(this)
    }
}

// ----------------- wrapping it all together -----------------

// reuse the same parser instance.
var parser = new JsonParserES6([])

module.exports = function(text) {
    var lexResult = JsonLexer.tokenize(text)
    // setting a new input will RESET the parser instance's state.
    parser.input = lexResult.tokens
    // any top level rule may be used as an entry point
    var value = parser.json()

    return {
        value:       value, // this is a pure grammar, the value will always be <undefined>
        lexErrors:   lexResult.errors,
        parseErrors: parser.errors
    }
}
<commit_msg>use const in ES6 example<commit_after>"use strict"
const chevrotain = require("chevrotain")

// ----------------- lexer -----------------
const Token = chevrotain.Token
const Lexer = chevrotain.Lexer
const Parser = chevrotain.Parser

// With ES6 we can define Tokens using the class keywords.

// Unfortunately no support for static class properties in ES2015, only in ES2016...
// so the PATTERN/GROUP static props are defined outside the class declarations.
// see: https://github.com/jeffmo/es-class-fields-and-static-properties
class True extends Token {}
True.PATTERN = /true/

class False extends Token {}
False.PATTERN = /false/

class Null extends Token {}
Null.PATTERN = /null/

class LCurly extends Token {}
LCurly.PATTERN = /{/

class RCurly extends Token {}
RCurly.PATTERN = /}/

class LSquare extends Token {}
LSquare.PATTERN = /\[/

class RSquare extends Token {}
RSquare.PATTERN = /]/

class Comma extends Token {}
Comma.PATTERN = /,/

class Colon extends Token {}
Colon.PATTERN = /:/

class StringLiteral extends Token {}
StringLiteral.PATTERN = /"(?:[^\\"]+|\\(?:[bfnrtv"\\/]|u[0-9a-fA-F]{4}))*"/

class NumberLiteral extends Token {}
NumberLiteral.PATTERN = /-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?/

class WhiteSpace extends Token {}
WhiteSpace.PATTERN = /\s+/
WhiteSpace.GROUP = Lexer.SKIPPED // marking WhiteSpace as 'SKIPPED' makes the lexer skip it.

const allTokens = [WhiteSpace, NumberLiteral, StringLiteral, LCurly, RCurly, LSquare, RSquare, Comma, Colon, True, False, Null]
const JsonLexer = new Lexer(allTokens)

// ----------------- parser -----------------
// Using ES6 the parser too can be defined as a class
class JsonParserES6 extends chevrotain.Parser {

    constructor(input) {
        super(input, allTokens)

        // not mandatory, using $ (or any other sign) to reduce verbosity (this. this. this. this. .......)
        const $ = this

        $.RULE("json", () => {
            $.OR([
                // using ES6 Arrow functions to reduce verbosity.
                {ALT: () => { $.SUBRULE($.object) }},
                {ALT: () => { $.SUBRULE($.array) }}
            ])
        })

        // the parsing methods
        $.RULE("object", () => {
            $.CONSUME(LCurly)
            $.OPTION(() => {
                $.SUBRULE($.objectItem)
                $.MANY(() => {
                    $.CONSUME(Comma)
                    $.SUBRULE2($.objectItem)
                })
            })
            $.CONSUME(RCurly)
        })

        $.RULE("objectItem", () => {
            $.CONSUME(StringLiteral)
            $.CONSUME(Colon)
            $.SUBRULE($.value)
        })

        $.RULE("array", () => {
            $.CONSUME(LSquare)
            $.OPTION(() => {
                $.SUBRULE($.value)
                $.MANY(() => {
                    $.CONSUME(Comma)
                    $.SUBRULE2($.value)
                })
            })
            $.CONSUME(RSquare)
        })

        $.RULE("value", () => {
            $.OR([
                {ALT: () => { $.CONSUME(StringLiteral) }},
                {ALT: () => { $.CONSUME(NumberLiteral) }},
                {ALT: () => { $.SUBRULE($.object) }},
                {ALT: () => { $.SUBRULE($.array) }},
                {ALT: () => { $.CONSUME(True) }},
                {ALT: () => { $.CONSUME(False) }},
                {ALT: () => { $.CONSUME(Null) }}
            ])
        })

        // very important to call this after all the rules have been defined.
        // otherwise the parser may not work correctly as it will lack information
        // derived during the self analysis phase.
        Parser.performSelfAnalysis(this)
    }
}

// ----------------- wrapping it all together -----------------

// reuse the same parser instance.
const parser = new JsonParserES6([])

module.exports = function(text) {
    const lexResult = JsonLexer.tokenize(text)
    // setting a new input will RESET the parser instance's state.
    parser.input = lexResult.tokens
    // any top level rule may be used as an entry point
    const value = parser.json()

    return {
        value:       value, // this is a pure grammar, the value will always be <undefined>
        lexErrors:   lexResult.errors,
        parseErrors: parser.errors
    }
}
<|endoftext|>