text:
var rows = [], cols = [], start, end;

function FigFamSorterStateObject(windowID, serveResource, getContextPath, keyword_search, familyType) {
	// save initial values
	this.windowID = windowID;
	this.serveURL = serveResource;
	this.contextPath = getContextPath;

	// set duration at 30 days or desired value
	this.duration = defaultDuration;

	this.familyType = familyType;

	this.keyword_search = keyword_search;

	this.syntonyId = "";

	this.ClusterRowOrder = [];
	this.ClusterColumnOrder = [];

	this.heatmapAxis = '';
	this.colorScheme = 'rgb';

	this.genomeIds = [];
	// this.genomeNames = [];
	this.genomeVSfilter = null;
	//this.orders = [];
	//this.ncbitaxIds = [];

	this.cType = '';
	this.cId = '';

	this.filter = '';
	this.regex = '';

	this.perfectFamMatch = 'A';

	this.minnumber_of_members = '';
	this.maxnumber_of_members = '';

	this.minnumber_of_species = '';
	this.maxnumber_of_species = '';

	this.heatmapState = null;

	this.loadData = FigFamSorterLoadData;
	this.saveData = FigFamSorterSaveData;
}

var GenomeVSFilterPair = ( function() {
		function init(index, genome_name) {
			this.index = index, this.status = ' ', this.genome_name = genome_name;
		}

		function getIndex() {
			return this.index;
		}

		function getGenomeName() {
			return this.genome_name;
		}

		function getStatus() {
			return this.status;
		}

		function setStatus(status) {
			this.status = status;
		}

		return function() {
			this.init = init, this.setStatus = setStatus, this.getStatus = getStatus, this.getGenomeName = getGenomeName, this.getIndex = getIndex;
			return this;
		};
	}());

//create a method for the required saveData link
function FigFamSorterSaveData(windowID, namespace) {
}

function FigFamSorterLoadData(namespace) {
}

function FigFamSorterOnReady(windowID, resourceURL, contextPath, cType, cId, keyword_search, idText, familyType, genomeFilter) {
	// register windowID to insure that state values gets stored to a cookie
	//   on page exits or refreshes
	addWindowID(windowID);
	// create a default state object with the critical values
	//   provided by the server
	var stateObject = new FigFamSorterStateObject(windowID, resourceURL, contextPath, keyword_search, familyType);

	//  try to get other state values that might have been saved in a cookie
	loadStateObject(windowID, stateObject);

	idForHeatmap = windowID;

	if ((idText != null) && (0 < idText.length)) {
		stateObject.genomeIds = idText.split(",");
		getGenomeNames(windowID, stateObject);
		stateObject.cType = cType;
		stateObject.cId = cId;
	} else if (cType == "genome") {
		stateObject.cType = cType;
		stateObject.cId = cId;
		stateObject.genomeIds = cId.split(",");
		getGenomeNames(windowID, stateObject);
	} else if (cType == "taxon") {
		stateObject.cType = cType;
		stateObject.cId = cId;
		Ext.Ajax.request({
			url : stateObject.serveURL,
			method : 'GET',
			timeout : 600000,
			params : {
				callType : "getTaxonIds",
				taxonId : cId,
				genomeFilter : genomeFilter
			},
			success : function(rs) {
				catchTaxonIds(windowID, stateObject, rs);
			}
		});
	}
}

function catchTaxonIds(windowID, stateObject, rs) {
	stateObject.genomeIds = (rs.responseText).split(",");
	getGenomeNames(windowID, stateObject);
}

function getGenomeNames(windowID, stateObject) {
	var genomeIds = stateObject.genomeIds, leftHtml, option1, option2, option3, option4;

	if (genomeIds.length > 500) {
		leftHtml = "
More than 500 genomes

";
	} else {
		leftHtml = "
" + genomeIds.length + " genomes (Change Genome Selection)
" + "

Present in all families

	Absent from all families

		Either/Mixed

" + "

";
	}

	option1 = "
Number of Proteins per Family

" + "<FORM NAME='" + windowID + "_memberForm' " + "ONSUBMIT=\"updateOrthoListTable('" + windowID + "'); return false;\">" + "

to

" + "</FORM>
";

	option2 = "

Number of Genomes per Family

" + "<FORM NAME='" + windowID + "_speciesForm' " + "ONSUBMIT=\"updateOrthoListTable('" + windowID + "'); return false;\">" + "

to

" + "</FORM>";

	option3 = "
" + "<INPUT title='Perfect Families (One protein per genome)' TYPE='radio' name='familySet' ID='" + windowID + "_perfectIn'\>Perfect Families (One protein per genome)
<INPUT title='Non Perfect Families' TYPE='radio' name='familySet' ID='" + windowID + "_perfectOut'/>Non Perfect Families" + "
<INPUT title='All Families' TYPE='radio' name='familySet' ID='" + windowID + "_perfectAll' CHECKED/>All Families" + "
";

	option4 = "Filter by one or more keywords
" + "

";

	leftHtml += "
" + option4 + option3 + option1 + option2 + "

<input type='button' class='button' style='padding: 2px 8px;' value='Filter' onclick=\"updateOrthoListTable('" + windowID + "');\"/>
";

	Ext.getDom("information_panel").innerHTML = "
For a description of what you can do from this Protein Families Sorter page, please see our " + "Protein Family Sorter User Guide.
";

	Ext.create('Ext.panel.Panel', {
		id : 'tabLayout',
		border : true,
		autoScroll : false,
		width : $(window).width() - 245,
		items : [{
			region : 'north',
			border : false,
			height : 22,
			xtype : 'tabpanel',
			id : 'tabPanel',
			items : [{
				title : "Table",
				id : "table-tab"
			}, {
				title : "Heatmap",
				id : "map-tab"
			}],
			listeners : {
				'tabchange' : function(tabPanel, tab) {
					var gridObject = getScratchObject(windowID);
					if (gridObject != null) {
						if (tab.getId() == "map-tab") {
							gridObject.activeTab = 1;
						} else {
							stateObject.ClusterRowOrder = [];
							stateObject.ClusterColumnOrder = [];
							gridObject.activeTab = 0;
							stateObject.heatmapState = displayStateOfFlash(jQuery(heatmapid)[0]);
							gridObject.gridState.storeInSession();
						}
						gridObject.showPanel(false);
					}
				}
			}
		}, {
			region : 'center',
			id : 'centerPanel',
			contentEl : 'information',
			height : 26,
			border : false,
			split : false
		}, {
			region : 'south',
			id : 'southPanel',
			html : "

",
			height : 775,
			border : false,
			autoScroll : true
		}],
		renderTo : 'sample-layout'
	});

	Ext.create('Ext.panel.Panel', {
		title : 'Filter By',
		renderTo : 'tree-panel',
		width : 239,
		height : 825,
		border : true,
		resizable : true,
		autoScroll : false,
		id : 'treePanel',
		collapsible : true,
		collapseDirection : 'left',
		items : [{
			id : 'westPanel',
			region : 'west',
			html : leftHtml,
			width : 239,
			height : 825,
			split : true,
			boder : false
		}],
		listeners : {
			resize : function(cmp, width, height, oldWidth, oldHeight, eOpts) {
				var Page = $Page;
				if (Page.getGrid()) {
					Ext.getCmp("westPanel").setWidth(width);
					Page.doTabLayout();
					if(Ext.getCmp(windowID + '_genome_grid'))
						Ext.getCmp(windowID + '_genome_grid').setWidth(width);
				}
			}
		}
	});

	createLeftBottomItems(windowID);
	doAjaxNames(windowID, stateObject);
}

function createLeftBottomItems(windowID) {

	Ext.create('Ext.form.field.TextArea', {
		id : windowID + '_toSetRegex',
		renderTo : 'textbox_div',
		width : 215,
		height : 75
	});

	Ext.create('Ext.form.field.Text', {
		id : windowID + '_minMembers',
		renderTo : '_minMembers',
		width : 40
	});

	Ext.create('Ext.form.field.Text', {
		id : windowID + '_maxMembers',
		renderTo : '_maxMembers',
		width : 40
	});

	Ext.create('Ext.form.field.Text', {
		id : windowID + '_minSpecies',
		renderTo : '_minSpecies',
		width : 40
	});

	Ext.create('Ext.form.field.Text', {
		id : windowID + '_maxSpecies',
		renderTo : '_maxSpecies',
		width : 40
	});

}

function doAjaxNames(windowID, stateObject) {"use strict";

	var stateObject = getStateObject(windowID), i, items, tableObject, gridObject;
	start = (new Date()).getMilliseconds();
	tableObject = new GroupGrid(windowID, stateObject, 0);

	if (stateObject.genomeIds == "") {
	    return false;
	}

	Ext.define('Genome_Store', {
		extend : 'Ext.data.Model',
		fields : [{
			name : 'genome_id',
			type : 'string'
		}, {
			name : 'genome_name',
			type : 'string'
		}, {
			name : 'genome_status',
			type : 'string'
		}, {
			name : 'isolation_country',
			type : 'string'
		}, {
			name : 'host_name',
			type : 'string'
		}, {
			name : 'disease',
			type : 'string'
		}, {
			name : 'collection_date',
			type : 'string'
		}, {
			name : 'completion_date',
			type : 'string'
		}]
	});

	Ext.create('Ext.data.Store', {
		storeId : 'ds_genome',
		model : 'Genome_Store',
		proxy : {
			type : 'ajax',
			url : stateObject.serveURL,
			timeout : 600000, //10*60*1000
			actionMethods : {
				create : 'POST',
				read : 'POST'
			},
			reader : {
				type : 'json',
				root : 'results',
				totalProperty : 'total'
			},
			extraParams : {
				keyword : 'genome_id:(' + stateObject.genomeIds.join(" OR ") + ")",
				fields: (stateObject.genomeIds.length > 500)?"genome_id,genome_name":"genome_id,genome_name,genome_status,isolation_country,host_name,disease,collection_date,completion_date",
				callType:'getGenomeDetails'
			}
		},
		autoLoad : true,
		remoteSort : false,
		listeners : {
			datachanged : function() {
				if (!stateObject.genomeVSfilter) {
					items = this.data.items;
					stateObject.genomeVSfilter = {};
					for ( i = 0; i < items.length; i++) {
						stateObject.genomeVSfilter[items[i].data.genome_id] = new GenomeVSFilterPair();
						stateObject.genomeVSfilter[items[i].data.genome_id].init(i, items[i].data.genome_name);
						// stateObject.genomeNames[i] = items[i].data.genome_name;
						// stateObject.genomeIds[i] = items[i].data.genome_id;
						stateObject.filter += " ";
					}

					tableObject.stateObject = stateObject;

					Ext.Ajax.request({
						url : stateObject.serveURL,
						method : 'POST',
						timeout : 600000,
						params : {
							callType : "getGroupStats",
							genomeIds : stateObject.genomeIds.join(","),
							keyword : stateObject.keyword_search,
							familyType : stateObject.familyType
						},
						success : function(rs) {
							catchGroupStats(windowID, rs);
						}
					});
				}
			}
		}
	});

	if (stateObject.genomeIds.length <= 500) {
		Ext.create('Ext.grid.Panel', {
			store : 'ds_genome',
			id : windowID + '_genome_grid',
			renderTo : windowID + "_4genome_grid",
			columns : [{
				header : '<input title=\"Present in all families\" type=\"radio\" id=\"' + windowID + '_scALL_0\" onclick=\"haveOrthoCareClick(\'' + windowID + '\', \'ALL\', \'0\')\"/>',
				hideable : false,
				menuDisabled : true,
				resizable : false,
				align : 'center',
				tooltip : 'Present in all families',
				width : 30,
				renderer : GenomeColumnRenderer
			}, {
				header : '<input title=\"Absent from all families\" type=\"radio\" id=\"' + windowID + '_scALL_1\" onclick=\"haveOrthoCareClick(\'' + windowID + '\', \'ALL\', \'1\')\"/>',
				hideable : false,
				menuDisabled : true,
				resizable : false,
				align : 'center',
				tooltip : 'Absent from all families',
				width : 30,
				renderer : GenomeColumnRenderer
			}, {
				header : '<input title=\"Either/Mixed\" type=\"radio\" checked id=\"' + windowID + '_scALL_2\" onclick=\"haveOrthoCareClick(\'' + windowID + '\', \'ALL\', \'2\')\"/>',
				hideable : false,
				menuDisabled : true,
				resizable : false,
				align : 'center',
				tooltip : "Either/Mixed",
				width : 30,
				renderer : GenomeColumnRenderer
			}, {
				header : 'Genome Name',
				width : 100,
				sortable : true,
				dataIndex : 'genome_name',
				renderer : BasicTooltipRenderer
			}, {
				header : 'Genome Status',
				width : 50,
				align : 'center',
				sortable : true,
				dataIndex : 'genome_status',
				renderer : BasicTooltipRenderer
			}, {
				header : 'Isolation Country',
				width : 80,
				sortable : true,
				dataIndex : 'isolation_country',
				renderer : BasicTooltipRenderer
			}, {
				header : 'Host Name',
				width : 80,
				sortable : true,
				dataIndex : 'host_name',
				renderer : BasicTooltipRenderer
			}, {
				header : 'Disease',
				width : 80,
				sortable : true,
				dataIndex : 'disease',
				renderer : BasicTooltipRenderer
			}, {
				header : 'Collection Date',
				width : 80,
				sortable : true,
				dataIndex : 'collection_date',
				renderer : BasicTooltipRenderer
			}, {
				header : 'Completion Date',
				width : 80,
				sortable : true,
				dataIndex : 'completion_date',
				renderer : BasicTooltipRenderer
			}],
			viewConfig : {
				forceFit : true
			},
			height : 370,
			border : false,
			listeners : {
				'sortchange' : function() {
					updateFilterHTML(stateObject);
					stateObject.ClusterRowOrder = [];
					stateObject.ClusterColumnOrder = [];
					gridObject = getScratchObject(windowID);
					if (gridObject.activeTab == 1)
						gridObject.showPanel();
				}
			}
		});
	}

	cacheObject(windowID, tableObject);
	$Page.doLayout();
}

function updateFilterHTML(stateObject) {"use strict";

	var windowID = stateObject.windowID, toSet, i, which = 0, j, genomeIds, idx, key=null, genomeVSfilter, filter;

	toSet = Ext.getCmp(windowID + '_toSetRegex');
	toSet.setValue(stateObject.regex);
	if (stateObject.perfectFamMatch == 'A') {
		toSet = document.getElementById(windowID + "_perfectAll");
		toSet.checked = true;
	} else if (stateObject.perfectFamMatch == 'Y') {
		toSet = document.getElementById(windowID + "_perfectIn");
		toSet.checked = true;
	} else if (stateObject.perfectFamMatch == 'N') {
		toSet = document.getElementById(windowID + "_perfectOut");
		toSet.checked = true;
	}

	toSet = Ext.getCmp(windowID + '_minMembers');
	toSet.setValue(stateObject.minnumber_of_members);

	toSet = Ext.getCmp(windowID + '_maxMembers');
	toSet.setValue(stateObject.maxnumber_of_members);

	toSet = Ext.getCmp(windowID + '_minSpecies');
	toSet.setValue(stateObject.minnumber_of_species);

	toSet = Ext.getCmp(windowID + '_maxSpecies');
	toSet.setValue(stateObject.maxnumber_of_species);

	genomeVSfilter = stateObject.genomeVSfilter;

	filter = stateObject.filter.split("");

	for ( i = 0; i < filter.length; i++) {
		for (key in genomeVSfilter) {
			if (genomeVSfilter[key].getIndex() == i) {
				genomeVSfilter[key].setStatus(filter[i]);
			}
		}
	}

	genomeIds = stateObject.genomeIds;

	for ( i = 0; i < genomeIds.length; i++) {
		which = genomeVSfilter[genomeIds[i]].getStatus();
		idx = which == '1' ? '0' : which == '0' ? '1' : '2';
		for ( j = 0; j < 3; j++) {
			toSet = document.getElementById(windowID + '_sc' + genomeIds[i] + '_' + j);
			toSet && (toSet.checked = j == idx);
		}
	}

	checkForHeaderRow(windowID);
}

function checkForHeaderRow(windowID) {"use strict";

	var stateObject = getStateObject(windowID), id, toSet, filter, j;

	function AllSame(element, index, array) {
		return element === array[0];
	}

	filter = stateObject.filter.split("");
	id = filter.every(AllSame) ? filter[0] == " " ? 2 : filter[0] == "0" ? 1 : 0 : null;

	for ( j = 0; j < 3; j++) {
		toSet = document.getElementById(windowID + '_scALL_' + j);
		toSet.checked = !(id != j);
	}
}

function BasicTooltipRenderer(value, metadata, record, rowIndex, colIndex, store) {"use strict";
	metadata.tdAttr = 'data-qtip="' + value + '" data-qclass="x-tip"';
	return value ? value : "";
}

function padNum(num, digits){
    var str = num + "";
    return num.length >= digits? str: padNum("0" + str, digits);
}

function catchGroupStats(windowID, ajaxHttp) {"use strict";

	var rowData, orthoRows = [], distribution = "", genomeIds = getStateObject(windowID).genomeIds, i, t, j, ordered = [];

	if(ajaxHttp.responseText){
		rowData = Ext.JSON.decode(ajaxHttp.responseText);

		for(var key in rowData) {
			var familyId = key;
            if (familyId != undefined) {
                ordered.push(familyId);
            }
		}

		ordered.sort(function(a, b) { return a - b;});

		for(j=0; j<ordered.length; j++){
			key = ordered[j];

			if(genomeIds.length <= 500){
				distribution = "";
				for(i=0; i<genomeIds.length; i++){
					t = rowData[key].genomes[genomeIds[i]]?(rowData[key].genomes[genomeIds[i]]).toString(16):"0";
					distribution += t.length == 2?t:"0"+t;
				}
			}

			orthoRows.push(new orthoRow(key,
					rowData[key].genomes, rowData[key].feature_count,
					rowData[key].genome_count,
					rowData[key].stats.min, rowData[key].stats.max,
					rowData[key].stats.mean, rowData[key].stats.stddev, rowData[key].description, j));
		}
	}

	cacheObject(windowID + "_groupRows", orthoRows);
	drawOrthoGroupTable(windowID);
	defineButtons(windowID);
	//createCopyBox(windowID);
	cacheInitialGroup(windowID);
	beginHashChecking();
	end = (new Date()).getMilliseconds();
	// console.log("Getting data from server and processing took "+ (end - start) +"ms");
}

function orthoRow(groupId, distribution, members, species, minLength, maxLength, mean, std, description, order) {
	this.groupId = groupId;
	this.intensity = distribution;
	this.members = members;
	this.species = species;
	this.minLength = minLength;
	this.maxLength = maxLength;
	this.mean = mean;
	this.std = std;
	this.description = description;
	this.order = order;
}

function sortNumber(a, b) {
	return a - b;
}

function setSyntenyOrder(windowID, genomeId) {
	currentData = null;
	rows = null;
	cols = null;
	var stateObject = getStateObject(windowID);
	var gridObject = getScratchObject(windowID);
	stateObject.syntonyId = genomeId;
	gridObject.gridState.syntonyId = genomeId;

	Ext.Ajax.request({
		url : stateObject.serveURL,
		method : 'GET',
		params : {
			callType : "getSyntonyOrder",
			familyType : stateObject.familyType,
			syntonyId : genomeId
		},
		success : function(rs) {
			catchSyntenyOrder(windowID, rs);
		},
		failure: function(){
			Ext.MessageBox.alert("Error", "Data is not available now. Please try again later or contact PATRIC team (http://enews.patricbrc.org/contact-us/).");
			Ext.get("sample-layout").unmask();
		}
	});
}

function catchSyntenyOrder(windowID, rs) {"use strict";
	var orthoRows = getScratchObject(windowID + "_groupRows"),
		orderPairs = Ext.JSON.decode(rs.responseText),
		colOrder = [],
		adjust,
		endAid,
		orderAt,
		gridObject = getScratchObject(windowID),
		stateObject = getStateObject(windowID);

	if (0 < orderPairs.length) {
		//adjust = -(orderPairs.length * 2);
		//adjust /= 2;
		adjust = -orderPairs.length;
		orderAt = 0;
		endAid = [];
		//for (i = 0, len = orthoRows.length; i < len; i++) {
		//	nextRow = orthoRows[i];
		orthoRows.sort(function(a, b) { return a.groupId.localeCompare(b.groupId); });
		orthoRows.forEach(function(nextRow) {
			if (orderPairs[orderAt] && nextRow.groupId == orderPairs[orderAt].groupId) {
				nextRow.order = orderPairs[orderAt].syntonyAt;
				++orderAt;
			} else {
				nextRow.order -= adjust;
				endAid.push(nextRow.order);
			}
		});
		if (0 < endAid.length) {
			adjust = -adjust;
			endAid.sort(sortNumber);
			var bumper = [];
			//for (i = 0, len = endAid.length; i < len; i++) {
			//	bumper[endAid[i]] = adjust;
			endAid.forEach(function(el) {
				bumper[el] = adjust;
				++adjust;
			});
			//for (i = 0, len = orthoRows.length; i < len; i++) {
			//	nextRow = orthoRows[i];
			orthoRows.forEach(function(nextRow){
				if (bumper[nextRow.order] != null) {
					nextRow.order = bumper[nextRow.order];
				}
			});
		}
		var emptySpot = 0;
		//for (j = 0; j < orthoRows.length; j++) {
		//if (colOrder[parseInt(orthoRows[j].order)] != null) {
		orthoRows.forEach(function(el) {
			if (colOrder[parseInt(el.order)] != null) {
				for (var i = 0; i < colOrder.length; i++) {
					if (colOrder[i] == null) {
						emptySpot = i;
					}
				}
				colOrder[emptySpot] = orthoRows[j].groupId;
			} else {
				colOrder[parseInt(el.order)] = el.groupId;
			}
		});
		filterOrthoTableData(windowID);

		if (stateObject.heatmapAxis != "Transpose") {
			stateObject.ClusterRowOrder = [];
			stateObject.ClusterColumnOrder = colOrder;
		} else {
			stateObject.ClusterRowOrder = colOrder;
			stateObject.ClusterColumnOrder = [];
		}
		gridObject.store.sorters.clear();
		gridObject.store.sorters.add(new Ext.util.Sorter({
			property : 'order',
			direction : 'ASC'
		}));
		gridObject.Pagingstore.sorters.clear();
		gridObject.Pagingstore.sorters.add(new Ext.util.Sorter({
			property : 'order',
			direction : 'ASC'
		}));
		gridObject.Pagingstore.sort([{
			'property' : 'order',
			'direction' : 'ASC'
		}]);
		gridObject.gridState.storeInSession();
		gridObject.showPanel();
	}
	Ext.get("sample-layout").unmask();
}

function GenomeColumnRenderer(value, metadata, record, rowIndex, colIndex, store) {
	var Page = $Page, property = Page.getPageProperties(), windowID = property.name, stateObject = getStateObject(windowID), genome_id = record.data.genome_id, checked, genomeVSfilter;

	genomeVSfilter = stateObject.genomeVSfilter;
	checked = genomeVSfilter[genome_id].getStatus();

	return '<input title=\"'+((colIndex == 0)?'Present in all families':(colIndex == 1)?'Absent from all families':'Either/Mixed')+'\" type=\"radio\" id=\"' + property.name + '_sc' + record.data.genome_id + '_' + colIndex + '\" ' + (colIndex == 0 && checked == '1' ? 'checked' : colIndex == 1 && checked == '0' ? 'checked' : colIndex == 2 && checked == ' ' ? 'checked' : '') + ' onclick=\"haveOrthoCareClick(\'' + property.name + '\', \'' + record.data.genome_id + '\', \'' + colIndex + '\')\"/>';
}

function haveOrthoCareClick(windowID, record_id, column) {"use strict";

	var stateObject = getStateObject(windowID), toSet, id = windowID, i, j, newFilter = [], genomeIds, genomeVSfilter, index;

	genomeIds = stateObject.genomeIds;
	genomeVSfilter = stateObject.genomeVSfilter;
	newFilter.length = genomeIds.length;

	if (record_id == "ALL") {

		for ( i = 0; i < 3; i++) {
			if (i != parseInt(column)) {
				id = windowID + '_sc' + record_id + '_' + i;
				toSet = document.getElementById(id);
				toSet.checked = false;
			}
		}

		for ( i = 0; i < genomeIds.length; i++) {
			newFilter[i] = column == 0 ? "1" : column == 1 ? "0" : " ";
			for ( j = 0; j < 3; j++) {
				id = windowID + '_sc' + genomeIds[i] + '_' + j;
				toSet = document.getElementById(id);
				toSet.checked = !(j != parseInt(column));
			}
		}

	} else {

		for ( i = 0; i < 3; i++) {
			if (i != parseInt(column)) {
				id = windowID + '_sc' + record_id + '_' + i;
				toSet = document.getElementById(id);
				toSet.checked = false;
			}
			id = windowID + '_scALL_' + i;
			toSet = document.getElementById(id);
			toSet.checked = false;
		}

		for ( i = 0; i < genomeIds.length; i++) {
			toSet = document.getElementById(windowID + '_sc' + genomeIds[i] + "_0");
			index = genomeVSfilter[genomeIds[i]].getIndex();
			if (toSet.checked) {
				newFilter[index] = '1';
			} else {
				toSet = document.getElementById(windowID + '_sc' + genomeIds[i] + "_1");
				newFilter[index] = toSet.checked ? '0' : ' ';
			}
			genomeVSfilter[genomeIds[i]].setStatus(newFilter[index]);
		}
	}
	stateObject.filter = newFilter.join('');
	checkForHeaderRow(windowID);
	updateOrthoListTable(windowID);
}

function updateOrthoListTable(windowID) {
	var stateObject = getStateObject(windowID);
	var toRead = Ext.getCmp(windowID + "_toSetRegex");
	stateObject.regex = toRead.getValue();

	toRead = document.getElementById(windowID + "_perfectIn");
	if (toRead.checked) {
		stateObject.perfectFamMatch = 'Y';
	}

	toRead = document.getElementById(windowID + "_perfectOut");
	if (toRead.checked) {
		stateObject.perfectFamMatch = 'N';
	}

	toRead = document.getElementById(windowID + "_perfectAll");
	if (toRead.checked) {
		stateObject.perfectFamMatch = 'A';
	}

	toRead = Ext.getCmp(windowID + "_minMembers");
	stateObject.minnumber_of_members = toRead.getValue();

	toRead = Ext.getCmp(windowID + "_maxMembers");
	stateObject.maxnumber_of_members = toRead.getValue();

	toRead = Ext.getCmp(windowID + "_minSpecies");
	stateObject.minnumber_of_species = toRead.getValue();

	toRead = Ext.getCmp(windowID + "_maxSpecies");
	stateObject.maxnumber_of_species = toRead.getValue();

	stateObject.syntonyId = "";
	stateObject.ClusterRowOrder = [];
	stateObject.ClusterColumnOrder = [];
	stateObject.heatmapState = null;
	updateFilterState(windowID, stateObject);
	var gridObject = getScratchObject(windowID);
	gridObject.gridState.syntonyId = "";
	drawOrthoGroupTable(windowID);
}

function getAddPopupPanel() {
	return (new Ext.form.FormPanel({
		formId : 'ATGform',
		baseCls : 'x-plain',
		labelWidth : 70,
		defaultType : 'textfield',
		items : [{
			fieldLabel : 'Name',
			name : 'group_name',
			id : 'group_name',
			anchor : '100%'
		}, {
			xtype : 'textarea',
			fieldLabel : 'Description',
			name : 'group_desc',
			id : 'group_desc',
			anchor : '100% -10'
		}, new Ext.form.Hidden({
			name : 'action_type',
			value : 'groupAction'
		}), new Ext.form.Hidden({
			name : 'action',
			value : 'add'
		}), new Ext.form.Hidden({
			id : 'group_members',
			name : 'fid'
		})]
	})
	);
}

function checkAddClick(windowID) {

	var gridObject = getScratchObject(windowID);

	if (gridObject.checkbox.getCheckAll() == true || gridObject.checkbox.getCount() > 0) {
		addSelectedItems("Feature");
	} else {
		alert("No item(s) are selected. At least one Figfam Group must be selected.");
	}

}

function addRectangleToGroup(windowID, figfamNames, genomeList) {

	var stateObject = getStateObject(windowID), object = {}, familyType = stateObject.familyType, familyId = familyType + '_id';

	object["genome_id"] = genomeList.replace(/,/g, '##');
	object[familyId] = figfamNames.replace(/,/g, '##');

	Ext.Ajax.request({
		url : stateObject.serveURL,
		method : 'POST',
		timeout : 600000,
		params : {
			callType : "getFeatureIds",
			keyword : constructKeyword(object, "Feature")
		},
		success : function(rs) {
			if (rs.responseText.length > 0) {
				addSelectedItems("Feature");
				Ext.getDom("fids").value = rs.responseText;
			}
		}
	});
}

function drawOrthoGroupTable(windowID) {
	var gridObject = getScratchObject(windowID);
	filterOrthoTableData(windowID);
	gridObject.showPanel();
}

function filterHeatmapData(stateObject, ds, windowID) {"use strict";

	var keeps = [], items = Ext.getStore('ds_genome').data.items, stateObject = getStateObject(windowID);
	var gridObject = getScratchObject(windowID), syntenyOrderStore = [], rowCount = ds.getTotalCount(), iMax = 0, clusterColumn = (stateObject.heatmapAxis == "Transpose") ? stateObject.ClusterRowOrder : stateObject.ClusterColumnOrder, clusterRow = (stateObject.heatmapAxis == "Transpose") ? stateObject.ClusterColumnOrder : stateObject.ClusterRowOrder, rowColor, labelColor, place, i, j, genome_id, genome_name, index, z, record, groupId, meta, colorStop = [],
			orthoFilter = stateObject.filter;
	rows = [], cols = [];

	//	var Tree = {}, TI = {};
	//var orders = stateObject.orders;

	if (clusterRow != null && clusterRow.length > 0 && clusterRow[0] != "") {
		place = 0;
		for ( j = 0; j < clusterRow.length; j++) {
			for ( i = 0; i < items.length; i++) {
				genome_id = items[i].data.genome_id, index = stateObject.genomeVSfilter[genome_id].getIndex(), genome_name = stateObject.genomeVSfilter[genome_id].getGenomeName();
				if (orthoFilter.charAt(index) != '0') {
					if (genome_id == clusterRow[j]) {
						keeps.push(2 * index);
						labelColor = ((i % 2) == 0) ? 0x000066 : null;
						rowColor = ((i % 2) == 0) ? 0xF4F4F4 : 0xd6e4f4;
						rows.push(new Row(place, genome_id, genome_name, labelColor, rowColor));

						/*TI = {index: place, children: null, rowID: genomeIds[i], leaf: true};
						 if(!Tree[orders[i]])
						 Tree[orders[i]] = [];
						 Tree[orders[i]].push(TI);*/

						syntenyOrderStore.push([genome_id, genome_name]); ++place;
					}
				}
			}
		}

	} else {

		for ( i = 0; i < items.length; i++) {
			genome_id = items[i].data.genome_id, index = stateObject.genomeVSfilter[genome_id].getIndex(), genome_name = stateObject.genomeVSfilter[genome_id].getGenomeName();

			if (orthoFilter.charAt(index) != '0') {
				keeps.push(2 * index);
				labelColor = ((i % 2) == 0) ? 0x000066 : null;
				rowColor = ((i % 2) == 0) ? 0xF4F4F4 : 0xd6e4f4;

				rows.push(new Row(i, genome_id, genome_name, labelColor, rowColor));
				/*	TI = {index: i, children: null, rowID: genomeIds[i], leaf: true};
				 if(!Tree[orders[i]])
				 Tree[orders[i]] = [];
				 Tree[orders[i]].push(TI);*/
				syntenyOrderStore.push([genome_id, genome_name]);

			}
		}

	}

	gridObject.syntenyComboStore.loadData(syntenyOrderStore);

	if (gridObject.gridState.syntonyId != "") {
		gridObject.syntenyCombo.setValue(gridObject.gridState.syntonyId);
		gridObject.Pagingstore.sort([{
			'property' : gridObject.gridState.sortField,
			'direction' : gridObject.gridState.sortDir
		}]);
	} else {
		gridObject.syntenyCombo.setValue("");
	}

	if (clusterColumn != null && clusterColumn.length > 0 && clusterColumn[0] != "") {

		for ( z = 0; z < clusterColumn.length; z++) {
			for ( i = 0; i < rowCount; i++) {
				record = gridObject.Pagingstore.data.items[i], groupId = record.data['groupId'];
				if (groupId == clusterColumn[z]) {
					meta = {
						'instances' : record.data['members'],
						'families' : record.data['species'],
						'min' : record.data['min'],
						'max' : record.data['max']
					}, iMax = createColumn(z, record, meta, groupId, keeps, iMax);
				}
			}
		}

	} else {

		for ( i = 0; i < rowCount; i++) {

			record = gridObject.Pagingstore.data.items[i], meta = {
				'instances' : record.data['members'],
				'families' : record.data['species'],
				'min' : record.data['min'],
				'max' : record.data['max']
			}, groupId = record.data['groupId'];
			iMax = createColumn(i, record, meta, groupId, keeps, iMax);
		}
	}

	if (iMax == 1) {
		colorStop = [new ColorStop(1, 0xfadb4e)];
	} else if (iMax == 2) {
		colorStop = [new ColorStop(1 / 2, 0xfadb4e), new ColorStop(2 / 2, 0xf6b437)];
	} else if (iMax >= 3) {
		colorStop = [new ColorStop(1 / iMax, 0xfadb4e), new ColorStop(2 / iMax, 0xf6b437), new ColorStop(3 / iMax, 0xff6633), new ColorStop(iMax / iMax, 0xff6633)];
	}

	currentData = {
		'rows' : rows,
		'columns' : cols,
		'colorStops' : colorStop,
		'rowLabel' : 'Genomes',
		'colLabel' : 'Protein Families',
		'rowTrunc' : 'mid',
		'colTrunc' : 'end',
		'offset' : 1,
		'digits' : 2,
		'countLabel' : 'Members',
		'negativeBit' : false,
		'cellLabelField' : '',
		'cellLabelsOverrideCount' : false,
		'beforeCellLabel' : '',
		'afterCellLabel' : ''
		//'rowTree': createCladogram(Tree),
	};

	if (stateObject.heatmapAxis == "Transpose") {
		flipAxises(windowID);
	}

	return rowCount;
}

function createColumn(i, record, meta, groupId, keeps, iMax) {

	var iSend = "", intensity = record.data['intensity'], j, pick, iSendDecimal, labelColor, columnColor;

	for ( j = 0; j < keeps.length; j++) {
		pick = keeps[j];
		iSend += intensity.charAt(pick); ++pick;
		iSend += intensity.charAt(pick);

		iSendDecimal = parseInt(intensity.charAt(pick - 1) + intensity.charAt(pick), 16);

		if (iMax <= iSendDecimal) {
			iMax = iSendDecimal;
		}
	}

	labelColor = ((i % 2) == 0) ? 0x000066 : null;
	columnColor = ((i % 2) == 0) ? 0xF4F4F4 : 0xd6e4f4;

	cols[i] = new Column(i, groupId, record.data['description'], iSend, labelColor, columnColor, meta);

	return iMax;
}

function createCladogram(Tree) {
	var rowTree = [{
		c : [],
		l : null
	}];

	function getCladogramChildren(parent) {
		var children = [];
		for (var j = 0; j < parent.length; j++) {
			if (parent[j].leaf) {
				var obj = {
					c : null,
					l : parent[j].index
				};
				children.push(rowTree.length);
				rowTree.push(obj);
			}
		}
		return children;
	}

	for (var i in Tree) {
		rowTree.push({});
		rowTree[0].c.push(rowTree.length - 1);
		rowTree[rowTree.length - 1] = {
			c : getCladogramChildren(Tree[i]),
			l : null
		};
	}

	return rowTree;
}

function getCellParts(windowID, groupId, genomeId) {
	var stateObject = getStateObject(windowID);

	var genomeVSfilter = stateObject.genomeVSfilter;
	var result = [];
	var depth = 2 * genomeVSfilter[genomeId].getIndex();
	result.push(genomeVSfilter[genomeId].getGenomeName());

	var orthoRows = getScratchObject(windowID + "_groupRows");
	for (var i = 0; i < orthoRows.length; i++) {
		var nextRow = orthoRows[i];
		if (groupId == nextRow.groupId) {
			result.push(nextRow.description);
			var density = nextRow.intensity;
			if (density.charAt(depth) != '0') {
				result.push(density.substr(depth, 2));
			} else {++depth;
				result.push(density.charAt(depth));
			}
			i = orthoRows.length;
		}
	}
	return result;
}

function getRectangleCount(windowID, familyIds, ids) {
	var depths = [];
	var stateObject = getStateObject(windowID);
	var genomeIds = stateObject.genomeIds;
	var found = ids.length;
	for (var i=0, genomeIdsCount=genomeIds.length; i < genomeIdsCount; i++) {
		var currentGenomeId=genomeIds[i];
		for (var j=0, idsCount=ids.length; j < idsCount; j++) {
			if (currentGenomeId === ids[j]) {
				j = idsCount;
				depths.push(2 * i); --found;
				if (found == 0) {
					i = genomeIdsCount;
				}
			}
		}
	}
	var orthoRows = getScratchObject(windowID + "_groupRows");
	var sorted = familyIds.slice(0);
	var sortedCount = sorted.length;
	var depthsCount = depths.length;
	sorted.sort();
	var sortAt = 1;
	var toFind = sorted[0];
	var result = 0;
	//  logic depends on current state where server sorts data by
	//    groupId
	for (var i=0, orthoRowsCount=orthoRows.length; i < orthoRowsCount; i++) {
		var nextRow = orthoRows[i];
		if (nextRow.groupId == toFind) {
			var counts = nextRow.intensity;
			for (var j = 0; j < depthsCount; j++) {
				var bump = counts.substr(depths[j], 2);
				bump = parseInt(bump, 16);
				result += bump;
			}
			if (sortAt < sortedCount) {
				toFind = sorted[sortAt]; ++sortAt;
				i = 0;
			} else {
				i = orthoRowsCount;
			}
		}
	}
	return result;
}

function filterOrthoTableData(windowID) {"use strict";

	var stateObject = getStateObject(windowID), orthoRows = getScratchObject(windowID + "_groupRows"), genomeIds = stateObject.genomeIds, genomeVSfilter = stateObject.genomeVSfilter, orthoFilter = stateObject.filter, nextRow = null, i, j, filterFlag, tableData = new Array(), kept = 0, gridObject = getScratchObject(windowID), index;

	if (orthoRows != null) {
		for ( i = 0; i < orthoRows.length; i++) {
			nextRow = orthoRows[i];
			if (AdvancedFilter(nextRow, stateObject)) {
				filterFlag = true;
				if(genomeIds.length <= 500){
					for ( j = 0; j < genomeIds.length; j++) {
						index = genomeVSfilter[genomeIds[j]].getIndex();
						if (orthoFilter[index] != ' ') {
							if (orthoFilter[index] == '1' && parseInt(nextRow.intensity.charAt(index * 2) + nextRow.intensity.charAt(index * 2 + 1), 16) > 0 || orthoFilter[index] == '0' && parseInt(nextRow.intensity.charAt(index * 2) + nextRow.intensity.charAt(index * 2 + 1), 16) == 0) {
								filterFlag = true;
							} else {
								filterFlag = false;
								break;
							}
						}
					}
				}
				if (filterFlag) {
					tableData[kept] = [nextRow.members, nextRow.species, nextRow.description, nextRow.minLength, nextRow.maxLength, nextRow.mean, nextRow.std, nextRow.groupId, nextRow.intensity, nextRow.order, windowID];
					kept++;
				}
			}
		}
	}

	gridObject.Pagingstore.loadData(tableData);
	// gridObject.Pagingstore.sort();
	gridObject.store.totalCount = tableData.length;

	return tableData;
}

function AdvancedFilter(nextRow, stateObject) {

	var minmem = null, maxmem = null, minspe = null, maxspe = null, regex = stateObject.regex.trim() && stateObject.regex.trim().toLowerCase().replace(/,/g, "~").replace(/\n/g, "~").replace(/ /g, "~").split("~"), perfectFamFilter = true, regexFilter = regex == '' ? true : false, memFilter = false, speFilter = false, a = false, b = false, i, rgxi;

	if (!regexFilter) {
		for ( i = 0; i < regex.length; i++) {
			rgxi = regex[i];
			if (rgxi && (nextRow.description.toLowerCase().indexOf(rgxi) >= 0 || nextRow.groupId.toLowerCase().indexOf(rgxi) >= 0)) {
				regexFilter = true;
				break;
			}
		}
	}

	minmem = stateObject.minnumber_of_members;
	maxmem = stateObject.maxnumber_of_members;

	if (minmem != '' || maxmem != '') {
		if (minmem == '' || (minmem && nextRow.members >= parseInt(minmem)))
			a = true;

		if (maxmem == '' || (maxmem && nextRow.members <= parseInt(maxmem)))
			b = true;

		if (a && b)
			memFilter = true;
	} else if (minmem == '' && maxmem == '') {
		memFilter = true;
	}

	minspe = stateObject.minnumber_of_species;
	maxspe = stateObject.maxnumber_of_species;

	if (minspe != '' || maxspe != '') {
		a = false, b = false;

		if (minspe == '' || (minspe && nextRow.species >= parseInt(minspe)))
			a = true;

		if (maxspe == '' || (maxspe && nextRow.species <= parseInt(maxspe)))
			b = true;

		if (a && b)
			speFilter = true;
	} else if (minspe == '' && maxspe == '') {
		speFilter = true;
	}

	if (stateObject.perfectFamMatch == 'Y') {
		if (nextRow.species == nextRow.members)
			perfectFamFilter = true;
		else
			perfectFamFilter = false;
	} else if (stateObject.perfectFamMatch == 'N') {
		if (nextRow.species == nextRow.members)
			perfectFamFilter = false;
		else
			perfectFamFilter = true;
	} else
		perfectFamFilter = true;

	return regexFilter && memFilter && speFilter && perfectFamFilter;
}

function prepareDataForCluster(windowID) {
	var stateObject = getStateObject(windowID);
	var tablePass = "";

	var c, r, id, datalabel;
	if (stateObject.heatmapAxis == "Transpose") {
		c = currentData.rows;
		r = currentData.columns;
		id = "rowID";
		datalabel = "colID";
	} else {
		c = currentData.columns;
		r = currentData.rows;
		id = "colID";
		datalabel = "rowID";
	}

	for (var i = 0; i < c.length; i++) {
		tablePass += "\t" + c[i][id];
	}

	tablePass += "\n";

	for (var i = 0; i < r.length; i++) {
		tablePass += r[i][datalabel];
		for (var j = 0; j < c.length; j++) {
			if (stateObject.heatmapAxis == "Transpose")
				tablePass += "\t" + parseInt(parseInt(r[i].distribution[j * 2 + 1], 16) + parseInt(r[i].distribution[j * 2 + 1], 16), 16);
			else
				tablePass += "\t" + parseInt(parseInt(c[j].distribution[i], 16) + parseInt(c[j].distribution[i + 1], 16), 16);
		}
		tablePass += "\n";
	}
	return tablePass;
}

function DoCluster(windowID) {

	var params = {};
	params.e = '1';
	params.g = '1';
	params.m = 'a';
	params.ge = '2';
	submitCluster(prepareDataForCluster(windowID), params, windowID);

}

function DoAdvancedCluster(windowID) {
	var stateObject = getStateObject(windowID);

	var s = {
		"No clustering" : "0",
		"Uncentered correlation" : "1",
		"Pearson correlation" : "2",
		"Uncentered correlation, absolute value" : "3",
		"Pearson correlation, absolute value" : "4",
		"Spearman rank correlation" : "5",
		"Kendall tau" : "6",
		"Euclidean distance" : "7",
		"City-block distance" : "8",
		"Pairwise complete-linkage" : "m",
		"Pairwise single-linkage" : "s",
		"Pairwise centroid-linkage" : "c",
		"Pairwise average-linkage" : "a"
	};

	if (stateObject.clusterWindow == null) {

		var clusterStore = Ext.create('Ext.data.Store', {
			fields : ['id', 'value'],
			data : [{
				id : "0",
				value : "No clustering"
			}, {
				id : "1",
				value : "Uncentered correlation"
			}, {
				id : "2",
				value : "Pearson correlation"
			}, {
				id : "3",
				value : "Uncentered correlation, absolute value"
			}, {
				id : "4",
				value : "Pearson correlation, absolute value"
			}, {
				id : "5",
				value : "Spearman rank correlation"
			}, {
				id : "6",
				value : "Kendall tau"
			}, {
				id : "7",
				value : "Euclidean distance"
			}, {
				id : "8",
				value : "City-block distance"
			}]
		});

		var distanceStore = Ext.create('Ext.data.Store', {
			fields : ['id', 'value'],
			data : [{
				id : "m",
				value : "Pairwise complete-linkage"
			}, {
				id : "s",
				value : "Pairwise single-linkage"
			}, {
				id : "c",
				value : "Pairwise centroid-linkage"
			}, {
				id : "a",
				value : "Pairwise average-linkage"
			}]
		});

		var distance = {
			xtype : 'fieldset',
			title : 'Clustering type',
			layout : 'anchor',
			defaults : {
				anchor : '100%',
				labelStyle : 'padding-left:4px;'
			},
			items : [{
				id : 'cluster_distance',
				xtype : 'combobox',
				store : distanceStore,
				valueField : 'id',
				displayField : 'value',
				value : 'Pairwise average-linkage',
				typeAhead : false
			}]
		};

		var algorithm = {
			xtype : 'fieldset',
			title : 'Clustering algorithm',
			layout : 'anchor',
			defaults : {
				anchor : '100%',
				labelStyle : 'padding-left:4px;'
			},
			items : [{
				id : 'cluster_algorithm',
				xtype : 'combobox',
				store : clusterStore,
				valueField : 'id',
				displayField : 'value',
				value : 'Pearson correlation',
				typeAhead : false
			}]
		};

		var radioGroup = {
			xtype : 'fieldset',
			title : 'Cluster by',
			layout : 'anchor',
			defaults : {
				anchor : '100%',
				labelStyle : 'padding-left:4px;',
				style : 'padding-top:4px;'
			},
			items : [{
				id : 'cluster_radio',
				xtype : 'radiogroup',
				columns : 1,
				items : [{
					boxLabel : 'Protein Families',
					name : 'val',
					inputValue : 2
				}, {
					boxLabel : 'Genomes',
					name : 'val',
					inputValue : 1
				}, {
					boxLabel : 'Both',
					name : 'val',
					inputValue : 3,
					checked : true
				}]
			}]
		};

		var fp = Ext.create('Ext.FormPanel', {
			items : [radioGroup, algorithm, distance],
			width : 300,
			buttons : [{
				text : 'Submit',
				handler : function() {
					Ext.get("sample-layout").mask('Loading...', 'x-mask-loading');
					var params = {};
					params.g = (Ext.getCmp('cluster_radio').getValue()['val'] == 3 || Ext.getCmp('cluster_radio').getValue()['val'] == 1) ? '1' : '0';
					params.e = (Ext.getCmp('cluster_radio').getValue()['val'] == 3 || Ext.getCmp('cluster_radio').getValue()['val'] == 2) ? '1' : '0';
					params.m = s[Ext.getCmp('cluster_distance').getValue()] || Ext.getCmp('cluster_distance').getValue();
					params.ge = s[Ext.getCmp('cluster_algorithm').getValue()] || Ext.getCmp('cluster_algorithm').getValue();

					submitCluster(prepareDataForCluster(windowID), params, windowID);
					stateObject.clusterWindow.hide();
				}
			}, {
				text : 'Cancel',
				handler : function() {
					stateObject.clusterWindow.hide();
				}
			}]
		});

		stateObject.clusterWindow = new Ext.create('Ext.Window', {
			layout : 'fit',
			closeAction : 'hide',
			plain : true,
			modal : true,
			shim : false,
			title : 'Advanced Clustering',
			autoScroll : true,
			items : fp
		});
		stateObject.clusterWindow.show();
	} else {
		stateObject.clusterWindow.show();
	}
}

function submitCluster(data, params, windowID) {

	var pk = +Date.now();
	var threshold = 1000000;
	if (data.length > threshold) {
		var place = 0;
		var sendData = [];

		for (var i = 0; i < data.length; i += threshold) {
			var end = i + threshold;

			if (end > data.length)
				end = i + data.length % threshold;

			sendData[place] = data.substring(i, end);
			place++;
		}

		for (var i = 0; i < place; i++) {
			if (i == place - 1)
				setTimeout(sendDataChunks(sendData[i], params, pk, 'Run', windowID), 1000);
			else if (i == 0)
				sendDataChunks(sendData[i], params, pk, 'Store', windowID);
			else
				setTimeout(sendDataChunks(sendData[i], params, pk, 'Store', windowID), 1000);
		}
	} else {
		sendDataChunks(data, params, pk, 'Run', windowID);
	}
}

function sendDataChunks(data, params, pk, action, windowID) {
	var stateObject = getStateObject(windowID);
	Ext.Ajax.request({
		url : stateObject.serveURL,
		method : 'POST',
		timeout : 6000000,
		params : {
			callType : "doClustering",
			data : data,
			m : params.m,
			g : params.g,
			e : params.e,
			ge : params.ge,
			pk : pk,
			action : action
		},
		success : function(rs) {

			if (action == 'Run') {
				var decoded = Ext.JSON.decode(rs.responseText);
				if (stateObject.heatmapAxis == "") {
					stateObject.ClusterRowOrder = decoded.rows;
					stateObject.ClusterColumnOrder = decoded.columns;
				} else {
					stateObject.ClusterRowOrder = decoded.columns;
					stateObject.ClusterColumnOrder = decoded.rows;
				}
				updateFilterState(windowID, stateObject);
				drawOrthoGroupTable(windowID);
				Ext.get("sample-layout").unmask();
			}
		}
	});

}

function submitFigfam(windowID, groupId) {
	var stateObject = getStateObject(windowID);

	Ext.Ajax.request({
		url : '/portal/portal/patric/SingleFIGfam/SingleFIGfamWindow?action=b&cacheability=PAGE',
		method : 'POST',
		timeout : 600000,
		params : {
			callType : "saveState",
			genomeIds : stateObject.genomeIds.join('##'),
			familyIds : groupId,
			familyType : stateObject.familyType
		},
		success : function(rs) {
			document.location.href = "SingleFIGfam?cType=" + stateObject.cType + "&cId=" + stateObject.cId + "&pk=" + rs.responseText;
		}
	});
}

function submitDetails(windowID, groupIds, genomeIds) {
	var stateObject = getStateObject(windowID);
	Ext.Ajax.request({
		url : '/portal/portal/patric/SingleFIGfam/SingleFIGfamWindow?action=b&cacheability=PAGE',
		method : 'POST',
		timeout : 600000,
		params : {
			callType : "saveState",
			genomeIds : genomeIds.replace(/,/g, '##'),
			familyIds : groupIds.replace(/,/g, '##'),
			familyType : stateObject.familyType
		},
		success : function(rs) {
			open_in_new_tab("SingleFIGfam?cType=" + stateObject.cType + "&cId=" + stateObject.cId + "&pk=" + rs.responseText);
		}
	});
}

function launchDetails(submitId, groupIds, genomeIds) {
	var toSubmit = document.getElementById(submitId);
	toSubmit.figfam_names.value = groupIds;
	toSubmit.genome_ids.value = genomeIds;
	toSubmit.submit();
}
/*
function OrthoDetails(genomeName, locus, length, description) {
	this.genomeName = genomeName;
	this.length = length;
	this.description = description;
	this.locus = locus;
}

function getOrthoAlignment(windowID, groupID) {
	var stateObject = getStateObject(windowID);
	var showIn = window.open("", "", "height=320,width=800,scrollbars");
	Ext.Ajax.request({
		url : stateObject.serveURL,
		method : 'POST',
		timeout : 600000,
		params : {
			callType : "projectName",
			figfamId : groupID,
			genomeIds : idText
		},
		success : function(rs) {
			popOrthoHtml(rs, showIn);
		}
	});

}*/

function setAllDetails(windowID, fileType) {
	var tableData = filterOrthoTableData(windowID);
	if (0 < tableData.length) {
		var toSet = document.getElementById('detailsToFile');
		toSet.detailsType.value = fileType;
		var idText = getStateObject(windowID).genomeIds.join(" OR ");
		toSet.detailsGenomes.value = idText;
		var figList = tableData[0][7];

		for (var i = 1; i < tableData.length; i++) {
			figList += ' OR ' + tableData[i][7];
		}
		toSet.detailsFamilyIds.value = figList;
		toSet.familyType.value = document.getElementById("familyType").elements["famType"].value;
		toSet.submit();
	}
}

function setTopOrtho(windowID, fileType) {
	// get the data for the table
	var tableData = filterOrthoTableData(windowID);

	var tablePass = "Id\tProteins\tGenomes\tProduct Description\tMin\tMax\tMean\tStd\n";

	var column_order = [7, 0, 1, 2, 3, 4, 5, 6];

	for (var i = 0; i < tableData.length; i++) {
		var rowData = tableData[i];
		tablePass += rowData[column_order[0]];

		for (var j = 1; j < column_order.length; j++) {
		  var str = new String(rowData[column_order[j]]);
			tablePass += "\t" + str.trim();
		}

		tablePass += "\n";
	}

	var toSet = document.getElementById('orthoToFile');
	toSet.OrthoFileName.value = 'groups';
	toSet.OrthoFileType.value = fileType;
	toSet.data.value = tablePass;

	toSet.submit();
}

function defineButtons(windowID) {
	var gridObject = getScratchObject(windowID), btn = $Page.getCartSaveButton();
	gridObject.allowHashing = true;

	if (btn) {
		btn.on('click', function() {
			if (gridObject.activeTab == 0) {
				getSelectedFeatures(windowID, "cart", "", "", "");
			} else {
				processFigfamSelectedItems(windowID, "heatmap_cart", "", "", "", "");
				Ext.getDom("fids").value = "";
			}
		});
	}
}

function setGroupPopup(windowID) {
	var gridObject = getScratchObject(windowID);
	if (saveToGroup(Ext.getDom("fids").value, "Feature")) {

		gridObject.checkbox.clearSelections();
		gridObject.checkbox.updateCheckAllIcon();
		gridObject.checkbox.setCheckAll(false);

		adjustCheckBoxes("unchecked");
		gridObject.checkbox.showMessage(Ext.getDom("fids").value.split(",").length, "Feature");
	}
}

function getSelectedFeatures(windowID, actiontype, showdownload, fastatype, to) {
	var gridObject = getScratchObject(windowID), stateObject = getStateObject(windowID), sl = gridObject.checkbox.getSelections(), familyType = stateObject.familyType, familyId = familyType + "_id";
	var familyIds = [], object = [];

	for (var i = 0; i < sl.length; i++) {
		familyIds.push((sl[i]).get('groupId'));
	}

	object["genome_id"] = stateObject.genomeIds.join('##');
	object[familyId] = familyIds.join("##");

	Ext.Ajax.request({
		url : stateObject.serveURL,
		method : 'POST',
		timeout : 600000,
		params : {
			callType : "getFeatureIds",
			keyword : constructKeyword(object, "Feature")
		},
		success : function(rs) {
			processFigfamSelectedItems(windowID, actiontype, showdownload, fastatype, to, rs);
		}
	});
}

function processFigfamSelectedItems(windowID, actiontype, showdownload, fastatype, to, rs) {
	var stateObject = getStateObject(windowID);
	if (actiontype == "cart") {
		Ext.getDom("fids").value = rs.responseText;
		setGroupPopup(windowID);
	} else if (actiontype == "fasta") {
		catchFastaIds(windowID, showdownload, fastatype, rs);
	} else if (actiontype == "msa") {
		/*var hrefBase = 'TreeAlignerB?cType=' + stateObject.cType + "&cId=" + stateObject.cId + "&";
		if (windowID.indexOf('FIGfamSorterB') < 0) {
			hrefBase = 'TreeAligner?';
		}*/
		var hrefBase = 'MSA?cType=' + stateObject.cType + "&cId=" + stateObject.cId + "&";
		catchAlignIds(rs.responseText.split(",").length, stateObject.serveURL, hrefBase, rs);
	} else if (actiontype == "idmap") {
		Ext.Ajax.request({
			url : "/portal/portal/patric/IDMapping/IDMappingWindow?action=b&cacheability=PAGE",
			method : 'POST',
			timeout : 600000,
			params : {
				keyword : rs.responseText,
				from : 'feature_id',
				to : to,
				fromGroup: 'PATRIC',
				toGroup: (["patric_id","feature_id","alt_locus_tag","refseq_locus_tag","protein_id","gene_id","gi"].indexOf(to) > -1)? "PATRIC": "Other",
				sraction : 'save_params'
			},
			success : function(response, opts) {
				document.location.href = "IDMapping?cType=taxon&cId=131567&dm=result&pk=" + response.responseText;
			}
		});
	} else if (actiontype == "heatmap_cart") {
		setGroupPopup(windowID);
	} else if (actiontype == "pathway_enrichment") {
		Ext.Ajax.request({
			url : "/portal/portal/patric/TranscriptomicsEnrichment/TranscriptomicsEnrichmentWindow?action=b&cacheability=PAGE",
			method : 'POST',
			timeout : 600000,
			params : {
				feature_id : rs.responseText,
				callType : 'saveParams'
			},
			success : function(response, opts) {
				document.location.href = "TranscriptomicsEnrichment?cType=taxon&cId=131567&pk=" + response.responseText;
			}
		});
	}
}

function submitFASTA(windowID, actionType, fastaType) {
	var gridObject = getScratchObject(windowID);

	if (gridObject.checkbox.getCheckAll() == true || gridObject.checkbox.getCount() > 0) {
		getSelectedFeatures(windowID, "fasta", actionType, fastaType, "");
	} else {
		alert("No item(s) are selected. At least one Figfam Group must be selected.");
	}
}

function catchFastaIds(windowID, actionType, fastaType, ajaxHttp) {
	var toSubmit = document.getElementById(windowID + "_fTableForm");
	toSubmit.action = "/portal/portal/patric/FeatureTable/FeatureTableWindow?action=b&cacheability=PAGE&mode=fasta";
	toSubmit.fastaaction.value = actionType;
	toSubmit.fastascope.value = "Selected";
	toSubmit.fastatype.value = fastaType;
	toSubmit.fids.value = ajaxHttp.responseText;
	if (actionType == "display") {
		toSubmit.target = "disp";
	} else {
		toSubmit.target = "";
	}
	toSubmit.submit();
	adjustCheckBoxes("unchecked");
}

function submitIDMapping(windowID, to) {

	var gridObject = getScratchObject(windowID);
	if (gridObject.checkbox.getCheckAll() == true || gridObject.checkbox.getCount() > 0) {
		getSelectedFeatures(windowID, "idmap", "", "", to);
	} else {
		alert("No item(s) are selected. At least one Figfam Group must be selected.");
	}

}

function submitEnrichment(windowID) {
	var gridObject = getScratchObject(windowID);

	if (gridObject.checkbox.getCheckAll() == true || gridObject.checkbox.getCount() > 0) {
		getSelectedFeatures(windowID, "pathway_enrichment", "", "", "");
	} else {
		alert("No item(s) are selected. At least one Figfam Group must be selected.");
	}
}

function submitAlign(windowID) {
	var gridObject = getScratchObject(windowID);

	if (gridObject.checkbox.getCheckAll() == true || gridObject.checkbox.getCount() > 0) {
		getSelectedFeatures(windowID, "msa", "", "", "");
	} else {
		alert("No item(s) are selected. At least one Figfam Group must be selected.");
	}
}

function catchAlignIds(figfamCount, serveURL, hrefBase, ajaxHttp) {
	var featureList = (ajaxHttp.responseText).split(',');
	if (featureList.length <= 262) {
		Ext.Ajax.request({
			url : serveURL,
			method : 'POST',
			timeout : 600000,
			params : {
				callType : "toAligner",
				featureIds : ajaxHttp.responseText
			},
			success : function(rs) {
				//relocate to result page
				document.location.href = hrefBase + "pk=" + rs.responseText;
			}
		});
	} else {
		Ext.Msg.alert(featureList.length + ' proteins selected!', 'Current resources can not handle this many proteins in ' + featureList.length + ' proteins.');
	}
}

function DownloadHeatmap(windowID) {
	document.getElementById(windowID + '_HeatmapData_form').data.value = JSON.stringify(currentData);
	document.getElementById(windowID + '_HeatmapData_form').submit();
}

function changeFamilyType(target) {
	var newHref = document.location.href.replace(/famType=(.)*/, "famType=" + target);
	console.log(newHref);
	document.location.href = newHref;
}


text:
package nl.basjes.parse.core;

public class Value {

    enum Filled {
        STRING,
        LONG,
        DOUBLE
    }

    private final Filled filled;
    private String s = null;
    private Long l = null;
    private Double d = null;

    public Value(String p) {
        filled = Filled.STRING;
        this.s = p;
    }

    public Value(Long p) {
        filled = Filled.LONG;
        this.l = p;
    }

    public Value(Double p) {
        filled = Filled.DOUBLE;
        this.d = p;
    }

    public String getString() {
        switch (filled) {
            case LONG:
                return l == null ? null : Long.toString(l);
            case DOUBLE:
                return d == null ? null : Double.toString(d);
            default: // == case STRING:
                return s;
        }
    }

    public Long getLong() {
        switch (filled) {
            case STRING:
                try {
                    return s == null ? null : Long.parseLong(s);
                } catch (NumberFormatException e) {
                    return null;
                }
            case DOUBLE:
                return d == null ? null : (long) Math.floor(d + 0.5d); // Apply rounding
            default: // == case LONG:
                return l;
        }
    }

    public Double getDouble() {
        switch (filled) {
            case STRING:
                try {
                    return s == null ? null : Double.parseDouble(s);
                } catch (NumberFormatException e) {
                    return null;
                }
            case LONG:
                return l == null ? null : Double.valueOf(l);
            default: // == case DOUBLE:
                return d;
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb  .append("Value{")
            .append("filled=").append(filled);
        if (s == null) {
            sb.append(", s=null");
        } else {
            sb.append(", s='").append(s).append('\'');
        }
        sb
            .append(", l=").append(l)
            .append(", d=").append(d)
            .append('}');
        return sb.toString();
    }
}

redpajama_set_name: RedPajamaGithub


text:
__author__ = "Mateusz Kobos mkobos@icm.edu.pl"

import subprocess
import os.path

class ImageConverter:
    """Takes GraphViz's graph in dot format and generates some derivative data.
    """

    def __init__(self, dot_graph, dot_program_path='/usr/bin/dot'):
        """
        Args:
            dot_graph (string): description of graph in GraphViz's dot format
            dot_program_path (string): path to the `dot` program installed
                in the system along with GraphViz library
        """
        if not os.path.isfile(dot_program_path):
            raise Exception('Given path to "dot" program ("{}") is incorrect. '
                            'It does not exist or it does not correspond '
                            'to a file. '
                            'This might mean that GraphViz library is not '
                            'installed in the system.')
        self.__dot_graph = dot_graph
        self.__dot_program_path = dot_program_path

    def to_image_map(self):
        """
        Returns:
            string: client-size image map ready to be embedded in
                HTML document. This is GraphViz's `cmapx` output
                (see http://www.graphviz.org/doc/info/output.html#a:cmapx).
        """
        raise NotImplementedError

    def to_image(self):
        """Convert the dot graph to a PNG image

        Return:
            byte string
        """
        p = subprocess.Popen([self.__dot_program_path, '-Tpng'],
                             stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        stdout, stderr = p.communicate(self.__dot_graph.encode('utf-8'))
        if len(stderr) > 0:
            raise Exception('Error output produced while running'
                            ' dot program: {} '.format(str(stderr)))
        return stdout


text:
describe('loginService', () => {
    describe('login', () => {
        it('Should invoke ajaxRequester.putJSON method.', (done) => {
            const fakeUser = {
                username: 'fake',
                authKey: 'fake'
            };

            const fakeResponse = {
                result: fakeUser
            };

            const stubCredentialManagerSave = sinon.stub(credentialManager, 'save');
            const mockRequester = sinon.mock(ajaxRequester);
            mockRequester
                .expects('putJSON')
                .returns(new Promise((resolve, reject) => {
                    resolve(fakeResponse);
                }))
                .once();

            loginService.login()
                .then(() => {
                    mockRequester.verify();
                })
                .then(() => {
                    credentialManager.save.restore();
                })
                .then(done, done);
        });

        it('Should invoke ajaxRequester.putJSON method with correct url.', (done) => {
            const fakeUser = {
                username: 'fake',
                authKey: 'fake'
            };

            const fakeResponse = {
                result: fakeUser
            };

            const stubCredentialManagerSave = sinon.stub(credentialManager, 'save');
            const mockRequester = sinon.mock(ajaxRequester);
            mockRequester
                .expects('putJSON')
                .returns(new Promise((resolve, reject) => {
                    resolve(fakeResponse);
                }))
                .withArgs('api/users/auth')
                .once();

            loginService.login()
                .then(() => {
                    mockRequester.verify();
                })
                .then(() => {
                    credentialManager.save.restore();
                })
                .then(done, done);
        });

        it('Should invoke ajaxRequester.putJSON method with correct user.', (done) => {
            const fakeUser = {
                username: 'fake',
                authKey: 'fake'
            };

            const fakeResponse = {
                result: fakeUser
            };

            const fakeUserParameter = {
                username: 'parameter',
                passHash: 'password'
            };

            const stubCredentialManagerSave = sinon.stub(credentialManager, 'save');
            const mockRequester = sinon.mock(ajaxRequester);
            mockRequester
                .expects('putJSON')
                .returns(new Promise((resolve, reject) => {
                    resolve(fakeResponse);
                }))
                .withArgs('api/users/auth', fakeUserParameter)
                .once();

            loginService.login(fakeUserParameter)
                .then(() => {
                    mockRequester.verify();
                })
                .then(() => {
                    credentialManager.save.restore();
                })
                .then(done, done);
        });

        it('Should invoke credentialManager.save method with correct user.', (done) => {
            const fakeUser = {
                username: 'fake',
                authKey: 'fake'
            };

            const fakeResponse = {
                result: fakeUser
            };

            const fakeUserParameter = {
                username: 'parameter',
                passHash: 'password'
            };

            const stubAjaxRequesterPutJSON = sinon.stub(ajaxRequester, 'putJSON');
            stubAjaxRequesterPutJSON
                .returns(new Promise((resolve, reject) => {
                    resolve(fakeResponse);
                }));

            const mockCredentialManager = sinon.mock(credentialManager);
            mockCredentialManager
                .expects('save')
                .withArgs(fakeUser)
                .once();

            loginService.login(fakeUserParameter)
                .then(() => {
                    mockCredentialManager.verify();
                })
                .then(() => {
                    ajaxRequester.putJSON.restore();
                })
                .then(done, done);
        });

        it('Should return the correct username.', (done) => {
            const fakeUser = {
                username: 'fake',
                authKey: 'fake'
            };

            const fakeResponse = {
                result: fakeUser
            };

            const fakeUserParameter = {
                username: 'parameter',
                passHash: 'password'
            };

            const stubAjaxRequesterPutJSON = sinon.stub(ajaxRequester, 'putJSON');
            stubAjaxRequesterPutJSON
                .returns(new Promise((resolve, reject) => {
                    resolve(fakeResponse);
                }));

            const stubCredentialManagerSave = sinon.stub(credentialManager, 'save');

            loginService.login(fakeUserParameter)
                .then((username) => {
                    chai.expect(username).to.equal(fakeUser.username);
                })
                .then(() => {
                    ajaxRequester.putJSON.restore();
                    credentialManager.save.restore();
                })
                .then(done, done);
        });
    });

    describe('register', () => {
        it('Should invoke ajaxRequester.postJSON method.', (done) => {
            const fakeUser = {
                username: 'fake',
                authKey: 'fake'
            };

            const fakeResponse = {
                result: fakeUser
            };

            const mockRequester = sinon.mock(ajaxRequester);
            mockRequester
                .expects('postJSON')
                .returns(new Promise((resolve, reject) => {
                    resolve(fakeResponse);
                }))
                .once();

            loginService.register()
                .then(() => {
                    mockRequester.verify();
                })
                .then(done, done);
        });

        it('Should invoke ajaxRequester.postJSON method with correct url.', (done) => {
            const fakeUser = {
                username: 'fake',
                authKey: 'fake'
            };

            const fakeResponse = {
                result: fakeUser
            };

            const mockRequester = sinon.mock(ajaxRequester);
            mockRequester
                .expects('postJSON')
                .returns(new Promise((resolve, reject) => {
                    resolve(fakeResponse);
                }))
                .withArgs('api/users')
                .once();

            loginService.register()
                .then(() => {
                    mockRequester.verify();
                })
                .then(done, done);
        });

        it('Should invoke ajaxRequester.postJSON method with correct user.', (done) => {
            const fakeUser = {
                username: 'fake',
                authKey: 'fake'
            };

            const fakeResponse = {
                result: fakeUser
            };

            const fakeUserParameter = {
                username: 'parameter',
                passHash: 'password'
            };

            const mockRequester = sinon.mock(ajaxRequester);
            mockRequester
                .expects('postJSON')
                .returns(new Promise((resolve, reject) => {
                    resolve(fakeResponse);
                }))
                .withArgs('api/users', fakeUserParameter)
                .once();

            loginService.register(fakeUserParameter)
                .then(() => {
                    mockRequester.verify();
                })
                .then(done, done);
        });

        it('Should return the correct username.', (done) => {
            const fakeUser = {
                username: 'fake',
                authKey: 'fake'
            };

            const fakeResponse = {
                result: fakeUser
            };

            const fakeUserParameter = {
                username: 'parameter',
                passHash: 'password'
            };

            const stubAjaxRequesterPutJSON = sinon.stub(ajaxRequester, 'postJSON');
            stubAjaxRequesterPutJSON
                .returns(new Promise((resolve, reject) => {
                    resolve(fakeResponse);
                }));

            loginService.register(fakeUserParameter)
                .then((username) => {
                    chai.expect(username).to.equal(fakeUser.username);
                })
                .then(() => {
                    ajaxRequester.postJSON.restore();
                })
                .then(done, done);
        });
    });
});


text:
CodeForces Eclipse plugin

# Features

* create a new project for each contest
* generates a JUnit testcase for each problem with given test cases already setup
* attempts to parse any modulo from the problem statement and make it available via MOD constant
* attempts to parse any relative error from the problem statement and uses it during solution checking
* parses timeout from the problem statement and adds it to the JUnit test case
* add additional test cases easily
* generated code template can be edited for usual input functions, etc...
* currently supports Java only. Other languages can be added via plugins

# Installing

An update site will be provided once I have time to set it up. For now, go to the releases and download the plugin JAR file. Place it inside your Eclipse plugins directory and reestart Eclipse.

# Using

Add the EclipseForces views to your perspective. Available ones:

* Contest List: provides a list of contests fetched from the Codeforces website
* Problem List: a list of all problems with contest, date, level and tags/categories
* Problem Statement: shows the problem statement for the currently opened solution code

From the Contest List, select the view menu and select one of the options to get the list of contests available (current ones, current contest list page or full list).

Once the contest list is updated, double-click on the desired contest and a new project will be created and the first problem opened in the editor.

# Bugs

If you find any bugs or issues, feel free to report them via the Github issues for this project.

# Acknowledgement

This plugin would not have been possible without the EclipseCoder plugin by Fredrik Fornwall (http://fornwall.net/eclipsecoder) which was used as the basis for this code.

# License

This plugin is available via the [Apache 2 License](http://www.apache.org/licenses/LICENSE-2.0)


text:
package cn.alandelip.teachingsupportapp.lesson.presenter.contract;

import java.util.List;

import cn.alandelip.teachingsupportapp.common.presenter.BasePresenter;
import cn.alandelip.teachingsupportapp.common.view.BaseView;
import cn.alandelip.teachingsupportapp.lesson.model.response.LessonResponse;

/**
 * @author v-zhuxu on 6/21/2017.
 */
public interface LessonContract {

    interface View extends BaseView<Presenter> {
    }

    interface Presenter extends BasePresenter {
    }
}


text:
namespace IxMilia.Dxf.Entities
{
    public class DxfLwPolylineVertex
    {
        public double X { get; set; }
        public double Y { get; set; }
        public int Identifier { get; set; }
        public double StartingWidth { get; set; }
        public double EndingWidth { get; set; }
        public double Bulge { get; set; }
    }
}


text:
<?php

namespace Symfony\Cmf\Bundle\BlockBundle\Document;

use Doctrine\ODM\PHPCR\Document\Image;
use Doctrine\ODM\PHPCR\Mapping\Annotations as PHPCRODM;

use Symfony\Cmf\Bundle\BlockBundle\Document\BaseBlock;

/**
 * Block to hold an image
 *
 * @PHPCRODM\Document(referenceable=true)
 */
class ImagineBlock extends BaseBlock
{
    /**
     * @var Image
     * @PHPCRODM\Child(cascade="persist")
     */
    protected $image;

    /** @PHPCRODM\String */
    protected $label;

    /**
     * Optional link url to use on the image
     * @PHPCRODM\String
     */
    protected $linkUrl;

    /** @PHPCRODM\String */
    protected $filter;

    /**
     * @var \PHPCR\NodeInterface
     * @PHPCRODM\Node
     */
    protected $node;

    /**
     * {@inheritdoc}
     */
    public function getType()
    {
        return 'cmf.block.imagine';
    }

    public function setLabel($label)
    {
        $this->label = $label;
    }

    public function getLabel()
    {
        return $this->label;
    }

    public function setLinkUrl($url)
    {
        $this->linkUrl = $url;
    }

    public function getLinkUrl()
    {
        return $this->linkUrl;
    }

    /**
     * Sets the Imagine filter which is going to be used
     */
    public function setFilter($filter)
    {
        $this->filter = $filter;
    }

    public function getFilter()
    {
        return $this->filter;
    }

    /**
     * Set the image for this block.
     *
     * Setting null will do nothing, as this is what happens when you edit this
     * block in a form without uploading a replacement file.
     *
     * If you need to delete the Image, you can use getImage and delete it with
     * the document manager. Note that this block does not make much sense
     * without an image, though.
     *
     * @param Image $image optional the image to update
     */
    public function setImage($image)
    {
        if (!$image) {
            return;
        } elseif ($this->image && $this->image->getFile()) {
            // TODO: this is needed due to a bug in PHPCRODM (http://www.doctrine-project.org/jira/browse/PHPCR-98)
            // TODO: this can be removed once the bug is fixed
            $this->image->getFile()->setFileContent($image->getFile()->getFileContent());
        } else {
            $this->image = $image;
        }
    }

    /**
     * @return Image
     */
    public function getImage()
    {
        return $this->image;
    }

    /**
     * @return \PHPCR\NodeInterface
     */
    public function getNode()
    {
        return $this->node;
    }

}


text:
<?php

namespace Tomarq\Detect\Types;

use Tomarq\Detect\FileType;

interface DetectorInterface {
    /**
     * Attempts to identify the given file.
     *
     * On success, returns a FileType
     * On failure, returns null
     *
     * @return FileType|null
     */
    public function getFileType($filename);

    /**
     * Returns an array of file types supported by this detector
     *
     * @return FileType[]
     */
    public function getSupportedTypes();
}


text:
<?php namespace Ivacuum\Generic\Commands;

class MakeAcpVueSection extends MakeAcpSection
{
    protected $signature = 'make:acp-vue-section {model} {base}';
    protected $description = 'Create a new Vue.js admin control panel section';

    protected $fs;
    protected $base;
    protected $model;
    protected $basePlural;
    protected $modelPlural;
    protected $basePluralLower;
    protected $modelPluralLower;

    public function handle()
    {
        $this->base = $this->argument('base');
        $this->model = $this->argument('model');
        $this->basePlural = \Str::plural($this->base);
        $this->modelPlural = \Str::plural($this->model);
        $this->basePluralLower = mb_strtolower($this->basePlural);
        $this->modelPluralLower = mb_strtolower($this->modelPlural);

        if ($this->fs->exists($this->controllerPath($this->modelPlural))) {
            $this->info("Контроллер [{$this->modelPlural}] уже существует");
        } elseif (!$this->fs->exists($this->controllerPath($this->basePlural))) {
            $this->info("Контроллер [{$this->basePlural}] не найден");
        } else {
            $this->putController();
            $this->info("Создан контроллер [{$this->modelPlural}]");
        }

        $this->putRoute();

        if (!$this->fs->exists($this->resourcePath($this->model))) {
            $this->putResource();
        }

        if (!$this->fs->exists($this->resourceCollectionPath($this->model))) {
            $this->putResourceCollection();
        }

        if ($this->fs->exists($this->componentsPath($this->modelPlural))) {
            $this->info("Папка с компонентами [{$this->modelPlural}] уже существует");
        } elseif (!$this->fs->exists($this->componentsPath($this->basePlural))) {
            $this->info("Папка с компонентами [{$this->basePlural}] не найдена");
        } else {
            $this->putComponents();
            $this->info("Созданы компоненты [{$this->modelPlural}]");
        }

        $this->replaceModelJsTrans();
        $this->printVueRoutes();
        $this->printAuthReminder();
    }

    protected function componentsPath(string $folder): string
    {
        return resource_path("js/components/acp/{$folder}");
    }

    protected function modelJsPath(string $folder): string
    {
        return resource_path("js/components/acp/{$folder}/Model.js");
    }

    protected function printVueRoutes(): void
    {
        if (str_contains($this->fs->get($this->routerPath()), "./components/acp/{$this->modelPlural}/Index.vue")) {
            return;
        }

        $this->info('Маршруты для вставки в resources/js/router.js');

        echo <<<VUE
{ path: '{$this->modelPluralLower}', component: () => import(/* webpackChunkName: "acp" */'./components/acp/{$this->modelPlural}/Index.vue') },
{ path: '{$this->modelPluralLower}/create', component: () => import(/* webpackChunkName: "acp" */'./components/acp/{$this->modelPlural}/Form.vue') },
{
  path: '{$this->modelPluralLower}/:id',
  component: () => import(/* webpackChunkName: "acp" */'./components/acp/{$this->modelPlural}/Layout.vue'),
  component: () => import(/* webpackChunkName: "acp" */'./components/acp/DefaultItemLayout.vue'),
  children: [
    { path: '/', component: () => import(/* webpackChunkName: "acp" */'./components/acp/{$this->modelPlural}/Show.vue') },
    { path: 'edit', component: () => import(/* webpackChunkName: "acp" */'./components/acp/{$this->modelPlural}/Form.vue') },
  ],
},

VUE;
    }

    protected function putComponents()
    {
        return $this->fs->copyDirectory(
            $this->componentsPath($this->basePlural),
            $this->componentsPath($this->modelPlural)
        );
    }

    protected function putResource()
    {
        $content = str_replace(
            $this->resourceReplaceArray('base'),
            $this->resourceReplaceArray('model'),
            $this->fs->get($this->resourcePath($this->base))
        );

        $this->fs->put($this->resourcePath($this->model), $content);
    }

    protected function putResourceCollection()
    {
        $content = str_replace(
            $this->resourceReplaceArray('base'),
            $this->resourceReplaceArray('model'),
            $this->fs->get($this->resourceCollectionPath($this->base))
        );

        $this->fs->put($this->resourceCollectionPath($this->model), $content);
    }

    protected function replaceModelJsTrans()
    {
        $path = $this->modelJsPath($this->modelPlural);

        $this->fs->put($path, preg_replace('/\''.$this->base.'\'/', "'{$this->model}'", $this->fs->get($path)));
    }

    protected function resourceCollectionPath(string $file): string
    {
        return app_path("Http/Resources/Acp/{$file}Collection.php");
    }

    protected function resourcePath(string $file): string
    {
        return app_path("Http/Resources/Acp/{$file}.php");
    }

    protected function resourceReplaceArray(string $var): array
    {
        $varPlural = "{$var}_plural";

        return [
            "Acp\\{$this->{$varPlural}}",
            "App\\{$this->{$var}}",
            "class {$this->{$var}}",
            "{$this->{$var}}::class",
        ];
    }

    protected function routerPath(): string
    {
        return resource_path('js/router.js');
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ceská Mykol. 46(3-4): 149 (1993)

#### Original name
Calycellina angulata Svrcek

### Remarks
null


text:
> Create a WOFF2 font from a TTF font with [Gulp](http://gulpjs.com/).

[![NPM version](https://badge.fury.io/js/gulp-ttf2woff2.svg)](https://npmjs.org/package/gulp-ttf2woff2) [![Run test](https://github.com/nfroidure/gulp-ttf2woff2/workflows/Run%20tests/badge.svg)](https://github.com/nfroidure/gulp-ttf2woff2/actions) [![Dependency Status](https://david-dm.org/nfroidure/gulp-ttf2woff2.svg)](https://david-dm.org/nfroidure/gulp-ttf2woff2) [![devDependency Status](https://david-dm.org/nfroidure/gulp-ttf2woff2/dev-status.svg)](https://david-dm.org/nfroidure/gulp-ttf2woff2#info=devDependencies) [![Coverage Status](https://coveralls.io/repos/nfroidure/gulp-ttf2woff2/badge.svg?branch=master)](https://coveralls.io/r/nfroidure/gulp-ttf2woff2?branch=master) [![Code Climate](https://codeclimate.com/github/nfroidure/gulp-ttf2woff2.svg)](https://codeclimate.com/github/nfroidure/gulp-ttf2woff2)

## Usage

First, install `gulp-ttf2woff2` as a development dependency:

```shell
npm install --save-dev gulp-ttf2woff2
```

Then, add it to your `gulpfile.js`:

```javascript
var ttf2woff2 = require('gulp-ttf2woff2');

gulp.task('ttf2woff2', function(){
  gulp.src(['fonts/*.ttf'])
    .pipe(ttf2woff2())
    .pipe(gulp.dest('fonts/'));
});
```

## API

### ttf2woff(options)

#### options.ignoreExt
Type: `Boolean`
Default value: `false`

Set to true to also convert files that doesn't have the .ttf extension.

#### options.clone
Type: `Boolean`
Default value: `false`

Set to true to clone the file before converting him so that it will output the
 original file too.

### Note

You may look after a full Gulp web font workflow, see
 [gulp-iconfont](https://github.com/nfroidure/gulp-iconfont)
  fot that matter.

## Stats

[![NPM](https://nodei.co/npm/gulp-ttf2woff2.png?downloads=true&stars=true)](https://nodei.co/npm/gulp-ttf2woff2/)
[![NPM](https://nodei.co/npm-dl/gulp-ttf2woff2.png)](https://nodei.co/npm/gulp-ttf2woff2/)

### Contributing / Issues

Please submit TTF to WOFF2 related issues to the
 [ttf2woff2 project](https://github.com/nfroidure/ttf2woff2)
 on wich gulp-ttf2woff2 is built.

This repository issues is only for gulp and gulp tasks related issues.

You may want to contribute to this project, pull requests are welcome if you
 accept to publish under the MIT licence.


text:
package com.googlecode.sparkleg;

import org.antlr.runtime.*;
import org.antlr.runtime.tree.*;
import org.antlr.stringtemplate.*;
import org.antlr.stringtemplate.language.*;

import org.junit.Test;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;

import java.io.*;

import java.util.logging.Level;
import java.util.logging.Logger;

import java.util.ArrayList;
import java.util.Collection;

/**
 *
 * @author Jürgen
 *
 * Select all queries from Sparql.testsuite with expected GUnit status OK.
 * The query is processed by the Sparkle Pretty Printer. The resulting
 * re-formatted query is stored in response1. This response1 query is
 * sent through the Sparkle Printer transformation pipeline, too.
 * The resulting output response2 is compared to the response1. In case
 * of equality the test case is evaluated as successfull.
 * A stable transformation algorithm should result in no changes when
 * repeatedly applied on the generated output.
 * This behaviour is neccessary but not sufficient, for this reason
 * the three data sequences: query, response1 and response2
 * are written for manual inspection in a log file.
 *
 * The test queries enclosed are not part of the gunit testsuite.
 * This is due to the lack of UTF8 support for GUnit at the moment.
 */
@RunWith(Parameterized.class)
public class IdentTest {

    static char[] data = null;
    static long n = -1;
    static OutputStreamWriter w = null;
    private String query;
    static int qcounter = 0;

    public IdentTest(String query) {
        this.query = query;
    }

    @Parameterized.Parameters
    public static Collection<Object[]> generateParams() {

        ArrayList<Object[]> queries = new ArrayList<Object[]>();

        String q1 = "# $Id: kanji-01.rq,v 1.3 2005/11/06 08:27:50 eric Exp $\n"
                + "# test kanji QNames\n"
                + "PREFIX foaf: <http://xmlns.com/foaf/0.1/>"
                + "PREFIX 食: <http://www.w3.org/2001/sw/DataAccess/tests/data/i18n/kanji.ttl#>"
                + "SELECT ?name ?food WHERE {"
                + "  [ foaf:name ?name ;"
                + "    食:食べる ?food ] . }"
                + ""
                + "# $Id: kanji-02.rq,v 1.4 2005/11/06 08:27:50 eric Exp $\n"
                + "# test wide spaces\n"
                + "PREFIX foaf: <http://xmlns.com/foaf/0.1/>"
                + "PREFIX 食: <http://www.w3.org/2001/sw/DataAccess/tests/data/i18n/kanji.ttl#>"
                + "SELECT ?name WHERE {"
                + "  [ foaf:name ?name ;"
                + "    食:食べる 食:海老 ] . }";

        String q2 = "# Figure out what happens with normalization form C.\n"
                + "PREFIX foaf: <http://xmlns.com/foaf/0.1/>"
                + "PREFIX HR: <http://www.w3.org/2001/sw/DataAccess/tests/data/i18n/normalization.ttl#>"
                + "SELECT ?name"
                + " WHERE { [ foaf:name ?name; "
                + "           HR:resumé ?resume ] . }";

        String q3 = "# Example 1 from\n"
                + "# http://lists.w3.org/Archives/Public/public-rdf-dawg/2005JulSep/0096\n"
                + "# $Id: normalization-02.rq,v 1.1 2005/08/09 14:35:26 eric Exp $\n"
                + "PREFIX : <http://example/vocab#>"
                + "PREFIX p1: <eXAMPLE://a/./b/../b/%63/%7bfoo%7d#>"
                + ""
                + "SELECT ?S WHERE { ?S :p p1:xyz }";

        String q4 = "# Example 2 from\n"
                + "# http://lists.w3.org/Archives/Public/public-rdf-dawg/2005JulSep/0096\n"
                + "# $Id: normalization-03.rq,v 1.1 2005/08/09 14:35:26 eric Exp $\n"
                + "PREFIX : <http://example/vocab#>"
                + "PREFIX p2: <http://example.com:80/#>"
                + ""
                + "SELECT ?S WHERE { ?S :p p2:abc }";

        String q5 = "PREFIX : <http://example.org/ns#> SELECT * WHERE { [ ?x ?y ] :p [ ?pa ?b ] }";

        String q6 = "PREFIX : <http://example/> SELECT * WHERE { <\u0078> :\u0070 ?xx\u0078 }";

        String q7 = "#Unicode\n"
                + "PREFIX : <http://example/>"
                + "SELECT *"
                + "# Comments can contain \\ u \n"
                + "# <\u0078> :\u0070 ?xx\u0078\n"
                + "WHERE { <\u0078> :\u0070 ?xx\u0078 }";

        String q8 = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>"
                + "PREFIX person: <http://localhost/persons/>"
                + "PREFIX foaf: <http://xmlns.com/foaf/0.1/>"
                + ""
                + "ASK {"
                + "  person:John_Q_Public rdf:type foaf:Person."
                + "}";

        String q9 = "# Just a comment and nothing else\n select * {}";

        queries.add(new Object[]{q1});
        queries.add(new Object[]{q2});
        queries.add(new Object[]{q3});
        queries.add(new Object[]{q4});
        queries.add(new Object[]{q5});
        queries.add(new Object[]{q6});
        queries.add(new Object[]{q7});
        queries.add(new Object[]{q8});
        queries.add(new Object[]{q9});

        return queries;
    }

    @BeforeClass
    public static void setUpClass() throws FileNotFoundException {
        String outFile = "./src/test/java/com/googlecode/sparkleg/syntactic_validator2.log";
        try {
            w = new OutputStreamWriter(new FileOutputStream(outFile), "UTF8");
        } catch (IOException ex) {
            Logger.getLogger(IdentGunitOkTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @AfterClass
    public static void tearDownClass() {
        try {
            w.close();
        } catch (IOException ex) {
            Logger.getLogger(IdentGunitOkTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    public void validate(String query, String methodName) throws IOException {

        w.write("\n#~~~Input " + methodName + " :\n");
        w.write(query);

        try {

            String response1 = sparklegPrettyPrinter(query);
            String response2 = sparklegPrettyPrinter(response1);

            w.write("\n#+++Response 1:\n");
            w.write(response1);
            w.write("\n#---Response 2:\n");
            w.write(response2);

            assertEquals("+++++++++\nInput:\n" + query + "\nResponse:\n", response1, response2);
        } catch (Exception ex) {
            Logger.getLogger(IdentTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Test
    public void syntacticValidator() {
        try {
            qcounter++;

            System.err.println("\n---Query "+qcounter+" START");

            w.write("\n#~~~Input " + qcounter + " :\n");
            w.write(query);

            try {
                String response1 = sparklegPrettyPrinter(this.query);
                String response2 = sparklegPrettyPrinter(response1);

                w.write("\n#+++Response 1:\n");
                w.write(response1);
                w.write("\n#---Response 2:\n");
                w.write(response2);

                assertEquals("+++++++++\nInput:\n" + query + "\nResponse:\n", response1, response2);
            } catch (Exception ex) {
                Logger.getLogger(IdentGunitOkTest.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (IOException ex) {
            Logger.getLogger(IdentGunitOkTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private String sparklegPrettyPrinter(String query) throws Exception {

        String stringTemplate = "./src/main/antlr3/com/googlecode/sparkleg/ident.stg";

        /* transformation pipline
         * step 1: Unicode pre-processing
         * step 2: Lexical analysis
         */
        SparqlLexer lex = new SparqlLexer(new SparkleUnicodePreprocessorStringStream(query));
        CommonTokenStream tokens = new CommonTokenStream(lex);

        /* transformation pipline
         * step 3: build parse tree
         * step 4: generate AST
         */
        SparqlParser parser = new SparqlParser(tokens);
        SparqlParser.query_return r = parser.query();

        /* transformation pipline
         * step 5: read AST
         * step 6: traverse AST, pass parameters to stringTemplate and write output to string
         */
        CommonTreeNodeStream nodes = new CommonTreeNodeStream(r.getTree());
        SparqlT walker = new SparqlT(nodes);

        StringTemplateGroup g = new StringTemplateGroup(new FileReader(stringTemplate), AngleBracketTemplateLexer.class);
        walker.setTemplateLib(g);
        RuleReturnScope t = null;
        try {
            t = walker.query();
        } catch (RecognitionException e) {
            e.printStackTrace();
        }

        return t.toString();
    }
}


text:
      {{ 'msg.board.create.data-preview' | translate }}

      {{ 'msg.board.create.join' | translate }}

      {{ 'msg.board.create.essential-filter' | translate }}

      {{ 'msg.board.create.unlink-datasource' | translate }}

        {{ dataSource.name }}
        {{ dataSource.uiDescription }}

          {{ commonUtil.formatBytes( dataSourceSummary.size, 1 ) }}

          {{headerCnt}} {{'msg.comm.detail.columns' | translate}}

          <component-input
            [value]="rowNum"
            [valueType]="'number'"
            [placeHolder]="'msg.board.ui.search.full-column.ph' | translate"
            (changeValue)="setGridRow($event)"></component-input>
           / {{ dataSourceSummary?.count }}
          {{'msg.comm.detail.rows' | translate}}

          {{colTypes.length}} Types

                   {{colType.cnt}}

         {{'msg.space.ui.no.data' | translate}}

           {{dataSource.name}}

                  {{join.name}}

                   {{'msg.board.btn.add.datasource.join' | translate}}

                  {{join.join.name}}

                 {{'msg.board.btn.add.datasource.join' | translate}}

        {{ 'msg.comm.ui.edit' | translate }}

              {{filter.field}}

<create-board-pop-join (complete)="changeJoin($event)"></create-board-pop-join>


text:
export type Not<T extends boolean> = T extends true ? false : true
export type Or<Types extends boolean[]> = Types[number] extends false ? false : true
export type And<Types extends boolean[]> = Types[number] extends true ? true : false
export type Eq<Left extends boolean, Right extends boolean> = Left extends true ? Right : Not<Right>
export type Xor<Types extends [boolean, boolean]> = Not<Eq<Types[0], Types[1]>>

const secret = Symbol('secret')
type Secret = typeof secret

export type IsNever<T> = [T] extends [never] ? true : false
export type IsAny<T> = [T] extends [Secret] ? Not<IsNever<T>> : false
export type IsUnknown<T> = [unknown] extends [T] ? Not<IsAny<T>> : false
export type IsNeverOrAny<T> = Or<[IsNever<T>, IsAny<T>]>

/**
 * Recursively walk a type and replace it with a branded type related to the original. This is useful for
 * equality-checking stricter than `A extends B ? B extends A ? true : false : false`, because it detects
 * the difference between a few edge-case types that vanilla typescript doesn't by default:
 * - `any` vs `unknown`
 * - `{ readonly a: string }` vs `{ a: string }`
 * - `{ a?: string }` vs `{ a: string | undefined }`
 */
export type DeepBrand<T> = IsNever<T> extends true
  ? {type: 'never'}
  : IsAny<T> extends true
  ? {type: 'any'}
  : IsUnknown<T> extends true
  ? {type: 'unknown'}
  : T extends string | number | boolean | symbol | bigint | null | undefined | void
  ? {
      type: 'primitive'
      value: T
    }
  : T extends new (...args: any[]) => any
  ? {
      type: 'constructor'
      params: ConstructorParams<T>
      instance: DeepBrand<InstanceType<Extract<T, new (...args: any) => any>>>
    }
  : T extends (...args: infer P) => infer R // avoid functions with different params/return values matching
  ? {
      type: 'function'
      params: DeepBrand<P>
      return: DeepBrand<R>
      this: DeepBrand<ThisParameterType<T>>
    }
  : T extends any[]
  ? {
      type: 'array'
      items: {[K in keyof T]: T[K]}
    }
  : {
      type: 'object'
      properties: {[K in keyof T]: DeepBrand<T[K]>}
      readonly: ReadonlyKeys<T>
      required: RequiredKeys<T>
      optional: OptionalKeys<T>
      constructorParams: DeepBrand<ConstructorParams<T>>
    }

export type RequiredKeys<T> = Extract<
  {
    [K in keyof T]-?: {} extends Pick<T, K> ? never : K
  }[keyof T],
  keyof T
>
export type OptionalKeys<T> = Exclude<keyof T, RequiredKeys<T>>

// adapted from some answers to https://github.com/type-challenges/type-challenges/issues?q=label%3A5+label%3Aanswer
// prettier-ignore
export type ReadonlyKeys<T> = Extract<{
  [K in keyof T]-?: ReadonlyEquivalent<
    {[_K in K]: T[K]},
    {-readonly [_K in K]: T[K]}
  > extends true ? never : K;
}[keyof T], keyof T>;

// prettier-ignore
type ReadonlyEquivalent<X, Y> = Extends<
  (<T>() => T extends X ? true : false),
  (<T>() => T extends Y ? true : false)
>

export type Extends<L, R> = IsNever<L> extends true ? IsNever<R> : [L] extends [R] ? true : false
export type StrictExtends<L, R> = Extends<DeepBrand<L>, DeepBrand<R>>

export type Equal<Left, Right> = And<[StrictExtends<Left, Right>, StrictExtends<Right, Left>]>

export type Params<Actual> = Actual extends (...args: infer P) => any ? P : never
export type ConstructorParams<Actual> = Actual extends new (...args: infer P) => any
  ? Actual extends new () => any
    ? P | []
    : P
  : never

type MismatchArgs<B extends boolean, C extends boolean> = Eq<B, C> extends true ? [] : [never]

export interface ExpectTypeOf<Actual, B extends boolean> {
  toBeAny: (...MISMATCH: MismatchArgs<IsAny<Actual>, B>) => true
  toBeUnknown: (...MISMATCH: MismatchArgs<IsUnknown<Actual>, B>) => true
  toBeNever: (...MISMATCH: MismatchArgs<IsNever<Actual>, B>) => true
  toBeFunction: (...MISMATCH: MismatchArgs<Extends<Actual, (...args: any[]) => any>, B>) => true
  toBeObject: (...MISMATCH: MismatchArgs<Extends<Actual, object>, B>) => true
  toBeArray: (...MISMATCH: MismatchArgs<Extends<Actual, any[]>, B>) => true
  toBeNumber: (...MISMATCH: MismatchArgs<Extends<Actual, number>, B>) => true
  toBeString: (...MISMATCH: MismatchArgs<Extends<Actual, string>, B>) => true
  toBeBoolean: (...MISMATCH: MismatchArgs<Extends<Actual, boolean>, B>) => true
  toBeVoid: (...MISMATCH: MismatchArgs<Extends<Actual, void>, B>) => true
  toBeSymbol: (...MISMATCH: MismatchArgs<Extends<Actual, symbol>, B>) => true
  toBeNull: (...MISMATCH: MismatchArgs<Extends<Actual, null>, B>) => true
  toBeUndefined: (...MISMATCH: MismatchArgs<Extends<Actual, undefined>, B>) => true
  toBeNullable: (...MISMATCH: MismatchArgs<Not<Equal<Actual, NonNullable<Actual>>>, B>) => true
  toMatchTypeOf: {
    <Expected>(...MISMATCH: MismatchArgs<Extends<Actual, Expected>, B>): true
    <Expected>(expected: Expected, ...MISMATCH: MismatchArgs<Extends<Actual, Expected>, B>): true
  }
  toEqualTypeOf: {
    <Expected>(...MISMATCH: MismatchArgs<Equal<Actual, Expected>, B>): true
    <Expected>(expected: Expected, ...MISMATCH: MismatchArgs<Equal<Actual, Expected>, B>): true
  }
  toBeCallableWith: B extends true ? (...args: Params<Actual>) => true : never
  toBeConstructibleWith: B extends true ? (...args: ConstructorParams<Actual>) => true : never
  toHaveProperty: <K extends string>(
    key: K,
    ...MISMATCH: MismatchArgs<Extends<K, keyof Actual>, B>
  ) => K extends keyof Actual ? ExpectTypeOf<Actual[K], B> : true
  extract: <V>(v?: V) => ExpectTypeOf<Extract<Actual, V>, B>
  exclude: <V>(v?: V) => ExpectTypeOf<Exclude<Actual, V>, B>
  parameter: <K extends keyof Params<Actual>>(number: K) => ExpectTypeOf<Params<Actual>[K], B>
  parameters: ExpectTypeOf<Params<Actual>, B>
  constructorParameters: ExpectTypeOf<ConstructorParams<Actual>, B>
  thisParameter: ExpectTypeOf<ThisParameterType<Actual>, B>
  instance: Actual extends new (...args: any[]) => infer I ? ExpectTypeOf<I, B> : never
  returns: Actual extends (...args: any[]) => infer R ? ExpectTypeOf<R, B> : never
  resolves: Actual extends PromiseLike<infer R> ? ExpectTypeOf<R, B> : never
  items: Actual extends ArrayLike<infer R> ? ExpectTypeOf<R, B> : never
  guards: Actual extends (v: any, ...args: any[]) => v is infer T ? ExpectTypeOf<T, B> : never
  asserts: Actual extends (v: any, ...args: any[]) => asserts v is infer T
    ? // Guard methods `(v: any) => asserts v is T` does not actually defines a return type. Thus, any function taking 1 argument matches the signature before.
      // In case the inferred assertion type `R` could not be determined (so, `unknown`), consider the function as a non-guard, and return a `never` type.
      // See https://github.com/microsoft/TypeScript/issues/34636
      unknown extends T
      ? never
      : ExpectTypeOf<T, B>
    : never
  not: ExpectTypeOf<Actual, Not<B>>
}
const fn: any = () => true

export type _ExpectTypeOf = {
  <Actual>(actual: Actual): ExpectTypeOf<Actual, true>
  <Actual>(): ExpectTypeOf<Actual, true>
}

/**
 * Similar to Jest's `expect`, but with type-awareness.
 * Gives you access to a number of type-matchers that let you make assertions about the
 * form of a reference or generic type parameter.
 *
 * @example
 * import {foo, bar} from '../foo'
 * import {expectTypeOf} from 'expect-type'
 *
 * test('foo types', () => {
 *   // make sure `foo` has type {a: number}
 *   expectTypeOf(foo).toMatchTypeOf({a: 1})
 *   expectTypeOf(foo).toHaveProperty('a').toBeNumber()
 *
 *   // make sure `bar` is a function taking a string:
 *   expectTypeOf(bar).parameter(0).toBeString()
 *   expectTypeOf(bar).returns.not.toBeAny()
 * })
 *
 * @description
 * See the [full docs](https://npmjs.com/package/expect-type#documentation) for lots more examples.
 */
export const expectTypeOf: _ExpectTypeOf = <Actual>(_actual?: Actual): ExpectTypeOf<Actual, true> => {
  const nonFunctionProperties = [
    'parameters',
    'returns',
    'resolves',
    'not',
    'items',
    'constructorParameters',
    'thisParameter',
    'instance',
    'guards',
    'asserts',
  ] as const
  type Keys = keyof ExpectTypeOf<any, any>

  type FunctionsDict = Record<Exclude<Keys, typeof nonFunctionProperties[number]>, any>
  const obj: FunctionsDict = {
    /* eslint-disable mmkal/@typescript-eslint/no-unsafe-assignment */
    toBeAny: fn,
    toBeUnknown: fn,
    toBeNever: fn,
    toBeFunction: fn,
    toBeObject: fn,
    toBeArray: fn,
    toBeString: fn,
    toBeNumber: fn,
    toBeBoolean: fn,
    toBeVoid: fn,
    toBeSymbol: fn,
    toBeNull: fn,
    toBeUndefined: fn,
    toBeNullable: fn,
    toMatchTypeOf: fn,
    toEqualTypeOf: fn,
    toBeCallableWith: fn,
    toBeConstructibleWith: fn,
    /* eslint-enable mmkal/@typescript-eslint/no-unsafe-assignment */
    extract: expectTypeOf,
    exclude: expectTypeOf,
    toHaveProperty: expectTypeOf,
    parameter: expectTypeOf,
  }

  const getterProperties: readonly Keys[] = nonFunctionProperties
  getterProperties.forEach((prop: Keys) => Object.defineProperty(obj, prop, {get: () => expectTypeOf({})}))

  return obj as ExpectTypeOf<Actual, true>
}