text:
function is_weixn(){//是否在微信客户端浏览器中打开
    var ua = navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i)=="micromessenger") {
        return true;
    } else {
        return false;
    }
}
function MSGwindowShow_JSON(data){
	if(data.action === "pay" && data.classid === "2" ){
		payAppsubmitGo(data);
	}else{
		if(data.islogin === '1'){
			$('#isrep').val('');
			$('#parentid').val('');
			$('#chrcontent').html('');
			$('#chrcontent2').val('');
			$('#maskTB').trigger('click');
			if(data.isopen === '0'){
				MSGwindowShow('revert','0','恭喜你,回复成功!请耐心等待系统审核!','','');
			}else{
				successPostRevert(data);
			}
		}else{
			MSGwindowShow('revert','0',data.error,'','');
		}
	}
}
function payAppsubmitGo(MSGkeyval){
	if(isapp ==="1"){
		var	YDB = new YDBOBJ();
		if(MSGkeyval.Payid === "7" ){//拉起微信app支付
			YDB.SetWxpayInfo(MSGkeyval.ProductName, MSGkeyval.Desicript, MSGkeyval.Price, MSGkeyval.OuttradeNo,MSGkeyval.attach);
		}
		else if(MSGkeyval.Payid === "1" ){//拉起阿里app支付
			YDB.SetAlipayInfo(MSGkeyval.ProductName, MSGkeyval.Desicript, MSGkeyval.Price, MSGkeyval.OuttradeNo);
		}
	}
}
function windowlocationhref(url){
	if(url.length > 5){window.location.href=url;}
}
function MSGwindowShow(action,showid,str,url,formcode){
	if(!!$('#form_submit_disabled')[0]){
		$('#form_submit_disabled').removeClass('disabled').prop('disabled',false);
	}
	var sys_tips = '

确定

';
	if(!$('#sys_tips')[0]){
		$('body').append(sys_tips);
	}
	var sys_tips = $('#sys_tips'),sys_tips_title = $('#sys_tips_title'),sys_tips_info = $('#sys_tips_info'),sys_tips_submit = $('#sys_tips_submit');
	if(action === "pay"){
		$('#have_login').hide();
		if(showid=="2"){
			document.getElementById('formcode').value=formcode;//赋值code
			document.forms['submitpay'].submit();//提交支付
			//这里添加支付中信息提示窗口
			//$('#pay_tips').show();
		}else if(showid=="1"){
			if(url.length > 5){window.location.href=url;}
		}else if(showid=="0"){
			alert(str);
			if(url.length > 5){window.location.href=url;}
		}else{
			alert(str);
		}
		document.getElementById('formcode').value="payok";//设置默认值防止二次提交
	}else{
		if(showid=="0"){ //只提示不跳转
			showConsole('提示',false);
		}else if(showid=="1"){ //提示加跳转
			showConsole('提示',true);
		}else if(showid=="2"){ //直接跳转
			windowlocationhref(url);
		}
		else if(showid=="3"){ //错误信息加跳转
			showConsole('出错了',true);
		}else if(showid=="4"){ //错误信息加只提示不跳转
			showConsole('出错了',false);
		}else{
			return false;
		}
	}
	function showConsole(tit,isredirect){
		sys_tips_info.html(str);
		sys_tips_title.html(tit);
		sys_tips_submit.bind('click',function(e){
			e.preventDefault();
			sys_tips.hide();
			isredirect&&windowlocationhref(url);
		});
		sys_tips.show();
		var w_h = $(window).height(),d_h = sys_tips.height(),s_h = $(document).scrollTop(),top_val = (w_h-d_h)/2;
		sys_tips.css({'top':top_val+'px'});
	}
}
//地图测距
function reloadLocation(){//切换地址 恢复当前位置
	if(navigator.geolocation){
		navigator.geolocation.getCurrentPosition(showMapGPSre, handleError, {enableHighAccuracy:true, maximumAge:1000,timeout:6000});
		window['location_timeout'] = setTimeout("geolocFail()", 10000);
	}else{
		MSGwindowShow('location','0','抱歉,您的浏览器不支持使用HTML 5来获取地理位置服务','','');
	}
}
function getLocation(){
	if(navigator.geolocation){
		navigator.geolocation.getCurrentPosition(showMapGPS, handleError, {enableHighAccuracy:true, maximumAge:1000,timeout:6000});
		window['location_timeout'] = setTimeout("geolocFail()", 10000);
	}else{
		MSGwindowShow('location','0','抱歉,您的浏览器不支持使用HTML 5来获取地理位置服务','','');
	}
}
window['location_timeout'] = null;
function geolocFail(){
	if(typeof keyvalues !== 'undefined'){
		getPagingGlobal();
	}
	MSGwindowShow('location','0','抱歉,我们没有获取到您的位置信息','','');
}
function handleError(value){
	clearTimeout(window['location_timeout']);
	geolocFail();
	switch(value.code){
		case value.PERMISSION_DENIED:
		  MSGwindowShow('location','0','抱歉,位置服务被拒绝','','');
		  break;
		case value.POSITION_UNAVAILABLE:
		  MSGwindowShow('location','0','抱歉,暂时获取不到位置信息','','');
		  break;
		case value.TIMEOUT:
		  MSGwindowShow('location','0','抱歉,获取信息超时','','');
		  break;
		case value.UNKNOWN_ERROR:
		  MSGwindowShow('location','0','抱歉,位置服务未知错误','','');
		  break;
	}
}
function showMapGPSre(value){
	clearTimeout(window['location_timeout']);
	var longitude = value.coords.longitude;
	var latitude = value.coords.latitude;
	var map = new BMap.Map();
	var gpsPoint = new BMap.Point(longitude, latitude); //GPS坐标
	BMap.Convertor.translate(gpsPoint, 0, function(point){
		var geoc = new BMap.Geocoder();
		geoc.getLocation(point, function(rs){
			var addComp = rs.addressComponents;
			$('#curLocation2').html(addComp.district + addComp.street + addComp.streetNumber);
		});
	});
}
function showMapGPS(value){
	clearTimeout(window['location_timeout']);
	var longitude = value.coords.longitude;
	var latitude = value.coords.latitude;
	var map = new BMap.Map();
	var gpsPoint = new BMap.Point(longitude, latitude); //GPS坐标
	BMap.Convertor.translate(gpsPoint, 0, function(point){
		setMap(map,point);

		if(typeof keyvalues !== 'undefined'){
			getPagingGlobal({'x':point.lng,'y':point.lat},true);
		}
	});
}
function showMapBD(longitude, latitude){
	if(longitude===''){return;}
	var map = new BMap.Map();
	var myPoint = new BMap.Point(longitude, latitude); //GPS坐标
	setMap(map,myPoint);
}
function setMap(map,point){
	var mapPointList = $('#mapPoint').find('.item');
	//逆向地址解析
	var geoc = new BMap.Geocoder();
	geoc.getLocation(point, function(rs){
		var addComp = rs.addressComponents;
		$('#curLocation').html(addComp.district + addComp.street + addComp.streetNumber);
	});
	//列表距离
	mapPointList.each(function(){
		var mapPoint = $(this);
		var dataX = mapPoint.attr('data-x'),dataY = mapPoint.attr('data-y');
		if(dataX === '' || dataX ==='0'){return;}
		var pointB = new BMap.Point(dataX,dataY);  // 商家坐标
		var txt = (map.getDistance(point,pointB)/1000).toFixed(2)+'公里';
		$(this).find('.juli').html(txt);
	});
}

//filter
function showFilter(option){
	var node = $('#'+option.ibox),
		fullbg = $('#'+option.fullbg),
		ct1 = $('#'+option.content1),
		ct2 = $('#'+option.content2),
		ctp1 = ct1.find('.innercontent'),
		ctp2 = ct2.find('.innercontent'),
		currentClass = 'current';
	var tabs = node.find('.tab .item'),
		conts = node.find('.inner');
	fullbg.css({'height':$(document).height()+'px'});

	var timelist = node.find('.inner > ul > li').filter(function(index) {
			return $('ul', this).length > 0;
		}),
		childUL = null;
	timelist.each(function(){
		var that = $(this);
		that.addClass('hasUL');
		that.children('a').addClass('hasUlLink');
	});
	ct1.on("click",".hasUlLink",function(e){
		e.preventDefault();
		var that = $(this).parent();
		if(!window['myScroll_inner']){
			window['myScroll_inner'] = new IScroll('#'+option.content2, {
				click: true,
				scrollX: false,
				scrollY: true,
				scrollbars: true,
				interactiveScrollbars: true,
				shrinkScrollbars: 'scale',
				fadeScrollbars: true
			});
		}
		setTimeout(function(){
			ctp1.find('.hasUL_current').removeClass('hasUL_current');
			that.addClass('hasUL_current');
			ctp2.html('
'+that.find('ul').html()+'
').show();
			ct1.css({'width':'50%'});
			ct2.show();
			window['myScroll_inner'].refresh();
		},100);
	});
	tabs.each(function(i){
		$(this).bind("click",function(e){
			e.preventDefault();
			if(!window['myScroll_parent']){
				window['myScroll_parent'] = new IScroll('#'+option.content1, {
					click: true,
					scrollX: false,
					scrollY: true,
					scrollbars: true,
					interactiveScrollbars: true,
					shrinkScrollbars: 'scale',
					fadeScrollbars: true
				});
			}
			setTimeout(function(){
				node.addClass('filter-fixed');
				ct2.hide();
				ctp1[0].innerHTML = conts.eq(i).html();
				ct1.css('width','100%').show();
				fullbg.show();
				tabs.removeClass(currentClass);
				tabs.eq(i).addClass(currentClass);
				window['myScroll_parent'].refresh();
			},100);
		});
	});
	fullbg.bind('click',function(e){
		e.preventDefault();
		hide_nav();
	});
	function hide_nav(){
		node.removeClass('filter-fixed');
		fullbg.hide();
		timelist.removeClass('hasUL_current');
		tabs.removeClass(currentClass);
		ct1.css('width','100%').hide();
		ct2.hide();
	}
}
//遮罩页
function showNewPage(tit,html,callback){
	var windowIframe = $('#windowIframe'),windowIframeTitle = $('#windowIframeTitle'),windowIframeBody = $('#windowIframeBody');
	function showBox(){
		windowIframe.show();
		//$('body').css({'height':$(window).height()+'px','overflow':'hidden'});
		$('.wrapper').hide();
	}
	function hideBox(){
		windowIframe.hide();
		//$('body').css({'height':'auto','overflow':'visible'});
		$('.wrapper').show();
	}
	var addEditAddressInit = function(){
		var w_h = $(window).height();
		windowIframeTitle.html(tit);
		windowIframeBody.html(html);
		windowIframe.css({'min-height':w_h+'px'});
		showBox();
		callback&&callback.call(this);
	};
	setTimeout(function(){addEditAddressInit();},10);
	windowIframe.on('click','.close',function(e){
		e.preventDefault();
		hideBox();
	});
}
function getCategory(node,sid,callback){

	var url = window['siteUrl']+'request.ashx?jsoncallback=?&action=category&id='+sid;
	$.getJSON(url,function(data){
		var d = data[0].MSG;
		window['loadCat']++;
		callback&&callback.call(this,node,d);

	});
}
var IDC2 = (function(){
	jQuery.extend(jQuery.easing,{easeOutCubic:function(t,e,i,n,o){return n*((e=e/o-1)*e*e+1)+i}});
	var closeGG = function(node){
		var node = $('#'+node),btn = node.find('.close');
		if(!!node.find('a')[0]){node.show();}
		btn.click(function(){
			node.slideUp('easeOutCubic');
		});
	}
	var loginout = function(siteUrl){
		var url = siteUrl+"request.ashx?action=loginout&json=1&jsoncallback=?&date=" + new Date();
		$.getJSON(url,function(data){

			if(data[0].islogin === '0'){
				if(data[0].bbsopen === "open"){
					var   f=document.createElement("IFRAME")
					f.height=0;
					f.width=0;
					f.src=data[0].bbsloginurl;
					if (f.attachEvent){
						f.attachEvent("onload", function(){
							window.location.href=siteUrl;
						});
					} else {
						f.onload = function(){
							window.location.href=siteUrl;
						};
					}
					document.body.appendChild(f);
				}else{
					window.location.href=siteUrl;
				}
			}else{
				alert("对不起,操作失败!");
			}
		}).error(function(){alert("对不起,操作失败!");});
	}
	var showLogin = function(){
		var loginIco = $('#login_ico'),
			login_inner = $('#login_inner'),
			login_ico = $('#login_ico');
		loginIco.click(function(){
			login_inner.slideToggle('easeOutCubic');
		});
	}
	var isLogin = function(siteUrl,siteName,source){
		var sourceS = source || '';
		var url = siteUrl+"request.ashx?action=islogin&tempid="+sourceS+"&json=1&jsoncallback=?",
			node = $("#login_inner"),login_ico = $('#login_ico'),txt='';
		var hash = '?from='+encodeURIComponent(window.location.href);

		$.getJSON(url,function(data){
			if(data[0].islogin==="1"){
				txt="
"+data[0].name+",您好!欢迎登录"+siteName+"!
[管理中心]  [退出]
<input value=\"1\" id=\"isLogin\" type=\"hidden\" /><input value=\""+data[0].jibie+"\" id=\"user_jibie\" type=\"hidden\" />";
				login_ico.addClass('ico_ok');
				//loadWEBmessage();//消息系统
				if(typeof getUserState !== 'undefined'){
					window['userDate'] = data[0];
					getUserState();
				}
			}else{
				$('#login_ico').attr({'href':siteUrl+'member/login.html'+hash});
				txt='
您好,欢迎来到'+siteName+'!
[登录]   [注册]<input value="0" id="isLogin" type="hidden" /><input value="" id="user_jibie" type="hidden" />
';
				if(typeof getUserState !== 'undefined'){
					window['userDate'] = {};
					getUserState();
				}
			}
			node.html(txt);
		});
	}

	var tabADS = function(node){
		var obj = node;
		var currentClass = "current";
		var tabs = obj.find(".tab-hd").find(".item");
		var conts = obj.find(".tab-cont");
		var t;
		tabs.eq(0).addClass(currentClass);
		conts.eq(0).nextAll().hide();
		tabs.each(function(i){
			$(this).bind("click",function(){
				 t = setTimeout(function(){
					conts.hide().eq(i).show();
					tabs.removeClass(currentClass).eq(i).addClass(currentClass);
				},300);
			});
		});
	}
	var textMarquee = function(e){
		var n=$(e),r=n.width(),w=$(window).width(),i=n.html(),s=0,speed=Math.round(r/w*30);
		if(r<w){return;}
		n.html(i+i),s=r;
		var o=s/speed,
			u="marque"+(new Date).valueOf(),
			a="@-webkit-keyframes "+u+" { 0% {-webkit-transform:translate3d(0,0,0)} 100% {-webkit-transform:translate3d(-"+s+"px,0,0)}}\n";
		a+=a.replace(/\-webkit\-/g,"");
		$("head").append("");
		var f=u+" "+o+"s linear infinite";
		n.css({"-webkit-animation":f,animation:f});
	}
	return {
		loginout:loginout,
		isLogin:isLogin,
		showLogin:showLogin,
		closeGG:closeGG,
		tabADS:tabADS,
		textMarquee:textMarquee
	}
})();
$.fn.radioForm = function(){
	this.each(function(){
		var list = $(this).find('.gx_radio');
		var forname = $(this).attr('data-name');
		var sid=$('input[name="'+forname+'"]:checked').attr('value');
		if(sid !=='' && !!sid){
			$(this).find('.gx_radio').removeClass('current');
			$(this).find('.gx_radio[data-val="'+sid+'"]').addClass('current');
		}
		list.click(function(e){
			e.preventDefault();
			$('input[name="'+forname+'"][value="'+$(this).attr('data-val')+'"]').prop('checked',true);
			list.removeClass('current');
			$(this).addClass('current');
		});
	});
}
$.fn.radioForm2 = function(){
	this.each(function(){
		var list = $(this).find('.gx_radio');
		list.click(function(e){
			e.preventDefault();
			$('#'+$(this).attr('data-id')+$(this).attr('data-val')).prop('checked',true);
			list.removeClass('checked');
			$(this).addClass('checked');
		});
	});
}
function setStatenum(selector){
	var statenum = Math.round(Math.random()*1E15);
	$(selector).val(statenum);
}

var message_pid="-1";
var message_isstop = false;//页面是否丢失服务权
var message_isforced = false;//是否被强制拉回服务权页面,被丢失时又强制拉回权时,完全停止弱探测
function loadWEBmessage(){
	var url = window['siteUrl']+'api/request.ashx?pid=' +message_pid + '&jsoncallback=?';
	$.getJSON(url,function(data){
		if(data[0].islogin === '1'){WebMessageShow(data);}
		if(data[0].islogin === '1' || data[0].islogin === '0'){
			/*if( message_pid != '-1' &&  message_pid != data[0].pid){
		  		$('#message_show').html('活动页面丢失,被重新找回连接权');
		    }*/
			message_pid=data[0].pid;
			window.setTimeout(function(){loadWEBmessage()},200);//高速探测:间隔时间短100-200毫秒,弱探测:间隔1-2分钟以上
		}else{
			/*$('#message_show').html('信息获取被另一页面取代,本页面抓取信息进入弱探测');*/
			message_isstop = true;
			if(message_isforced){
				message_isforced=false;
			}else{
				if( message_pid === '-1' )message_pid='0';
			    window.setTimeout(function(){loadWEBmessage()},1*60000);////被取代后每2分钟尝试一次连接,检测活动页面是否丢失
			}
		}
	}).error(function(err){//失败2分钟后尝试一次
		window.setTimeout(function(){loadWEBmessage()},2*60000);
	});
	/*
	data[0].islogin:0无信息,1:有信息MSG,2:停止高速探测,改为弱探测区别是间隔时间.
	*/
	$(window).blur(function(){
		RunOnunload();
	});
	$(window).focus(function(){
		newloadWEBmessage();
	});
}
function newloadWEBmessage(){
	//当页面发生任何刷新或鼠标动作或任意操作时,表示前活动页面已经不是焦点页面,当前页面重新初始参数强行抓回信息获取权
	//问题:如何防止本页面并行执行loadWEBmessage(),自动执行一次,强制执行一次.
	if(message_isstop){
	  	message_isstop = false;
		message_isforced =true;
    	message_pid="-1";
	    loadWEBmessage();
    }
}
function RunOnunload(){//当前页面关闭时执行,将程序里当前链接关闭,无需返回任何数据
	var url = window['siteUrl']+'api/request.ashx?action=close&pid=' +message_pid + '&jsoncallback=?';
	$.getJSON(url,function(data){});
}
function WebMessageShow(data){
	var idata = data[0]['MSG'];
	var newOrderId='webMessage';
	function countItem(){
		var len = $('#'+newOrderId).find('.item').length;
		$('#WebMessageNum').html(len);
		if(len === 0){
			$('#'+newOrderId).hide();
		}
	}
	if(typeof idata['mp3'] !== 'undefined' && idata['mp3'] !==''){
		WebMessageMusic(idata['mp3']);
	}
	if(!$('#'+newOrderId)[0]){
		var divs = document.createElement('div');
		divs.id = newOrderId;
		$('body').append(divs);
		divs.innerHTML = '
您有0条新信息

收起移除';
		$('#'+newOrderId).find('.close').click(function(e){
			e.preventDefault();
			$('#WebMessageInner').slideToggle();
			$(this).toggleClass('open');
		}).end().find('.remove').click(function(e){
			e.preventDefault();
			$('#'+newOrderId).hide();
		}).end().on( "click", ".view", function(e){
			if(typeof idata['notViewCloseALL'] !=='undefined' && idata['notViewCloseALL'] === '1'){//点击查看移除全部同类型消息
				$(this).parent().parent().remove();
			}else{
				$('#'+newOrderId).find('.tplid_'+$(this).attr('data-tplid')).remove();
			}
			countItem();
		}).on( "click", ".del", function(e){
			e.preventDefault();
			$(this).parent().parent().remove();
			countItem();
		});
	}else{
		$('#'+newOrderId).show();
		$('#WebMessageInner').slideDown();
	}
	var txt = $('
'+idata.title+'
'+idata.dtappenddate+'
查看详细 忽略<s class="s"></s>
');
	$('#WebMessageInner').prepend(txt);
	$('#WebMessageNum').html(parseInt($('#WebMessageNum').html())+1);
}
window['if_played_mp3'] = false;
function WebMessageMusic(file){
	if(!$('#html5_jplayer')[0]){
		$('body').append('<audio id="html5_jplayer" controls="false" hidden="true"></audio>');
		$(window).one('click',function(){
			$('#html5_jplayer').attr('src',file);
			$('#html5_jplayer')[0].play();
		});

	}else{
		$('#html5_jplayer').attr('src',file);
		$('#html5_jplayer')[0].play();
	}
	return false;
}
function showloupanAddTG(Loupan_loupanid){
	var heightV = 420;
	var mask = $('#mask');
	mask.css({'height':$(document).height()+'px'});
	var inner_iframe = $('#inner_iframe');
	var martop = Math.ceil(($(window).height()-heightV)/2);
	inner_iframe.css({'top':martop+'px'});

	if(document.getElementById('isLogin').value !== '1'){
		window.location.href=nowdomain+"member/login.html?from="+(encodeURIComponent(window.location.href));
	}
	else{
		mask.show();
		inner_iframe.show();
		var myiframe = '';
		inner_iframe[0].innerHTML=myiframe;
	}
	$('#mask').click(function(e){e.preventDefault();LoginHide();});
	return false;
}
function LoginHide(){
	$('#inner_iframe').hide();
	$('#mask').hide();
}


text:
define([
	"dojo/_base/declare",
	"dojo/_base/array",
	"dojo/json",
	"dojo/on",
	"dojo/_base/lang",
	"dojo/dom-class",
	"plugins/core/Common/Util",
	"dojo/domReady!",

	"dijit/_Widget",
	"dijit/_Templated",
	"dojox/form/DateTextBox"
	],

function (declare, arrayUtil, JSON, on, lang, domClass, CommonUtil) {

return declare("plugins.form.DateTextBox",
	[ dijit._Widget, dijit._Templated, CommonUtil ], {

//Path to the template of this widget.
templatePath: require.toUrl("plugins/form/templates/datetextbox.html"),

// Calls dijit._Templated.widgetsInTemplate
widgetsInTemplate : true,

_earlyTemplatedStartup: true,

noStart : false,

// OR USE @import IN HTML TEMPLATE
cssFiles : [
	require.toUrl("dojo/resources/dojo.css"),
	require.toUrl("dijit/themes/dijit.css"),
	require.toUrl("dijit/themes/soria/soria.css"),
	require.toUrl("dijit/themes/tundra/tundra.css"),
	require.toUrl("dojox/widget/Calendar/Calendar.css"),
	require.toUrl("plugins/form/css/datetextbox.css")
],

// parentWidget : Object
// 		The widget that created this widget
parentWidget : null,

// core : HashRef
//		Exchange for major objects
core : null,

// pattern : String
// 		Pattern is used in regex to validate input
pattern : ".*",

// value : String
// 		Default value displayed in textbox
value : null,

// promptMessage : String
//		Display this message if user clicks on empty input if its required
promptMessage : null,

// invalidMessage : String
//		Display this message the input is invalid
invalidMessage : null,

// required : Boolean
//		True if input is required, otherwise false
required : null,

// constraints : String
//		Hash
constraints : null,

/////}}}}}
constructor : function(args) {
	dojo.mixin(this, args);

	this.loadCSS();
},
postCreate : function() {
	this.startup();
},
startup : function () {
	this.inherited(arguments);

	this.setParameters();

	this.showValue();
},
showValue : function () {
	console.log("DateTextBox.showValue    this.value: " + this.value);
	if ( this.value ) {
		this.input.textbox.value = this.value;
	}
	else {
		var date = new Date();
		console.log("DateTextBox.showValue    this.value: " + this.value);
		console.dir({date:date});

		var dateString = this.formatDate(date);
		console.log("DateTextBox.showValue    dateString: " + dateString);

		this.input.textbox.value = dateString;
	}
},
formatDate : function (date) {
	var string = ('0' + (date.getMonth()+1)).slice(-2) + '/'
		+ ('0' + date.getDate()).slice(-2) + '/'
		+ date.getFullYear();

	return string;
},
setParameters : function () {
	var parameters = [
		"pattern",
		"maxlength",
		"value",
		"invalidMessage",
		"promptMessage",
		"required"
	];
	for ( var i in parameters ) {
		var parameter = parameters[i];
		this.input[parameter] = this[parameter];
	}
},
isValid : function () {
	var value = this.input.valueNode.value;
	//console.log("DateTextBox.isValid    value: " + value);
	var valid	= this.validate(value);
	//console.log("DateTextBox.isValid    valid: " + valid);

	if ( ! valid ) {
		this.input._set("state", "Error")
	}
	else {
		this.input._set("state", "")
	}

	return valid;
},
validate : function(value){
	var result = true;
	if (
		value == ""
		|| value == null
		|| isNaN(value)
		|| typeof value == "object"
		|| value.toString() == this._invalidDate
	) {
		valid = false;
	}

	var regex = new RegExp(this.pattern);
	if ( ! value.match(regex) ) {
		result = false;
	}

	return result;
},
getValue : function () {
	return this.input.textbox.value;
}

}); 	//	end declare

});	//	end define

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Orleans.Transactions.Abstractions
{
    public interface ITransactionManager
    {
        /// <summary>
        /// Request sent by TA to TM. The TM responds after committing or aborting the transaction.
        /// </summary>
        /// <param name="transactionId">the id of the transaction to prepare</param>
        /// <param name="accessCount">number of reads/writes performed on this participant by this transaction</param>
        /// <param name="timeStamp">the commit timestamp for this transaction</param>
        /// <param name="writerResources">the participants who wrote during the transaction</param>
        /// <param name="totalParticipants">the total number of participants in the transaction</param>
        /// <returns>the status of the transaction</returns>
        Task<TransactionalStatus> PrepareAndCommit(Guid transactionId, AccessCounter accessCount, DateTime timeStamp,
            List<ParticipantId> writerResources, int totalParticipants);

        /// <summary>
        /// One-way message sent by a participant to the TM after it (successfully or unsuccessfully) prepares.
        /// </summary>
        /// <param name="transactionId">The id of the transaction</param>
        /// <param name="timeStamp">The commit timestamp of the transaction</param>
        /// <param name="resource">The participant sending the message</param>
        /// <param name="status">The outcome of the prepare</param>
        /// <returns></returns>
        Task Prepared(Guid transactionId, DateTime timeStamp, ParticipantId resource, TransactionalStatus status);

        /// <summary>
        /// One-way message sent by participants to TM, to let TM know they are still waiting to hear about
        /// the fate of a transaction.
        /// </summary>
        /// <param name="transactionId">The id of the transaction</param>
        /// <param name="timeStamp">The commit timestamp of the transaction</param>
        /// <param name="resource">The participant sending the message</param>
        Task Ping(Guid transactionId, DateTime timeStamp, ParticipantId resource);
    }

    /// <summary>
    /// Counts read and write accesses on a transaction participant.
    /// </summary>
    [Serializable]
    public struct AccessCounter
    {
        public int Reads;
        public int Writes;

        public static AccessCounter operator +(AccessCounter c1, AccessCounter c2)
        {
            return new AccessCounter { Reads = c1.Reads + c2.Reads, Writes = c1.Writes + c2.Writes };
        }
    }
}


text:
package uk.ac.ebi.gxa.index.builder;

import uk.ac.ebi.gxa.index.builder.listener.IndexBuilderListener;

import java.util.List;

/**
 * Interface for building a Gene Expression Atlas index.
 *

 * By default, all genes and experiments are included, and all experiments (both pending and non-pending) are included.
 *

 * If you are using an IndexBuilder in a standalone application (not a web application) and you do not want to reuse
 * IndexBuilder for multiple index building calls, you should make sure you register a listener that performs a {@link
 * #shutdown()} upon completion.  This will allow any resources being used by the IndexBuilder implementation to be
 * reclaimed.  Otherwise, an IndexBuilder instance may run indefinitely.
 *
 * @author Tony Burdett
 */
public interface IndexBuilder {
    /**
     * Set collection of index names to build
     * @param includeIndexes collection of names
     */
    void setIncludeIndexes(List<String> includeIndexes);

    /**
     * Build the index and register a listener that provides a callback on completion of the build task.
     * The listener supplied will provide callbacks whenever the indexbuilder has interesting events to report.
     *
     * @param command command to process
     * @param listener a listener that can be used to supply callbacks when building of the index completes, or when any
     *                 errors occur.
     */
    void doCommand(IndexBuilderCommand command, IndexBuilderListener listener);

    /**
     * Register index update handler. Those handlers will be called when index build starts and finishes.
     * @param handler handler to register
     */
    void registerIndexBuildEventHandler(IndexBuilderEventHandler handler);

    /**
     * Unregister index update handler. Handlers will not receive notifications anymore.
     * @param handler handler to unregister
     */
    void unregisterIndexBuildEventHandler(IndexBuilderEventHandler handler);
}


text:
package org.testng;

/**
 * Represents an exception that is thrown when a configuration method is not invoked. One of the
 * use-cases when this can happen is when the user does the following:
 *
 *

 *
User defines a configuration method
 *
The class that houses the configuration method defines support for callbacks via {@link
 *       IConfigurable} implementation
 *
User willfully skips invoking the callback and also fails at altering the configuration
 *       method's status via {@link ITestResult#setStatus(int)}
 *

 */
public class ConfigurationNotInvokedException extends TestNGException {

  public ConfigurationNotInvokedException(ITestNGMethod tm) {
    super(
        tm.getQualifiedName()
            + " defines a callback via "
            + IConfigurable.class.getName()
            + " but neither the callback was invoked nor the status was altered to "
            + String.join("|", ITestResult.finalStatuses()));
  }
}


text:
<SOAP:Envelope
  xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
  <SOAP:Body>
    <SOAP:Fault>
      <faultcode>Server.Data</faultcode>
      <faultstring>Unable to ticket without pricing information.</faultstring>
      <detail>
        <common_v47_0:ErrorInfo
          xmlns:common_v47_0="http://www.travelport.com/schema/common_v47_0">
          <common_v47_0:Code>3788</common_v47_0:Code>
          <common_v47_0:Service>AIRSVC</common_v47_0:Service>
          <common_v47_0:Type>Data</common_v47_0:Type>
          <common_v47_0:Description>Unable to ticket without pricing information.</common_v47_0:Description>
          <common_v47_0:TransactionId>AF672B320A07406E56693BD96EA3B6A5</common_v47_0:TransactionId>
        </common_v47_0:ErrorInfo>
      </detail>
    </SOAP:Fault>
  </SOAP:Body>
</SOAP:Envelope>


text:
        Ordine corrente

            <food-entry name="item.food.name" quantity="item.quantity" note="item.note" onnote="showNote(item)" onplus="orderFood(item)" onminus="reduceFood(item)"></food-entry>

X

            <food-entry name="note.item.food.name" quantity="note.item.quantity" note="item.note" onplus="orderFood(item)" onminus="reduceFood(item)"></food-entry>

Salva

            Prendi una nota:
            <textarea ng-value="note.text" ng-model="note.text"></textarea>

        <button class="rmt-button flex1" ng-hide="note.visible" ng-click="sendToKitchen(appstate.order); sentToKitchen = true;">Invia</button>
        <vr style="width: 1px"></vr>
        <button class="rmt-button flex1" ng-hide="note.visible" ng-click="sendInvoice(appstate.order); sentInvoice = true;">Conto</button>

    <rmt-modal ng-show="sentToKitchen" rmt-modal-title="'Comanda inviata!'" rmt-modal-onclose="appstate.setView('table-selection')">
        Inviato in cucina e al bar.
    </rmt-modal>

    <rmt-modal ng-show="sentInvoice" rmt-modal-title="'Conto inviato!'" rmt-modal-onclose="appstate.setView('table-selection')">
        Inviato alla cassa.

                {{item.quantity + 'x'}}, {{item.food.name}}, {{multiply(item.food.price, item.quantity) + '€'}}

Totale: {{total + '€'}}

    </rmt-modal>


text:
'use strict';

(function () {
    AudioNetwork.Injector
        .registerFactory('Rewrite.PhysicalLayer.TxSymbolManager', TxSymbolManager);

    TxSymbolManager.$inject = [
        'Rewrite.PhysicalLayer.TxSymbol'
    ];

    function TxSymbolManager(
        TxSymbol
    ) {
        var TxSymbolManager;

        TxSymbolManager = function () {
            this.$$txSymbolId = 1;
            this.$$txSymbol = null;
            this.$$txSymbolCurrent = this.$$getTxSymbolIdle();
            this.$$txSymbolQueue = [];
        };

        TxSymbolManager.prototype.clearTxSymbolQueue = function () {
            this.$$txSymbolQueue.length = 0;
        };

        TxSymbolManager.prototype.getTxSymbol = function () {
            return this.$$txSymbol.cloneClean();
        };

        TxSymbolManager.prototype.getTxSymbolCurrent = function () {
            return this.$$txSymbolCurrent;
        };

        TxSymbolManager.prototype.getTxSymbolProgress = function () {
            var
                result = {},
                i;

            result.txSymbol = this.getTxSymbol();

            result.txSymbolCurrent = this.$$txSymbolCurrent.cloneClean();

            result.txSymbolQueue = [];
            for (i = 0; i < this.$$txSymbolQueue.length; i++) {
                result.txSymbolQueue.push(
                    this.$$txSymbolQueue[i].cloneClean()
                );
            }

            result.isTxInProgress = this.isTxInProgress();

            return result;
        };

        TxSymbolManager.prototype.isTxInProgress = function () {
            return this.$$txSymbolQueue.length > 0 ||
                this.$$txSymbolCurrent.isNotIdle();
        };

        TxSymbolManager.prototype.addTxFskSymbol = function (txFskSymbol) {
            var txSymbol = new TxSymbol(
                this.$$txSymbolId++,
                TxSymbol.TX_SYMBOL_FSK
            );

            txSymbol.setTxFskSymbol(txFskSymbol);
            this.$$txSymbolQueue.push(txSymbol);

            return txSymbol.getId();
        };

        TxSymbolManager.prototype.addTxSymbolGapImportant = function () {
            var txSymbolGapImportant = new TxSymbol(
                this.$$txSymbolId++,
                TxSymbol.TX_SYMBOL_GAP_IMPORTANT
            );
            this.$$txSymbolQueue.push(txSymbolGapImportant);
        };

        TxSymbolManager.prototype.addTxSymbolGapDeletable = function () {
            var txSymbolGapDeletable = new TxSymbol(
                this.$$txSymbolId++,
                TxSymbol.TX_SYMBOL_GAP_DELETABLE
            );
            this.$$txSymbolQueue.push(txSymbolGapDeletable);
        };

        TxSymbolManager.prototype.$$getTxSymbolIdle = function () {
            return new TxSymbol(
                this.$$txSymbolId++,
                TxSymbol.TX_SYMBOL_IDLE
            );
        };

        TxSymbolManager.prototype.isTxAboutToStart = function () {
            var isQueueNotEmpty = this.$$txSymbolQueue.length !== 0;

            return this.$$txSymbolCurrent.isIdle() && isQueueNotEmpty;
        };

        TxSymbolManager.prototype.isTxAboutToEnd = function () {
            var isQueueEmpty = this.$$txSymbolQueue.length === 0;

            return isQueueEmpty && this.$$txSymbolCurrent.isNotIdle();
        };

        TxSymbolManager.prototype.tick = function () {
            var txSymbolIdle, isQueueEmpty;

            isQueueEmpty = this.$$txSymbolQueue.length === 0;
            this.$$txSymbol = this.$$txSymbolCurrent;

            if (isQueueEmpty) {
                txSymbolIdle = this.$$getTxSymbolIdle();
                this.$$txSymbolCurrent = txSymbolIdle;
            } else {
                this.$$txSymbolCurrent = this.$$txSymbolQueue.shift();
            }
        };

        TxSymbolManager.prototype.handleGapLogicAtStart = function () {
            // When device A sends some data to device B
            // then device B cannot respond immediately. We
            // need make sure that device A will have some time
            // to reinitialize microphone again. This is solved
            // by adding two 'gap' symbols in the beginning
            // Similar problem we have at the end. If we enable
            // microphone at the same time as last symbol stops
            // then we have a glitch. We need to add one 'gap'
            // symbol after the last symbol.
            // If symbol is not last we need to remove that
            // unnecessary gap.
            if (this.isTxInProgress()) {
                this.$$clearAllDeletableGapFromTheEndOfTheQueue();
            } else {
                this.addTxSymbolGapDeletable();  // #1
                this.addTxSymbolGapDeletable();  // #2
            }
        };

        TxSymbolManager.prototype.handleGapLogicAtEnd = function () {
            // will be removed if subsequent symbol will arrive
            this.addTxSymbolGapDeletable();
        };

        TxSymbolManager.prototype.handleGapLogicAtEndOfSync = function (gapImportantNumber) {
            var i;

            for (i = 0; i < gapImportantNumber; i++) {
                this.addTxSymbolGapImportant();
            }
        };

        TxSymbolManager.prototype.$$clearAllDeletableGapFromTheEndOfTheQueue = function () {
            var i;

            for (i = this.$$txSymbolQueue.length - 1; i >= 0; i--) {
                if (this.$$txSymbolQueue[i].isNotGapDeletable()) {
                    this.$$txSymbolQueue.length = i + 1;
                    break;
                }
            }
        };

        return TxSymbolManager;
    }

})();


text:
module JavaScript
  VERSION = "0.0.3"
end


text: {{ include.description }}


text:
import { requireNativeComponent, View, findNodeHandle } from 'react-native';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
var NativeModules = require('react-native').NativeModules;
var createReactClass = require('create-react-class');
import { checkMisnamedProps } from './Utilities/ViroProps';

var ViroBox = createReactClass({
  propTypes: {
    ...View.propTypes,
    position: PropTypes.arrayOf(PropTypes.number),
    scale: PropTypes.arrayOf(PropTypes.number),
    rotation: PropTypes.arrayOf(PropTypes.number),
    scalePivot: PropTypes.arrayOf(PropTypes.number),
    rotationPivot: PropTypes.arrayOf(PropTypes.number),
    renderingOrder: PropTypes.number,
    visible: PropTypes.bool,
    opacity: PropTypes.number,
    width: PropTypes.number,
    height: PropTypes.number,
    length: PropTypes.number,
    materials: PropTypes.oneOfType([
      PropTypes.arrayOf(PropTypes.string),
      PropTypes.string
    ]),
    animation: PropTypes.shape({
      name: PropTypes.string,
      delay: PropTypes.number,
      loop: PropTypes.bool,
      onStart: PropTypes.func,
      onFinish: PropTypes.func,
      run: PropTypes.bool,
      interruptible: PropTypes.bool,
    }),
    transformBehaviors: PropTypes.oneOfType([
      PropTypes.arrayOf(PropTypes.string),
      PropTypes.string
    ]),
    lightReceivingBitMask : PropTypes.number,
    shadowCastingBitMask : PropTypes.number,
    ignoreEventHandling: PropTypes.bool,
    dragType: PropTypes.oneOf(["FixedDistance", "FixedDistanceOrigin", "FixedToWorld", "FixedToPlane"]),
    dragPlane: PropTypes.shape({
      planePoint : PropTypes.arrayOf(PropTypes.number),
      planeNormal : PropTypes.arrayOf(PropTypes.number),
      maxDistance : PropTypes.number
    }),

    onTransformUpdate: PropTypes.func,
    onHover: PropTypes.func,
    onClick: PropTypes.func,
    onClickState: PropTypes.func,
    onTouch: PropTypes.func,
    onScroll: PropTypes.func,
    onSwipe: PropTypes.func,
    onDrag: PropTypes.func,
    onPinch: PropTypes.func,
    onRotate: PropTypes.func,
    onFuse: PropTypes.oneOfType([
      PropTypes.shape({
        callback: PropTypes.func.isRequired,
        timeToFuse: PropTypes.number
      }),
      PropTypes.func,
    ]),
    /**
     * Enables high accuracy event collision checks for this object.
     * This can be useful for complex 3D objects where the default
     * checking method of bounding boxes do not provide adequate
     * collision detection coverage.
     *
     * NOTE: Enabling high accuracy event collision checks has a high
     * performance cost and should be used sparingly / only when
     * necessary.
     *
     * Flag is set to false by default.
     */
    highAccuracyEvents:PropTypes.bool,
    /* DEPRECATION WARNING - highAccuracyGaze has been deprecated, please use highAccuracyEvents instead */
    highAccuracyGaze:PropTypes.bool,
    physicsBody: PropTypes.shape({
      type: PropTypes.oneOf(['Dynamic','Kinematic','Static']).isRequired,
      mass: PropTypes.number,
      restitution: PropTypes.number,
      shape: PropTypes.shape({
        type: PropTypes.oneOf(["Box", "Sphere", "Compound"]).isRequired,
        params: PropTypes.arrayOf(PropTypes.number)
      }),
      friction: PropTypes.number,
      useGravity: PropTypes.bool,
      enabled: PropTypes.bool,
      velocity: PropTypes.arrayOf(PropTypes.number),
      force:  PropTypes.oneOfType([
        PropTypes.arrayOf(PropTypes.shape({
          value: PropTypes.arrayOf(PropTypes.number),
          position: PropTypes.arrayOf(PropTypes.number)
        })),
        PropTypes.shape({
          value: PropTypes.arrayOf(PropTypes.number),
          position: PropTypes.arrayOf(PropTypes.number)
        }),
      ]),
      torque: PropTypes.arrayOf(PropTypes.number)
    }),

    viroTag: PropTypes.string,
    onCollision: PropTypes.func,
  },

  _onHover: function(event: Event) {
    this.props.onHover && this.props.onHover(event.nativeEvent.isHovering, event.nativeEvent.position, event.nativeEvent.source);
  },

  _onClick: function(event: Event) {
    this.props.onClick && this.props.onClick(event.nativeEvent.position, event.nativeEvent.source);
  },

  _onClickState: function(event: Event) {
    this.props.onClickState && this.props.onClickState(event.nativeEvent.clickState, event.nativeEvent.position, event.nativeEvent.source);
    let CLICKED = 3; // Value representation of Clicked ClickState within EventDelegateJni.
    if (event.nativeEvent.clickState == CLICKED){
      this._onClick(event)
    }
  },

  _onTouch: function(event: Event) {
    this.props.onTouch && this.props.onTouch(event.nativeEvent.touchState, event.nativeEvent.touchPos, event.nativeEvent.source);
  },

  _onScroll: function(event: Event) {
    this.props.onScroll && this.props.onScroll(event.nativeEvent.scrollPos, event.nativeEvent.source);
  },

  _onSwipe: function(event: Event) {
    this.props.onSwipe && this.props.onSwipe(event.nativeEvent.swipeState, event.nativeEvent.source);
  },

  _onPinch: function(event: Event) {
    this.props.onPinch && this.props.onPinch(event.nativeEvent.pinchState, event.nativeEvent.scaleFactor, event.nativeEvent.source);
  },

  _onRotate: function(event: Event) {
    this.props.onRotate && this.props.onRotate(event.nativeEvent.rotateState, event.nativeEvent.rotationFactor, event.nativeEvent.source);
  },

  _onDrag: function(event: Event) {
    this.props.onDrag
      && this.props.onDrag(event.nativeEvent.dragToPos, event.nativeEvent.source);
  },

  _onFuse: function(event: Event){
    if (this.props.onFuse){
      if (typeof this.props.onFuse === 'function'){
        this.props.onFuse(event.nativeEvent.source);
      } else if (this.props.onFuse != undefined && this.props.onFuse.callback != undefined){
        this.props.onFuse.callback(event.nativeEvent.source);
      }
    }
  },

  _onAnimationStart: function(event: Event) {
    this.props.animation && this.props.animation.onStart && this.props.animation.onStart();
  },

  _onAnimationFinish: function(event: Event) {
    this.props.animation && this.props.animation.onFinish && this.props.animation.onFinish();
  },

  async getTransformAsync() {
    return await NativeModules.VRTNodeModule.getNodeTransform(findNodeHandle(this));
  },

  async getBoundingBoxAsync() {
    return await NativeModules.VRTNodeModule.getBoundingBox(findNodeHandle(this));
  },

  applyImpulse: function(force, position) {
    NativeModules.VRTNodeModule.applyImpulse(findNodeHandle(this), force, position);
  },

  applyTorqueImpulse: function(torque) {
    NativeModules.VRTNodeModule.applyTorqueImpulse(findNodeHandle(this), torque);
  },

  setVelocity: function(velocity) {
    NativeModules.VRTNodeModule.setVelocity(findNodeHandle(this), velocity);
  },

  _onCollision: function(event: Event){
    if (this.props.onCollision){
      this.props.onCollision(event.nativeEvent.viroTag,
        event.nativeEvent.collidedPoint, event.nativeEvent.collidedNormal);
    }
  },

  // Called from native on the event a positional change has occured
  // for the underlying control within the renderer.
  _onNativeTransformUpdate: function(event: Event){
    var position =  event.nativeEvent.position;
    if (this.props.onTransformUpdate){
      this.props.onTransformUpdate(position);
    }
  },

  setNativeProps: function(nativeProps) {
    this._component.setNativeProps(nativeProps);
  },

  render: function() {

    checkMisnamedProps("ViroBox", this.props);

    // Since materials and transformBehaviors can be either a string or an array, convert the string to a 1-element array.
    let materials = typeof this.props.materials === 'string' ? new Array(this.props.materials) : this.props.materials;
    let transformBehaviors = typeof this.props.transformBehaviors === 'string' ?
        new Array(this.props.transformBehaviors) : this.props.transformBehaviors;

    if(materials) {
      if(materials.length!=1 && materials.length!=6) {
        console.error("<ViroBox> can only take 1 material for all sides or 6, one for each side.");
      }
    }

    let timeToFuse = undefined;
    if (this.props.onFuse != undefined && typeof this.props.onFuse === 'object'){
      timeToFuse = this.props.onFuse.timeToFuse;
    }

    let transformDelegate = this.props.onTransformUpdate != undefined ? this._onNativeTransformUpdate : undefined;

    let highAccuracyEvents = this.props.highAccuracyEvents;
    if (this.props.highAccuracyEvents == undefined && this.props.highAccuracyGaze != undefined) {
      console.warn("**DEPRECATION WARNING** highAccuracyGaze has been deprecated/renamed to highAccuracyEvents");
      highAccuracyEvents = this.props.highAccuracyGaze;
    }

    return (
      <VRTBox
        {...this.props}
        ref={ component => {this._component = component; }}
        highAccuracyEvents={highAccuracyEvents}
        transformBehaviors={transformBehaviors}
        onNativeTransformDelegateViro={transformDelegate}
        hasTransformDelegate={this.props.onTransformUpdate != undefined}
        materials={materials}
        canHover={this.props.onHover != undefined}
        canClick={this.props.onClick != undefined || this.props.onClickState != undefined}
        canTouch={this.props.onTouch != undefined}
        canScroll={this.props.onScroll != undefined}
        canSwipe={this.props.onSwipe != undefined}
        canDrag={this.props.onDrag != undefined}
        canPinch={this.props.onPinch != undefined}
        canRotate={this.props.onRotate != undefined}
        canFuse={this.props.onFuse != undefined}
        onHoverViro={this._onHover}
        onClickViro={this._onClickState}
        onTouchViro={this._onTouch}
        onScrollViro={this._onScroll}
        onSwipeViro={this._onSwipe}
        onDragViro={this._onDrag}
        onPinchViro={this._onPinch}
        onRotateViro={this._onRotate}
        onFuseViro={this._onFuse}
        onAnimationStartViro={this._onAnimationStart}
        onAnimationFinishViro={this._onAnimationFinish}
        canCollide={this.props.onCollision != undefined}
        onCollisionViro={this._onCollision}
        timeToFuse={timeToFuse}/>
    );
  }
});

var VRTBox = requireNativeComponent(
  'VRTBox', ViroBox, {
    nativeOnly: {
      canHover: true,
      canClick: true,
      canTouch: true,
      canScroll: true,
      canSwipe: true,
      canDrag: true,
      canPinch: true,
      canRotate: true,
      canFuse: true,
      onHoverViro:true,
      onClickViro:true,
      onTouchViro:true,
      onScrollViro:true,
      onSwipeViro:true,
      onDragViro:true,
      onPinchViro:true,
      onRotateViro:true,
      onFuseViro:true,
      timeToFuse:true,
      canCollide:true,
      onCollisionViro:true,
      onNativeTransformDelegateViro:true,
      hasTransformDelegate:true,
      onAnimationStartViro:true,
      onAnimationFinishViro:true
    }
  }
);

module.exports = ViroBox;


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <parent>
    <artifactId>spring-richclient</artifactId>
    <groupId>org.springframework.richclient</groupId>
    <version>1.1.1-SNAPSHOT</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>
  <artifactId>spring-richclient-integrations</artifactId>
  <packaging>pom</packaging>

  <name>Spring Rich Client integrations</name>
  <description>
    Spring Rich Client integration projects
  </description>

  <modules>
    <module>spring-richclient-vldocking</module>
    <module>spring-richclient-flexdock</module>
    <module>spring-richclient-swingdocking</module>
    <module>spring-richclient-jideoss</module>
    <!-- JIDE integration isn't built automatically due to licensing  -->
    <!--<module>spring-richclient-jide</module>-->
  </modules>

  <dependencies>
    <dependency>
      <groupId>org.springframework.richclient</groupId>
      <artifactId>spring-richclient-core</artifactId>
    </dependency>
  </dependencies>
</project>


text:
package software.amazon.awssdk.awscore.client.builder;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.awscore.client.config.AwsAdvancedClientOption.ENABLE_DEFAULT_REGION_DETECTION;
import static software.amazon.awssdk.awscore.client.config.AwsClientOption.SERVICE_SIGNING_NAME;
import static software.amazon.awssdk.awscore.client.config.AwsClientOption.SIGNING_REGION;
import static software.amazon.awssdk.core.client.config.SdkAdvancedClientOption.SIGNER;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.net.URI;
import java.time.Duration;
import java.util.Arrays;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.auth.signer.Aws4Signer;
import software.amazon.awssdk.awscore.client.config.AwsClientOption;
import software.amazon.awssdk.awscore.internal.defaultsmode.AutoDefaultsModeDiscovery;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.core.signer.Signer;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpConfigurationOption;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.utils.AttributeMap;

/**
 * Validate the functionality of the {@link AwsDefaultClientBuilder}.
 */
@RunWith(MockitoJUnitRunner.class)
public class DefaultAwsClientBuilderTest {

    private static final AttributeMap MOCK_DEFAULTS = AttributeMap
        .builder()
        .put(SdkHttpConfigurationOption.READ_TIMEOUT, Duration.ofSeconds(10))
        .build();

    private static final String ENDPOINT_PREFIX = "s3";
    private static final String SIGNING_NAME = "demo";
    private static final String SERVICE_NAME = "Demo";
    private static final Signer TEST_SIGNER = Aws4Signer.create();
    private static final URI ENDPOINT = URI.create("https://example.com");

    @Mock
    private SdkHttpClient.Builder defaultHttpClientBuilder;

    @Mock
    private SdkAsyncHttpClient.Builder defaultAsyncHttpClientFactory;

    @Mock
    private AutoDefaultsModeDiscovery autoModeDiscovery;

    @Before
    public void setup() {
        when(defaultHttpClientBuilder.buildWithDefaults(any())).thenReturn(mock(SdkHttpClient.class));
        when(defaultAsyncHttpClientFactory.buildWithDefaults(any())).thenReturn(mock(SdkAsyncHttpClient.class));
    }

    @Test
    public void buildIncludesServiceDefaults() {
        TestClient client = testClientBuilder().region(Region.US_WEST_1).build();
        assertThat(client.clientConfiguration.option(SIGNER)).isEqualTo(TEST_SIGNER);
        assertThat(client.clientConfiguration.option(SIGNING_REGION)).isNotNull();
        assertThat(client.clientConfiguration.option(SdkClientOption.SERVICE_NAME)).isEqualTo(SERVICE_NAME);
    }

    @Test
    public void buildWithRegionShouldHaveCorrectEndpointAndSigningRegion() {
        TestClient client = testClientBuilder().region(Region.US_WEST_1).build();

        assertThat(client.clientConfiguration.option(SdkClientOption.ENDPOINT))
            .hasToString("https://" + ENDPOINT_PREFIX + ".us-west-1.amazonaws.com");
        assertThat(client.clientConfiguration.option(SIGNING_REGION)).isEqualTo(Region.US_WEST_1);
        assertThat(client.clientConfiguration.option(SERVICE_SIGNING_NAME)).isEqualTo(SIGNING_NAME);
    }

    @Test
    public void buildWithFipsRegionThenNonFipsFipsEnabledRemainsSet() {
        TestClient client = testClientBuilder()
            .region(Region.of("us-west-2-fips")) // first call to setter sets the flag
            .region(Region.of("us-west-2"))// second call should clear
            .build();

        assertThat(client.clientConfiguration.option(AwsClientOption.AWS_REGION)).isEqualTo(Region.US_WEST_2);
        assertThat(client.clientConfiguration.option(AwsClientOption.FIPS_ENDPOINT_ENABLED)).isTrue();
    }

    @Test
    public void buildWithSetFipsTrueAndNonFipsRegionFipsEnabledRemainsSet() {
        TestClient client = testClientBuilder()
            .fipsEnabled(true)
            .region(Region.of("us-west-2"))
            .build();

        assertThat(client.clientConfiguration.option(AwsClientOption.AWS_REGION)).isEqualTo(Region.US_WEST_2);
        assertThat(client.clientConfiguration.option(AwsClientOption.FIPS_ENDPOINT_ENABLED)).isTrue();
    }

    @Test
    public void buildWithEndpointShouldHaveCorrectEndpointAndSigningRegion() {
        TestClient client = testClientBuilder().region(Region.US_WEST_1).endpointOverride(ENDPOINT).build();

        assertThat(client.clientConfiguration.option(SdkClientOption.ENDPOINT)).isEqualTo(ENDPOINT);
        assertThat(client.clientConfiguration.option(SIGNING_REGION)).isEqualTo(Region.US_WEST_1);
        assertThat(client.clientConfiguration.option(SERVICE_SIGNING_NAME)).isEqualTo(SIGNING_NAME);
    }

    @Test
    public void noClientProvided_DefaultHttpClientIsManagedBySdk() {
        TestClient client = testClientBuilder().region(Region.US_WEST_2).build();
        assertThat(client.clientConfiguration.option(SdkClientOption.SYNC_HTTP_CLIENT))
            .isNotInstanceOf(AwsDefaultClientBuilder.NonManagedSdkHttpClient.class);
        verify(defaultHttpClientBuilder, times(1)).buildWithDefaults(any());
    }

    @Test
    public void noAsyncClientProvided_DefaultAsyncHttpClientIsManagedBySdk() {
        TestAsyncClient client = testAsyncClientBuilder().region(Region.US_WEST_2).build();
        assertThat(client.clientConfiguration.option(SdkClientOption.ASYNC_HTTP_CLIENT))
            .isNotInstanceOf(AwsDefaultClientBuilder.NonManagedSdkAsyncHttpClient.class);
        verify(defaultAsyncHttpClientFactory, times(1)).buildWithDefaults(any());
    }

    @Test
    public void clientFactoryProvided_ClientIsManagedBySdk() {
        TestClient client = testClientBuilder()
            .region(Region.US_WEST_2)
            .httpClientBuilder((SdkHttpClient.Builder) serviceDefaults -> {
                assertThat(serviceDefaults).isEqualTo(MOCK_DEFAULTS);
                return mock(SdkHttpClient.class);
            })
            .build();
        assertThat(client.clientConfiguration.option(SdkClientOption.SYNC_HTTP_CLIENT))
            .isNotInstanceOf(AwsDefaultClientBuilder.NonManagedSdkHttpClient.class);
        verify(defaultHttpClientBuilder, never()).buildWithDefaults(any());
    }

    @Test
    public void asyncHttpClientFactoryProvided_ClientIsManagedBySdk() {
        TestAsyncClient client = testAsyncClientBuilder()
            .region(Region.US_WEST_2)
            .httpClientBuilder((SdkAsyncHttpClient.Builder) serviceDefaults -> {
                assertThat(serviceDefaults).isEqualTo(MOCK_DEFAULTS);
                return mock(SdkAsyncHttpClient.class);
            })
            .build();
        assertThat(client.clientConfiguration.option(SdkClientOption.ASYNC_HTTP_CLIENT))
            .isNotInstanceOf(AwsDefaultClientBuilder.NonManagedSdkAsyncHttpClient.class);
        verify(defaultAsyncHttpClientFactory, never()).buildWithDefaults(any());
    }

    @Test
    public void explicitClientProvided_ClientIsNotManagedBySdk() {
        String clientName = "foobarsync";
        SdkHttpClient sdkHttpClient = mock(SdkHttpClient.class);
        TestClient client = testClientBuilder()
            .region(Region.US_WEST_2)
            .httpClient(sdkHttpClient)
            .build();
        when(sdkHttpClient.clientName()).thenReturn(clientName);
        assertThat(client.clientConfiguration.option(SdkClientOption.SYNC_HTTP_CLIENT))
            .isInstanceOf(AwsDefaultClientBuilder.NonManagedSdkHttpClient.class);

        assertThat(client.clientConfiguration.option(SdkClientOption.SYNC_HTTP_CLIENT).clientName())
            .isEqualTo(clientName);
        verify(defaultHttpClientBuilder, never()).buildWithDefaults(any());
    }

    @Test
    public void explicitAsyncHttpClientProvided_ClientIsNotManagedBySdk() {
        String clientName = "foobarasync";
        SdkAsyncHttpClient sdkAsyncHttpClient = mock(SdkAsyncHttpClient.class);
        TestAsyncClient client = testAsyncClientBuilder()
            .region(Region.US_WEST_2)
            .httpClient(sdkAsyncHttpClient)
            .build();
        assertThat(client.clientConfiguration.option(SdkClientOption.ASYNC_HTTP_CLIENT))
            .isInstanceOf(AwsDefaultClientBuilder.NonManagedSdkAsyncHttpClient.class);

        when(sdkAsyncHttpClient.clientName()).thenReturn(clientName);

        assertThat(client.clientConfiguration.option(SdkClientOption.ASYNC_HTTP_CLIENT))
            .isInstanceOf(AwsDefaultClientBuilder.NonManagedSdkAsyncHttpClient.class);

        assertThat(client.clientConfiguration.option(SdkClientOption.ASYNC_HTTP_CLIENT).clientName())
            .isEqualTo(clientName);
        verify(defaultAsyncHttpClientFactory, never()).buildWithDefaults(any());
    }

    @Test
    public void clientBuilderFieldsHaveBeanEquivalents() throws Exception {
        AwsClientBuilder<TestClientBuilder, TestClient> builder = testClientBuilder();

        BeanInfo beanInfo = Introspector.getBeanInfo(builder.getClass());
        Method[] clientBuilderMethods = AwsClientBuilder.class.getDeclaredMethods();

        Arrays.stream(clientBuilderMethods).filter(m -> !m.isSynthetic()).forEach(builderMethod -> {
            String propertyName = builderMethod.getName();

            Optional<PropertyDescriptor> propertyForMethod =
                Arrays.stream(beanInfo.getPropertyDescriptors())
                      .filter(property -> property.getName().equals(propertyName))
                      .findFirst();

            assertThat(propertyForMethod).as(propertyName + " property").hasValueSatisfying(property -> {
                assertThat(property.getReadMethod()).as(propertyName + " getter").isNull();
                assertThat(property.getWriteMethod()).as(propertyName + " setter").isNotNull();
            });
        });

    }

    private AwsClientBuilder<TestClientBuilder, TestClient> testClientBuilder() {
        ClientOverrideConfiguration overrideConfig =
            ClientOverrideConfiguration.builder()
                                       .putAdvancedOption(SIGNER, TEST_SIGNER)
                                       .putAdvancedOption(ENABLE_DEFAULT_REGION_DETECTION, false)
                                       .build();

        return new TestClientBuilder().credentialsProvider(AnonymousCredentialsProvider.create())
                                      .overrideConfiguration(overrideConfig);
    }

    private AwsClientBuilder<TestAsyncClientBuilder, TestAsyncClient> testAsyncClientBuilder() {
        ClientOverrideConfiguration overrideConfig =
            ClientOverrideConfiguration.builder()
                                       .putAdvancedOption(SIGNER, TEST_SIGNER)
                                       .putAdvancedOption(ENABLE_DEFAULT_REGION_DETECTION, false)
                                       .build();

        return new TestAsyncClientBuilder().credentialsProvider(AnonymousCredentialsProvider.create())
                                           .overrideConfiguration(overrideConfig);
    }

    private static class TestClient {
        private final SdkClientConfiguration clientConfiguration;

        public TestClient(SdkClientConfiguration clientConfiguration) {
            this.clientConfiguration = clientConfiguration;
        }
    }

    private class TestClientBuilder extends AwsDefaultClientBuilder<TestClientBuilder, TestClient>
        implements AwsClientBuilder<TestClientBuilder, TestClient> {

        public TestClientBuilder() {
            super(defaultHttpClientBuilder, null, autoModeDiscovery);
        }

        @Override
        protected TestClient buildClient() {
            return new TestClient(super.syncClientConfiguration());
        }

        @Override
        protected String serviceEndpointPrefix() {
            return ENDPOINT_PREFIX;
        }

        @Override
        protected String signingName() {
            return SIGNING_NAME;
        }

        @Override
        protected String serviceName() {
            return SERVICE_NAME;
        }

        @Override
        protected AttributeMap serviceHttpConfig() {
            return MOCK_DEFAULTS;
        }
    }

    private static class TestAsyncClient {
        private final SdkClientConfiguration clientConfiguration;

        private TestAsyncClient(SdkClientConfiguration clientConfiguration) {
            this.clientConfiguration = clientConfiguration;
        }
    }

    private class TestAsyncClientBuilder extends AwsDefaultClientBuilder<TestAsyncClientBuilder, TestAsyncClient>
        implements AwsClientBuilder<TestAsyncClientBuilder, TestAsyncClient> {

        public TestAsyncClientBuilder() {
            super(defaultHttpClientBuilder, defaultAsyncHttpClientFactory, autoModeDiscovery);
        }

        @Override
        protected TestAsyncClient buildClient() {
            return new TestAsyncClient(super.asyncClientConfiguration());
        }

        @Override
        protected String serviceEndpointPrefix() {
            return ENDPOINT_PREFIX;
        }

        @Override
        protected String signingName() {
            return SIGNING_NAME;
        }

        @Override
        protected String serviceName() {
            return SERVICE_NAME;
        }

        @Override
        protected AttributeMap serviceHttpConfig() {
            return MOCK_DEFAULTS;
        }
    }
}


text:
// Dstl (c) Crown Copyright 2017
package uk.gov.dstl.baleen.annotators.cleaners;

import static java.util.stream.Collectors.toList;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import org.apache.uima.UIMAException;
import org.apache.uima.UimaContext;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.fit.descriptor.ConfigurationParameter;
import org.apache.uima.fit.factory.JCasFactory;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.tcas.Annotation;
import org.apache.uima.resource.ResourceInitializationException;

import uk.gov.dstl.baleen.core.pipelines.orderers.AnalysisEngineAction;
import uk.gov.dstl.baleen.exceptions.BaleenException;
import uk.gov.dstl.baleen.types.semantic.Entity;
import uk.gov.dstl.baleen.uima.BaleenAnnotator;
import uk.gov.dstl.baleen.uima.utils.TypeSystemSingleton;
import uk.gov.dstl.baleen.uima.utils.TypeUtils;

/**
 * Merge adjacent entities of the same type.
 *
 *
This can be useful if a gazetteer contains name parts rather than full names, and you want to
 * combine those into single entities.
 *
 * @baleen.javadoc
 */
public class MergeAdjacent extends BaleenAnnotator {
  /**
   * A regular expression that sets what is allowed between entities for them to be considered
   * adjacent.
   *
   * @baleen.config \h*
   */
  public static final String PARAM_SEPARATOR = "separator";

  @ConfigurationParameter(name = PARAM_SEPARATOR, defaultValue = "\\h*")
  String separator;

  Pattern separatorPattern;

  /**
   * A list of the allowed entity types. Entities will still only be compared with entities of the
   * same type, but only entity types on this list (excluding subtypes) will be checked.
   *
   *
This may be ignored by some annotators which inherit from this class.
   *
   * @baleen.config
   */
  public static final String PARAM_TYPE = "types";

  @ConfigurationParameter(
      name = PARAM_TYPE,
      defaultValue = {})
  String[] types;

  List<Class<? extends Entity>> classTypes = new ArrayList<>();

  @Override
  public void doInitialize(UimaContext aContext) throws ResourceInitializationException {
    separatorPattern = Pattern.compile(separator);

    JCas jCas;
    try {
      jCas = JCasFactory.createJCas(TypeSystemSingleton.getTypeSystemDescriptionInstance());
    } catch (UIMAException e) {
      throw new ResourceInitializationException(e);
    }
    for (String type : types) {
      try {
        classTypes.add(TypeUtils.getEntityClass(type, jCas));
      } catch (BaleenException e) {
        getMonitor().error("Couldn't parse type - type will not be included", e);
      }
    }
    if (classTypes.isEmpty()) {
      getMonitor().warn("No valid types specified, no merging of entities will take place");
    }
  }

  @Override
  protected void doProcess(JCas jCas) throws AnalysisEngineProcessException {
    for (Class<? extends Entity> klass : classTypes) {
      processType(jCas, klass);
    }
  }

  private void processType(JCas jCas, Class<? extends Entity> type) {
    List<List<Entity>> mergeables = findAllEntitiesToMerge(jCas, type);

    for (List<Entity> mergeable : mergeables) {
      int begin = mergeable.get(0).getBegin();
      int end = mergeable.get(mergeable.size() - 1).getEnd();

      Double lowestConfidence =
          mergeable.stream()
              .min((e1, e2) -> Double.compare(e1.getConfidence(), e2.getConfidence()))
              .map(Entity::getConfidence)
              .orElse(Double.valueOf(0.0));

      // Build a new annotation
      try {
        Entity merged = type.getConstructor(JCas.class).newInstance(jCas);

        merged.setBegin(begin);
        merged.setEnd(end);

        merged.setValue(jCas.getDocumentText().substring(begin, end));
        merged.setConfidence(lowestConfidence);

        if (mergeAdditionalProperties(merged, type, mergeable)) {
          mergeWithNew(merged, mergeable);
        } else {
          merged = null;
        }
      } catch (Exception e) {
        getMonitor().error("Unable to merge entities", e);
      }
    }
  }

  private List<List<Entity>> findAllEntitiesToMerge(JCas jCas, Class<? extends Entity> type) {
    List<List<Entity>> mergeables = new LinkedList<>();
    Map<Entity, List<Entity>> toMerge = new HashMap<>();

    // Create a mapping of annotations to join together
    List<Entity> entities = filterEntities(JCasUtil.select(jCas, type), type);
    for (Entity current : entities) {
      List<Entity> following =
          filterEntities(JCasUtil.selectFollowing(jCas, type, current, 1), type);
      if (following.isEmpty()) {
        continue;
      }

      Entity next = following.get(0);

      String between = jCas.getDocumentText().substring(current.getEnd(), next.getBegin());

      // Check that the entities are only separated by whitespace,
      if (separatorPattern.matcher(between).matches() && shouldMerge(current, next)) {

        List<Entity> list;
        if (toMerge.containsKey(current)) {
          list = toMerge.get(current);
        } else {
          list = new LinkedList<>();
          list.add(current);
          toMerge.put(current, list);
          mergeables.add(list);
        }
        list.add(next);
        toMerge.put(next, list);
      }
    }
    return mergeables;
  }

  private List<Entity> filterEntities(
      Collection<? extends Entity> entities, Class<? extends Entity> type) {
    return entities.stream().filter(e -> e.getClass().equals(type)).collect(toList());
  }

  /** Returns true if e1 should be merged with e2 */
  public boolean shouldMerge(Entity e1, Entity e2) {
    return true;
  }

  /**
   * Merge additional properties from originalEntities into merged.
   *
   *
If this method returns false, then none of the entities will be merged
   */
  public boolean mergeAdditionalProperties(
      Entity merged, Class<? extends Entity> type, List<Entity> originalEntities) {
    // Do nothing here - this is intended to be overridden if additional merging is required
    return true;
  }

  @Override
  public AnalysisEngineAction getAction() {
    Set<Class<? extends Annotation>> annotatorTypes = new HashSet<>();
    annotatorTypes.addAll(classTypes);

    return new AnalysisEngineAction(annotatorTypes, annotatorTypes);
  }
}


text:
/*
 * entry_iterator_test.cpp
 *
 *  Created on: Oct 27, 2015
 *      Author: hendrik
 */

#include <boost/test/unit_test.hpp>
#include "dictionary/fsa/entry_iterator.h"
#include "dictionary/testing/temp_dictionary.h"

namespace keyvi {
namespace dictionary {
namespace fsa {

BOOST_AUTO_TEST_SUITE( EntryIteratorTests )

BOOST_AUTO_TEST_CASE( EmptyDictionary ) {

  // empty dictionary
  std::vector<std::string> test_data =
          { };
  testing::TempDictionary dictionary(test_data);
  automata_t f = dictionary.GetFsa();

  EntryIterator it(f);
  EntryIterator end_it = EntryIterator();

  BOOST_CHECK(end_it == it);
}

BOOST_AUTO_TEST_SUITE_END()

} /* namespace fsa */
} /* namespace dictionary */
} /* namespace keyvi */


text:
#include <iostream>
#include <fstream>
#include <vector>
#include <cassert>
#include <ctime>
#include <algorithm>
using namespace std;

int main()
{
	vector<int> data;
	int temp;

	// Read data.
	//
	ifstream filein("id.ascii");

	filein >> temp;
	while (filein)
	{
		data.push_back(temp);
		filein >> temp;
	}
	filein.close();

	assert(data.size() == 999);

	// Output data.
	//
	ofstream fileout("candidate/id");
	fileout.write(reinterpret_cast<char*>(&data[0]), sizeof(int)*data.size());
	fileout.close();

	// Output metadata.
	//
	ofstream meta("candidate/-part.txt");
	meta << "BEGIN HEADER" << endl;
	meta << "DataSet.Name = \"candidate\""<< endl;
	meta << "DataSet.Description = \"Generated by hand.\"" << endl;
	meta << "Number_of_columns = 1" << endl;
	meta << "Number_of_rows = " << data.size() << endl;
	meta << "Timestamp = " << static_cast<long unsigned int>(time(0)) << endl;
	meta << "END HEADER" << endl;
	meta << endl;
	meta << "Begin Column" << endl;
	meta << "name = \"id\"" << endl;
	meta << "data_type = \"int\"" << endl;
	meta << "minimum = " << *min_element(data.begin(), data.end()) << endl;
	meta << "maximum = " << *max_element(data.begin(), data.end()) << endl;
	meta << "End Column" << endl;
	meta.close();

	return 0;
}


text:
require 'spec_helper'

describe Bnet::Starcraft2::Match do
  describe '.all(profile)', vcr: {cassette_name: 'SC2 Matches for Naniwa Profile found'} do
    subject{described_class.all(profile)}
    let(:profile) { Bnet::Starcraft2::Profile.new(profile_id: 2210662, name: 'NaNiwa', region: 'eu')}

    it "returns a collection of matches for a given profile"  do
      expect(subject).to include(
        an_object_having_attributes( map: "Deadwing LE", match_type: "SOLO", decision: "WIN", speed: "FASTER", date: 1410222237),
        an_object_having_attributes( map: "Deadwing LE", match_type: "SOLO", decision: "WIN", speed: "FASTER", date: 1410221657),
        an_object_having_attributes( map: "King Sejong Station LE", match_type: "SOLO", decision: "WIN", speed: "FASTER", date: 1410220846)
      )
    end

  end
end


text:
<?php

namespace Sim\CoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Page
 *
 * @ORM\Table(name="pages")
 * @ORM\Entity(repositoryClass="Sim\CoreBundle\Entity\PageRepository")
 */
class Page
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     *
     * @var integer
     */
    private $id;

    /**
     * @ORM\Column(name="title", type="string")
     *
     * @var string
     */
    private $title;

    /**
     * @ORM\Column(name="slug", type="string", length=255)
     *
     * @var string
     */
    private $slug;

    /**
     * @ORM\Column(name="content", type="text")
     *
     * @var string
     */
    private $content;

    /**
     * @ORM\Column(name="visible", type="boolean")
     *
     * @var boolean
     */
    private $visible = TRUE;

    public function getId() {
        return $this->id;
    }

    public function setId($id) {
        $this->id = $id;
    }

    public function getTitle() {
        return $this->title;
    }

    public function setTitle($title) {
        $this->title = $title;
    }

    public function getSlug() {
        return $this->slug;
    }

    public function setSlug($slug) {
        $this->slug = $slug;
    }

    public function getContent() {
        return $this->content;
    }

    public function setContent($content) {
        $this->content = $content;
    }

    public function getVisible() {
        return $this->visible;
    }

    public function setVisible($visible) {
        $this->visible = $visible;
    }
}


text:
namespace Portable.IO
{
	using System;

	/// <summary>
	/// Static accessor for the current platform-specific implementation of <see cref="IFileSystem"/>.
	/// </summary>
	public static class FileSystem
	{
		private static readonly IFileSystem currentFileSystem = FileSystem.CreateFileSystem();

		/// <summary>
		/// Gets the current platform-specific implementation of <see cref="IFileSystem"/>.
		/// </summary>
		public static IFileSystem Current
		{
			get
			{
				if (currentFileSystem == null)
				{
					throw new NotImplementedException ("The platform-specific implementation of IFileSystem is missing.");
				}

				return currentFileSystem;
			}
		}

		private static IFileSystem CreateFileSystem()
		{
#if NET45
			return new DektopFileSystem();
#elif WINDOWS_PHONE
			return new WindowsPhoneFileSystem();
#elif ANDROID
			return new AndroidFileSystem();
#elif IOS
			return new IOSFileSystem();
#else
			return null;
#endif
		}
	}
}


text:
package net.oscartech.tesseract.node;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import net.oscartech.tesseract.node.pojo.NodeProposal;
import net.oscartech.tesseract.node.util.MarshallUtils;

import java.io.IOException;

/**
 * Created by tylaar on 15/4/27.
 */
@ChannelHandler.Sharable
public class NodeClientInboundHandler extends ChannelInboundHandlerAdapter {

    private NodeProposalBroker broker;

    public NodeClientInboundHandler(final NodeProposalBroker broker) {
        this.broker = broker;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("active read");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf m = (ByteBuf) msg;
        try {
            NodeProposal reply = MarshallUtils.fromStringToProposal(m.toString(CharsetUtil.UTF_8));
            System.out.println("CLIENT read reply" + reply.getProposalId() + " and type: " + reply.getType());
            /**
             * One thing that we shall always bear in mind is that, proposal broker
             * theoretically shall be state less. The code is shared by different
             * thread.
             */
            broker.handleAck(reply);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

}


text:
package com.structurizr;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.structurizr.documentation.Documentable;
import com.structurizr.documentation.Documentation;
import com.structurizr.model.*;
import com.structurizr.view.ViewSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.annotation.Nonnull;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;

/**
 * Represents a Structurizr workspace, which is a wrapper for a
 * software architecture model, views and documentation.
 */
public final class Workspace extends AbstractWorkspace implements Documentable {

    private static final Log log = LogFactory.getLog(Workspace.class);

    private Model model = createModel();
    private ViewSet viewSet;
    private Documentation documentation;

    Workspace() {
    }

    /**
     * Creates a new workspace.
     *
     * @param name          the name of the workspace
     * @param description   a short description
     */
    public Workspace(String name, String description) {
        super(name, description);

        model = createModel();
        viewSet = createViewSet();
        documentation = new Documentation();
    }

    /**
     * Gets the software architecture model.
     *
     * @return  a Model instance
     */
    public Model getModel() {
        return model;
    }

    void setModel(Model model) {
        this.model = model;
    }

    /**
     * Gets the set of views onto a software architecture model.
     *
     * @return  a ViewSet instance
     */
    public ViewSet getViews() {
        return viewSet;
    }

    void setViews(ViewSet viewSet) {
        this.viewSet = viewSet;
    }

    private Model createModel() {
        try {
            Constructor constructor = Model.class.getDeclaredConstructor();
            constructor.setAccessible(true);
            return (Model)constructor.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private ViewSet createViewSet() {
        try {
            Constructor constructor = ViewSet.class.getDeclaredConstructor(Model.class);
            constructor.setAccessible(true);
            return (ViewSet)constructor.newInstance(model);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Called when deserialising JSON, to re-create the object graph
     * based upon element/relationship IDs.
     */
    public void hydrate() {
        if (viewSet == null) {
            viewSet = createViewSet();
        }

        hydrateModel();
        hydrateViewSet();
    }

    private void hydrateModel() {
        try {
            Method hydrateMethod = Model.class.getDeclaredMethod("hydrate");
            hydrateMethod.setAccessible(true);
            hydrateMethod.invoke(model);
        } catch (InvocationTargetException ite) {
            if (ite.getCause() != null && ite.getCause() instanceof WorkspaceValidationException) {
                throw (WorkspaceValidationException)ite.getCause();
            } else {
                throw new RuntimeException(ite.getCause());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void hydrateViewSet() {
        try {
            Method hydrateMethod = ViewSet.class.getDeclaredMethod("hydrate", Model.class);
            hydrateMethod.setAccessible(true);
            hydrateMethod.invoke(viewSet, model);
        } catch (InvocationTargetException ite) {
            if (ite.getCause() != null && ite.getCause() instanceof WorkspaceValidationException) {
                throw (WorkspaceValidationException)ite.getCause();
            } else {
                throw new RuntimeException(ite.getCause());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Gets the documentation associated with this workspace.
     *
     * @return  a Documentation object
     */
    public Documentation getDocumentation() {
        return documentation;
    }

    /**
     * Sets the documentation associated with this workspace.
     *
     * @param documentation a Documentation object
     */
    void setDocumentation(@Nonnull Documentation documentation) {
        this.documentation = documentation;
    }

    /**
     * Determines whether this model is empty.
     *
     * @return  true if the model has no elements, views or documentation; false otherwise
     */
    @JsonIgnore
    public boolean isEmpty() {
        return model.isEmpty() && viewSet.isEmpty() && documentation.isEmpty();
    }

    /**
     * Counts and logs any warnings within the workspace (e.g. missing element descriptions).
     *
     * @return  the number of warnings
     */
    public int countAndLogWarnings() {
        final List<String> warnings = new LinkedList<>();

        // find elements with a missing description
        getModel().getElements().stream()
                .filter(e -> !(e instanceof SoftwareSystemInstance) && !(e instanceof ContainerInstance) && !(e instanceof DeploymentNode) && !(e instanceof InfrastructureNode))
                .filter(e -> e.getDescription() == null || e.getDescription().trim().length() == 0)
                .forEach(e -> warnings.add(e.getCanonicalName() + " is missing a description."));

        // find containers with a missing technology
        getModel().getElements().stream()
                .filter(e -> e instanceof Container)
                .map(e -> (Container)e)
                .filter(c -> c.getTechnology() == null || c.getTechnology().trim().length() == 0)
                .forEach(c -> warnings.add(c.getCanonicalName() + " is missing a technology."));

        // find components with a missing technology
        getModel().getElements().stream()
                .filter(e -> e instanceof Component)
                .map(e -> (Component)e)
                .filter(c -> c.getTechnology() == null || c.getTechnology().trim().length() == 0)
                .forEach(c -> warnings.add(c.getCanonicalName() + " is missing a technology."));

        // find component relationships with a missing description
        for (Relationship relationship : getModel().getRelationships()) {
            if (relationship.getSource() instanceof Component && relationship.getDestination() instanceof Component &&
                    relationship.getSource().getParent().equals(relationship.getDestination().getParent())) {
                // ignore component-component relationships inside the same container because these are
                // often identified using reflection and won't have a description
                // (i.e. let's not flood the user with warnings)
            } else {
                if (relationship.getDescription() == null || relationship.getDescription().trim().length() == 0) {
                    warnings.add("The relationship between " + relationship.getSource().getCanonicalName() + " and " + relationship.getDestination().getCanonicalName() + " is missing a description.");
                }
            }
        }

        // diagram keys have not been specified - this is only applicable to
        // workspaces created with the early versions of Structurizr for Java
        getViews().getSystemLandscapeViews().stream()
                .filter(v -> v.getKey() == null)
                .forEach(v -> warnings.add("System Landscape view \"" + v.getName() + "\": Missing key"));
        getViews().getSystemContextViews().stream()
                .filter(v -> v.getKey() == null)
                .forEach(v -> warnings.add("System Context view \"" + v.getName() + "\": Missing key"));
        getViews().getContainerViews().stream()
                .filter(v -> v.getKey() == null)
                .forEach(v -> warnings.add("Container view \"" + v.getName() + "\": Missing key"));
        getViews().getComponentViews().stream()
                .filter(v -> v.getKey() == null)
                .forEach(v -> warnings.add("Component view \"" + v.getName() + "\": Missing key"));
        getViews().getDynamicViews().stream()
                .filter(v -> v.getKey() == null)
                .forEach(v -> warnings.add("Dynamic view \"" + v.getName() + "\": Missing key"));
        getViews().getDeploymentViews().stream()
                .filter(v -> v.getKey() == null)
                .forEach(v -> warnings.add("Deployment view \"" + v.getName() + "\": Missing key"));

        warnings.forEach(log::warn);

        return warnings.size();
    }

    private String typeof(Element element) {
        if (element instanceof SoftwareSystem) {
            return "software system";
        } else {
            return element.getClass().getSimpleName().toLowerCase();
        }
    }

}


text:
<?php

namespace Exposure\Tests\ODM;

use Exposure\Model\DefaultProjectOwnerRights,
    Exposure\Model\ViewRights,
    Exposure\Model\ProjectRights,
    Sociable\ODM\ObjectDocumentMapper;

class DefaultProjectOwnerRightsODMTest extends \PHPUnit_Framework_TestCase {
    protected static $dm ;

    protected $defaultProjectOwnerRights;

    const LABEL = 'ZZZZZ';
    protected $projectRights;
    protected $viewRights;

    public static function setUpBeforeClass() {
        include EXPOSURE_ROOT.'/sys/config/config-test.inc.php' ; // initialises $config
        self::$dm = $config->getDocumentManager();
    }

    public function setUp() {
        self::cleanup();

        $this->defaultProjectOwnerRights = new DefaultProjectOwnerRights();
        $this->defaultProjectOwnerRights->setLabel(self::LABEL);
        $this->viewRights = new ViewRights();
        $this->defaultProjectOwnerRights->setViewRights($this->viewRights);
        $this->projectRights = new ProjectRights();
        $this->defaultProjectOwnerRights->setProjectRights($this->projectRights);
        $this->defaultProjectOwnerRights->validate();

        self::$dm->persist($this->defaultProjectOwnerRights);
        self::$dm->flush();

        self::$dm->clear();
    }

    public function testFound() {
        $this->defaultProjectOwnerRights = ObjectDocumentMapper::getByLabel(self::$dm,
            'Exposure\Model\DefaultProjectOwnerRights', self::LABEL);
        $this->assertNotNull($this->defaultProjectOwnerRights);
    }

    public function testIsValid() {
        $this->defaultProjectOwnerRights = ObjectDocumentMapper::getByLabel(self::$dm,
            'Exposure\Model\DefaultProjectOwnerRights', self::LABEL);
        $this->defaultProjectOwnerRights->validate();
    }

    public function testIsEqual() {
        $defaultProjectOwnerRights = ObjectDocumentMapper::getByLabel(self::$dm,
            'Exposure\Model\DefaultProjectOwnerRights', self::LABEL);
        $this->assertEquals($this->defaultProjectOwnerRights->getLabel(), $defaultProjectOwnerRights->getLabel());
        $this->assertEquals($this->projectRights, $this->defaultProjectOwnerRights->getProjectRights());
        $this->assertEquals($this->viewRights, $this->defaultProjectOwnerRights->getViewRights());
    }

    public function testRemove() {
        $this->defaultProjectOwnerRights = ObjectDocumentMapper::getByLabel(self::$dm,
            'Exposure\Model\DefaultProjectOwnerRights', self::LABEL);
        self::$dm->remove($this->defaultProjectOwnerRights);
        self::$dm->flush();

        $this->assertNull(ObjectDocumentMapper::getByLabel(self::$dm,
            'Exposure\Model\DefaultProjectOwnerRights', self::LABEL));
    }

    public function testDuplicate() {
        $this->defaultProjectOwnerRights = new DefaultProjectOwnerRights();
        $this->defaultProjectOwnerRights->setLabel(self::LABEL);
        $this->defaultProjectOwnerRights->setViewRights($this->viewRights);
        $this->defaultProjectOwnerRights->setProjectRights($this->projectRights);
        $this->defaultProjectOwnerRights->validate();

        self::$dm->persist($this->defaultProjectOwnerRights);

        $this->setExpectedException('MongoCursorException');
        self::$dm->flush();
    }

    public function tearDown() {
        self::cleanup();
    }

    public static function tearDownAfterClass() {
        self::cleanup();
    }

    public static function cleanUp() {
        self::$dm->clear();
        $defaultProjectOwnerRights = ObjectDocumentMapper::getByLabel(self::$dm,
            'Exposure\Model\DefaultProjectOwnerRights', self::LABEL);
        if(!is_null($defaultProjectOwnerRights)) {
            self::$dm->remove($defaultProjectOwnerRights);
            self::$dm->flush();
        }
    }

}

?>


text:
<manifest package="com.android.log.lisa"
          xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools">

  <application/>
</manifest>


text:
d3.sv_table = function(){
  //default values
  var column_names = ['Name']

  function table(selection){
    var data = selection.data()

    // Data Join
    var all_rows = selection.selectAll('tbody')
                            .data(data);

    // Create a row for each school
    var rows = all_rows.selectAll('tr')
                       .data(function(d) {return d})

        rows.enter()
            .append('tr')
            .classed('data_elem', true)
            .selectAll('td')
            .data(function(d){
              var outs = [];
              for (var i=0; i<column_names.length; i++){
              outs[i]=d[column_names[i]]
              }
              return outs;
            })
            .enter().append('td')
            .text(function(d,i){ return d})
            }

  // getter-setters

  table.column_names = function(value){
        if(!arguments.length) return column_names;
        column_names = value;
        return table;
    }
 return table;
}