text:
/**
 *判断浏览器类型方法
 *
 */
function BrowserType(){
	var OsObject = "";
	if(navigator.userAgent.indexOf("MSIE")>0) {
		OsObject = "MSIE";
	}
	if(isFirefox=navigator.userAgent.indexOf("Firefox")>0){
		OsObject = "Firefox";
	}
	if(isSafari=navigator.userAgent.indexOf("Safari")>0&&navigator.userAgent.indexOf("Chrome")<0) {
		OsObject = "Safari";
	}
	if(isCamino=navigator.userAgent.indexOf("Chrome")>0){
		OsObject = "Chrome";
	}
	return OsObject;
}

var fast_hidecol_sumheight;
var fast_hidecol_sumwidth;
var hideColHeaderArray;
var showMenuTd=null;
var addBtnCell=new Array();//记录要加按钮的单元格
var cloneArr;//克隆单元格的原始信息
var clearHid=false;
$(document).click(function(event){
	if($("#menuDiv")[0]){
		if($(event.target).parents("#menuDiv").length>0|| $(event.target).attr("name")=="menuButton" || $(event.target).parent("div").attr("name")=="menuButton"){
		}else{
			removeMenu();
		}
	}

});

/** 初始化表格,给相应单元格添加按钮,并保存表格的一些原始信息**/
function addBtn(reportId){
	Resizeold(reportId,null,true);
	var sortData=null;
	var url=PathUtils.getRelativeUrl("/mis2/vrsr/json/demo1_action14.json");
	$.ajax({type:"POST", url:url, async:false, cache:false, data:{"resID":base64.encode(reportID),"reportDefineId":base64.encode(reportDefineId)}, dataType:"json",
		success:function (data) {
			sortData=data;
		}, error:function () {
			alert("获取排序信息失败");
		}}
	);
	var cornerTableId = "report_"+reportId+"_table_corner";
	var colHeaderTableId = "report_"+reportId+"_table_colHeader"
	var cornerTable = $("#"+cornerTableId);
	var colHeaderTable = $("#"+colHeaderTableId);
	var dataTableId = "report_"+reportId+"_table_data";
	var dataTable = $("#"+dataTableId);

	colHeaderTable.attr("oldWidth",colHeaderTable.css("width"));
	dataTable.attr("oldWidth",dataTable.css("width"));

	var btn ="
" + $(IconFactory.getIcon("gezico_p_xialashuzhankai")).html() + "
";
	//给分组字段加按钮
	$(cornerTable.find("tr").get(0)).find("td").each(function(){
		var element=this;
		$.each(sortData.groupFields,function(i, item) {
			//if(item.label==$(element).html()){
			if(item.label==$(element)[0].innerText){
				if(item.data=='升序'){
					$(element).attr("sort","asc");
				}else{
					$(element).attr("sort","desc");
				}
			}
		});
//		$(this).attr("colName",$(this).html());
		$(this).append(btn);
//		$(this).css("position","relative");
//		$(this).children("div").eq(0).css("position", "absolute");
//		$(this).children("div").eq(2).css("z-index", "999");
//		$(this).children("div").eq(0).css("left",$(this).offset().left + $(this).outerWidth() - 10);
//		$(this).children("div").eq(0).css("top",$(this).offset().top + $(this).outerHeight() - 10);
		var menuButton = $(this).children("div[name='menuButton']");
		menuButton.find("i").removeClass("i1").css("color",$(this).css("color"));
		menuButton.css("top",parseInt($(this).height()) - (parseInt(menuButton.offset().top) - parseInt($(this).offset().top))- 10 - 5);
		if(window.navigator.userAgent.toLowerCase().indexOf("chrome") != -1){
			//Chrome下允许的字体最小为12px。所以图标使用transform进行缩放,重新设置右位移
			menuButton.css("right","8px");
		}
		menuButton.hide();
		//鼠标移入
		$(this).mouseover(function(){
			$(this).children("div[id=tmp]").children("div[name='menuButton']").show();
		});
		//鼠标移出
		$(this).mouseout(function(){
			if(	$(this).children("div[id=tmp]").children("div[name='menuButton']").attr("hasShow") != "true"){
				$(this).children("div[id=tmp]").children("div[name='menuButton']").hide();
			}
			if(	$(this).children("div[name='menuButton']").attr("hasShow") != "true"){
				$(this).children("div[name='menuButton']").hide();
			}
		});

		//下面代码影响横向双箭头

//		$(this).children("div").eq(0).css("right","-10px");
//		if(parseInt($(this).css("height"))>50){ //区分处理复杂表头
//			//$(this).children("div").eq(0).css("top","50px");
//			$(this).children("div").eq(0).css("top",parseInt($(this).height())-10);
//			//$(this).children("div").eq(2).css("bottom","-10px");
//		}else{
//			$(this).children("div").eq(0).css("top","20px");
//			//$(this).children("div").eq(2).css("bottom","-10px");
//		}

	});

	//给数据列字段加按钮
	addBtnCell = new Array();
	$(colHeaderTable.find("tr").get(0)).find("td").each(function(index){
		addBtnCell[index] = $(this);
	});
	$(colHeaderTable).find("tr").each(function(){
		var tr = $(this)
		$(tr).find("td").each(function(index){
			var element=this;
			$.each(sortData.selectFields,function(i, item) {
				//if(item.label==$(element).html()){
				if(item.label==$(element)[0].innerText){
					if(item.data=='升序'){
						$(element).attr("sort","asc");
					}else{
						$(element).attr("sort","desc");
					}
				}
			});
			if($(this).css("display")!='none'){
				addBtnCell[index] = $(this);
				$(this).attr("oldCellHeight",$(this).css("height"));
				$(this).attr("oldColSpan",$(this).attr("colSpan"));
				$(this).attr("oldCellWidth",$(this).css("width"));
			}else{
				$(this).attr("oldCellHeight",$(this).css("height"));
				$(this).attr("oldColSpan",$(this).attr("colSpan"));
				$(this).attr("oldCellWidth",$(this).css("width"));

			}
		});
	});
	cloneArr = new Array();
	for(var i=0;i<addBtnCell.length;i++){
		var cell = $(addBtnCell[i]);
		cloneArr[i] = cell.css("height");
//		$(cell).attr("colName",$(cell).html());
		cell.append(btn);
//		cell.css("position","relative")
//		cell.children("div").eq(0).css("position", "absolute");
//		cell.children("div").eq(0).css("left",cell.offset().left + cell.outerWidth() - 10);
//		cell.children("div").eq(0).css("top",cell.offset().top + cell.outerHeight() - 10);
		var menuButton = $(cell).children("div[name='menuButton']");
		menuButton.find("i").removeClass("i1").css("color",cell.css("color"));
		menuButton.css("top",parseInt($(cell).height()) - (parseInt(menuButton.offset().top) - parseInt($(cell).offset().top))- 10 - 5);
		if(window.navigator.userAgent.toLowerCase().indexOf("chrome") != -1){
			//Chrome下允许的字体最小为12px。所以图标使用transform进行缩放,重新设置右位移
			menuButton.css("right","8px");
		}

		menuButton.hide();
		//鼠标移入
		$(cell).mouseenter(function(){
			$(this).children("div[id=tmp]").children("div[name='menuButton']").show();
		});
		//鼠标移出
		$(cell).mouseleave(function(){
			if(	$(this).children("div[id=tmp]").children("div[name='menuButton']").attr("hasShow") != "true"){
				$(this).children("div[id=tmp]").children("div[name='menuButton']").hide();
			}
			if(	$(this).children("div[name='menuButton']").attr("hasShow") != "true"){
				$(this).children("div[name='menuButton']").hide();
			}
		});

//		cell.children("div").eq(0).css("right","-10px");
//		if(parseInt(cloneArr[i])>50){  //区分处理复杂表头
//			//cell.children("div").eq(0).css("top","50px");
//			cell.children("div").eq(0).css("top",parseInt(cloneArr[i])-10);
//			//cell.children("div").eq(2).css("bottom","-10px");
//		}else{
//			cell.children("div").eq(0).css("top","20px");
//			//cell.children("div").eq(2).css("bottom","-10px");
//
//		}
		//cell.children("div").eq(0).css("left",cell.offsetLeft+cell.offsetWidth-10);

	}

}
//弹出菜单div
function showMenu(div){
	//var td = $(div).parent("td");
	var td = $(div).parent("div").parent("td")
	var offset = td.offset();
		var newDivX=parseInt(offset.left) + td.outerWidth(true) - 10;
		var newDivY=parseInt(offset.top) + td.outerHeight(true);
		if($.browser.msie&&parseInt($.browser.version)<=8){
			var offset =  $(div).offset();
			newDivX =offset.left;
			var table = $(div).parents("table:last");
			newDivY = $(div).attr("offsetTop")+$(table).attr("offsetTop");
		}
		if(showMenuTd){
			removeMenu();
			$("#menuDiv").remove();
		}
		showMenuTd=this;
		if(!$(div).attr("hasShow")){
			$(div).attr("hasShow",false);
		}
	if($(div).attr("hasShow")=="false"){
		$(div).attr("hasShow",true);
		var createDiv=document.createElement("div");
		createDiv.id="menuDiv";
		createDiv.style.width = 200;
		createDiv.style.height = 400;
		var height = 0;
		var footheight=$("span[class='foot']").height();
		if(!footheight){
			footheight=0;
		}
		if($('#tableDiv').attr('clientHeight')){
			 height = $('#tableDiv').attr('clientHeight') - newDivY-footheight;
		}else{
			 height = $('#tableDiv').height() - newDivY-footheight;
		}
		createDiv.style.position = "absolute";
		createDiv.style.background = "#F6f6f6";
		//判断弹出层如果超出页面范围,则left属性往左移动保证弹出层能显示在当前屏幕中
		if(parseInt(newDivX)+166>$(document.body).width()){
			newDivX = parseInt(newDivX)-166;
		}
		createDiv.style.left=newDivX;
		createDiv.style.top =newDivY;
		var base64 = new Base64();
		$(createDiv).html("");
		if($.browser.msie&&parseInt($.browser.version)<=8){
			document.getElementById("tableDiv").appendChild(createDiv);
		}else{
			document.body.appendChild(createDiv);
		}
		//iframe加载完再设置弹出层高度
		var myIFrame = $("#menuIframe");
		var isOnLoad = true;
		myIFrame.load(function() {
			isOnLoad = false;// 加载完成
			try{
				var setContentHeight = $(".setContent",window.frames["menuIframe"].contentWindow.document).height();
			}catch(e){
				var setContentHeight = $(".setContent",window.frames["menuIframe"].document).height();
			}
			if(height>setContentHeight){
				//+10边框宽度
				if("Chrome"==BrowserType()||"Firefox"==BrowserType()){
					createDiv.style.height = setContentHeight+2;
					createDiv.style.width = 164;//加上滚动条宽度
				}else{
					if($.browser.msie&&parseInt($.browser.version)==8){
						createDiv.style.height = setContentHeight+3;
						createDiv.style.width = 163;//加上滚动条宽度
					}else{
						createDiv.style.height = setContentHeight+7;
						createDiv.style.width = 166;//加上滚动条宽度
					}
				}

			}else{
				createDiv.style.height = height;
				createDiv.style.width = 185;//加上滚动条宽度
			}

		});
	}else{
		$(div).attr("hasShow",false);
	}
}

function test(div){
	var v = $(div).parent().attr("v");
	hideCol(v,12066);
}

function vrsrHideCol(v,reportId){
	var colHeaderTableId = "report_"+reportId+"_table_colHeader";
	var colHeaderTable = $("#"+colHeaderTableId);
	var cell = colHeaderTable.find("td[v="+v+"]").get(0);
	var nodeIndex = parseInt($(cell).attr("nodeIndex"));
	var colId = parseInt($(cell).attr("colId"));
	var sizset = $(cell).parent().attr("sizset");
	fast_hidecol_sumwidth = $(cell).css("width").substring(0,$(cell).css("width").length-2);
	var miniColSpan = 1;
	//父级节点的colSpan谷歌单独处理
	if("Chrome"==BrowserType()||"Firefox"==BrowserType()){
		var tr = $(colHeaderTable).find("tr").get(0);
		$(tr).children().each(function(){
				if(parseInt($(this).attr("colId"))==colId){
					if($(this).css("display")=="none"||$(this).attr("oldColSpan")!=undefined){
						//处理父级节点的colSpan
						deleteFatherColSpanForGoogle(colHeaderTable,miniColSpan,colId);
						sizset=1;
					}
				}
		});
	}

	//隐藏colheaderTable中的单元格
	hideColHeaderArray = new Array();
	hideColHeaderArray.push($(cell));

	//处理父级节点的colSpan
	if(sizset>0){
		if("Chrome"!=BrowserType()&&"Firefox"!=BrowserType()){
			deleteFatherColSpan(colHeaderTable,miniColSpan,sizset-1,nodeIndex);
		}
	}else{
		var newWidth = parseInt( $(cell).css("width").substring(0,$(cell).css("width").length-2))-parseInt(fast_hidecol_sumwidth);
		$(this).css("width",newWidth+"px");
		var newTableWidth =  parseInt( $(colHeaderTable).css("width").substring(0,$(colHeaderTable).css("width").length-2))-parseInt(fast_hidecol_sumwidth);
		$(colHeaderTable).css("width",newTableWidth+"px");
	}

	fast_hidecol_sumheight = 0;

	for(var j=0;j<hideColHeaderArray.length;j++){
		var cell = hideColHeaderArray[j];
		var cellHeight = $(cell).css("height").substring(0,$(cell).css("height").length-2);
		fast_hidecol_sumheight = fast_hidecol_sumheight+parseInt(cellHeight);
	}
	for(var i=0;i<hideColHeaderArray.length;i++){
		var cell = hideColHeaderArray[i];
		$(cell).attr("vr_hide_cell","true");
		$(cell).hide();
	}
	//处理字段在首行的的td的高度
	for(var i=0;i<addBtnCell.length;i++){
		var cell = $(addBtnCell[i]);
		if(cell.parent().attr("sizset")==0){
			var oldCellHeight = cloneArr[i];
			var cellHeight = oldCellHeight.substring(0,oldCellHeight.length-2);
			var newHeight = parseInt(cellHeight)-parseInt(fast_hidecol_sumheight);
			cell.css("height",newHeight+"px");
		}
	}

	//隐藏table_data中的单元格
	var dataTableId = "report_"+reportId+"_table_data";
	var dataTable = $("#"+dataTableId);
	var newTableWidth =  parseInt( $(dataTable).css("width").substring(0,$(dataTable).css("width").length-2))-parseInt(fast_hidecol_sumwidth);
	$(dataTable).css("width",newTableWidth+"px");
	dataTable.find("td[colId="+colId+"]").each(function(){
		$(this).attr("vr_hide_cell","true");
		$(this).hide();
	});
	//处理title,foot 宽度
	var table_title_span = $("#report_"+reportId+"_table_title_div span");
	var table_foot_span = $("#report_"+reportId+"_table_foot_div span");
	var newTitlefootDivWidth ;
	if(BrowserType()=="Chrome"||BrowserType()=="Firefox"){
		newTitlefootDivWidth = parseInt( $(table_title_span).width())-parseInt(fast_hidecol_sumwidth);
	}else{
		newTitlefootDivWidth = parseInt( $(table_title_span).get(0).clientWidth)-parseInt(fast_hidecol_sumwidth);
	}
	$(table_title_span).css("width",newTitlefootDivWidth+"px");
	$(table_foot_span).css("width",newTitlefootDivWidth+"px");
}
function vrsrHideFields(v,reportId){
	var colHeaderTableId = "report_"+reportId+"_table_colHeader";
	var colHeaderTable = $("#"+colHeaderTableId);
	var cell = colHeaderTable.find("td[v="+v+"]").get(0);
	var nodeIndex = parseInt($(cell).attr("nodeIndex"));

	var colId = parseInt($(cell).attr("colId"));
	var sizset = parseInt($(cell).parent().attr("sizset"));
	fast_hidecol_sumwidth = $(cell).css("width").substring(0,$(cell).css("width").length-2);

	//隐藏colheaderTable中的单元格
	hideColHeaderArray = new Array();
	hideColHeaderArray.push($(cell));

	//处理父级节点的colSpan
	var miniColSpan = 1;
	if(sizset>0){
		deleteFatherColSpan(colHeaderTable,miniColSpan,sizset-1,nodeIndex);
	}else{
		var newWidth = parseInt( $(cell).css("width").substring(0,$(cell).css("width").length-2))-parseInt(fast_hidecol_sumwidth);
		$(this).css("width",newWidth+"px");
		var newTableWidth =  parseInt( $(colHeaderTable).css("width").substring(0,$(colHeaderTable).css("width").length-2))-parseInt(fast_hidecol_sumwidth);
		$(colHeaderTable).css("width",newTableWidth+"px");
	}

	fast_hidecol_sumheight = 0;

	for(var j=0;j<hideColHeaderArray.length;j++){
		var cell = hideColHeaderArray[j];
		var cellHeight = $(cell).css("height").substring(0,$(cell).css("height").length-2);
		fast_hidecol_sumheight = fast_hidecol_sumheight+parseInt(cellHeight);
	}
	for(var i=0;i<hideColHeaderArray.length;i++){
		var cell = hideColHeaderArray[i];
		$(cell).attr("vr_hide_field","true");
		$(cell).hide();
	}
	//处理字段在首行的的td的高度
	for(var i=0;i<addBtnCell.length;i++){
		var cell = $(addBtnCell[i]);
		if(cell.parent().attr("sizset")==0){
			var oldCellHeight = cloneArr[i];
			var cellHeight = oldCellHeight.substring(0,oldCellHeight.length-2);
			var newHeight = parseInt(cellHeight)-parseInt(fast_hidecol_sumheight);
			cell.css("height",newHeight+"px");
		}
	}

	//隐藏table_data中的单元格
	var dataTableId = "report_"+reportId+"_table_data";
	var dataTable = $("#"+dataTableId);
	var newTableWidth =  parseInt( $(dataTable).css("width").substring(0,$(dataTable).css("width").length-2))-parseInt(fast_hidecol_sumwidth);
	$(dataTable).css("width",newTableWidth+"px");
	dataTable.find("td[colId="+colId+"]").each(function(){
		$(this).attr("vr_hide_field","true");
		$(this).hide();
	});

	//处理title,foot 宽度
	var table_title_span = $("#report_"+reportId+"_table_title_div span");
	var table_foot_span = $("#report_"+reportId+"_table_foot_div span");
	var newTitlefootDivWidth = parseInt( $(table_title_span).get(0).clientWidth)-parseInt(fast_hidecol_sumwidth);
	$(table_title_span).css("width",newTitlefootDivWidth+"px");
	$(table_foot_span).css("width",newTitlefootDivWidth+"px");
}
function deleteFatherColSpanForGoogle(colHeaderTable,miniColSpan,colId){
	var newTableWidth =  parseInt( $(colHeaderTable).css("width").substring(0,$(colHeaderTable).css("width").length-2))-parseInt(fast_hidecol_sumwidth);
	if("Firefox"==BrowserType()){newTableWidth = newTableWidth+1;}
	$(colHeaderTable).css("width",newTableWidth+"px");
	var tr = $(colHeaderTable).find("tr").get(0);
	$(tr).children().each(function(){
		var fatherTdNodeIndex = parseInt($(this).attr("colId"))+parseInt($(this).attr("oldColSpan"))-1;
		if(parseInt($(this).attr("colId"))<=colId&&colId<=fatherTdNodeIndex){
			if(parseInt($(this).attr("colId"))==colId&&$(this).css("display")!="none"&&$(this).attr("colSpan")==miniColSpan){
				//hideColHeaderArray.push($(this));
				//$(this).hide();
			}else{
				var newColSpan = parseInt($(this).attr("colSpan"))-parseInt(miniColSpan);
				$(this).attr("colSpan",newColSpan);
				if($(this).css("display")!="none"&&$(this).attr("colSpan")==0){
					$(this).hide();
				}
			}
			if($(this).css("display")!="none"){
				var newWidth = parseInt( $(this).css("width").substring(0,$(this).css("width").length-2))-parseInt(fast_hidecol_sumwidth);
				$(this).css("width",newWidth+"px");
			}
		}
	});
}

//处理父级单元格的colSpan和宽度
function deleteFatherColSpan(colHeaderTable,miniColSpan,sizset,nodeIndex){
	var newTableWidth =  parseInt( $(colHeaderTable).css("width").substring(0,$(colHeaderTable).css("width").length-2))-parseInt(fast_hidecol_sumwidth);
	$(colHeaderTable).css("width",newTableWidth+"px");
	var tr = $(colHeaderTable).find("tr[sizset="+sizset+"]").get(0);
	$(tr).children().each(function(){
		var fatherTdNodeIndex = parseInt($(this).attr("nodeIndex"))+parseInt($(this).attr("oldColSpan"))-1;
		if(parseInt($(this).attr("nodeIndex"))<=nodeIndex&&nodeIndex<=fatherTdNodeIndex){
			if(parseInt($(this).attr("nodeIndex"))==nodeIndex&&$(this).css("display")!="none"&&$(this).attr("colSpan")==miniColSpan){
				hideColHeaderArray.push($(this));
				//$(this).hide();
			}else{
				var newColSpan = parseInt($(this).attr("colSpan"))-parseInt(miniColSpan);
				$(this).attr("colSpan",newColSpan);
				if($(this).css("display")!="none"&&$(this).attr("colSpan")==0){
					$(this).hide();
				}
			}
			if(sizset>0){
				deleteFatherColSpan(colHeaderTable,miniColSpan,sizset-1,nodeIndex);
			}
			if(sizset==0&&$(this).css("display")!="none"){
				var newWidth = parseInt( $(this).css("width").substring(0,$(this).css("width").length-2))-parseInt(fast_hidecol_sumwidth);
				$(this).css("width",newWidth+"px");
			}
		}
	});
}
var cancleJson = new Object(); //用于获取原set方法Json参数值
//展现隐藏列
function showCol(reportId){
	cancleSet(cancleJson);
	if(!reportId){
		reportId=viewer.reportId;
	}
	clearHid=true;
	var colHeaderTableDivId = "report_"+reportId+"_table_colHeader_div";
	var colHeaderTableDiv = $("#"+colHeaderTableDivId);
	var colHeaderTableId = "report_"+reportId+"_table_colHeader";
	var colHeaderTable = $("#"+colHeaderTableId);
	var dataTableId = "report_"+reportId+"_table_data";
	var dataTable = $("#"+dataTableId);
	colHeaderTable.find("td[vr_hide_cell=true]").each(function(){
		$(this).show();
	});
	dataTable.find("td[vr_hide_cell=true]").each(function(){
		$(this).show();
	});
	//colHeaderTable.find("td").each(function(){
		//$(this).css("width",$(this).attr("oldCellWidth"));
		//$(this).css("height",$(this).attr("oldCellHeight"));
		//$(this).attr("colSpan",$(this).attr("oldColSpan"));
	//});
	if("Chrome"==BrowserType()){
		//colHeaderTable.css("width",colHeaderTableDiv.width());
		//dataTable.css("width",colHeaderTableDiv.width());
	}else{
		colHeaderTable.css("width",colHeaderTable.attr("oldWidth"));
		dataTable.css("width",dataTable.attr("oldWidth"));
	}
}
function removeMenu(){
	$("div[name='menuButton']").attr("hasShow",false).hide();
	showMenuTd=null;
	$("#menuDiv").remove();
}
function set(json){
	cancleJson = json;  //获取json参数,供cancleSet方法调用
	var colIndex=json.colIndex;
	var hideCol=false;
	var base64 = new Base64();
	if(json.visible=="false"||json.visible==false){
		hideCol=true;
		viewer.reportConfig.hiddenFields[viewer.reportConfig.hiddenFields.length]=json.colName;
	}
	if(clearHid){
		viewer.reportConfig.hiddenFields=new Array();
	}
	setJson="{colName:\""+base64.encode(json.colName)+"\",clearHid:\""+clearHid+"\",inVisible:\""+hideCol+"\",sort:\""+json.sort+"\",filterData:[";
	clearHid=false;
	if(schema=='design'){//设计界面模式
		try{
			var filterData=json.filterData.toString();
			if(filterData==""){
				filterData="NODATA";
			}
			parent.parent.setFieldFilter(colIndex,filterData);
		}catch(e){
		}
		try{
			var sortMode=json.sort.toString();
			parent.parent.setFiledOrder(colIndex,sortMode);
		}catch(e){
		}
	}
	/*var colJson = getColData(json.colName);
	var dataNum = colJson.dataNum;
	var filterData = colJson.data;

	if(dataNum < 10){
			var temp=json.filterData;
		var b=false;
    	for(var i=0;i<dataNum;i++){
    		var bool=true;
			for(var j=0;j<temp.length;j++){
				if(temp[j]!=filterData[i]){
					bool=false;
					break;
				}
			}
			if(bool){
				b=true;
				setJson+=filterData[i]+",";
			}
		}
    	if(b){
			setJson=setJson.substring(0,setJson.length-1);
		}
	}*/

	var dataNum = json.filterData.length;
	var filterData = json.filterData;
	if(dataNum < 10&&dataNum>0){
		for(var i=0;i<dataNum;i++){
			setJson+="\""+base64.encode(filterData[i])+"\",";
		}
		setJson=setJson.substring(0,setJson.length-1);
	}
	setJson+="]}";
	refreshData="no";
	removeMenu();
	//viewer.initPageCount();
	viewer.pageChangedHandler();
}

function cancleSet(json){
	var colIndex=json.colIndex;
	var hideCol=false;
	var base64 = new Base64();
	setJson="{colName:\""+base64.encode(json.colName)+"\",clearHid:\""+true+"\",inVisible:\""+false+"\",sort:\""+json.sort+"\",filterData:[";
	var dataNum = json.filterData.length;
	var filterData = json.filterData;
	if(dataNum < 10&&dataNum>0){
		for(var i=0;i<dataNum;i++){
			setJson+="\""+base64.encode(filterData[i])+"\",";
		}
		setJson=setJson.substring(0,setJson.length-1);
	}
	setJson+="]}";
	refreshData="no";
	removeMenu();
	viewer.pageChangedHandler();
}

//字段设置
function  setFieldDetail(names,tablePosition){
	var fieldName = names.substr(names.indexOf("-_-")+3);
	var base64 = new Base64();
	var action = 28;//列表字段为28,分组字段为30
	if(tablePosition == "corner"){
		action = 30;
	}
	$.ajax({
		url:PathUtils.getRelativeUrl("showFastReportServlet"),
		data:{"action":action,"fieldName":base64.encode(fieldName),"reportDefineId":base64.encode(reportDefineId),"resID":base64.encode(reportID),"time":new Date().getTime()},
		cache:false,
		success:function(data){
			try{data = eval('(' + data + ')');}catch(e){}
			if(typeof data == "object"){
				var fieldInfo = formatFieldInfo(data);
				if(action == 30){//分组字段
					var width = 400;
					var height = 240;
				}else{//列表字段
					var width = 480;
					var height = 320;
				}
				var url=PathUtils.getAbsoluteJspUrl("vrsr/show/customer/fastFieldSetDetail.jsp?fieldName=" + base64.encode(fieldName) + "&reportDefineId="+base64.encode(reportDefineId)+"&resID="+base64.encode(reportID)+"&fieldInfo="+base64.encode(fieldInfo));
				showDialog(url,"fastReportField",fieldName,height,width,null, null, null , null, null, null,null,true,null,false,true);
			}
		},
		error:function(){
			alert("获取字段信息请求失败!");
		}
	});
}

//格式化字段信息
function formatFieldInfo(data){
	var fieldInfo = {};
	for(var key in data){
		if(key == "title"){
			fieldInfo["dispValue"] = data[key][0];
		}else{
			fieldInfo[key] = data[key][0];
		}
	}

	fieldInfo = JSON.stringify(fieldInfo);
	return fieldInfo;
}

//高级设置
function WarningPropertiesSet(params){
	var swfNameAndPath = "fastReport/analysis/swf/WarningPropertiesAnalyse.swf";
	var url=PathUtils.getAbsoluteJspUrl("fastReport/analysis/testPopUp.jsp?appName="+swfNameAndPath+"&params="+params);
	var wid =850;
	var height = 450;
	showDialog(url,"swfWindow","预警属性设置",height,wid,null, null, null, true, null, null,null,true,null,false);
}

//预警设置确定
function warningProBack(params){
	//var result = decode(params);
	var result = params;
	if(typeof window.frames["dialogframefastReportField"] != "undefined"){
		window.frames["dialogframefastReportField"].setBackValue("alarmString",result);
	}
	closeDialog("swfWindow");
}
//预警设置窗口关闭
function closeSwfWindow(backParams){
	closeDialog("swfWindow");
}
//显示格式设置-其它格式回调
function contentStyleBack(from,result){
	if(typeof window.frames["dialogframefastReportField"] != "undefined"){
		window.frames["dialogframefastReportField"].contentStyleBack(from,result);
	}
	closeDialog("swfWindowContentStyleMore");
}
//显示格式设置-其它格式弹窗关闭
function closeContentSWF(){
	closeDialog("swfWindowContentStyleMore");
}


text:
<?php

namespace spec\Nim\Bundle\FormBundle\Model;

use Nim\Bundle\FormBundle\Model\Politeness;
use PhpSpec\ObjectBehavior;

class PolitenessSpec extends ObjectBehavior
{
    public function it_is_initializable()
    {
        $this->shouldHaveType('Nim\Bundle\FormBundle\Model\Politeness');
    }

    public function it_should_return_gender_options()
    {
        $this::getOptions()->shouldReturn(array(
            Politeness::MADAM => 'politeness.'.Politeness::MADAM,
            Politeness::MISS => 'politeness.'.Politeness::MISS,
            Politeness::MISTER => 'politeness.'.Politeness::MISTER,
        ));
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?hh
/**
 * This is a file of elearn-foundation.
 *
 * (c) Tony Yip <tony@opensource.hk>
 * @license http://opensource.org/licenses/MIT MIT License.
 */

namespace Elearn\Foundation\ClassLoader;

/**
 * The Symfony ClassLoader in Hack Language to improve the performance.
 */
class ClassLoader extends AbstractClassLoader
{
	private Map<string, Set<string>> $prefixes;

	public function __construct()
	{
		$this->prefixes = new Map([]);
	}

	public function getPrefixes(): array<string, Set>
	{
		return $this->prefixes->toArray();
	}

	public function addPrefixes(array $prefixes): void
	{
		foreach ($prefixes as $prefix => $path) {
			$this->addPrefix($prefix, $path);
		}
	}

	public function addPrefix(string $prefix, mixed $path)
	{
		if ($this->prefixes->containsKey($prefix)) {
			$this->prefixes[$prefix]->addAll((array)$path);
		} else {
			$this->prefixes[$prefix] = new Set((array)$path);
		}
	}

	public function findFile(string $class): ?string
	{
		if (false !== $pos = strpos($class, '\\')) {
			// namespaced class namespaced
			$classPath = str_replace('\\', DIRECTORY_SEPARATOR, substr($class, 0, $pos)).DIRECTORY_SEPARATOR;
            $className = substr($class, $pos + 1);
		} else {
			// PEAR-like class name
            $classPath = null;
            $className = $class;
		}

		$classPath .= str_replace('_', DIRECTORY_SEPARATOR, $className);

		foreach ($this->prefixes as $prefix => $dirs) {
            if ($class === strstr($class, $prefix)) {
                foreach ($dirs as $dir) {
                	$classFile = $dir . DIRECTORY_SEPARATOR . $classPath;
                    if (file_exists($classFile . '.php')) {
                        return $dir . DIRECTORY_SEPARATOR . $classPath . '.php';
                    } elseif (file_exists($classFile . '.hh')) {
                    	return $dir . DIRECTORY_SEPARATOR . $classPath . '.hh';
                    }
                }
            }
        }

        return null;
	}

}


text:
<?php

/**
 * Schema Resource "Trigger"
 */

namespace Dboss\Schema\Resource\Pg;

use Dboss\Schema\Resource\ResourceAbstract;

class SqlTrigger extends ResourceAbstract
{
    /**
     *
     */
    public function __construct(array $params = array())
    {
        parent::__construct($params);

        $this->resource_type = "trigger";
    }

    /**
     *
     */
    public function getResourceListSql(array $params = array())
    {
        $exclude_order_by = FALSE;

        extract($params, EXTR_IF_EXISTS);

        $sql = "
            SELECT *
            FROM (
                SELECT
                    n.nspname as schema_name,
                    NULL::text as table_name,
                    t.tgname as resource_name,
                    NULL::text as resource_arguments,
                    '{$this->resource_type}'::text as resource_type
                FROM pg_catalog.pg_trigger t
                JOIN pg_class c ON c.oid = t.tgrelid
                JOIN pg_namespace n ON n.oid = c.relnamespace
                WHERE NOT t.tgisinternal
            ) as main
        ";
        $sql .= $this->getWhere($params);

        if ( ! $exclude_order_by) {
            $sql .= $this->getOrderBy($params);
        }

        $this->resource_list = $this->db->query($sql)->execute();

        return $sql;
    }

    /**
     *
     */
    public function getResourceDefinition(array $params = array())
    {
        $schema_name = NULL;
        $resource_name = NULL;
        $resource_arguments = NULL;

        extract($params, EXTR_IF_EXISTS);

        if ( ! $schema_name || ! $resource_name) {
            throw new Exception("Invalid resource ({$this->resource_type}) in " . __METHOD__);
        }

        $sql = "
            SELECT
                n.nspname as schema_name,
                t.tgname as resource_name,
                pg_catalog.pg_get_triggerdef(t.oid, true) as definition
            FROM pg_catalog.pg_trigger t
            JOIN pg_class c ON c.oid = t.tgrelid
            JOIN pg_namespace n ON n.oid = c.relnamespace
            WHERE n.nspname = '$schema_name' AND t.tgname = '$resource_name'
        ";

        $results = $this->db->query($sql)->execute();

        // Should be only one result
        $row = $results->current();

        return $row['definition'] . ";\n";
    }
}


text:
``` java
    private String prettyDate (Date date) {
        StringBuilder prettydate = new StringBuilder();
        prettydate.append(prettyMonth (date.getMonth() + 1));
        prettydate.append(" " + date.getDate() + ", ");
        prettydate.append((date.getYear() + 1900) + " at ");
        prettydate.append(prettyTime(date.getHours(), date.getMinutes()));
        return prettydate.toString();
    }

    private String prettyMonth (int month) {
        switch (month) {
        case 1 : return "January";
        case 2 : return "February";
        case 3 : return "March";
        case 4 : return "April";
        case 5 : return "May";
        case 6 : return "June";
        case 7 : return "July";
        case 8 : return "August";
        case 9 : return "September";
        case 10 : return "October";
        case 11 : return "November";
        case 12 : return "December";
        default : return null;
        }
    }

    private String prettyTime (int hours, int minutes) {
        String suffix = (hours <= 12) ? "am" : "pm";
        String hour = (hours <= 12) ? Integer.toString(hours) : Integer.toString(hours - 12);
        String minute = (minutes < 10) ? "0" + Integer.toString(minutes) : Integer.toString(minutes);
        return hour + ":" + minute + suffix;
    }

```
###### \java\seedu\doist\storage\XmlAliasListMapStorageTest.java
``` java
public class XmlAliasListMapStorageTest {
    private static final String TEST_DATA_FOLDER = FileUtil.getPath("./src/test/data/XmlAliasListMapStorageTest/");

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Rule
    public TemporaryFolder testFolder = new TemporaryFolder();

    @Test
    public void readAliasListMap_nullFilePath_assertionFailure() throws Exception {
        thrown.expect(AssertionError.class);
        readAliasListMap(null);
    }

    private java.util.Optional<ReadOnlyAliasListMap> readAliasListMap(String filePath) throws Exception {
        return new XmlAliasListMapStorage(filePath).readAliasListMap(addToTestDataPathIfNotNull(filePath));
    }

    private String addToTestDataPathIfNotNull(String prefsFileInTestDataFolder) {
        return prefsFileInTestDataFolder != null
                ? TEST_DATA_FOLDER + prefsFileInTestDataFolder
                : null;
    }

    @Test
    public void read_missingFile_emptyResult() throws Exception {
        assertFalse(readAliasListMap("NonExistentFile.xml").isPresent());
    }

    @Test
    public void read_notXmlFormat_exceptionThrown() throws Exception {

        thrown.expect(DataConversionException.class);
        readAliasListMap("NotXmlFormatAliasListMap.xml");
    }

    @Test
    public void readAndSaveTodoList_allInOrder_success() throws Exception {
        String filePath = testFolder.getRoot().getPath() + "TempAliasListMap.xml";
        AliasListMap original = new AliasListMap();
        XmlAliasListMapStorage xmlAliasListMapStorage = new XmlAliasListMapStorage(filePath);

        //Save in new file and read back
        xmlAliasListMapStorage.saveAliasListMap(original, filePath);
        ReadOnlyAliasListMap readBack = xmlAliasListMapStorage.readAliasListMap(filePath).get();
        assertEquals(original, new AliasListMap(readBack));

        //Modify data, overwrite exiting file, and read back
        original.setAlias("hello", "add");
        xmlAliasListMapStorage.saveAliasListMap(original, filePath);
        readBack = xmlAliasListMapStorage.readAliasListMap(filePath).get();
        assertEquals(original, new AliasListMap(readBack));

        //Save and read without specifying file path
        original.setAlias("goodbye", "add");
        xmlAliasListMapStorage.saveAliasListMap(original); //file path not specified
        readBack = xmlAliasListMapStorage.readAliasListMap().get(); //file path not specified
        assertEquals(original, new AliasListMap(readBack));
    }

    @Test
    public void saveAliasListMap_nullTodoList_assertionFailure() throws IOException {
        thrown.expect(AssertionError.class);
        saveAliasListMap(null, "SomeFile.xml");
    }

    private void saveAliasListMap(ReadOnlyAliasListMap aliasListMap, String filePath) throws IOException {
        new XmlAliasListMapStorage(filePath).saveAliasListMap(aliasListMap, addToTestDataPathIfNotNull(filePath));
    }

    @Test
    public void saveAliasListMap_nullFilePath_assertionFailure() throws IOException {
        thrown.expect(AssertionError.class);
        saveAliasListMap(new AliasListMap(), null);
    }
}
```


text:
<?php

namespace extpoint\yii2\file\processors;

class ImageCrop extends BaseFileProcessor
{
    /**
     * @var int
     */
    public $width;

    /**
     * @var int
     */
    public $height;

    /**
     * @var int
     */
    public $offsetX;

    /**
     * @var int
     */
    public $offsetY;

    /**
     * @var int
     */
    public $thumbQuality = 90;

    protected function runInternal()
    {
        $imageContent = file_get_contents($this->filePath);
        list($originalWidth, $originalHeight) = getimagesizefromstring($imageContent);

        // Check if crop is smaller or equal than original image
        $isCropSizeCorrect = ($originalWidth >= $this->width) && ($originalHeight >= $this->height);

        // Check if crop offset doesn't exceed original image
        $isCropOffsetCorrect = ($this->offsetX < $originalWidth) && ($this->offsetY < $originalHeight);

        // Leaving image intact when crop sizes or offsets are incorrect
        if (!$isCropSizeCorrect || !$isCropOffsetCorrect) {
            $this->width = $originalWidth;
            $this->height = $originalHeight;
            return;
        }

        $bool = true;
        $src = imagecreatefromstring($imageContent);
        $extension = strtolower(pathinfo($this->filePath, PATHINFO_EXTENSION));

        // Auto-rotate
        if ($extension === 'jpg' || $extension === 'jpeg') {
            try {
                $exif = exif_read_data($this->filePath);
            } catch (\Exception $e) {
            };

            if (!empty($exif['Orientation'])) {
                switch ($exif['Orientation']) {
                    case 3:
                        $src = imagerotate($src, 180, 0);
                        break;

                    case 6:
                        $src = imagerotate($src, -90, 0);
                        break;

                    case 8:
                        $src = imagerotate($src, 90, 0);
                        break;
                }
            }
        }

        // Create blank image
        $dst = ImageCreateTrueColor($this->width, $this->height);
        if ($extension === 'png') {
            $bool = $bool && imagesavealpha($dst, true) && imagealphablending($dst, false);
        }

        // Place, resize and save file

        $bool = $bool && imagecopyresampled($dst, $src, 0, 0, $this->offsetX, $this->offsetY, $this->width, $this->height, $this->width, $this->height);
        $bool && $extension === 'png' ?
            imagepng($dst, $this->filePath) :
            imagejpeg($dst, $this->filePath, $this->thumbQuality);

        // Clean
        if ($src) {
            imagedestroy($src);
        }
        if ($dst) {
            imagedestroy($dst);
        }
    }
}


text:
package jp.cafebabe.pochi;

import jp.cafebabe.birthmarks.comparators.ComparatorBuilder;
import jp.cafebabe.birthmarks.comparators.ComparatorType;
import jp.cafebabe.birthmarks.entities.BirthmarkType;
import jp.cafebabe.birthmarks.extractors.ExtractorBuilder;
import jp.cafebabe.pochi.comparators.ComparatorBuilders;
import jp.cafebabe.pochi.extractors.ExtractorBuilders;

public class BirthmarkSystem {
    private ExtractorBuilders extractors = new ExtractorBuilders();
    private ComparatorBuilders comparators = new ComparatorBuilders();

    public ExtractorBuilder extractor(BirthmarkType type){
        return extractors.builder(type);
    }

    public BirthmarkType[] availableExtractors(){
        return extractors.availableTypes()
                .toArray(BirthmarkType[]::new);
    }

    public void register(ExtractorBuilder builder) {
        extractors.register(builder);
    }

    public void register(ComparatorBuilder builder) {
        comparators.register(builder);
    }

    public ComparatorBuilder comparator(ComparatorType type){
        return comparators.builder(type);
    }

    public ComparatorType[] availableComparators(){
        return comparators.availableTypes()
                .toArray(ComparatorType[]::new);
    }
}


text:
<?php
namespace G4MR\Configs;

use igorw;

/**
 * @package G4MR\Configs
 */
class Item
{
    /**
     * @var array $data
     */
    private $data = [];

    /**
     * @param array $data
     */
    public function __construct(array $data)
    {
        $this->data = $data;
    }

    /**
     * Gets item from array if it exists else return default value
     * @param string $item dot notation config_file.array.item
     * @param mixed $default value if it doesn't exist
     * @return mixed
     */
    public function get($key, $default = null)
    {
        if(!is_string($key) || empty($key)) {
            return $default;
        }

        //split string into array
        $item_pieces = explode('.', $key);

        //let igorw check if array item exists
        return igorw\get_in($this->data, $item_pieces, $default);
    }

    /**
     * Set key:value pair and overwite if one exists
     * @param string
     * @param mixed
     */
    public function set($key, $value)
    {

        if(is_array($key) || empty($key)) {
            throw new \Exception('Key should be a string value');
        }

        //split string into array
        $item_pieces = explode('.', $key);

        if(count($item_pieces) == 1) {
            $this->data[current($item_pieces)] = $value;
            return;
        }

        $current_array =& $this->data[current($item_pieces)];
        array_shift($item_pieces);

        //loop through pieces
        foreach($item_pieces as $piece) {
            $current_array =& $current_array[$piece];
        }

        $current_array = $value;
    }

    /**
     * @return array
     */
    public function getAll()
    {
        return $this->data;
    }

    /**
     * alias for `set()`
     * @param string
     * @param mixed
     */
    public function __set($key, $value)
    {
        $this->set($key, $value);
    }

    /**
     * alias for `get()`
     * @param string
     * @return mixed
     */
    public function __get($key)
    {
        return $this->get($key);
    }
}


text:
@interface MyModel : BaseModel
@property(nonatomic,strong)NSString* uid;
@property(nonatomic,strong)NSString* telephone;
@property(nonatomic,strong)NSString* balance;
@property(nonatomic,strong)NSString* credit;
@property(nonatomic,strong)NSString* status;
@property(nonatomic,strong)NSString* levelcredit;
@end


text:
- Python 2.6, 2.7
- Preferably pyenv

## Local Installation

```shell
pyenv virtualenv 2.6.6 estail      # create a virtualenv
pyenv activate estail
pip install -r requirements        # installed required packages to created virtualenv
alias estail='python ./estail.py'  # not strictly required, but you'll get bash completion
source ./estail_completion.sh      # get bash autocompletion
```

## Configuration

Configuration for estail can be sourced from two locations.  The first and most specific is from the users home directory $HOME/.estail.conf. A second global configuration file is sourced from /etc/estail/estail.conf  It's possible to change the name of the file that's sourced by changing the name that's passed to common.LoadElasticConfig.

### Sample Configuration
```
{
    "hosts": {"prod": "https://elastic.prod.example.com", "qa": "https://elastic.qa.example.com", "dev":"https://elastic.dev.example.com"},
    "port": 443,
    "index_date_pattern": "%Y.%m.%d",
    "application_field": "application",
    "product": ["mail","cron"],
    "timezone": "UTC"
}
```
The hosts are an object where the key is the environment and the value is the host(s) of elasticsearch. The product is an array and is the first thing that would be pivoted on when filtering through documents. It's expected that the product is a name in the index between logstash and the date.  It isn't necessary to have separate indexes becdc1e you can use filtered aliases in a single index where the product is a field in the document.

The application_field is the second pivot that's used in a term filter. It's suggested that the mapping for this field be analyzed as a keyword to prevent splitting on possible dashes.

Products are intended to be their own indexes or aliases that either point to other indexes with a filter on a field. Example: logstash-cron-2015.12.30

## Output

Two different kinds of applications are used through estail at Indeed: Java and Python. The fields are easily built using the JSONEventLayout logging libraries for those two languages: https://github.com/logstash/log4j-jsonevent-layout and https://github.com/madzak/python-json-logger. The supervisor type is used for stdout or stderr where only the message and timestamp are available.  It's simple to extend the result mapping to more types with if statements in the `_map_from_record` function.

## Autocompletion

Sourcing `estail_completion.sh` enhances estail's usability by autocompleting application names, product names, and command line switches.
Autocompletions are stored in files under `$HOME/.estail`, and are valid for 24 hours, after which they are recreated.

## Usage

```shell
usage: estail.py [-h]
                 [-p {}]
                 [-a APPLICATIONS] [-L] [-l LOOKBACK] [-r REFRESH] [-g GREP]
                 [-f] [-s STARTDATE] [-e ENDDATE] [--env {prod,qa}]
                 [-d DATACENTER] [-H HOSTNAME] [-n NUM_LOGS] [--verbose] [-P]

This script is used to tail logs out of elasticsearch. It will not follow the
logs unless -f is specified

optional arguments:
  -h, --help            show this help message and exit
  -p {}, --product {}
                        Picks the elasticsearch product instance to look in
  -a APPLICATIONS, --application APPLICATIONS
                        Application(s) to tail logs from (can be specified
                        multiple times)
  -L, --list            List all available applications, or list of
                        applications in specified the product group
  -l LOOKBACK, --lookback LOOKBACK
                        Number of seconds in the initial lookback
  -r REFRESH, --refresh REFRESH
                        How often to refresh the view (defaults to 10 seconds)
  -g GREP, --grep GREP  Search against this pattern before printing
  -f, --follow          Follow logs instead of doing a one-time tail
  -s STARTDATE, --startdate STARTDATE
                        Start date for searching between a set of dates. This
                        is the oldest date. Format: YYYY-MM-DD HH:MM
  -e ENDDATE, --enddate ENDDATE
                        End date for searching between a set of dates. This is
                        the newest date. Format: YYYY-MM-DD HH:MM
  --env {prod,qa}       Environment to search in. Defaults to prod
  -d DATACENTER, --datacenter DATACENTER
                        Filter by datacenter
  -H HOSTNAME, --hostname HOSTNAME
                        Filter by host
  -n NUM_LOGS, --logevents NUM_LOGS
                        Get number of log lines instead of logs over a time
                        period. Only works on today's date
  --verbose             Verbose mode. Prints more information
  -P, --list_products   List all product groups. Normally used for generating
                        a list file for bash auto-completion
```

## Examples

### Specify an application without specifying product
`python estail.py -a app1 -s '2014-02-06 10:30' -e '2014-02-06 11:00'`

### Specify multiple applications
`python estail.py -a app1 -a app2 -a app3`

### Specify only start time
`python estail.py -p group1 -a app1 -s '2014-02-06 10:30`

### Tail the logs continuously until stopped
`python estail.py -p group1 -a app1 -f`

### Refresh every 5 seconds
`python estail.py -p group1 -a app1 -l 1800 -r 5`

### Filter by hostname
`python estail.py -p group1 -a app1 -H host1`

### Filter by datacenter
`python estail.py -p group2 -a app5 -d dc1`

### Get last 100 log messages
`python estail.py -p group1 -a app1 -n 100`


text:
#ifndef LOVE_PHYSICS_BOX2D_WRAP_PULLEY_JOINT_H
#define LOVE_PHYSICS_BOX2D_WRAP_PULLEY_JOINT_H

// LOVE
#include "common/runtime.h"
#include "wrap_Joint.h"
#include "PulleyJoint.h"

namespace love
{
namespace physics
{
namespace box2d
{

PulleyJoint *luax_checkpulleyjoint(lua_State *L, int idx);
int w_PulleyJoint_getGroundAnchors(lua_State *L);
int w_PulleyJoint_getLengthA(lua_State *L);
int w_PulleyJoint_getLengthB(lua_State *L);
int w_PulleyJoint_getRatio(lua_State *L);
extern "C" int luaopen_pulleyjoint(lua_State *L);

} // box2d
} // physics
} // love

#endif // LOVE_PHYSICS_BOX2D_WRAP_PULLEY_JOINT_H


text:
package com.github.kevinjava.pattern.behavior.strategy;

public class Animation {
	Interpolator interpolator;

	void setInterpolator(Interpolator interpolator) {
		this.interpolator = interpolator;
	}

	void doAction() {
		interpolator.getInterpolation(1.0f);
	}
}


text:
import json
from xml.dom import minidom as xml

import requests

from salaryzenaggr import fetchers

def _verify_response(response):
        if not response or response.status_code != 200:
            print("Failed to access %s with status_code %s" % (response.url, response.status_code))
            exit(-1)

class RestApiFetcher(fetchers.Fetcher):

    def _fetch_url(self, url, params=None):
        response = requests.get(url, params=params)
        _verify_response(response)
        return response

class XmlRestApiFetcher(RestApiFetcher):
    def _fetch_url(self, url, params=None):
        response = super(XmlRestApiFetcher, self)._fetch_url(url, params=params)
        return xml.parseString(response.text)

class JsonRestApiFetcher(RestApiFetcher):
    def _fetch_url(self, url, params=None):
        response = super(JsonRestApiFetcher, self)._fetch_url(url, params=params)
        return json.loads(response.text)


text:
class DropSchedulerTables < ActiveRecord::Migration
  def change
    drop_table :cal_events
  end
end


text:
// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#ifndef RUNTIME_VM_LOCKERS_H_
#define RUNTIME_VM_LOCKERS_H_

#include "platform/assert.h"
#include "vm/allocation.h"
#include "vm/globals.h"
#include "vm/isolate.h"
#include "vm/os_thread.h"

namespace dart {

const bool kNoSafepointScope = true;
const bool kDontAssertNoSafepointScope = false;

/*
 * Normal mutex locker :
 * This locker abstraction should only be used when the enclosing code can
 * not trigger a safepoint. In debug mode this class increments the
 * no_safepoint_scope_depth variable for the current thread when the lock is
 * taken and decrements it when the lock is released. NOTE: please do not use
 * the passed in mutex object independent of the locker class, For example the
 * code below will not assert correctly:
 *    {
 *      MutexLocker ml(m);
 *      ....
 *      m->Exit();
 *      ....
 *      m->Enter();
 *      ...
 *    }
 * Always use the locker object even when the lock needs to be released
 * temporarily, e.g:
 *    {
 *      MutexLocker ml(m);
 *      ....
 *      ml.Exit();
 *      ....
 *      ml.Enter();
 *      ...
 *    }
 */
class MutexLocker : public ValueObject {
 public:
  explicit MutexLocker(Mutex* mutex, bool no_safepoint_scope = true)
      :
#if defined(DEBUG)
        no_safepoint_scope_(no_safepoint_scope),
#endif
        mutex_(mutex) {
    ASSERT(mutex != NULL);
#if defined(DEBUG)
    if (no_safepoint_scope_) {
      Thread* thread = Thread::Current();
      if (thread != NULL) {
        thread->IncrementNoSafepointScopeDepth();
      } else {
        no_safepoint_scope_ = false;
      }
    }
#endif
    mutex_->Lock();
  }

  virtual ~MutexLocker() {
    mutex_->Unlock();
#if defined(DEBUG)
    if (no_safepoint_scope_) {
      Thread::Current()->DecrementNoSafepointScopeDepth();
    }
#endif
  }

  void Lock() const {
#if defined(DEBUG)
    if (no_safepoint_scope_) {
      Thread::Current()->IncrementNoSafepointScopeDepth();
    }
#endif
    mutex_->Lock();
  }
  void Unlock() const {
    mutex_->Unlock();
#if defined(DEBUG)
    if (no_safepoint_scope_) {
      Thread::Current()->DecrementNoSafepointScopeDepth();
    }
#endif
  }

 private:
  DEBUG_ONLY(bool no_safepoint_scope_;)
  Mutex* const mutex_;

  DISALLOW_COPY_AND_ASSIGN(MutexLocker);
};

/*
 * Normal monitor locker :
 * This locker abstraction should only be used when the enclosed code can
 * not trigger a safepoint. In debug mode this class increments the
 * no_safepoint_scope_depth variable for the current thread when the lock is
 * taken and decrements it when the lock is released. NOTE: please do not use
 * the passed in mutex object independent of the locker class, For example the
 * code below will not assert correctly:
 *    {
 *      MonitorLocker ml(m);
 *      ....
 *      m->Exit();
 *      ....
 *      m->Enter();
 *      ...
 *    }
 * Always use the locker object even when the lock needs to be released
 * temporarily, e.g:
 *    {
 *      MonitorLocker ml(m);
 *      ....
 *      ml.Exit();
 *      ....
 *      ml.Enter();
 *      ...
 *    }
 */
class MonitorLocker : public ValueObject {
 public:
  explicit MonitorLocker(Monitor* monitor, bool no_safepoint_scope = true)
      : monitor_(monitor), no_safepoint_scope_(no_safepoint_scope) {
    ASSERT(monitor != NULL);
#if defined(DEBUG)
    if (no_safepoint_scope_) {
      Thread* thread = Thread::Current();
      if (thread != NULL) {
        thread->IncrementNoSafepointScopeDepth();
      } else {
        no_safepoint_scope_ = false;
      }
    }
#endif
    monitor_->Enter();
  }

  virtual ~MonitorLocker() {
    monitor_->Exit();
#if defined(DEBUG)
    if (no_safepoint_scope_) {
      Thread::Current()->DecrementNoSafepointScopeDepth();
    }
#endif
  }

  void Enter() const {
#if defined(DEBUG)
    if (no_safepoint_scope_) {
      Thread::Current()->IncrementNoSafepointScopeDepth();
    }
#endif
    monitor_->Enter();
  }
  void Exit() const {
    monitor_->Exit();
#if defined(DEBUG)
    if (no_safepoint_scope_) {
      Thread::Current()->DecrementNoSafepointScopeDepth();
    }
#endif
  }

  Monitor::WaitResult Wait(int64_t millis = Monitor::kNoTimeout) {
    return monitor_->Wait(millis);
  }

  Monitor::WaitResult WaitWithSafepointCheck(
      Thread* thread,
      int64_t millis = Monitor::kNoTimeout);

  Monitor::WaitResult WaitMicros(int64_t micros = Monitor::kNoTimeout) {
    return monitor_->WaitMicros(micros);
  }

  void Notify() { monitor_->Notify(); }

  void NotifyAll() { monitor_->NotifyAll(); }

 private:
  Monitor* const monitor_;
  bool no_safepoint_scope_;

  DISALLOW_COPY_AND_ASSIGN(MonitorLocker);
};

/*
 * Safepoint mutex locker :
 * This locker abstraction should be used when the enclosing code could
 * potentially trigger a safepoint.
 * This locker ensures that other threads that try to acquire the same lock
 * will be marked as being at a safepoint if they get blocked trying to
 * acquire the lock.
 * NOTE: please do not use the passed in mutex object independent of the locker
 * class, For example the code below will not work correctly:
 *    {
 *      SafepointMutexLocker ml(m);
 *      ....
 *      m->Exit();
 *      ....
 *      m->Enter();
 *      ...
 *    }
 */
class SafepointMutexLocker : public ValueObject {
 public:
  explicit SafepointMutexLocker(Mutex* mutex);
  virtual ~SafepointMutexLocker() { mutex_->Unlock(); }

 private:
  Mutex* const mutex_;

  DISALLOW_COPY_AND_ASSIGN(SafepointMutexLocker);
};

/*
 * Safepoint monitor locker :
 * This locker abstraction should be used when the enclosing code could
 * potentially trigger a safepoint.
 * This locker ensures that other threads that try to acquire the same lock
 * will be marked as being at a safepoint if they get blocked trying to
 * acquire the lock.
 * NOTE: please do not use the passed in monitor object independent of the
 * locker class, For example the code below will not work correctly:
 *    {
 *      SafepointMonitorLocker ml(m);
 *      ....
 *      m->Exit();
 *      ....
 *      m->Enter();
 *      ...
 *    }
 */
class SafepointMonitorLocker : public ValueObject {
 public:
  explicit SafepointMonitorLocker(Monitor* monitor);
  virtual ~SafepointMonitorLocker() { monitor_->Exit(); }

  Monitor::WaitResult Wait(int64_t millis = Monitor::kNoTimeout);

 private:
  Monitor* const monitor_;

  DISALLOW_COPY_AND_ASSIGN(SafepointMonitorLocker);
};

class RwLock {
 public:
  RwLock() {}
  ~RwLock() {}

 private:
  friend class ReadRwLocker;
  friend class WriteRwLocker;

  void EnterRead() {
    MonitorLocker ml(&monitor_);
    while (state_ == -1) {
      ml.Wait();
    }
    ++state_;
  }
  void LeaveRead() {
    MonitorLocker ml(&monitor_);
    ASSERT(state_ > 0);
    if (--state_ == 0) {
      ml.NotifyAll();
    }
  }

  void EnterWrite() {
    MonitorLocker ml(&monitor_);
    while (state_ != 0) {
      ml.Wait();
    }
    state_ = -1;
  }
  void LeaveWrite() {
    MonitorLocker ml(&monitor_);
    ASSERT(state_ == -1);
    state_ = 0;
    ml.NotifyAll();
  }

  Monitor monitor_;
  // [state_] > 0  : The lock is held by multiple readers.
  // [state_] == 0 : The lock is free (no readers/writers).
  // [state_] == -1: The lock is held by a single writer.
  intptr_t state_ = 0;
};

/*
 * Locks a given [RwLock] for reading purposes.
 *
 * It will block while the lock is held by a writer.
 *
 * If this locker is long'jmped over (e.g. on a background compiler thread) the
 * lock will be freed.
 *
 * NOTE: If the locking operation blocks (due to a writer) it will not check
 * for a pending safepoint operation.
 */
class ReadRwLocker : public StackResource {
 public:
  ReadRwLocker(ThreadState* thread_state, RwLock* rw_lock);
  ~ReadRwLocker();

 private:
  RwLock* rw_lock_;
};

/*
 * Locks a given [RwLock] for writing purposes.
 *
 * It will block while the lock is held by one or more readers.
 *
 * If this locker is long'jmped over (e.g. on a background compiler thread) the
 * lock will be freed.
 *
 * NOTE: If the locking operation blocks (due to a writer) it will not check
 * for a pending safepoint operation.
 */
class WriteRwLocker : public StackResource {
 public:
  WriteRwLocker(ThreadState* thread_state, RwLock* rw_lock);
  ~WriteRwLocker();

 private:
  RwLock* rw_lock_;
};

}  // namespace dart

#endif  // RUNTIME_VM_LOCKERS_H_


text:
module Main where

import Lib
import Config

import Api.Post
import Data.Proxy
import Data.Text as T

import Database.PostgreSQL.Simple as PGS
import qualified Database.Transaction as DB
import Database.Migration

main :: IO ()
main = do
  conf <- Config 8080 <$> config
  startApp conf

config :: IO (PGS.Connection)
config = connect $ PGS.defaultConnectInfo
  { PGS.connectDatabase = "xavio_development" }


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@android:color/transparent"
    android:visibility="invisible">

    <include
        android:id="@+id/top_bar_pay"
        android:layout_alignParentTop="true"
        layout="@layout/gfan_top_bar_pay" />

    <TextView
        android:id="@+id/charge_tv_balance_info"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/top_bar_pay"
        android:paddingLeft="20dp"
        android:paddingTop="10dp"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/charge_tv_input"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/charge_tv_balance_info"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:paddingTop="10dp"
        android:textSize="16sp" />

    <EditText
        android:id="@+id/charge_edit_input"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/charge_tv_input"
        android:layout_centerVertical="true"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="10dp"
        android:inputType="number"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/charge_tv_exchangeinfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/charge_edit_input"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/charge_edit_input"
        android:textSize="16sp" />

    <RadioGroup
        android:id="@+id/charge_rg"
        android:layout_width="fill_parent"
        android:layout_height="42dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:orientation="horizontal"
        android:visibility="gone"
        android:layout_below="@+id/charge_edit_input" >

        <RadioButton
            android:id="@+id/charge_rb_debitcard"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="@string/text_debit_card"
            android:textColor="#000000" />

        <RadioButton
            android:layout_marginLeft="40dp"
            android:id="@+id/charge_rb_creditcard"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="false"
            android:text="@string/text_credit_card"
            android:textColor="#000000" />
    </RadioGroup>

    <Button
        android:id="@+id/charge_btn_ok"
        android:layout_width="fill_parent"
        android:layout_height="42dp"
        android:layout_below="@+id/charge_rg"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/gfan_selector_btn_orange"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@color/text_orange" />

</RelativeLayout>


text:
A personal repo for working through the exercises in the book "Purescript by Example" by Phil Freeman [link](https://leanpub.com/purescript/read)

**Warning: Here by Dragons!**

# LICENSE
If you should be brave enough to look at any of this code yourself, I've licensed it under the MIT license - so free for use but caveat emptor - see LICENSE file.


text:
require 'rubygems'
require 'fileutils'
require 'pathname'

# TEMPLATE_TST
TEMPLATE_TST ||= '#include "unity.h"
%2$s#include "%1$s.h"

void setUp(void)
{
}

void tearDown(void)
{
}

void test_%1$s_NeedToImplement(void)
{
    TEST_IGNORE_MESSAGE("Need to Implement %1$s");
}
'.freeze

# TEMPLATE_SRC
TEMPLATE_SRC ||= '%2$s#include "%1$s.h"
'.freeze

# TEMPLATE_INC
TEMPLATE_INC ||= '#ifndef _%3$s_H
#define _%3$s_H
%2$s

#endif // _%3$s_H
'.freeze

class UnityModuleGenerator
  ############################
  def initialize(options = nil)
    here = File.expand_path(File.dirname(__FILE__)) + '/'

    @options = UnityModuleGenerator.default_options
    case options
    when NilClass then @options
    when String   then @options.merge!(UnityModuleGenerator.grab_config(options))
    when Hash     then @options.merge!(options)
    else raise 'If you specify arguments, it should be a filename or a hash of options'
    end

    # Create default file paths if none were provided
    @options[:path_src] = here + '../src/'    if @options[:path_src].nil?
    @options[:path_inc] = @options[:path_src] if @options[:path_inc].nil?
    @options[:path_tst] = here + '../test/'   if @options[:path_tst].nil?
    @options[:path_src] += '/'                unless @options[:path_src][-1] == 47
    @options[:path_inc] += '/'                unless @options[:path_inc][-1] == 47
    @options[:path_tst] += '/'                unless @options[:path_tst][-1] == 47

    # Built in patterns
    @patterns = {
      'src'  =>  {
        '' =>  { inc: [] }
      },
      'test' =>  {
        '' =>  { inc: [] }
      },
      'dh'   =>  {
        'Driver'    =>  { inc: [create_filename('%1$s', 'Hardware.h')] },
        'Hardware'  =>  { inc: [] }
      },
      'dih'  =>  {
        'Driver'    =>  { inc: [create_filename('%1$s', 'Hardware.h'), create_filename('%1$s', 'Interrupt.h')] },
        'Interrupt' =>  { inc: [create_filename('%1$s', 'Hardware.h')] },
        'Hardware'  =>  { inc: [] }
      },
      'mch'  =>  {
        'Model'     =>  { inc: [] },
        'Conductor' =>  { inc: [create_filename('%1$s', 'Model.h'), create_filename('%1$s', 'Hardware.h')] },
        'Hardware'  =>  { inc: [] }
      },
      'mvp'  =>  {
        'Model'     =>  { inc: [] },
        'Presenter' =>  { inc: [create_filename('%1$s', 'Model.h'), create_filename('%1$s', 'View.h')] },
        'View'      =>  { inc: [] }
      }
    }
  end

  ############################
  def self.default_options
    {
      pattern: 'src',
      includes: {
        src: [],
        inc: [],
        tst: []
      },
      update_svn: false,
      boilerplates: {},
      test_prefix: 'Test',
      mock_prefix: 'Mock'
    }
  end

  ############################
  def self.grab_config(config_file)
    options = default_options
    unless config_file.nil? || config_file.empty?
      require 'yaml'
      yaml_guts = YAML.load_file(config_file)
      options.merge!(yaml_guts[:unity] || yaml_guts[:cmock])
      raise "No :unity or :cmock section found in #{config_file}" unless options
    end
    options
  end

  ############################
  def files_to_operate_on(module_name, pattern = nil)
    # strip any leading path information from the module name and save for later
    subfolder = File.dirname(module_name)
    module_name = File.basename(module_name)

    # create triad definition
    prefix = @options[:test_prefix] || 'Test'
    triad = [{ ext: '.c', path: @options[:path_src], prefix: '', template: TEMPLATE_SRC, inc: :src, boilerplate: @options[:boilerplates][:src] },
             { ext: '.h', path: @options[:path_inc], prefix: '',     template: TEMPLATE_INC, inc: :inc, boilerplate: @options[:boilerplates][:inc] },
             { ext: '.c', path: @options[:path_tst], prefix: prefix, template: TEMPLATE_TST, inc: :tst, boilerplate: @options[:boilerplates][:tst] }]

    # prepare the pattern for use
    pattern = (pattern || @options[:pattern] || 'src').downcase
    patterns = @patterns[pattern]
    raise "ERROR: The design pattern '#{pattern}' specified isn't one that I recognize!" if patterns.nil?

    # single file patterns (currently just 'test') can reject the other parts of the triad
    triad.select! { |v| v[:inc] == :tst } if pattern == 'test'

    # Assemble the path/names of the files we need to work with.
    files = []
    triad.each do |cfg|
      patterns.each_pair do |pattern_file, pattern_traits|
        submodule_name = create_filename(module_name, pattern_file)
        filename = cfg[:prefix] + submodule_name + cfg[:ext]
        files << {
          path: (Pathname.new("#{cfg[:path]}#{subfolder}") + filename).cleanpath,
          name: submodule_name,
          template: cfg[:template],
          boilerplate: cfg[:boilerplate],
          includes: case (cfg[:inc])
                    when :src then (@options[:includes][:src] || []) | (pattern_traits[:inc].map { |f| format(f, module_name) })
                    when :inc then (@options[:includes][:inc] || [])
                    when :tst then (@options[:includes][:tst] || []) | (pattern_traits[:inc].map { |f| format("#{@options[:mock_prefix]}#{f}", module_name) })
                    end
        }
      end
    end

    files
  end

  ############################
  def create_filename(part1, part2 = '')
    if part2.empty?
      case (@options[:naming])
      when 'bumpy' then part1
      when 'camel' then part1
      when 'snake' then part1.downcase
      when 'caps'  then part1.upcase
      else              part1.downcase
      end
    else
      case (@options[:naming])
      when 'bumpy' then part1 + part2
      when 'camel' then part1 + part2
      when 'snake' then part1.downcase + '_' + part2.downcase
      when 'caps'  then part1.upcase + '_' + part2.upcase
      else              part1.downcase + '_' + part2.downcase
      end
    end
  end

  ############################
  def generate(module_name, pattern = nil)
    files = files_to_operate_on(module_name, pattern)

    # Abort if all of the module files already exist
    all_files_exist = true
    files.each do |file|
      all_files_exist = false unless File.exist?(file[:path])
    end
    raise "ERROR: File #{files[0][:name]} already exists. Exiting." if all_files_exist

    # Create Source Modules
    files.each_with_index do |file, _i|
      # If this file already exists, don't overwrite it.
      if File.exist?(file[:path])
        puts "File #{file[:path]} already exists!"
        next
      end
      # Create the path first if necessary.
      FileUtils.mkdir_p(File.dirname(file[:path]), verbose: false)
      File.open(file[:path], 'w') do |f|
        f.write("#{file[:boilerplate]}\n" % [file[:name]]) unless file[:boilerplate].nil?
        f.write(file[:template] % [file[:name],
                                   file[:includes].map { |ff| "#include \"#{ff}\"\n" }.join,
                                   file[:name].upcase])
      end
      if @options[:update_svn]
        `svn add \"#{file[:path]}\"`
        if $!.exitstatus.zero?
          puts "File #{file[:path]} created and added to source control"
        else
          puts "File #{file[:path]} created but FAILED adding to source control!"
        end
      else
        puts "File #{file[:path]} created"
      end
    end
    puts 'Generate Complete'
  end

  ############################
  def destroy(module_name, pattern = nil)
    files_to_operate_on(module_name, pattern).each do |filespec|
      file = filespec[:path]
      if File.exist?(file)
        if @options[:update_svn]
          `svn delete \"#{file}\" --force`
          puts "File #{file} deleted and removed from source control"
        else
          FileUtils.remove(file)
          puts "File #{file} deleted"
        end
      else
        puts "File #{file} does not exist so cannot be removed."
      end
    end
    puts 'Destroy Complete'
  end
end

############################
# Handle As Command Line If Called That Way
if $0 == __FILE__
  destroy = false
  options = {}
  module_name = nil

  # Parse the command line parameters.
  ARGV.each do |arg|
    case arg
    when /^-d/            then destroy = true
    when /^-u/            then options[:update_svn] = true
    when /^-p\"?(\w+)\"?/ then options[:pattern] = Regexp.last_match(1)
    when /^-s\"?(.+)\"?/  then options[:path_src] = Regexp.last_match(1)
    when /^-i\"?(.+)\"?/  then options[:path_inc] = Regexp.last_match(1)
    when /^-t\"?(.+)\"?/  then options[:path_tst] = Regexp.last_match(1)
    when /^-n\"?(.+)\"?/  then options[:naming] = Regexp.last_match(1)
    when /^-y\"?(.+)\"?/  then options = UnityModuleGenerator.grab_config(Regexp.last_match(1))
    when /^(\w+)/
      raise "ERROR: You can't have more than one Module name specified!" unless module_name.nil?
      module_name = arg
    when /^-(h|-help)/
      ARGV = [].freeze
    else
      raise "ERROR: Unknown option specified '#{arg}'"
    end
  end

  unless ARGV[0]
    puts ["\nGENERATE MODULE\n-------- ------",
          "\nUsage: ruby generate_module [options] module_name",
          "  -i\"include\" sets the path to output headers to 'include' (DEFAULT ../src)",
          "  -s\"../src\"  sets the path to output source to '../src'   (DEFAULT ../src)",
          "  -t\"C:/test\" sets the path to output source to 'C:/test'  (DEFAULT ../test)",
          '  -p"MCH"     sets the output pattern to MCH.',
          '              dh   - driver hardware.',
          '              dih  - driver interrupt hardware.',
          '              mch  - model conductor hardware.',
          '              mvp  - model view presenter.',
          '              src  - just a source module, header and test. (DEFAULT)',
          '              test - just a test file.',
          '  -d          destroy module instead of creating it.',
          '  -n"camel"   sets the file naming convention.',
          '              bumpy - BumpyCaseFilenames.',
          '              camel - camelCaseFilenames.',
          '              snake - snake_case_filenames. (DEFAULT)',
          '              caps  - CAPS_CASE_FILENAMES.',
          '  -u          update subversion too (requires subversion command line)',
          '  -y"my.yml"  selects a different yaml config file for module generation',
          ''].join("\n")
    exit
  end

  raise 'ERROR: You must have a Module name specified! (use option -h for help)' if module_name.nil?
  if destroy
    UnityModuleGenerator.new(options).destroy(module_name)
  else
    UnityModuleGenerator.new(options).generate(module_name)
  end

end


text:
package cashregister;

public class Item {

    private final String name;
    private final double price;

    public Item(String name, double price) {

        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }
}


text:
@class BaseRequest;

@interface GetCardConfigInfoRequest : WXPBGeneratedMessage
{
}

+ (void)initialize;

// Remaining properties
@property(retain, nonatomic) BaseRequest *baseRequest; // @dynamic baseRequest;

@end


text:
package org.synyx.urlaubsverwaltung.web;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.autoconfigure.web.BasicErrorController;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorProperties;

import org.springframework.stereotype.Controller;

import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Customize default Spring Boot error page.
 *
 * @author  Aljona Murygina - murygina@synyx.de
 */
@Controller
public class ErrorController extends BasicErrorController {

    @Autowired
    public ErrorController(ErrorAttributes errorAttributes) {

        super(errorAttributes, new ErrorProperties());
    }

    @Override
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {

        ModelAndView modelAndView = new ModelAndView("errors");
        modelAndView.addObject("statusCode", response.getStatus());

        return modelAndView;
    }
}


text:
#ifndef __XPD_CONFIG_H_
#define __XPD_CONFIG_H_

/* TODO step 1: specify device header */
#include <stm32l476xx.h>

/* TODO step 2: enable desired used XPD modules error handling */
/* #define __XPD_DMA_ERROR_DETECT */

/* TODO step 3: specify power supplies */
#define VDD_VALUE_mV                   3000 /* Value of VDD in mV */
#define VDDA_VALUE_mV                  3000 /* Value of VDD Analog in mV */

/* TODO step 4: specify oscillator parameters */
/* #define HSE_VALUE_Hz 80000000
 * #define LSE_VALUE_Hz 32768 */

#endif /* __XPD_CONFIG_H_ */


text:
package io.netty.channel;

import io.netty.channel.embedded.EmbeddedChannel;
import org.junit.Test;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayDeque;
import java.util.Queue;

import static org.junit.Assert.*;

public class CombinedChannelDuplexHandlerTest {

    private static final Object MSG = new Object();
    private static final SocketAddress ADDRESS = new InetSocketAddress(0);

    private enum Event {
        REGISTERED,
        UNREGISTERED,
        ACTIVE,
        INACTIVE,
        CHANNEL_READ,
        CHANNEL_READ_COMPLETE,
        EXCEPTION_CAUGHT,
        USER_EVENT_TRIGGERED,
        CHANNEL_WRITABILITY_CHANGED,
        HANDLER_ADDED,
        HANDLER_REMOVED,
        BIND,
        CONNECT,
        WRITE,
        FLUSH,
        READ,
        REGISTER,
        DEREGISTER,
        CLOSE,
        DISCONNECT
    }

    @Test(expected = IllegalStateException.class)
    public void testInboundRemoveBeforeAdded() {
        CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler> handler =
                new CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler>(
                        new ChannelInboundHandlerAdapter(), new ChannelOutboundHandlerAdapter());
        handler.removeInboundHandler();
    }

    @Test(expected = IllegalStateException.class)
    public void testOutboundRemoveBeforeAdded() {
        CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler> handler =
                new CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler>(
                        new ChannelInboundHandlerAdapter(), new ChannelOutboundHandlerAdapter());
        handler.removeOutboundHandler();
    }

    @Test(expected = IllegalArgumentException.class)
    public void testInboundHandlerImplementsOutboundHandler() {
        new CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler>(
                new ChannelDuplexHandler(), new ChannelOutboundHandlerAdapter());
    }

    @Test(expected = IllegalArgumentException.class)
    public void testOutboundHandlerImplementsInboundHandler() {
        new CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler>(
                new ChannelInboundHandlerAdapter(), new ChannelDuplexHandler());
    }

    @Test(expected = IllegalStateException.class)
    public void testInitNotCalledBeforeAdded() throws Exception {
        CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler> handler =
                new CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler>() { };
        handler.handlerAdded(null);
    }

    @Test
    public void testExceptionCaughtBothCombinedHandlers() {
        final Exception exception = new Exception();
        final Queue<ChannelHandler> queue = new ArrayDeque<ChannelHandler>();

        ChannelInboundHandler inboundHandler = new ChannelInboundHandlerAdapter() {
            @Override
            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                assertSame(exception, cause);
                queue.add(this);
                ctx.fireExceptionCaught(cause);
            }
        };
        ChannelOutboundHandler outboundHandler = new ChannelOutboundHandlerAdapter() {
            @Override
            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                assertSame(exception, cause);
                queue.add(this);
                ctx.fireExceptionCaught(cause);
            }
        };
        ChannelInboundHandler lastHandler = new ChannelInboundHandlerAdapter() {
            @Override
            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                assertSame(exception, cause);
                queue.add(this);
            }
        };
        EmbeddedChannel channel = new EmbeddedChannel(
                new CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler>(
                        inboundHandler, outboundHandler), lastHandler);
        channel.pipeline().fireExceptionCaught(exception);
        assertFalse(channel.finish());
        assertSame(inboundHandler, queue.poll());
        assertSame(outboundHandler, queue.poll());
        assertSame(lastHandler, queue.poll());
        assertTrue(queue.isEmpty());
    }

    @Test
    public void testInboundEvents() {
        final Queue<Event> queue = new ArrayDeque<Event>();

        ChannelInboundHandler inboundHandler = new ChannelInboundHandlerAdapter() {
            @Override
            public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
                queue.add(Event.HANDLER_ADDED);
            }

            @Override
            public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
                queue.add(Event.HANDLER_REMOVED);
            }

            @Override
            public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
                queue.add(Event.REGISTERED);
            }

            @Override
            public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
                queue.add(Event.UNREGISTERED);
            }

            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                queue.add(Event.ACTIVE);
            }

            @Override
            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                queue.add(Event.INACTIVE);
            }

            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                queue.add(Event.CHANNEL_READ);
            }

            @Override
            public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                queue.add(Event.CHANNEL_READ_COMPLETE);
            }

            @Override
            public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                queue.add(Event.USER_EVENT_TRIGGERED);
            }

            @Override
            public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
                queue.add(Event.CHANNEL_WRITABILITY_CHANGED);
            }

            @Override
            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                queue.add(Event.EXCEPTION_CAUGHT);
            }
        };

        CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler> handler =
                new CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler>(
                inboundHandler, new ChannelOutboundHandlerAdapter());

        EmbeddedChannel channel = new EmbeddedChannel(handler);
        channel.pipeline().fireChannelWritabilityChanged();
        channel.pipeline().fireUserEventTriggered(MSG);
        channel.pipeline().fireChannelRead(MSG);
        channel.pipeline().fireChannelReadComplete();

        assertEquals(Event.HANDLER_ADDED, queue.poll());
        assertEquals(Event.REGISTERED, queue.poll());
        assertEquals(Event.ACTIVE, queue.poll());
        assertEquals(Event.CHANNEL_WRITABILITY_CHANGED, queue.poll());
        assertEquals(Event.USER_EVENT_TRIGGERED, queue.poll());
        assertEquals(Event.CHANNEL_READ, queue.poll());
        assertEquals(Event.CHANNEL_READ_COMPLETE, queue.poll());

        handler.removeInboundHandler();
        assertEquals(Event.HANDLER_REMOVED, queue.poll());

        // These should not be handled by the inboundHandler anymore as it was removed before
        channel.pipeline().fireChannelWritabilityChanged();
        channel.pipeline().fireUserEventTriggered(MSG);
        channel.pipeline().fireChannelRead(MSG);
        channel.pipeline().fireChannelReadComplete();

        // Should have not received any more events as it was removed before via removeInboundHandler()
        assertTrue(queue.isEmpty());
        assertTrue(channel.finish());
        assertTrue(queue.isEmpty());
    }

    @Test
    public void testOutboundEvents() {
        final Queue<Event> queue = new ArrayDeque<Event>();

        ChannelInboundHandler inboundHandler = new ChannelInboundHandlerAdapter();
        ChannelOutboundHandler outboundHandler = new ChannelOutboundHandlerAdapter() {
            @Override
            public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
                queue.add(Event.HANDLER_ADDED);
            }

            @Override
            public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
                queue.add(Event.HANDLER_REMOVED);
            }

            @Override
            public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise)
                    throws Exception {
                queue.add(Event.BIND);
            }

            @Override
            public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress,
                                SocketAddress localAddress, ChannelPromise promise) throws Exception {
                queue.add(Event.CONNECT);
            }

            @Override
            public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
                queue.add(Event.DISCONNECT);
            }

            @Override
            public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
                queue.add(Event.CLOSE);
            }

            @Override
            public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
                queue.add(Event.DEREGISTER);
            }

            @Override
            public void read(ChannelHandlerContext ctx) throws Exception {
                queue.add(Event.READ);
            }

            @Override
            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                queue.add(Event.WRITE);
            }

            @Override
            public void flush(ChannelHandlerContext ctx) throws Exception {
                queue.add(Event.FLUSH);
            }
        };

        CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler> handler =
                new CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler>(
                        inboundHandler, outboundHandler);

        EmbeddedChannel channel = new EmbeddedChannel();
        channel.pipeline().addFirst(handler);

        doOutboundOperations(channel);

        assertEquals(Event.HANDLER_ADDED, queue.poll());
        assertEquals(Event.BIND, queue.poll());
        assertEquals(Event.CONNECT, queue.poll());
        assertEquals(Event.WRITE, queue.poll());
        assertEquals(Event.FLUSH, queue.poll());
        assertEquals(Event.READ, queue.poll());
        assertEquals(Event.CLOSE, queue.poll());
        assertEquals(Event.CLOSE, queue.poll());
        assertEquals(Event.DEREGISTER, queue.poll());

        handler.removeOutboundHandler();
        assertEquals(Event.HANDLER_REMOVED, queue.poll());

        // These should not be handled by the inboundHandler anymore as it was removed before
        doOutboundOperations(channel);

        // Should have not received any more events as it was removed before via removeInboundHandler()
        assertTrue(queue.isEmpty());
        assertTrue(channel.finish());
        assertTrue(queue.isEmpty());
    }

    private static void doOutboundOperations(Channel channel) {
        channel.pipeline().bind(ADDRESS);
        channel.pipeline().connect(ADDRESS);
        channel.pipeline().write(MSG);
        channel.pipeline().flush();
        channel.pipeline().read();
        channel.pipeline().disconnect();
        channel.pipeline().close();
        channel.pipeline().deregister();
    }

    @Test(timeout = 3000)
    public void testPromisesPassed() {
        ChannelOutboundHandler outboundHandler = new ChannelOutboundHandlerAdapter() {
            @Override
            public void bind(ChannelHandlerContext ctx, SocketAddress localAddress,
                             ChannelPromise promise) throws Exception {
                promise.setSuccess();
            }

            @Override
            public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress,
                                SocketAddress localAddress, ChannelPromise promise) throws Exception {
                promise.setSuccess();
            }

            @Override
            public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
                promise.setSuccess();
            }

            @Override
            public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
                promise.setSuccess();
            }

            @Override
            public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
                promise.setSuccess();
            }

            @Override
            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                promise.setSuccess();
            }
        };
        EmbeddedChannel ch = new EmbeddedChannel(outboundHandler,
                new CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler>(
                        new ChannelInboundHandlerAdapter(), new ChannelOutboundHandlerAdapter()));
        ChannelPipeline pipeline = ch.pipeline();

        ChannelPromise promise = ch.newPromise();
        pipeline.connect(new InetSocketAddress(0), new InetSocketAddress(0), promise);
        promise.syncUninterruptibly();

        promise = ch.newPromise();
        pipeline.bind(new InetSocketAddress(0), promise);
        promise.syncUninterruptibly();

        promise = ch.newPromise();
        pipeline.close(promise);
        promise.syncUninterruptibly();

        promise = ch.newPromise();
        pipeline.disconnect(promise);
        promise.syncUninterruptibly();

        promise = ch.newPromise();
        pipeline.write("test", promise);
        promise.syncUninterruptibly();

        promise = ch.newPromise();
        pipeline.deregister(promise);
        promise.syncUninterruptibly();
        ch.finish();
    }

    @Test(expected = IllegalStateException.class)
    public void testNotSharable() {
        new CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler>() {
            @Override
            public boolean isSharable() {
                return true;
            }
        };
    }
}


text:
package com.mxgraph.shape;

import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.Map;

import javax.swing.CellRendererPane;

import com.mxgraph.canvas.mxGraphics2DCanvas;
import com.mxgraph.util.mxConstants;
import com.mxgraph.util.mxLightweightLabel;
import com.mxgraph.util.mxUtils;
import com.mxgraph.view.mxCellState;

/**
 * To set global CSS for all HTML labels, use the following code:
 *
 *

 * mxGraphics2DCanvas.putTextShape(mxGraphics2DCanvas.TEXT_SHAPE_HTML,
 *   new mxHtmlTextShape()
 *   {
 *     protected String createHtmlDocument(Map<String, Object> style, String text)
 *     {
 *       return mxUtils.createHtmlDocument(style, text, 1, 0,
 *           "");
 *     }
 *   }
 * );
 *

 */
public class mxHtmlTextShape implements mxITextShape
{

	/**
	 * Specifies if linefeeds should be replaced with breaks in HTML markup.
	 * Default is true.
	 */
	protected boolean replaceHtmlLinefeeds = true;

	/**
	 * Returns replaceHtmlLinefeeds
	 */
	public boolean isReplaceHtmlLinefeeds()
	{
		return replaceHtmlLinefeeds;
	}

	/**
	 * Returns replaceHtmlLinefeeds
	 */
	public void setReplaceHtmlLinefeeds(boolean value)
	{
		replaceHtmlLinefeeds = value;
	}

	/**
	 *
	 */
	protected String createHtmlDocument(Map<String, Object> style, String text,
			int w, int h)
	{
		String overflow = mxUtils.getString(style, mxConstants.STYLE_OVERFLOW, "");

		if (overflow.equals("fill"))
		{
			return mxUtils.createHtmlDocument(style, text, 1, w, null, "height:" + h + "pt;");
		}
		else if (overflow.equals("width"))
		{
			return mxUtils.createHtmlDocument(style, text, 1, w);
		}
		else
		{
			return mxUtils.createHtmlDocument(style, text);
		}
	}

	/**
	 *
	 */
	public void paintShape(mxGraphics2DCanvas canvas, String text,
			mxCellState state, Map<String, Object> style)
	{
		mxLightweightLabel textRenderer = mxLightweightLabel
				.getSharedInstance();
		CellRendererPane rendererPane = canvas.getRendererPane();
		Rectangle rect = state.getLabelBounds().getRectangle();
		Graphics2D g = canvas.getGraphics();

		if (textRenderer != null
				&& rendererPane != null
				&& (g.getClipBounds() == null || g.getClipBounds().intersects(
						rect)))
		{
			double scale = canvas.getScale();
			int x = rect.x;
			int y = rect.y;
			int w = rect.width;
			int h = rect.height;

			if (!mxUtils.isTrue(style, mxConstants.STYLE_HORIZONTAL, true))
			{
				g.rotate(-Math.PI / 2, x + w / 2, y + h / 2);
				g.translate(w / 2 - h / 2, h / 2 - w / 2);

				int tmp = w;
				w = h;
				h = tmp;
			}

			// Replaces the linefeeds with BR tags
			if (isReplaceHtmlLinefeeds())
			{
				text = text.replaceAll("\n", "
");
			}

			// Renders the scaled text
			textRenderer.setText(createHtmlDocument(style, text,
					(int) Math.round(w / state.getView().getScale()),
					(int) Math.round(h / state.getView().getScale())));
			textRenderer.setFont(mxUtils.getFont(style, canvas.getScale()));
			g.scale(scale, scale);
			rendererPane.paintComponent(g, textRenderer, rendererPane,
					(int) (x / scale) + mxConstants.LABEL_INSET,
					(int) (y / scale) + mxConstants.LABEL_INSET,
					(int) (w / scale), (int) (h / scale), true);
		}
	}

}


text:
package io.github.exaberries.boa.gui.module;

import io.github.exaberries.boa.gui.EditorDataPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;

public class EditorCueDataPane extends Pane {
	public EditorCueDataPane() {
		HBox hbox = new HBox();
		hbox.setSpacing(10);
		CueStackPane cueStackPane = new CueStackPane();
		hbox.getChildren().add(cueStackPane);
		VBox vbox = new VBox();
		vbox.setSpacing(10);
		CuePane cuePane = new CuePane();
		vbox.getChildren().add(cuePane);
		EditorDataPane editorDataPane = new EditorDataPane();
		vbox.getChildren().add(editorDataPane);
		hbox.getChildren().add(vbox);
		getChildren().add(hbox);
	}
}