text:
// TODO:
	// .pineappleconfig file
	// Base directory
	// File indexing for public folders.

"use strict";
const OF = require("./ObjectFormatter");
const Toolbox = require("./Toolbox");
const CookieChef = require("./CookieChef");
const HTTP_CODES = require("./HTTP_Codes");
const MIME_TYPES = require("./ContentTypes");

const http = require("http");
const https = require("https");
const fs = require("fs");
const querystring = require("querystring");
const url = require("url");
const __PATH__ = require("path");
const vm = require("vm");

const backend = require("./backend");
const Controller = require("./Controller");

const _Events = ["start","request","response","error","server_error"];
const RespDefs = {
	Status: {types:["Number","Function"],def:null},
	Content: {types:["String","Function"],def:""},
	Headers: {types:["Object","Function"],def:{}},
	Encoding: {types:["String"],def:null},
	Backend:{types:["Object","Function"],def:{}},
	Serve:{types:["String","Function","Number"],def:"",required:false},
	Controller:{types:["Function"],def:(c)=>{}},
	Message:{types:["String","Function"],def:null}
};
const PageDefs = {
	CaseSensitive: {types:["Boolean"],def:false},
	Accepts:{types:["Array"],def:["*"]},
	Response:{types:["Function","Object"],def:()=>{return {};}},
	Path:{types:["String"],def:"/"},
	Serve:{types:["String","Number"],def:"",required:false},
	Controller:{types:["Function"],def:c=>{}},
	Realm:{types:["String"],def:"",required:false},
	Template:{types:["Boolean"],def:false}
};
const RequestResponseDefs = {
	Headers:{
		types:["Object"],
		def:{
			"Content-Type":"text/html"
		}
	},
	Message:{
		types:["String"],
		def:"OK"
	},
	Status:{
		types:["Number"],
		def:200
	},
	Response:{
		types:["String","Buffer"],
		def:""
	},
	Encoding:{
		types:["String","Function"],
		def:"utf8"
	}
};
const Indexes = [
	"index.html",
	"index.htm",
	"home.html",
	"home.htm"
];
module.exports = class{
	constructor(ops){
		if(!OF.isObject(ops)){
			ops = {protocol:"http"};
		}
		if(typeof ops.protocol!=="string"){
			ops.protocol = "http";
		}
		if(ops.protocol.toUpperCase()=="HTTPS"){
			this._protocol = https;
			delete ops.protocol;
			this._options = [ops];
			this._isHTTPS = true;
		}else{
			this._protocol = http;
			this._options = [];
			this._isHTTPS = false;
		}
		this.version = require("../package.json").version;
		this.ContentTypes=MIME_TYPES;
		this.runningServer=[];
		this.runBackend = ["","html","json","xml","txt","htm","yaml","yml","js","css"];
		this.GlobalControllers = [];
		this.HTTP_CODES=HTTP_CODES;
		this.pages = [
			...(()=>{
				let fea = [];
				for(let p in this.HTTP_CODES){
					fea.push(OF.format({
						Path:("#"+p),
						Response:{
							Backend:{
								code:p,
								message:this.HTTP_CODES[p],
								version:this.version
							},
							Status:parseInt(p),
							Serve:__PATH__.join(__dirname,"Pages","Error.html")
						},
						Template:true
					},PageDefs));
				}
				return fea;
			})()
		];
		this.events = {
			pages:[],
			HTTP_CODES:[]
		};
		for(let i=0;i<_Events.length;i++){
			this.events[_Events[i]]=[];
		}
		this.aliases = [];
		this.SuperURLs = [];
		this.realms={};
		this.config = {
			port:process.env.PORT||80,
			https_port:443,
			enable_HEAD:true,
			enable_OPTIONS:true,
			auto_https:true,
			templating:false,
			host:"127.0.0.1"
		};
	}
	GET_EXTENSION(f){
		return f.split("/").pop().split("\\").pop().split(".").pop();
	}
	GET_TYPE(f){
		if(typeof f!=="string"||f.length==0){return "text/plain";}
		f=Toolbox.GetValue(this.GET_EXTENSION(f),this.ContentTypes);
		return f==null?"text/html":f;
	}
	on(evt,callback,third,fourth){
		let isGlobalController = typeof evt=="function"&&typeof callback=="undefined";
		if(isGlobalController){
			this.GlobalControllers.push(evt);
			return this;
		}
		if(typeof evt!=="string"){return false;}
		let isEvent = typeof callback=="function"&&this.events.hasOwnProperty(evt)&&_Events.indexOf(evt)>-1;
		let isPage = evt.charAt(0)=="/"&&typeof callback=="object"&&OF.isObject(callback);
		let isErrorPage = evt.charAt(0)=="#"&&typeof callback=="object"&&!isNaN(evt.substr(1,evt.length))&&evt.length>1;
		let isPageEvent = typeof callback=="function"&&evt.charAt(0)=="/";
		let isErrorEvent = typeof callback=="function"&&evt.charAt(0)=="#"&&!isNaN(evt.substr(1,evt.length))&&evt.length>1;
		let isAlias = (evt.charAt(0)=="/")&&typeof callback=="string";
		let isMIMEType = evt.charAt(0)=="."&&evt.length>1&&typeof callback=="string"&&callback.split("/").filter(v=>v.length>0).length>1;
		let isSuperURLPage = evt.charAt(0)=="/"&&typeof callback=="object"&&OF.isObject(callback)&&typeof third=="object"&&OF.isObject(third);
		let isBackendRunner = evt.charAt(0)=="."&&evt.length>1&&typeof callback=="boolean";
		let isUserCredentials = evt.charAt(0)=="|"&&evt.length>1&&typeof callback=="string"&&typeof third=="string";
		if(!isEvent&&!isPage&&!isErrorPage&&!isPageEvent&&!isErrorEvent&&!isAlias&&!isMIMEType&&!isSuperURLPage&&!isBackendRunner&&!isGlobalController&&!isUserCredentials){return false;}
		if(isEvent){
			this.events[evt].push(callback);
		}else if(isSuperURLPage){
			if(Object.keys(callback).length>0){
				let sup = OF.format(third,PageDefs);
				delete sup.Path;
				this.SuperURLs.push([evt,callback,sup]);
			}else{
				return this.on(evt,third);
			}
		}else if(isPage||isErrorPage){
			var page = OF.format(callback,PageDefs);
			page.Path = evt;
			this.pages.push(page);
		}else if(isPageEvent){
			let PECS = false;
			if(typeof third=="boolean"){
				PECS = third;
			}
			this.events.pages.push({
				Path:evt,
				callback:callback,
				CaseSensitive:PECS
			});
		}else if(isErrorEvent){
			this.events.HTTP_CODES.push({
				code:parseInt(evt.substr(1,evt.length)),
				callback:callback
			});
		}else if(isAlias){
			let SC = 301;
			let ACS = false;
			if(typeof third=="boolean"){
				ACS = third;
			}
			if(typeof fourth=="number"&&(fourth==302||fourth==301)){
				SC = fourth;
			}
			this.aliases.push([evt,callback,ACS,SC]);
		}else if(isMIMEType){
			this.ContentTypes[evt.slice(1)]=callback;
		}else if(isBackendRunner){
			if(callback&&this.runBackend.indexOf(evt)<=-1){
				this.runBackend.push(evt.slice(1).toLowerCase());
			}else if(this.runBackend.indexOf(evt)>-1&&!callback){
				this.runBackend.splice(this.runBackend.indexOf(evt),1);
			}
		}else if(isUserCredentials){
			let realm = evt.slice(1);
			if(!Toolbox.Has(realm,this.realms)){
				this.realms[realm]=[];
			}
			realm = Toolbox.GetName(realm,this.realms);
			for(let i=0;i<this.realms[realm].length;i++){
				if(this.realms[realm][i][0].toLowerCase()==callback.toLowerCase()){
					this.realms[realm][i][1]=third;
					return this;
				}
			}
			this.realms[realm].push([callback.toLowerCase(),third]);
		}
		return this;
	}
	set(_var,_val){
		if(typeof _var=="undefined"||typeof _val=="undefined"){return false;}
		if(this.config.hasOwnProperty(_var)&&typeof this.config[_var]==typeof _val){
			this.config[_var]=_val;
		}
		return this;
	}
	getPage(path,Method,__Data,evt){
		if(typeof __Data=="undefined"){__Data = {};}
		path = Toolbox.ActualPath(path);
		let __Page = null;
		let __PageExists = false;
		for(let i=0;i<this.pages.length;i++){
			if(((new RegExp("^"+this.pages[i].Path+"$").test(path)||((!this.pages[i].CaseSensitive)&&new RegExp("^"+this.pages[i].Path+"$","i").test(path)))||(path.charAt(0)=="#"&&path==this.pages[i].Path))){
				if(this.pages[i].Accepts.indexOf(Method)>-1||this.pages[i].Accepts.indexOf("*")>-1){
					__Page = this.pages[i];
					break;
				}else{
					__PageExists = true;
				}
			}
		}
		if(__Page==null){
			for(let i=0;i<this.SuperURLs.length;i++){
				let flags = "";
				if(!this.SuperURLs[i][2].CaseSensitive){
					flags += "i";
				}
				let sureg = new RegExp(this.SuperURLs[i][0],flags);
				if(sureg.test(path)){
					if(this.SuperURLs[i][2].Accepts.indexOf(Method)||this.SuperURLs[i][2].Accepts.indexOf("*")>-1){
						__Page = this.SuperURLs[i][2];
						let matches = sureg.exec(path);
						let args = Object.assign({},this.SuperURLs[i][1]);
						for(let p in args){
							if(args.hasOwnProperty(p)){
								/*for(let m=0;m<matches.length;m++){
									args[p] = String(args[p]).replace(new RegExp("\{\{[\\x"+m.toString().charCodeAt(0).toString(16)+"]\}\}","g"),typeof matches[m]!=="undefined"?matches[m]:"");
								}*/
								args[p] = String(args[p]).replace(/\{\{([0-9]+)\}\}/gi,(f,o)=>{
									if(typeof matches[parseInt(o)]=="string"){
										return matches[parseInt(o)];
									}else{
										return "";
									}
								});
							}
						}
						args = Object.assign(__Data,args);
						return [__Page,args];
					}else{
						__PageExists = true;
					}
				}
			}
		}
		if(__Page==null){
			for(let i=0;i<this.aliases.length;i++){
				if((!this.aliases[i][2]&&new RegExp("^"+this.aliases[i][0]+"$","i").test(path))||(this.aliases[i][2]&&new RegExp("^"+this.aliases[i][0]+"$").test(path))||(path.charAt(0)=="#"&&path==this.aliases[i][0])){
					let matches = path.match(this.aliases[i][0]);
					let FPU = this.aliases[i][1].replace(/\{\{([0-9]){1,}\}\}/g,(F,N)=>{
						if(typeof matches[parseInt(N)]!=="undefined"){
							return matches[parseInt(N)];
						}
						return "";
					});
					let pFPU = url.parse(FPU);
					let isURL = pFPU.protocol!==null&&pFPU.host!==null&&pFPU.host.split(".").filter(v=>v.length>0).length>1;
					if(isURL){
						let frh = [this.aliases[i][3]];
						if(this.HTTP_CODES.hasOwnProperty(frh[0].toString())){
							frh.push(this.HTTP_CODES[frh[0].toString()]);
						}
						frh.push({
							"Location":FPU
						});
						return frh;
					}
					let AFPU = url.parse(FPU,true);
					return this.getPage(AFPU.pathname,Method,Object.assign(__Data,AFPU.query));
				}
			}
		}
		if(__Page==null){
			// #404 || #405
			if(__PageExists){
				return this.getPage("#405",Method,__Data,"#405");
			}else{
				return this.getPage("#404",Method,__Data,"#404");
			}
		}
		__Page = OF.format(__Page,PageDefs);
		let ToReturn = [__Page,__Data];
		if(typeof evt=="string"){
			ToReturn.push(evt);
		}
		return ToReturn;
	}
	runEvent(evt,args){
		if(typeof args=="undefined"){args = [];}
		if(typeof evt!=="string"&&evt!=="pages"&&evt!=="HTTP_CODES"){return false;}
		let _PageEvent = evt.charAt(0)=="/";
		let _ErrorEvent = evt.charAt(0)=="#"&&!isNaN(evt.substr(1))&&evt.length>1;
		let _Event = this.events.hasOwnProperty(evt);
		if(!_PageEvent&&!_ErrorEvent&&!_Event){return false;}
		if(_PageEvent){
			for(let i=0;i<this.events.pages.length;i++){
				let PRE = new RegExp("^"+this.events.pages[i].Path+"$","i");
				if(this.events.pages[i].CaseSensitive){
					PRE = new RegExp("^"+this.events.pages[i].Path+"$");
				}
				if(PRE.test(evt)){
					this.events.pages[i].callback.apply(this,args);
				}
			}
		}else if(_ErrorEvent){
			let EC = parseInt(evt.substr(1));
			for(let i=0;i<this.events.HTTP_CODES.length;i++){
				if(this.events.HTTP_CODES[i].code==EC){
					this.events.HTTP_CODES[i].callback.apply(this,args);
				}
			}
			this.runEvent("error",args);
		}else if(_Event){
			for(let i=0;i<this.events[evt].length;i++){
				this.events[evt][i].apply(this,args);
			}
		}
	}
	request(_URL,_Data,_Method,_RequestHeaders,isUser,_Request){
		if(typeof _URL=="undefined"){_URL="/";}
		if(typeof _Data=="undefined"){_Data={};}
		if(typeof _Method=="undefined"){_Method="GET";}
		if(typeof _RequestHeaders=="undefined"){_RequestHeaders={};}
		if(typeof isUser!=="boolean"){isUser=true;}
		if(typeof _Request=="undefined"){_Request={};}
		let _Response = {};
		let URLAnalysis = url.parse(_URL,true);
		let _Path = Toolbox.ActualPath(URLAnalysis.pathname);
		var HTTP_Controller;
		if(isUser){
			this.runEvent(_Path,[_URL,_Data,_Method,_Request]);
		}
		let _Page = {};
		if(_URL.charAt(0)=="#"&&parseInt(_URL.slice(1))!==NaN){
			_Page = this.getPage(_URL,_Method,_Data);
		}else{
			_Page = this.getPage(_Path,_Method,URLAnalysis.query);
		}
		if(typeof _Page[2]=="string"&&isUser){
			this.runEvent(_Page[2],[parseInt(_Page[2].slice(1)),_Request]);
		}
		if(_Page[0]==null){
			return Object.assign({Status:500},this.request("#500",_Data,_Method,_RequestHeaders,false,_Request));
		}else{
			if(_Page[0].hasOwnProperty("Realm")&&_Page[0].Realm.length>0&&Toolbox.Has(_Page[0].Realm,this.realms)){
				let unauthorized = true;
				let s_realm = Toolbox.GetName(_Page[0].Realm,this.realms);
				let AuthorizationCredentials = Toolbox.GetValue("Authorization",_RequestHeaders);
				if(AuthorizationCredentials!==null){
					if(Array.isArray(AuthorizationCredentials)){
						AuthorizationCredentials = AuthorizationCredentials[0];
					}
					AuthorizationCredentials = AuthorizationCredentials.trim().split(/[\s]{1,}/);
					if(AuthorizationCredentials.length>1&&AuthorizationCredentials[0].trim().toUpperCase()=="BASIC"){
						let creds = new Buffer(AuthorizationCredentials[1],"base64").toString("ascii").split(":");
						if(creds.length==2){
							let un = creds[0];
							let pw = creds[1];
							for(let i=0;i<this.realms[s_realm].length;i++){
								if(this.realms[s_realm][i][0].toLowerCase()===un.toLowerCase()&&this.realms[s_realm][i][1]===pw){
									unauthorized = false;
								}
							}
						}
					}
				}
				if(unauthorized){
					let AuReRe = this.request("#401",_Data,_Method,_RequestHeaders,false,_Request);
					this.runEvent("#401",[_URL,_Data,_Method,_Request,401]);
					AuReRe.Headers["WWW-Authenticate"] = "Basic realm=\""+s_realm+"\"";
					return AuReRe;
				}
			}
			if(typeof _Page[0]=="number"&&(typeof _Page[1]=="object"||(typeof _Page[1]=="string"&&typeof _Page[2]=="object"))){
				_Response.Status = _Page[0];
				if(typeof _Page[1]=="object"){
					_Response.Headers = _Page[1];
				}else{
					_Response.Message = _Page[1];
					_Response.Headers = _Page[2];
				}
			}else{
				var GET = _Page[1];
				var __COOKIES__ = {};
				for(let h in _RequestHeaders){
					if(_RequestHeaders.hasOwnProperty(h)&&h.toUpperCase()=="COOKIE"){
						__COOKIES__ = CookieChef.eat(_RequestHeaders[h]);
					}
				}
				let _Protocol = (()=>{
					try{
						let tfp = vm.runInNewContext("_RQST.connection.encrypted",{
							_RQST:_Request
						});
						if(typeof tfp!=="undefined"){
							return "https";
						}
						return "http";
					}catch(e){
						return "http";
					}
				})()+"://";
				let _Host = Toolbox.GetValue("Host",_RequestHeaders);
				if(_Host==null){
					_Host = "127.0.0.1";
				}
				let FULL_URL = _Protocol+Toolbox.ActualPath(_Host+"/"+_URL);
				HTTP_Controller = new Controller(_Path,GET,_Data,_Method,__COOKIES__,_RequestHeaders,FULL_URL,_Request);
				let resp = {};
				let parse_args = [HTTP_Controller];
				if(typeof _Page[0].Response=="function"){
					resp = _Page[0].Response(...parse_args);
				}else if(typeof _Page[0].Response=="object"){
					resp = _Page[0].Response;
				}
				resp = OF.format(resp,RespDefs);
				let StatusCode = resp.Status;
				if(typeof StatusCode=="function"){
					StatusCode = StatusCode(...parse_args);
				}
				if(typeof StatusCode=="string"){
					StatusCode = parseInt(StatusCode);
				}
				if(typeof StatusCode=="number"&&StatusCode!==NaN){
					HTTP_Controller.Status(StatusCode);
				}
				StatusCode=null;
				let Headers = resp.Headers;
				if(typeof Headers=="function"){
					Headers = Headers(...parse_args);
				}
				if(typeof Headers=="object"&&Headers!==null&&Headers.constructor.name=="Object"){
					HTTP_Controller.Header(Headers);
				}
				Headers=null;
				let Content = resp.Content;
				if(typeof Content=="function"){
					Content = Content(...parse_args);
				}
				if(typeof Content!=="undefined"){
					HTTP_Controller.Write(Content);
				}
				Content = null;
				let Encoding = resp.Encoding;
				if(typeof Encoding=="function"){
					Encoding = Encoding(...parse_args);
				}
				if(typeof Encoding=="string"){
					HTTP_Controller.Encoding(Encoding);
				}
				Encoding = null;
				let Message = resp.Message;
				if(typeof Message=="function"){
					Message = Message(...parse_args);
				}
				if(typeof Message=="string"){
					HTTP_Controller.Message(Message);
				}
				Message = null;
				let __Backend = resp.Backend;
				if(typeof __Backend=="function"){
					__Backend = __Backend(HTTP_Controller);
				}
				if(typeof __Backend=="object"&&__Backend!==null&&__Backend.constructor.name=="Object"){
					for(let p in __Backend){
						if(__Backend.hasOwnProperty(p)){
							HTTP_Controller.Backend(p,__Backend[p]);
						}
					}
				}
				__Backend = null;
				_Page[0].Controller(...parse_args);
				resp.Controller(...parse_args);
				for(let i=0;i<this.GlobalControllers.length;i++){
					this.GlobalControllers[i].apply(this,parse_args);
				}
				let serve = HTTP_Controller.Serve();
				let serve_Response = {};
				if(resp.hasOwnProperty("Serve")||_Page[0].hasOwnProperty("Serve")){
					serve = resp.hasOwnProperty("Serve")?resp.Serve:_Page[0].Serve;
					if(typeof serve=="function"){
						serve = serve(...parse_args);
					}
				}
				let serve_found = false;
				if(typeof serve=="number"&&this.HTTP_CODES.hasOwnProperty(serve.toString())){
					serve_Response = this.request("#"+serve,_Data,_Method,_RequestHeaders,false,_Request);
					serve_found = true;
				}
				let ServeContent = "";
				serve = String(serve);
				if(serve.length>0&&fs.existsSync(serve)&&fs.fstatSync(fs.openSync(serve,"r")).isFile()&&!serve_found){
					if(Object.keys(HTTP_Controller.Backend()).length>0||this.runBackend.indexOf(this.GET_EXTENSION(serve).toLowerCase())>-1){
						let BI = {
							__dirname:__PATH__.parse(serve).dir,
							Controller:HTTP_Controller
						};
						let t = new backend(fs.readFileSync(serve).toString(),BI,(this.config.templating||_Page[0].Template));
						ServeContent = t.render(HTTP_Controller.Backend());
					}else{
						HTTP_Controller.Encoding("base64");
						ServeContent = new Buffer(fs.readFileSync(serve)).toString("base64");
					}
					HTTP_Controller.Header({
						"Content-Type":this.GET_TYPE(serve)
					},true);
				}
				HTTP_Controller.Write(ServeContent);
				HTTP_Controller.Header({
					"Content-Type":"text/html"
				},true);
				let _Setted_Cookies = HTTP_Controller.CookiesToSet;
				let _Final_Cookies = [...(()=>{
					let ExistingHeader = HTTP_Controller.Header("Set-Cookie");
					if(ExistingHeader!==null){
						if(typeof ExistingHeader=="string"){
							return[ExistingHeader];
						}else if(Array.isArray(ExistingHeader)){
							return ExistingHeader;
						}
					}
					return[];
				})()];
				for(let i=0;i<_Setted_Cookies.length;i++){
					let CookedCookie = CookieChef.cook(_Setted_Cookies[i]);
					if(CookedCookie!==null&&typeof CookedCookie=="string"&&CookedCookie.length>0){
						_Final_Cookies.push(CookedCookie);
					}
				}
				if(_Final_Cookies.length>0){
					HTTP_Controller.Header({
						"Set-Cookie":_Final_Cookies
					});
				}
				if(isUser){
					for(let i=0;i<HTTP_Controller.Trigger().length;i++){
						let la = [];
						if(HTTP_Controller.Trigger()[i].charAt(0)=="#"){
							la.push(parseInt(HTTP_Controller.Trigger()[i].slice(1)));
						}
						this.runEvent(HTTP_Controller.Trigger()[i],[_URL,_Data,_Method,_Request]);
					}
				}
				_Response.Status = HTTP_Controller.Status();
				_Response.Headers = HTTP_Controller.Headers;
				_Response.Response = HTTP_Controller.Content;
				_Response.Message = HTTP_Controller.Message()==null?(typeof this.HTTP_CODES[HTTP_Controller.Status().toString()]=="string"?this.HTTP_CODES[HTTP_Controller.Status().toString()]:"OK"):HTTP_Controller.Message();
				_Response.Encoding = HTTP_Controller.Encoding();
				_Response = OF.SuperMerge(serve_Response,_Response,{
					Merge:["Response"],
					Prioritize:["Status","Message"]
				});
			}
		}
		return OF.format(_Response,RequestResponseDefs);
	}
	public(p,a,index){
		if(typeof a=="undefined"){a = "";}
		if(fs.existsSync(p)){
			let _Stat = fs.statSync(p);
			if(_Stat.isDirectory()){
				let dp = Toolbox.ActualPath(p);
				let ep = typeof a=="string"&&a.length>0?a:__PATH__.parse(p).name;
				if(ep.charAt(0)!=="/"){
					ep = "/"+ep;
				}
				ep = Toolbox.ActualPath(ep);
				if(ep.length>0){
					this.on(ep+"(.*)?",{f:"{{1}}"},{
						Controller:(c)=>{
							if(c.GET.hasOwnProperty("f")&&c.GET.f.length>0){
								let fr = Toolbox.ActualPath(dp+"/"+c.GET.f.toString());
								if(Toolbox.ActualPath(c.GET.f.toString())=="/"||Toolbox.ActualPath(c.GET.f.toString()).length<=0){
									c.Serve(403);
									c.Trigger("#403");
								}else if(fs.existsSync(fr)){
									let rrs = fs.statSync(fr);
									if(rrs.isFile()){
										c.Serve(fr);
									}else{
										c.Serve(403);
										c.Trigger("#403");
									}
								}else{
									c.Serve(404);
									c.Trigger("#404");
								}
							}else{
								let ExistingIndex = Indexes.map((v)=>fs.existsSync(__PATH__.join(p,v)));
								if(ExistingIndex.indexOf(true)>-1){
									ExistingIndex = Indexes[ExistingIndex.indexOf(true)];
								}else{
									ExistingIndex = "";
								}
								if(typeof index=="string"&&fs.existsSync(index)){
									c.Serve(index);
								}else if(ExistingIndex.length>0){
									c.Serve(__PATH__.join(p,ExistingIndex));
								}else{
									c.Serve(403);
									c.Trigger("#403");
								}
							}
						}
					});
				}
			}else if(_Stat.isFile()){
				let fn = typeof a=="string"&&a.length>0?a:__PATH__.parse(p).base;
				if(fn.charAt(0)!=="/"){
					fn = "/"+fn;
				}
				this.on(fn,{
					Serve:p
				});
			}
		}
		return this;
	}
	server(){
		let request_callback = (request,response)=>{
			if(this._isHTTPS&&this.config.auto_https&&(typeof request.connection.encrypted=="undefined"||(typeof request.connection.encrypted=="boolean"&&request.connection.encrypted==false))){
				response.writeHead(301,HTTP_CODES["301"],{
					"Location":"https://"+Toolbox.ActualPath(Toolbox.GetValue("Host",request.headers)+"/"+request.url)
				});
				response.end();
			}
			if(this.config.enable_OPTIONS&&request.method=="OPTIONS"){
				let _All_Methods = ["GET","HEAD","POST","PUT","DELETE","CONNECT","OPTIONS","TRACE","PATCH"];
				let _Supported_Methods = [];
				for(let i=0;i<this.pages.length;i++){
					if(this.pages[i].Path.charAt(0)!=="#"){
						if(this.pages[i].Accepts.indexOf("*")>-1){
							_Supported_Methods = _Supported_Methods.concat(_All_Methods);
						}
						_Supported_Methods = _Supported_Methods.concat(this.pages[i].Accepts);
					}
				}
				_Supported_Methods = _Supported_Methods.filter((v,i,a)=>{
					return a.indexOf(v)===i&&typeof v=="string"&&v!=="*";
				}).join(", ");
				response.writeHead(200,HTTP_CODES["200"],{
					"Allow":_Supported_Methods
				});
				response.end();
			}
			this.runEvent("request",[request]);
			let data = "";
			request.on("data",chunk=>{
				data+=chunk;
			}).on("end",()=>{
				data = querystring.parse(data);
				let $Response = this.request(request.url,data,request.method,request.headers,true,request);
				response.writeHead($Response.Status,$Response.Message,$Response.Headers);
				if($Response.Response.length>0&&((!(this.config.enable_HEAD))||(this.config.enable_HEAD&&request.method.toUpperCase()!=="HEAD"))){
					response.end($Response.Response,$Response.Encoding);
				}else{
					response.end();
				}
				this.runEvent("response",[response,request.url,data,request.method,request]);
			});
		};
		let server = [http.createServer(request_callback)];
		if(this._isHTTPS){
			server.push(https.createServer(...this._options,request_callback));
		}
		for(let s=0;s<server.length;s++){
			server[s].on("error",e=>this.runEvent("server_error",[e]));
		}
		return server;
	}
	start(){
		this.runningServer = this.server();
		this.runningServer[0].listen(this.config.port,this.config.host);
		let ports = [this.config.port];
		if(typeof this.runningServer[1]!=="undefined"){
			this.runningServer[1].listen(this.config.https_port,this.config.port);
			ports.push(this.config.https_port);
		}
		this.runEvent("start",[this.runningServer,ports]);
		return this.runningServer;
	}
	stop(){
		if(typeof this.runningServer[0]!=="undefined"){
			this.runningServer[0].close();
		}
		if(typeof this.runningServer[1]!=="undefined"){
			this.runningServer[1].close();
		}
		this.runningServer = [];
		return this;
	}
}


text:
var concat = require('broccoli-concat');
var uglifyJavaScript = require('broccoli-uglify-js');
var mergeTrees = require('broccoli-merge-trees')

var src = 'src';

var js = concat(src, {
    inputFiles: [
      '**/*.js'
    ],
    outputFile: '/photosphere.js'
});

var min = uglifyJavaScript(
  concat(src, {
    inputFiles: [
      '**/*.js'
    ],
    outputFile: '/photosphere.min.js'
  })
);

var tree = mergeTrees([js, min]);

module.exports = tree;

redpajama_set_name: RedPajamaGithub


text:
import unittest
from gyun.misc.json_tool import json_dump, json_load

class JsonToolTestCase(unittest.TestCase):

    def test_json_dump_dict(self):
        obj = {'1': 1, 'str': 'string', 'none': None}
        expected = '{"1":1,"none":null,"str":"string"}'
        self.assertEqual(json_dump(obj), expected)

    def test_json_dump_invalid_obj(self):
        obj = {unittest: 'invalid key'}
        expected = None
        self.assertEqual(json_dump(obj), expected)

    def test_json_dump_list(self):
        obj = [1, 4, '3']
        expected = '[1,4,"3"]'
        self.assertEqual(json_dump(obj), expected)

    def test_json_load_list(self):
        string = '{"int":1,"none":null,"str":"string"}'
        expected = {'int': 1, 'str': 'string', 'none': None}
        self.assertEqual(json_load(string), expected)

    def test_json_load_string(self):
        string = '{"int":1,"none":null,"str":"string"}'
        expected = {'int': 1, 'str': 'string', 'none': None}
        self.assertEqual(json_load(string), expected)

    def test_json_load_invalid_string(self):
        string = '{"int":1,:null,"str":"string"}'
        expected = None
        self.assertEqual(json_load(string), expected)


text:
@echo off
echo Preparing PostgreSQL
echo PostgreSQL home: %%POSTGRESQL%=%POSTGRESQL%
echo Data is stored in: %%PGDATA%%=%PGDATA%
echo If the folder doesn't exist, a new db will be created there
echo Alternative, mount a external folder to %PGDATA%, to store the data outside the container
echo Like turbo run --mount C:\my-data-folder=%PGDATA%
echo Default username and password are: postgres postgres
echo If you don't want to start the db, but have a command line
echo Use the --startup-file=cmd option
echo PostgreSQL uses default port: 5432

if not exist %PGDATA% (
  mkdir %PGDATA%
)

set LANG=en

cd %TEMP%

if not exist %PGDATA%\PG_VERSION (
  echo postgres>tmp-pwd.file
  initdb --locale=en-us -U postgres -A password -E utf8 --pwfile=tmp-pwd.file
  del tmp-pwd.file
)
cd %PGDATA%

echo Starting DB now

postgres -D %PGDATA%


text:
package com.osvr.android.gles2sample;

import com.osvr.common.jni.JNIBridge;

// Wrapper for native library

public class MainActivityJNILib {

    private static boolean librariesLoaded = false;

    static {
        JNIBridge.enableCamera();
        JNIBridge.loadLibraries();
        System.loadLibrary("native-activity");
    }
    /**
     * @param width the current view width
     * @param height the current view height
     */
    public static native void initGraphics(int width, int height);
    public static native void initOSVR();
    public static native void step();
    public static native void stop();
}


text:
require 'spec_helper'

describe Prettyp::Formatter::XML::Xmllint do

  subject { described_class.new }

  it 'can be used' do
    expect(subject.check_requirement).to be true
  end

  context 'format' do

    let(:format) { subject.format(input, :xml) }

    context 'invalid input' do
      let(:input) { 'abcd' }
      it 'raises a format error' do
        expect{ format }.to raise_error Prettyp::Formatter::FormatError
      end
    end

    context 'valid input' do
      let(:input) do
%|<?xml version="1.0" encoding="UTF-8"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>|
      end

      it 'returns a formatted document' do
        expect(format.split("\n").size).to be >= 2
      end
    end

  end
end


text:
Fitting.data_server
===================

.. toctree::
   :maxdepth: 2
   :caption: Contents:

.. automodule:: fitting.data_server

.. autofunction:: fitting.data_server.data_handler.generate_key
.. autofunction:: fitting.data_server.data_handler.append_key
.. autofunction:: fitting.data_server.data_handler.store_user_data
.. autofunction:: fitting.data_server.data_handler.get_plot_data_from_server
.. autofunction:: fitting.data_server.data_handler.get_user_files_from_server


text:
module TeamsHelper
	def assign_players(stats,total,sport,user_stat)
		teams = limit_players(stats,total,user_stat)
		locations = location_results(teams,sport)
		teams = Team.shuffle_rand_teams(teams,total)
		match = Match.create_match(sport.id,locations.sample)
		# match = Match.create_match(sport.id,'123 Main St SF, CA')
		if match.save
			home = Team.create_teams("true",sport.id,match.id)
			away = Team.create_teams("false",sport.id,match.id)
			if home.save && away.save
				result = Userteam.join_team(teams[:Home],home,sport.id)
				return result if result!= "success"
				result = Userteam.join_team(teams[:Away],away,sport.id)
				return result if result!= "success"
				{Home:home,Home_team: parse_team_inform(teams[:Home]),Away:away,Away_team:parse_team_inform(teams[:Away]),match:match}
			else
				return home.errors.full_messages if home.errors.full_messages != nil
				return away.errors.full_messages if away.errors.full_messages != nil
			end
		else
			match.errors.full_messages
		end
	end

	def limit_players(stats,total,user_stat)
		stats = stats.order(:updated_at)
		i = 1
		teams = [user_stat.user]
		while i < total
			player = stats[i].user
			teams << player
			i+=1
		end
		teams
	end

	def parse_team_inform(teams)
		teams.map! do |user|
			pass_user_params(user)
		end
		teams
	end
end


text:
package commands

import (
	"time"

	"github.com/github/git-lfs/git"
	"github.com/github/git-lfs/lfs"
	"github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx"
	"github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra"
)

var (
	fetchCmd = &cobra.Command{
		Use:   "fetch",
		Short: "Downloads LFS files",
		Run:   fetchCommand,
	}
)

func fetchCommand(cmd *cobra.Command, args []string) {
	var refs []string

	if len(args) > 0 {
		refs = args
	} else {
		ref, err := git.CurrentRef()
		if err != nil {
			Panic(err, "Could not fetch")
		}
		refs = []string{ref}
	}

	// Fetch refs sequentially per arg order; duplicates in later refs will be ignored
	for _, ref := range refs {
		fetchRef(ref)
	}

}

func init() {
	RootCmd.AddCommand(fetchCmd)
}

func fetchRefToChan(ref string) chan *lfs.WrappedPointer {
	c := make(chan *lfs.WrappedPointer)
	pointers, err := lfs.ScanRefs(ref, "", nil)
	if err != nil {
		Panic(err, "Could not scan for Git LFS files")
	}

	go fetchAndReportToChan(pointers, c)

	return c
}

// Fetch all binaries for a given ref (that we don't have already)
func fetchRef(ref string) {
	pointers, err := lfs.ScanRefs(ref, "", nil)
	if err != nil {
		Panic(err, "Could not scan for Git LFS files")
	}
	fetchPointers(pointers)
}

func fetchPointers(pointers []*lfs.WrappedPointer) {
	fetchAndReportToChan(pointers, nil)
}

// Fetch and report completion of each OID to a channel (optional, pass nil to skip)
func fetchAndReportToChan(pointers []*lfs.WrappedPointer, out chan<- *lfs.WrappedPointer) {

	totalSize := int64(0)
	for _, p := range pointers {
		totalSize += p.Size
	}
	q := lfs.NewDownloadQueue(len(pointers), totalSize, false)

	for _, p := range pointers {
		// Only add to download queue if local file is not the right size already
		// This avoids previous case of over-reporting a requirement for files we already have
		// which would only be skipped by PointerSmudgeObject later
		if !lfs.ObjectExistsOfSize(p.Oid, p.Size) {
			q.Add(lfs.NewDownloadable(p))
		} else {
			// If we already have it, report it to chan immediately to support pull/checkout
			if out != nil {
				out <- p
			}

		}
	}

	if out != nil {
		dlwatch := q.Watch()

		go func() {
			// fetch only reports single OID, but OID *might* be referenced by multiple
			// WrappedPointers if same content is at multiple paths, so map oid->slice
			oidToPointers := make(map[string][]*lfs.WrappedPointer, len(pointers))
			for _, pointer := range pointers {
				plist := oidToPointers[pointer.Oid]
				oidToPointers[pointer.Oid] = append(plist, pointer)
			}

			for oid := range dlwatch {
				plist, ok := oidToPointers[oid]
				if !ok {
					continue
				}
				for _, p := range plist {
					out <- p
				}
			}
			close(out)
		}()

	}
	processQueue := time.Now()
	q.Wait()
	tracerx.PerformanceSince("process queue", processQueue)
}


text:
import cython

try:
    from typing import Optional
except ImportError:
    pass

# not OK

def optional_cython_types(i: Optional[cython.int], d: Optional[cython.double], f: Optional[cython.float],
                          c: Optional[cython.complex], l: Optional[cython.long], ll: Optional[cython.longlong]):
    pass

MyStruct = cython.struct(a=cython.int, b=cython.double)

def optional_cstruct(x: Optional[MyStruct]):
    pass

# OK

def optional_pytypes(i: Optional[int], f: Optional[float], c: Optional[complex], l: Optional[long]):
    pass

def optional_memoryview(d: double[:], o: Optional[double[:]]):
    pass

_ERRORS = """
13:44: typing.Optional[...] cannot be applied to non-Python type int
13:69: typing.Optional[...] cannot be applied to non-Python type double
13:97: typing.Optional[...] cannot be applied to non-Python type float
14:44: typing.Optional[...] cannot be applied to non-Python type double complex
14:73: typing.Optional[...] cannot be applied to non-Python type long
14:100: typing.Optional[...] cannot be applied to non-Python type long long

20:33: typing.Optional[...] cannot be applied to non-Python type MyStruct
"""


text:
module Trebuchet
  module Operation
    module Common
      class SetupOrganization < Trebuchet::Engine::KatelloCommand
        include Trebuchet::Engine::MultiOperationComponent

        def katello_commands
          @org = @config[:org]
          @environments = @config[:environments]

          commands = [
                      { :id=> "org_create_#{@org}",
                        :command => "org create --name=#{esc(@org)}" }
                     ]

          @environments.each_with_index do |env, index|
            if index % 3 == 0
              previous = 'Library'
            else
              previous = @environments[index-1]
            end
            commands << { :id=>"env_#{env}_create",
                        :command=>"environment create --org=#{esc(@org)} --name=#{esc(env)} --prior=#{previous}"}
          end
          commands << { :id=>:provider_create,
                              :command=>"provider create --org=#{esc(@org)} --name=#{esc(@org)}"}
          commands
        end

        def required_configs
          [:org, :environments]
        end

      end
    end
  end
end


text:
package org.apache.river.test.spec.renewalservice;

import java.util.logging.Level;

// net.jini
import net.jini.core.lease.Lease;
import net.jini.lease.LeaseRenewalManager;
import net.jini.lease.LeaseRenewalService;
import net.jini.lease.LeaseRenewalSet;

//
import org.apache.river.qa.harness.TestException;
import org.apache.river.qa.harness.Test;

// org.apache.river.qa
import org.apache.river.qa.harness.QATestEnvironment;
import org.apache.river.test.share.BasicLeaseOwner;
import org.apache.river.test.share.TestLease;
import org.apache.river.test.share.TestLeaseProvider;

/**
 * Assert that the remove method returns null when the lease is not in the set.
 *
 */
public class LeaseNotInSetTest extends AbstractLeaseRenewalServiceTest {

    /**
     * Provides leases for this test.
     */
    private TestLeaseProvider leaseProvider = null;

    /**
     *  The owner (aka landlord) of the test leases
     */
    private BasicLeaseOwner leaseOwner = null;

    /**
     *  The LeaseRenewalManager used for LRS impls that grant only short leases
     */
    private LeaseRenewalManager lrm = null;

    /**
     * Sets up the testing environment.
     */
    public Test construct(org.apache.river.qa.harness.QAConfig sysConfig) throws Exception {

       // mandatory call to parent
       super.construct(sysConfig);

       // Announce where we are in the test
       logger.log(Level.FINE, "LeaseNotInSetTest: In setup() method.");

       // instantiate a lease provider
       leaseProvider = new TestLeaseProvider(1);

       // create an owner to for testing definite exceptions
       leaseOwner = new BasicLeaseOwner(Lease.FOREVER);

       // create lease renewal manager for wider use across implementations
       lrm = new LeaseRenewalManager(sysConfig.getConfiguration());
       return this;
    }

    /**
     * Assert that the remove method returns null when the lease is
     * not in the set.
     */
    public void run() throws Exception {

	// Announce where we are in the test
	logger.log(Level.FINE, "LeaseNotInSetTest: In run() method.");

	// grab the ever popular LRS
	LeaseRenewalService lrs = getLRS();

	// create a renewal set
	logger.log(Level.FINE, "Creating renewal set with lease duration of " +
			  "Lease.FOREVER.");
	long renewSetDur = Lease.FOREVER;
	LeaseRenewalSet set = lrs.createLeaseRenewalSet(renewSetDur);
	set = prepareSet(set);
	lrm.renewFor(prepareLease(set.getRenewalSetLease()), renewSetDur, null);

	// create a test lease to be managed
	logger.log(Level.FINE, "Creating the lease to be managed.");
	logger.log(Level.FINE, "Duration == Lease.FOREVER");
	TestLease testLease =
	    leaseProvider.createNewLease(leaseOwner, Lease.FOREVER);

	// remove the lease
	Lease managedLease = set.remove(testLease);
	if (managedLease != null) {
	    String message = "Removal of non-managed lease does NOT\n" +
			     "return null as required.";
	    throw new TestException(message);
	}
    }
} // LeaseNotInSetTest


text:
'use strict';

var path = require('path'),
    fs = require('fs'),
    child_process = require('child_process'),

    async = require('async'),
    x509 = require('x509');

function chop(array, quantity){
    var result = [],
        subArray = [],
        count = 0;

    array.forEach(function(element){
        if(count === quantity){
            result.push(subArray);
            subArray = [];
            count = 0;
        }

        subArray.push(element);
        count++;
    });

    if(subArray.length > 0) {
        result.push(subArray);
    }

    return result;
};

function removeBagAttributes(content) {
    var title;

    if(content.indexOf('CERTIFICATE') > -1) {
        title = 'CERTIFICATE';
    }

    if(content.indexOf('PRIVATE KEY') > -1) {
        title = 'PRIVATE KEY';
    }

    if(content.indexOf('RSA PRIVATE KEY') > -1) {
        title = 'RSA PRIVATE KEY';
    }

    var regexp = new RegExp('-----BEGIN ' + title + '-----(.*)-----END ' + title + '-----');

    content = content.replace(/\n/g, '');
    content = regexp.exec(content) || [];
    content = content[1].split('');
    content = chop(content, 76);
    content = content.map(function(line) {
        return line.join('');
    }).join('\n');

    return '-----BEGIN ' + title + '-----\n' + content + '\n' + '-----END ' + title + '-----';
}

function fromPfx(params, callback) {
    params.path = '"' + params.path + '"';
    function attributes(cb) {
        var command = [
            'openssl pkcs12 -in',
            params.path,
            '-nodes -passin pass:' + (params.password || '')
        ].join(' ');

        child_process.exec(command, function(err, stdout, stderr) {
            if(err) {
                return cb(err);
            }

            var attributes = x509.parseCert(stdout);

            cb(null, attributes);
        });
    }

    function key(cb) {
        var command = [
            'openssl pkcs12 -in',
            params.path,
            '-nodes -nocerts ',
            '-passin pass:' + (params.password || '')
        ].join(' ');

        child_process.exec(command, function(err, stdout, stderr) {
            if(err) {
                return cb(err);
            }

            cb(null, removeBagAttributes(stdout));
        });
    }

    function certificate(cb) {
        var command = [
            'openssl pkcs12 -in',
            params.path,
            '-nodes -clcerts -nokeys',
            '-passin pass:' + (params.password || '')
        ].join(' ');

        child_process.exec(command, function(err, stdout, stderr) {
            if(err) {
                return cb(err);
            }

            cb(null, removeBagAttributes(stdout));
        });
    }

    async.parallel({
        attributes: attributes,
        key: key,
        certificate: certificate
    }, function(err, result) {
        if(err) {
            return callback(err);
        }

        callback(null, result);
    });
}

module.exports.fromPfx = fromPfx;

function fromDer(params, cb) {
    params.path = '"' + params.path + '"';

    var command = [
        'openssl x509 -in',
        params.path,
        '-inform der -outform pem',
        '-passin pass:' + (params.password || '')
    ].join(' ');

    try {
        child_process.exec(command, function(err, stdout, stderr){
            if(err) {
                return cb(err);
            }

            var cert = x509.parseCert(stdout);

            cb(null, cert);
        });
    } catch(e) {
        cb(e);
    }
}

module.exports.fromDer = fromDer;


text:
var moduleDependencies = {
	fusion: "https://raw.githubusercontent.com/Library-of-Kaeon/Library-of-Kaeon/master/Library%20of%20Kaeon/3%20-%20Collection/1%20-%20Original/1%20-%20Computation/1%20-%20APIs/1%20-%20ONE/2%20-%20FUSION/1%20-%20JavaScript/1%20-%20Source/FUSION.js",
	kaeonACE: "https://raw.githubusercontent.com/Library-of-Kaeon/Library-of-Kaeon/master/Library%20of%20Kaeon/3%20-%20Collection/1%20-%20Original/1%20-%20Computation/1%20-%20APIs/3%20-%20Kaeon%20Series/3%20-%20Kaeon%20ACE/1%20-%20APIs/1%20-%20Babylon/1%20-%20Core/1%20-%20Source/KaeonACE.js",
	philosophersStone: "https://raw.githubusercontent.com/Library-of-Kaeon/Library-of-Kaeon/master/Library%20of%20Kaeon/3%20-%20Collection/1%20-%20Original/1%20-%20Computation/1%20-%20APIs/2%20-%20Philosopher's%20Stone/1%20-%20Philosopher's%20Stone/1%20-%20JavaScript/1%20-%20Source/PhilosophersStone.js",
	widgets: "https://raw.githubusercontent.com/Library-of-Kaeon/Library-of-Kaeon/master/Library%20of%20Kaeon/3%20-%20Collection/1%20-%20Original/1%20-%20Computation/1%20-%20APIs/4%20-%20Utilities/3%20-%20UI/1%20-%20Visual/3%20-%20Widgets/1%20-%20General/1%20-%20JavaScript/1%20-%20Source/widgets.js"
};

var fusion = require(moduleDependencies.fusion);
var kaeonACE = require(moduleDependencies.kaeonACE);
var philosophersStone = require(moduleDependencies.philosophersStone);
var widgets = require(moduleDependencies.widgets);

function getACECallback(fusion, ace) {

	return function(element) {
		kaeonACE.run(fusion, ace, element);
	};
}

let ACEModule = function() {

	philosophersStone.abide(this, new fusion.FUSIONUnit());

	this.verify = function(element) {
		return element.parent == null;
	}

	this.process = function(element, processed) {

		widgets.createStartScreen(
			document.documentElement,
			"Start",
			getACECallback(this.fusion, element)
		);
	}
}

module.exports = function(fusion) {

	let aceModule = new ACEModule();
	aceModule.fusion = fusion;

	philosophersStone.connect(fusion, aceModule, [], true);
};


text:
package website.automate.jwebrobot.executor.action;

import org.openqa.selenium.WebDriver;
import org.springframework.stereotype.Service;
import website.automate.jwebrobot.context.ScenarioExecutionContext;
import website.automate.jwebrobot.executor.ActionExecutorUtils;
import website.automate.jwebrobot.executor.ActionResult;
import website.automate.waml.io.model.main.action.EnsureAction;

@Service
public class EnsureActionExecutor extends BaseActionExecutor<EnsureAction> {

    @Override
    public void execute(EnsureAction action,
                        ScenarioExecutionContext context,
                        ActionResult result,
                        ActionExecutorUtils utils) {
        final WebDriver driver = context.getDriver();

        (utils.getWebdriverWaitProvider()
            .getInstance(driver, utils.getTimeoutResolver()
            .resolve(action, context))).until(
                condition -> new WaitCondition(action, context, result, utils).apply(driver)
        );
    }

    @Override
    public Class<EnsureAction> getSupportedType() {
        return EnsureAction.class;
    }
}


text:
@charset "utf-8";

div#addInterface {
	margin: 30px auto 15px;
	min-width: 620px;
}

div#addInterface form {
	text-align: center;
}

div#addInterface form table {
	display: inline-block;
	*display: inline;
	*zoom: 1;
	vertical-align: middle;
}

div#addInterface form table tr {
	display: block;
	margin: 6px auto;
}

div#addInterface form table td {
	text-align: left;
}

div#addInterface form table td:first-child {
	text-align: center;
}

div#addInterface form .text {
	width: 600px;
}

div#addInterface form div#buttonDiv{
	width:506px;
	margin:20px auto;
	position:relative;
	left:83px;
}

div#addInterface form button#submit,div#addInterface form a#cancel img {
	*zoom: 1;
	vertical-align: middle;
	background-color: transparent;
	border: none;
	margin: 0px 10px;
	cursor: pointer;
	padding:0;
}

div#addInterface form button#submit {
	display: inline-block;
	*display: inline;
	*zoom: 1;
	vertical-align: middle;
	background-color: transparent;
	border: none;
	cursor: pointer;
}


text:
import { CMapCompressionType } from '../../src/shared/util';
import isNodeJS from '../../src/shared/is_node';
import { isRef } from '../../src/core/primitives';

class NodeFileReaderFactory {
  static fetch(params) {
    var fs = require('fs');
    var file = fs.readFileSync(params.path);
    return new Uint8Array(file);
  }
}

const TEST_PDFS_PATH = {
  dom: '../pdfs/',
  node: './test/pdfs/',
};

function buildGetDocumentParams(filename, options) {
  let params = Object.create(null);
  if (isNodeJS()) {
    params.data = NodeFileReaderFactory.fetch({
      path: TEST_PDFS_PATH.node + filename,
    });
  } else {
    params.url = new URL(TEST_PDFS_PATH.dom + filename, window.location).href;
  }
  for (let option in options) {
    params[option] = options[option];
  }
  return params;
}

class NodeCMapReaderFactory {
  constructor({ baseUrl = null, isCompressed = false, }) {
    this.baseUrl = baseUrl;
    this.isCompressed = isCompressed;
  }

  fetch({ name, }) {
    if (!this.baseUrl) {
      return Promise.reject(new Error('CMap baseUrl must be specified, ' +
        'see "PDFJS.cMapUrl" (and also "PDFJS.cMapPacked").'));
    }
    if (!name) {
      return Promise.reject(new Error('CMap name must be specified.'));
    }
    return new Promise((resolve, reject) => {
      let url = this.baseUrl + name + (this.isCompressed ? '.bcmap' : '');

      let fs = require('fs');
      fs.readFile(url, (error, data) => {
        if (error || !data) {
          reject(new Error('Unable to load ' +
                           (this.isCompressed ? 'binary ' : '') +
                           'CMap at: ' + url));
          return;
        }
        resolve({
          cMapData: new Uint8Array(data),
          compressionType: this.isCompressed ?
            CMapCompressionType.BINARY : CMapCompressionType.NONE,
        });
      });
    });
  }
}

class XRefMock {
  constructor(array) {
    this._map = Object.create(null);

    for (let key in array) {
      let obj = array[key];
      this._map[obj.ref.toString()] = obj.data;
    }
  }

  fetch(ref) {
    return this._map[ref.toString()];
  }

  fetchAsync(ref) {
    return Promise.resolve(this.fetch(ref));
  }

  fetchIfRef(obj) {
    if (!isRef(obj)) {
      return obj;
    }
    return this.fetch(obj);
  }

  fetchIfRefAsync(obj) {
    return Promise.resolve(this.fetchIfRef(obj));
  }
}

export {
  NodeFileReaderFactory,
  NodeCMapReaderFactory,
  XRefMock,
  buildGetDocumentParams,
  TEST_PDFS_PATH,
};


text:
<?php

  include_once realpath(dirname(__FILE__) . '/../../bootstrap/functional.php');
  include_once sfConfig::get('sf_symfony_lib_dir') . '/vendor/lime/lime.php';

$sfContext = sfContext::getInstance();
  $cacheManager = $sfContext->getViewCacheManager();
  /* @var $cacheManager sfViewCacheTagManager */
  $tagging = $cacheManager->getTaggingCache();

  $con = Doctrine_Manager::getInstance()->getCurrentConnection();
  $con->beginTransaction();
  $cleanQuery = "SET FOREIGN_KEY_CHECKS = 0; TRUNCATE `food`; TRUNCATE `book`; SET FOREIGN_KEY_CHECKS = 1;";
  $con->exec($cleanQuery);
  $con->commit();
  $tagging->clean();

  $t = new lime_test();

  # checking getTags

  $versionBeforeFoodCreated = sfCacheTaggingToolkit::generateVersion();
  $banana = new Food();
  $banana->setTitle('Banana')->save();

  $bananaCollectionVersion = $banana->obtainCollectionVersion();

  # obtainCollectionName
  $t->is(
    $banana->obtainCollectionName(),
    sfCacheTaggingToolkit::obtainCollectionName($banana->getTable()),
    'Call obtainCollectionName() returns Collection name');

  # obtainCollectionVersion 1
  $t->cmp_ok($banana->obtainCollectionVersion(), '>', $versionBeforeFoodCreated, 'Food version is higher then it could be before creation');

  # obtainCollectionVersion 2
  $banana->setTitle('Tasty banana')->save();
  $t->is($bananaCollectionVersion, $banana->obtainCollectionVersion(), 'By updating banana collection version stays unchanged');

  # obtainCollectionVersion 3
  $eggs = new Food();
  $eggs->setTitle('Eggs')->save();
  $t->cmp_ok($bananaCollectionVersion, '<', $eggs->obtainCollectionVersion(), 'By creating eggs objects, collection tag version increased');

  # obtainCollectionVersion 4
  $t->is($banana->obtainCollectionVersion(), $eggs->obtainCollectionVersion(), 'Banana and eggs collection versions are equal, because of fetching it directly from cache backend');

  # obtainCollectionVersion 5
  # Delete with SoftDelete
  $eggsCollectionVersion = $eggs->obtainCollectionVersion();
  $eggs->delete();

  $t->cmp_ok($eggsCollectionVersion, '<', $banana->obtainCollectionVersion(), 'Banana collection version increased when some other Food object is deleted (object)');

  # obtainCollectionVersion 6

  $bananaCollectionVersion = $banana->obtainCollectionVersion();

  $eggs = new Food();
  $eggs->setTitle('Eggs')->save();

  $q = FoodTable::getInstance()->createQuery();
  $t->is($q->delete()->where('title = ?', 'Eggs')->execute(), 1, 'SoftDelete sets deleted_at (no physical deletion');
  $t->is(FoodTable::getInstance()->findOneByTitle('Eggs'), false, 'Teoreticaly it is removed');

  $t->cmp_ok($bananaCollectionVersion, '<', $banana->obtainCollectionVersion(), 'Banana collection version increased when some other Food object is deleted (DQL)');

  # Delete without SoftDelete behavior
  /**
   * @todo add tests with "Book" table, object and DQL deletes
   */

  $beforeVersion = sfCacheTaggingToolkit::generateVersion();

  $bible = new Book();
  $bible->setLang('en');
  $bible->setSlug('the-holy-bible');
  $bible->save();

  $afterVersion = sfCacheTaggingToolkit::generateVersion();

  $bibleCollectionVersion = $bible->obtainCollectionVersion();

  $t->cmp_ok($bibleCollectionVersion, '>', $beforeVersion, 'Bible collection version is greater then microtime taken before');
  $t->cmp_ok($bibleCollectionVersion, '<', $afterVersion, 'Bible collection version is less then microtime taken after');

  $meinKampf = new Book();
  $meinKampf->setLang('de');
  $meinKampf->setSlug('mein-kampf');
  $meinKampf->save();

  $t->cmp_ok($bibleCollectionVersion, '<', $meinKampf->obtainCollectionVersion(), 'By adding new Book, collection version increases');

  $meinKampfCollectionVersion = $meinKampf->obtainCollectionVersion();

  $meinKampf->setLang('de_CH');
  $meinKampf->save();

  $t->is($meinKampfCollectionVersion, $meinKampf->obtainCollectionVersion(), 'By updating existing Book, collection version stays unchanged');
  $meinKampfCollectionVersion = $meinKampf->obtainCollectionVersion();
  $meinKampf->delete();

  $t->cmp_ok($meinKampfCollectionVersion, '<', $bible->obtainCollectionVersion(), 'By removing Book, collection version increases');

  $bibleCollectionVersion = $bible->obtainCollectionVersion();

  $meinKampf = new Book();
  $meinKampf->setLang('de');
  $meinKampf->setSlug('mein-kampf');
  $meinKampf->save();

  $q = BookTable::getInstance()->createQuery();
  $t->is($q->delete()->where('slug = ?', 'mein-kampf')->execute(), 1, 'DQL removing Book "mein-kampf"');

  $t->cmp_ok($bibleCollectionVersion, '<', $bible->obtainCollectionVersion(), 'By removing Book using DQL, collection version increases');

  $con->exec($cleanQuery);
  $tagging->clean();


text:
#include <inttypes.h>
#include <architecture/peekpoke.h>
#include <system/board.h>
#include "../driver/jz47xx-timer/timer_internal.h"

#include <stage1/timer_basic.h>

/*
 * Spin timer functions
*/
void spintimer_init(void)
{
	/* Timer keeps counting, ignoring comparison value */
	poke32(TCU_OSTCSR, OSTCSR_CNT_MD | OSTCSR_PRESCALE_16);

	/* Counter initial value. */
	poke32(TCU_OSTCNTH, 0);
	poke32(TCU_OSTCNTL, 0);

	/* Use EXTCLK as the clock source */
	poke32(TCU_OSTCSR, peek32(TCU_OSTCSR) | OSTCSR_EXT_EN);

	/* Enable the timer*/
	poke32(TESR, TER_OSTEN);
}

void spintimer_usleep(uint64_t usec)
{
	/* Doesn't handle the wrap case, which, with 64-bit values and 3 million
	 * ticks per second, may crop up once every 194980 years. */
	uint64_t target = spintimer_getval() + (usec * OS_TIMER_USEC_DIV);

	while(spintimer_getval() < target)
		;
}

uint64_t spintimer_getval(void)
{
	return peek32(TCU_OSTCNTL) | ((uint64_t)(peek32(TCU_OSTCNTHBUF)) << 32);
}


text:
module Pos.Chain.Update.Constants
       ( -- * Genesis constants
         genesisBlockVersion
       , genesisSoftwareVersions
       , genesisAppNames
       ) where

import           Universum

import           Pos.Chain.Update.ApplicationName (ApplicationName (..))
import           Pos.Chain.Update.BlockVersion (BlockVersion (..))
import           Pos.Chain.Update.SoftwareVersion (SoftwareVersion (..))

----------------------------------------------------------------------------
-- Genesis constants
----------------------------------------------------------------------------

-- | BlockVersion used at the very beginning.
genesisBlockVersion :: BlockVersion
genesisBlockVersion =
    BlockVersion
    { bvMajor = 0
    , bvMinor = 0
    , bvAlt = 0
    }

-- | Software Versions
genesisSoftwareVersions :: [SoftwareVersion]
genesisSoftwareVersions = map f genesisAppNames
  where
    f (_, appName) = SoftwareVersion {svAppName = appName, svNumber = 0}

genesisAppNames :: [(Text, ApplicationName)]
genesisAppNames = map f ["cardano-sl", "csl-daedalus"]
  where
    f name = (name, ApplicationName name)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<link rel="stylesheet" type="text/css" href="../../css/help_small.css"/>
		<title>How "Search Region" property works | CustomBlocker Help</title>

How "Search Region" property works

		This XPath expression specifies in which elements this extension search for keywords.
		If some of specified elements contain keyword and the elements are contained by "Elements to Hide", the rule works and "Elements to Hide" will be hidden.

		You can get XPaths easily by clicking "Suggest" and click one of target elements.
		Some XPaths which can select similar elements are suggested.

		When "Block Anyway" is checked this property is useless because elements selected by XPath of "Elements to Hide" will be hidden, whether keywords are contained or not.


text:
package it.tiwiz.whatsong.utils;

import android.os.Parcel;
import android.os.Parcelable;

import org.intellij.lang.annotations.MagicConstant;

/**
 * This class represents the basic package data needed to
 * filter and identify the correct installed music recognition
 * providers.
 */
public class PackageData implements Parcelable {

    private static final int PACKAGE_NAME = 0;
    private static final int PACKAGE_LABEL = 1;

    @MagicConstant(intValues = {PACKAGE_NAME, PACKAGE_LABEL})
    private @interface Keys {
    }

    private final String packageName;
    private final String packageLabel;

    public PackageData(String packageName, String packageLabel) {
        this.packageName = packageName;
        this.packageLabel = packageLabel;
    }

    private PackageData(Parcel in) {
        packageName = in.readString();
        packageLabel = in.readString();
    }

    public String getPackageName() {
        return packageName;
    }

    public String getPackageLabel() {
        return packageLabel;
    }

    @Override
    public String toString() {
        return String.format("%s (%s)", packageLabel, packageName);
    }

    /**
     * This method uses the {@link org.intellij.lang.annotations.MagicConstant} annotation
     * to decide which of the data it needs to return.
     *
     * @return a {@link java.lang.String} representing the
     */
    protected String getStringFromKey(@Keys int key) {
        String result;

        switch (key) {
            case PACKAGE_NAME:
                result = packageName;
                break;
            case PACKAGE_LABEL:
                result = packageLabel;
                break;
            default:
                result = null;
                break;
        }

        return result;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(packageName);
        dest.writeString(packageLabel);
    }

    public static final Creator<PackageData> CREATOR = new Creator<PackageData>() {
        @Override
        public PackageData createFromParcel(Parcel source) {
            return new PackageData(source);
        }

        @Override
        public PackageData[] newArray(int size) {
            return new PackageData[size];
        }
    };

    /**
     * This class contains the methods for extracting the packages and the names of the installed apps.
     * <p>
     * This is needed because we want to filter only for the providers that are actually installed,
     * so that we have a shorter list of apps to chose from.
     *
     * @see #getNames(PackageData[]) getting packages name
     * @see #getPackages(PackageData[]) getting packages label
     * @see #getStringFromKey(int) getting specific package data by key
     */
    public static class Utils {

        public static String[] getPackages(PackageData[] data) {

            return getStrings(data, PACKAGE_NAME);
        }

        public static String[] getNames(PackageData[] data) {

            return getStrings(data, PACKAGE_LABEL);
        }

        /**
         * This is a generic method for getting any of the package data using the
         * {@link #getStringFromKey(int)} method and the {@link org.intellij.lang.annotations.MagicConstant}
         * annotation for {@code Keys} interface
         */
        private static String[] getStrings(PackageData[] data, @Keys int key) {
            int size = data.length;
            String[] result = new String[size];

            for (int i = 0; i < size; i++)
                result[i] = data[i].getStringFromKey(key);

            return result;
        }
    }
}


text:
namespace google {
namespace spanner {
namespace emulator {
namespace backend {

absl::Status PartitionabilityValidator::ValidatePartitionability(
    const zetasql::ResolvedNode* node) {
  ZETASQL_DCHECK(node->node_kind() == zetasql::RESOLVED_QUERY_STMT);
  if (HasSubquery(node)) {
    return error::NonPartitionableQuery("Query contains subquery.");
  }
  return ValidateSimpleScan(node);
}

// Verifies that query is a simple scan on one table.
//
// Example query:
//   SELECT o.obj_k FROM Obj o
// ResolvedAST:
// QueryStmt
// +-output_column_list=
// | +-Obj.obj_k#2 AS obj_k [STRING]
// +-query=
//   +-ProjectScan
//     +-column_list=[Obj.obj_k#2]
//     +-input_scan=
//       +-TableScan(column_list=[Obj.obj_k#2], table=Obj)
//
absl::Status PartitionabilityValidator::ValidateSimpleScan(
    const zetasql::ResolvedNode* node) {
  absl::Status error_status =
      error::NonPartitionableQuery("Query is not a simple table scan.");
  const zetasql::ResolvedNode* current_node = node;
  while (true) {
    switch (current_node->node_kind()) {
      case zetasql::RESOLVED_QUERY_STMT:
        current_node =
            current_node->GetAs<zetasql::ResolvedQueryStmt>()->query();
        if (current_node != nullptr &&
            current_node->node_kind() == zetasql::RESOLVED_PROJECT_SCAN) {
          break;
        }
        return error_status;
      case zetasql::RESOLVED_PROJECT_SCAN:
        current_node =
            current_node->GetAs<zetasql::ResolvedProjectScan>()->input_scan();
        if (current_node != nullptr &&
            (current_node->node_kind() == zetasql::RESOLVED_TABLE_SCAN ||
             current_node->node_kind() == zetasql::RESOLVED_FILTER_SCAN)) {
          break;
        }
        return error_status;
      case zetasql::RESOLVED_FILTER_SCAN:
        current_node =
            current_node->GetAs<zetasql::ResolvedFilterScan>()->input_scan();
        if (current_node != nullptr &&
            current_node->node_kind() == zetasql::RESOLVED_TABLE_SCAN) {
          break;
        }
        return error_status;
      case zetasql::RESOLVED_TABLE_SCAN:
        return absl::OkStatus();
      default:
        return error_status;
    }
  }
}

bool PartitionabilityValidator::HasSubquery(
    const zetasql::ResolvedNode* node) {
  ZETASQL_DCHECK(node != nullptr);
  if (node->node_kind() == zetasql::RESOLVED_SUBQUERY_EXPR) {
    return true;
  }
  std::vector<const zetasql::ResolvedNode*> child_nodes;
  node->GetChildNodes(&child_nodes);  // only non-null children returned.
  for (const zetasql::ResolvedNode* child : child_nodes) {
    if (HasSubquery(child)) {
      return true;
    }
  }
  return false;
}

}  // namespace backend
}  // namespace emulator
}  // namespace spanner
}  // namespace google


text:
import EventEmitter from '../../EventEmitter';

export default class Listenable {
  constructor( eventEmitter?: EventEmitter<unknown> ); // TODO:
  addListener: ( eventName: string, listener: () => unknown ) => () => unknown; // TODO: returns remote listener func
  removeListener: ( eventName: string, listener: () => unknown ) => void;
  on: (eventName: string, listener: (...args: any[]) => unknown) => unknown; // TODO: returns remote listener func
  off: (eventName: string, listener: (...args: any[]) => unknown) => void;
}


text:
package org.apache.carbondata.core.scan.collector.impl;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.carbondata.common.annotations.InterfaceAudience;
import org.apache.carbondata.core.constants.CarbonCommonConstants;
import org.apache.carbondata.core.scan.executor.infos.BlockExecutionInfo;
import org.apache.carbondata.core.scan.model.ProjectionMeasure;
import org.apache.carbondata.core.scan.result.BlockletScannedResult;
import org.apache.carbondata.core.scan.wrappers.ByteArrayWrapper;
import org.apache.carbondata.core.stats.QueryStatistic;
import org.apache.carbondata.core.stats.QueryStatisticsConstants;

/**
 * It is not a collector it is just a scanned result holder.
 * This class returns all the dimensions in a ByteArrayWrapper and append
 * blockletNo/PageId/RowId at end of the row.
 */
@InterfaceAudience.Internal
public class RowIdRestructureBasedRawResultCollector extends RestructureBasedRawResultCollector {

  public RowIdRestructureBasedRawResultCollector(BlockExecutionInfo blockExecutionInfos) {
    super(blockExecutionInfos);
  }

  @Override
  protected void scanAndFillData(BlockletScannedResult scannedResult, int batchSize,
                               List<Object[]> listBasedResult, ProjectionMeasure[] queryMeasures) {
    int numberOfPages = scannedResult.numberOfPages();
    // loop will exit once the batchSize data has been read or the pages have been exhausted
    while (scannedResult.getCurrentPageCounter() < numberOfPages) {
      int currentPageRowCount = scannedResult.getCurrentPageRowCount();
      if (currentPageRowCount == 0) {
        scannedResult.incrementPageCounter();
        continue;
      }
      int rowCounter = scannedResult.getRowCounter();
      // getRowCounter holds total number rows processed. Calculate the
      // Left over space through getRowCounter only.
      int availableRows = currentPageRowCount - rowCounter;
      // rows available in current page that can be processed from current page
      int availableBatchRowCount = Math.min(batchSize, availableRows);
      // this condition will be true if no data left in the current block/blocklet to be scanned
      if (availableBatchRowCount < 1) {
        break;
      }
      if (batchSize > availableRows) {
        batchSize = batchSize - availableRows;
      } else {
        // this is done because in IUD cases actual rows fetch can be less than batch size as
        // some of the rows could have deleted. So in those cases batchSize need to be
        // re initialized with left over value
        batchSize = 0;
      }
      // for every iteration of available rows filling newly created list of Object[] and add it to
      // the final list so there is no mismatch in the counter while filling dimension and
      // measure data
      List<Object[]> collectedData = new ArrayList<>(availableBatchRowCount);
      // fill dimension data
      fillDimensionData(scannedResult, collectedData, queryMeasures, availableBatchRowCount);
      fillMeasureData(scannedResult, collectedData);
      // increment the number of rows scanned in scanned result statistics
      // incrementScannedResultRowCounter(scannedResult, availableBatchRowCount);
      // assign the left over rows to batch size if the number of rows fetched are lesser
      // than batchSize
      if (collectedData.size() < availableBatchRowCount) {
        batchSize += availableBatchRowCount - listBasedResult.size();
      }
      // add the collected data to the final list
      listBasedResult.addAll(collectedData);
    }
  }

  private void fillDimensionData(BlockletScannedResult scannedResult,
               List<Object[]> listBasedResult, ProjectionMeasure[] queryMeasures, int batchSize) {
    long startTime = System.currentTimeMillis();
    List<byte[]> dictionaryKeyArrayBatch = scannedResult.getDictionaryKeyArrayBatch(batchSize);
    List<byte[][]> noDictionaryKeyArrayBatch =
        scannedResult.getNoDictionaryKeyArrayBatch(batchSize);
    List<byte[][]> complexTypeKeyArrayBatch = scannedResult.getComplexTypeKeyArrayBatch(batchSize);
    // it will same for one blocklet so can be computed only once
    byte[] implicitColumnByteArray = scannedResult.getBlockletId()
        .getBytes(Charset.forName(CarbonCommonConstants.DEFAULT_CHARSET));
    // Note: size check in for loop is for dictionaryKeyArrayBatch as this size can be lesser than
    // batch size in case of IUD scenarios
    for (int i = 0; i < dictionaryKeyArrayBatch.size(); i++) {
      // 1 for ByteArrayWrapper object which will contain dictionary and no dictionary data
      // 3 for blockletId, pageId, rowId
      Object[] row = new Object[1 + queryMeasures.length + 3];
      scannedResult.incrementCounter();
      row[1 + queryMeasures.length] = scannedResult.getBlockletNumber();
      row[1 + queryMeasures.length + 1] = scannedResult.getCurrentPageCounter();
      ByteArrayWrapper wrapper = new ByteArrayWrapper();
      wrapper.setDictionaryKey(dictionaryKeyArrayBatch.get(i));
      wrapper.setNoDictionaryKeys(noDictionaryKeyArrayBatch.get(i));
      wrapper.setComplexTypesKeys(complexTypeKeyArrayBatch.get(i));
      wrapper.setImplicitColumnByteArray(implicitColumnByteArray);
      row[0] = wrapper;
      row[1 + queryMeasures.length + 2] = scannedResult.getCurrentRowId();
      listBasedResult.add(row);
    }
    QueryStatistic keyColumnFillingTime = queryStatisticsModel.getStatisticsTypeAndObjMap()
        .get(QueryStatisticsConstants.KEY_COLUMN_FILLING_TIME);
    keyColumnFillingTime.addCountStatistic(QueryStatisticsConstants.KEY_COLUMN_FILLING_TIME,
        keyColumnFillingTime.getCount() + (System.currentTimeMillis() - startTime));
  }

  private void fillMeasureData(BlockletScannedResult scannedResult,
                               List<Object[]> listBasedResult) {
    long startTime = System.currentTimeMillis();
    // if list is not empty after filling the dimension data then only fill the measure data
    if (!listBasedResult.isEmpty()) {
      fillMeasureDataBatch(listBasedResult, 1, scannedResult);
    }
    QueryStatistic measureFillingTime = queryStatisticsModel.getStatisticsTypeAndObjMap()
        .get(QueryStatisticsConstants.MEASURE_FILLING_TIME);
    measureFillingTime.addCountStatistic(QueryStatisticsConstants.MEASURE_FILLING_TIME,
        measureFillingTime.getCount() + (System.currentTimeMillis() - startTime));
  }
}


text:
/*
 * Minio Client (C) 2015 Minio, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package main

import (
	"os"
	"regexp"

	"github.com/minio/mc/pkg/console"
	. "gopkg.in/check.v1"
)

func (s *TestSuite) TestValidSessionID(c *C) {
	validSid := regexp.MustCompile("^[a-zA-Z]+$")
	sid := newRandomID(8)
	c.Assert(len(sid), Equals, 8)
	c.Assert(validSid.MatchString(sid), Equals, true)
}

func (s *TestSuite) TestSession(c *C) {
	perr := createSessionDir()
	c.Assert(perr, IsNil)
	c.Assert(isSessionDirExists(), Equals, true)

	session := newSessionV2()
	c.Assert(session.Header.CommandArgs, IsNil)
	c.Assert(len(session.SessionID), Equals, 8)

	perr = session.Close()
	c.Assert(perr, IsNil)

	savedSession, perr := loadSessionV2(session.SessionID)
	c.Assert(perr, IsNil)
	c.Assert(session.SessionID, Equals, savedSession.SessionID)

	perr = savedSession.Close()
	c.Assert(perr, IsNil)

	perr = savedSession.Delete()
	c.Assert(perr, IsNil)
}

func (s *TestSuite) TestSessionContext(c *C) {
	err := app.Run([]string{os.Args[0], "session", "list"})
	c.Assert(err, IsNil)
	c.Assert(console.IsExited, Equals, false)

	// reset back
	console.IsExited = false

	err = app.Run([]string{os.Args[0], "session", "clear", "all"})
	c.Assert(err, IsNil)
	c.Assert(console.IsExited, Equals, false)

	// reset back
	console.IsExited = false

	err = app.Run([]string{os.Args[0], "session", "resume", "invalid"})
	c.Assert(err, IsNil)
	c.Assert(console.IsExited, Equals, true)

	// reset back
	console.IsExited = false

	err = app.Run([]string{os.Args[0], "session", "clear", "invalid"})
	c.Assert(err, IsNil)
	c.Assert(console.IsExited, Equals, true)

	// reset back
	console.IsExited = false

	perr := createSessionDir()
	c.Assert(perr, IsNil)
	c.Assert(isSessionDirExists(), Equals, true)

	// reset back
	console.IsExited = false

	session := newSessionV2()
	c.Assert(session.Header.CommandArgs, IsNil)
	c.Assert(len(session.SessionID), Equals, 8)

	perr = session.Save()
	c.Assert(perr, IsNil)

	c.Assert(session.Close(), IsNil)

	err = app.Run([]string{os.Args[0], "session", "clear", session.SessionID})
	c.Assert(err, IsNil)
	c.Assert(console.IsExited, Equals, false)

	// reset back
	console.IsExited = false
}


text:
package eu.homan.algorithms.capstone.algorithm;

import eu.homan.algorithms.capstone.graph.Graph;

import java.util.HashSet;
import java.util.Set;

public final class GreedyMinimumDominantSet<T> implements MinimumDominantSet<T> {

    private final Set<T> minimumDominantSet = new HashSet<>();

    public GreedyMinimumDominantSet(final Graph<T> graph) {

        final Set<T> uncovered = new HashSet<>();
        graph.forEach(uncovered::add);

        // Greedily adding vertices that cover the most neighbour to the minimum dominant set
        while (!uncovered.isEmpty()) {
            final T nextDominant = maxCovering(uncovered, graph);
            if (nextDominant == null) {
                return;
            }
            minimumDominantSet.add(nextDominant);
            uncovered.remove(nextDominant);
            graph.adj(nextDominant).forEach(uncovered::remove);
        }
    }

    /**
     * @inheritDoc
     */
    @Override
    public Set<T> get() {
        return minimumDominantSet;
    }

    private T maxCovering(final Set<T> uncovered, final Graph<T> graph) {

        final int[] maxCoverage = {0};
        final T[] currentDominant = (T[]) new Object[]{null};

        // Finding the next vertex that can cover the most neighbours
        uncovered.forEach(v -> {
            final Set<T> uncoveredNeighbours = new HashSet<>();
            uncoveredNeighbours.add(v);
            graph.adj(v).forEach(t -> {
                if (uncovered.contains(t)) {
                    uncoveredNeighbours.add(t);
                }
            });

            if (uncoveredNeighbours.size() > maxCoverage[0]) {
                maxCoverage[0] = uncoveredNeighbours.size();
                currentDominant[0] = v;
            }
        });

        return currentDominant[0];
    }
}


text:
package org.eclipse.jdt.internal.corext.refactoring.typeconstraints;

import org.eclipse.core.runtime.Assert;

import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.Type;

import org.eclipse.jdt.internal.corext.dom.ASTNodes;

public final class TypeVariable extends ConstraintVariable {

	private final String fSource;
	private final CompilationUnitRange fTypeRange;

	public TypeVariable(Type type){
		super(type.resolveBinding());
		fSource= type.toString();
		ICompilationUnit cu= ASTCreator.getCu(type);
		Assert.isNotNull(cu);
		fTypeRange= new CompilationUnitRange(cu, ASTNodes.getElementType(type));
	}

	public TypeVariable(ITypeBinding binding, String source, CompilationUnitRange range){
		super(binding);
		fSource= source;
		fTypeRange= range;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return fSource;
	}

	public CompilationUnitRange getCompilationUnitRange() {
		return fTypeRange;
	}
}


text:
A repo full of helpful shell code snippets

### What is this?

This is my playground for learning shell scripting. Zsh is my shell
of choice but I plan to start off writing these script to be compatible with
bash because a) bash is ubiquitous, and b) there is already a lot of free,
high bash scripting tutorials available to everyone.

### Goals

- learn the syntax
- investigate compatibility issues
- explore existing programs for general structure

### Resources

I will update this list as I go along.

[An in-depth exploration of the art of shell scripting](http://tldp.org/LDP/abs/html/)
[A great intro to sed](http://www.grymoire.com/Unix/Sed.html)

### Good code examples

[Concurrent](https://github.com/themattrix/bash-concurrent/blob/master/concurrent.lib.sh)


text:
local require           = require

--local log				= require "hs.logger".new "index"

local fcp               = require "cp.apple.finalcutpro"
local i18n              = require "cp.i18n"
local tools             = require "cp.tools"
local dialog            = require "cp.dialog"

local playErrorSound    = tools.playErrorSound

local plugin = {
    id = "finalcutpro.browser.csv",
    group = "finalcutpro",
    dependencies = {
        ["finalcutpro.commands"]    = "fcpxCmds",
        ["finalcutpro.menu.manager"] = "menuManager",
    }
}

function plugin.init(deps)
    --------------------------------------------------------------------------------
    -- Only load plugin if FCPX is supported:
    --------------------------------------------------------------------------------
    if not fcp:isSupported() then return end

    local cmds = deps.fcpxCmds

    local list = fcp.libraries.list

    local saveBrowserContentsToCSV = function()
        fcp:launch(5)
        list:show()
        if list:isShowing() then
            local result = list.contents:toCSV()
            if result then
                local path = dialog.displayChooseFolder(i18n("selectAFolderToSaveCSV") .. ":")
                if path then
                    tools.writeToFile(path .. "/Browser Contents.csv", result)
                end
                return
            end
        end
        playErrorSound()
    end

    --------------------------------------------------------------------------------
    -- Command:
    --------------------------------------------------------------------------------
    cmds:add("saveBrowserContentsToCSV")
        :whenActivated(saveBrowserContentsToCSV)
        :titled(i18n("saveBrowserContentsToCSV"))

    --------------------------------------------------------------------------------
    -- Menubar:
    --------------------------------------------------------------------------------
    local menu = deps.menuManager.browser
    menu
        :addItems(1001, function()
            return {
                {   title = i18n("saveBrowserContentsToCSV"),
                    fn = saveBrowserContentsToCSV,
                },
            }
        end)
end

return plugin


text:
@interface FlickrPhotoTests : XCTestCase

@end

@implementation FlickrPhotoTests

- (void)setUp {
    [super setUp];
    // Put setup code here. This method is called before the invocation of each test method in the class.
}

- (void)tearDown {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    [super tearDown];
}

- (void)testPhotoUrlForSizeBig {
    // This is an example of a functional test case.
  NSString *expectedUrlString = @"https://farm1.static.flickr.com/2/1418878_1e9228336_b.jpg";
  NSURL *expectedUrl = [[NSURL alloc] initWithString:expectedUrlString];
  NSURL *actualUrl = [SWFlickrPhoto photoUrlForSize:BIG_IMAGE_SIZE photoId:@"1418878" server:@"2" secret:@"1e9228336" farm:@"1"];
  XCTAssertTrue([[expectedUrl absoluteString] isEqualToString:[actualUrl absoluteString]], @"pass");
}

- (void)testPhotoUrlForSizeSmall {
  // This is an example of a functional test case.
  NSString *expectedUrlString = @"https://farm1.static.flickr.com/2/1418878_1e9228336_s.jpg";
  NSURL *expectedUrl = [[NSURL alloc] initWithString:expectedUrlString];
  NSURL *actualUrl = [SWFlickrPhoto photoUrlForSize:SMALL_IMAGE_SIZE photoId:@"1418878" server:@"2" secret:@"1e9228336" farm:@"1"];
  XCTAssertTrue([[expectedUrl absoluteString] isEqualToString:[actualUrl absoluteString]], @"pass");
}

@end


text:
{-# LANGUAGE FlexibleContexts #-}

module Rows (
    main,
) where

import AnsiColor (Layer(Foreground, Background), availableColors, colorize)
import Color (Color)
import Color.Names (rainbow)
import Control.Monad ((<=<), filterM)
import qualified Control.Monad.State.Lazy as L
import qualified Control.Monad.State.Strict as S
import Data.Char (isSpace, isPrint)
import Data.Interpolate (interpolate)
import Data.List (group)
import Data.Metric (closest)
import Data.Proxy (Proxy(Proxy))
import qualified Data.Stream as Stream
import Data.Stream (Stream(Cons))
import Rgb (Rgb(Rgb), fromRgb, toRgb)
import System.Environment (getArgs, lookupEnv)
import System.Exit (exitFailure)
import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering))

data ColorState = ColorState (Stream Color)

mkColorState :: Stream Color -> ColorState
mkColorState = ColorState

nextColor :: ColorState -> (ColorState, Color)
nextColor (ColorState (c `Cons` cs)) = (ColorState cs, c)

squash :: (Eq a) => [a] -> [a]
squash = take 1 <=< group

fullRainbow :: [Color]
fullRainbow = squash $ concat $ zipWith f rainbow $ tail $ cycle rainbow
    where
        denom = 255
        availableRgbs = map toRgb availableColors
        closest' = closest (Proxy :: Proxy Double) availableRgbs
        f c1 c2 = squash $ map (fromRgb . closest' . toRgb) $ do
            numer <- [0 .. denom]
            return $ interpolate c1 c2 $ numer / denom

data EscapeStatus
    = Escaping
    | NotEscaping

printables :: String -> String
printables = const id $ flip S.evalState NotEscaping . filterM p
    where
        p c = do
            escStatus <- S.get
            case escStatus of
                Escaping -> case c of
                    'm' -> S.put NotEscaping >> return False
                    _ -> return False
                NotEscaping -> case c of
                    '\ESC' -> S.put Escaping >> return False
                    _ -> return $ or $ map ($ c) [isSpace, isPrint]

textWidth :: String -> Int
textWidth = flip S.execState 0 . mapM_ width
    where
        tabWidth = 8
        width c = case c of
            '\t' -> S.gets ((tabWidth -) . (`mod` tabWidth)) >>= \n -> S.modify (+ n)
            _ -> S.modify (+ 1)

colorify :: Options -> String -> L.State ColorState String
colorify opts str = do
    (colorSt, color) <- L.gets nextColor
    L.put colorSt
    return $ colorize layer color $ if layer == Background && padBg
        then str ++ replicate padLen ' '
        else str
    where
        layer = optLayer opts
        padBg = optPadBackgroundColor opts
        cols = optColumns opts
        lineLen = textWidth $ printables str
        padLen = if lineLen == 0
            then cols
            else (cols - (lineLen `mod` cols)) `mod` cols

data Options = Options {
    optLayer :: Layer,
    optPadBackgroundColor :: Bool,
    optColumns :: Int,
    optStartingColors :: Stream Color }

tryRead :: (Read a) => String -> Maybe a
tryRead str = case reads str of
    [(x, "")] -> Just x
    _ -> Nothing

readColumns :: IO Int
readColumns = do
    mColStr <- lookupEnv "COLUMNS"
    return $ case tryRead $ maybe "" id mColStr of
        Just cols -> cols
        Nothing -> 80

defaultColorStream :: Stream Color
defaultColorStream = let
    grayColors = Stream.cycle $ map fromRgb [Rgb 50 50 50, Rgb 5 5 5]
    rainbowColors = Stream.fromList $ squash $ cycle fullRainbow
    in case True of
        True -> rainbowColors
        False -> grayColors

parseOptions :: IO Options
parseOptions = do
    args <- getArgs
    layer <- case args of
        [] -> return Foreground
        ["--fg"] -> return Foreground
        ["--bg"] -> return Background
        _ -> exitFailure
    columns <- readColumns
    return Options {
        optLayer = layer,
        optPadBackgroundColor = True,
        optColumns = columns,
        optStartingColors = defaultColorStream }

processContent :: Options -> String -> String
processContent opts = unlines . flip L.evalState st . mapM f . lines
    where
        st = mkColorState $ optStartingColors opts
        f = colorify opts

main :: IO ()
main = do
    hSetBuffering stdout LineBuffering
    opts <- parseOptions
    interact $ processContent opts


text:
import {URL} from 'url';
import {parse, format} from 'path';

export const VALID_CDN_ORIGIN = 'https://cdn.ampproject.org';

/**
 * Convert an existing URL to one from the local `serve` command.
 */
export function CDNURLToLocalDistURL(
  url: URL,
  pathnames: [string | null, string | null] = [null, null],
  extension: string = '.js'
): URL {
  url.protocol = 'http';
  url.hostname = 'localhost';
  url.port = '8000';

  const [overwriteablePathname, newPathname] = pathnames;
  if (url.pathname === overwriteablePathname && newPathname !== null) {
    url.pathname = newPathname;
  }

  const parsedPath = parse('/dist' + url.pathname);
  if (parsedPath.ext !== extension) {
    parsedPath.base = parsedPath.base.replace(parsedPath.ext, extension);
    parsedPath.ext = extension;
  }
  url.pathname = format(parsedPath);

  return url;
}

/**
 * Convert an existing URL to one from a specific RTV.
 */
export function CDNURLToRTVURL(
  url: URL,
  mode: string,
  pathnames: [string | null, string | null] = [null, null],
  extension: string = '.js'
): URL {

  const [overwriteablePathname, newPathname] = pathnames;
  if (url.pathname === overwriteablePathname && newPathname !== null) {
    url.pathname = newPathname;
  }

  const parsedPath = parse(`/rtv/${mode}/${url.pathname}`);
  if (parsedPath.ext !== extension) {
    parsedPath.base = parsedPath.base.replace(parsedPath.ext, extension);
    parsedPath.ext = extension;
  }
  url.pathname = format(parsedPath);

  return url;
}


text:
package gov.nih.nci.cagrid.fqp.resultsretrieval.service.globus.resource;

import gov.nih.nci.cagrid.fqp.processor.exceptions.FederatedQueryProcessingException;
import gov.nih.nci.cagrid.fqp.results.stubs.types.InternalErrorFault;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;

import javax.xml.namespace.QName;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cagrid.data.dcql.DCQLQuery;
import org.cagrid.data.dcql.results.DCQLQueryResultsCollection;
import org.cagrid.fqp.execution.QueryExecutionParameters;
import org.cagrid.fqp.results.metadata.ProcessingStatus;
import org.cagrid.fqp.results.metadata.ResultsRange;
import org.globus.gsi.GlobusCredential;
import org.globus.wsrf.ResourceException;

/**
 * The implementation of this FederatedQueryResultsRetrievalResource type.
 *
 * @created by Introduce Toolkit version 1.4
 *
 */
public class FederatedQueryResultsRetrievalResource extends FederatedQueryResultsRetrievalResourceBase {
    protected static Log LOG = LogFactory.getLog(FederatedQueryResultsRetrievalResource.class.getName());

    // resource property manager
    private ResourcePropertyManager resourcePropertyManager = null;

    // initialization values of this resource
    private DCQLQuery query;
    private ExecutorService workExecutor;
    private GlobusCredential delegatedCredential;
    private QueryExecutionParameters executionParameters;

    // pending query execution
    private Future queryFuture = null;

    // result values of this resource
    private String statusMessage = null;
    private Exception processingException = null;
    private DCQLQueryResultsCollection queryResults = null;

    public FederatedQueryResultsRetrievalResource() {
        super();
    }

    public void initialize(Object resourceBean,
        QName resourceElementQName,
        Object id) throws ResourceException {
        super.initialize(resourceBean, resourceElementQName, id);
        resourcePropertyManager = new ResourcePropertyManager(this);
    }

    // ----------------------------------
    // Setters to initialize the resource
    // ----------------------------------

    /**
     * Sets the query to be executed by this resource
     */
    public void setQuery(DCQLQuery query) {
        this.query = query;
    }

    /**
     * Sets the ExecutionService instance which will handle the threaded
     * execution of the query
     * @param workExecutor
     */
    public void setWorkExecutor(ExecutorService workExecutor) {
        this.workExecutor = workExecutor;
    }

    /**
     * OPTIONAL
     * Sets the (delegated) client credential credential.  If supplied, the credential
     * will be used to execute queries against the data services referenced in the query
     * @param credentialRef
     */
    public void setDelegatedCredential(GlobusCredential clientCredential) {
        this.delegatedCredential = clientCredential;
    }

    /**
     * OPTIONAL
     * Sets the query execution parameters to be used by the federated query engine.
     * @param parameters
     */
    public void setQueryExecutionParameters(QueryExecutionParameters parameters) {
        this.executionParameters = parameters;
    }

    // -----------------------
    // starts query processing
    // -----------------------

    public void beginQueryProcessing() throws FederatedQueryProcessingException {
        // the set up for this needs to run synchronously so we can report
        // misconfigurations and setup problems back to the caller
        setStatusMessage("Verifying proper state for query processing");
        // verify the resource is in a state where it can run the query
        if (query == null) {
            throw new IllegalStateException(
                "DCQL query was not set before begining query processing!");
        }
        if (workExecutor == null) {
            throw new IllegalStateException(
                "No work manager set to handle query processing tasks!");
        }

        // set up a query processing listener to change resource property status
        AsynchronousFQPProcessingStatusListener listener = getStatusListener();

        Runnable queryWork =
            new QueryExecutionTask(query, delegatedCredential, executionParameters, workExecutor, listener);
        try {
            listener.processingStatusChanged(ProcessingStatus.Waiting_To_Begin, "Scheduling query for execution");
            this.queryFuture = workExecutor.submit(queryWork);
        } catch (RejectedExecutionException ex) {
            String message = "Error scheduling query: " + ex.getMessage();
            listener.processingStatusChanged(ProcessingStatus.Complete_With_Error, message);
            FederatedQueryProcessingException fqpException = new FederatedQueryProcessingException(message, ex);
            setProcessingException(fqpException);
            throw fqpException;
        }
    }

    /**
     * Additional implementation cancels the query execution task if it hasn't
     * already begun executing
     */
    public void remove() throws ResourceException {
        LOG.debug("Removing resource");
        super.remove();
        if (queryFuture != null) {
            LOG.debug("Canceling query execution work");
            queryFuture.cancel(true);
        }
    }

    // ------------------------
    // public interface methods
    // ------------------------

    /**
     * Returns the DCQL query results of the query.
     * @return
     */
    public DCQLQueryResultsCollection getResults() {
        // assumes that results already exist, and isComplete() == true
        return queryResults;
    }

    public DCQLQuery getQuery() {
        return this.query;
    }

    /**
     * Indicates if processing of the query is complete
     */
    public boolean isComplete() {
        return this.queryResults != null || this.processingException != null;
    }

    // ---------------------------------------
    // logging, debugging, and error reporting
    // ---------------------------------------

    private void setStatusMessage(String message) {
        LOG.debug(message);
        this.statusMessage = message;
        try {
            resourcePropertyManager.setExecutionDetailMessage(message);
        } catch (ResourceException ex) {
            LOG.warn("Error setting execution detail message on resource property: "
                + ex.getMessage(), ex);
        }
    }

    private void setProcessingException(Exception ex) {
        LOG.error("Error during federated query processing: " + ex.getMessage(), ex);
        this.processingException = ex;
    }

    // ----------------------------
    // things I'm changing around via notification and resource properties
    // ----------------------------

    public String getStatusMessage() {
        return this.statusMessage;
    }

    public Exception getProcessingException() {
        return this.processingException;
    }

    // --------------------------------------
    // listens for status changes and updates the resource properties
    // --------------------------------------

    private AsynchronousFQPProcessingStatusListener getStatusListener() {
        AsynchronousFQPProcessingStatusListener listener = new AsynchronousFQPProcessingStatusListener() {

            public void processingStatusChanged(ProcessingStatus status, String message) {
                try {
                    resourcePropertyManager.setProcessingStatus(status);
                    resourcePropertyManager.setExecutionDetailMessage(message);
                } catch (ResourceException ex) {
                    handleResourceException(ex);
                }
            }

            public void targetServiceOk(String serviceURL) {
                try {
                    resourcePropertyManager.setTargetServiceConnectionStatusOk(serviceURL);
                } catch (InternalErrorFault ex) {
                    handleInternalError(ex);
                } catch (ResourceException ex) {
                    handleResourceException(ex);
                }
            }

            public void targetServiceReturnedResults(String serviceURL, ResultsRange range) {
                try {
                    resourcePropertyManager.setServiceResultsRange(serviceURL, range);
                } catch (InternalErrorFault ex) {
                    handleInternalError(ex);
                } catch (ResourceException ex) {
                    handleResourceException(ex);
                }
            }

            public void targetServiceConnectionRefused(String serviceURL) {
                try {
                    resourcePropertyManager.setTargetServiceConnectionStatusRefused(serviceURL);
                } catch (InternalErrorFault ex) {
                    handleInternalError(ex);
                } catch (ResourceException ex) {
                    handleResourceException(ex);
                }
            }

            public void targetServiceThrowsException(String serviceURL, Exception exception) {
                try {
                    resourcePropertyManager.setTargetServiceConnectionStatusException(serviceURL, exception);
                } catch (InternalErrorFault ex) {
                    handleInternalError(ex);
                } catch (ResourceException ex) {
                    handleResourceException(ex);
                }
            }

            public void targetServiceReturnedInvalidResult(String serviceURL, FederatedQueryProcessingException exception) {
                try {
                    resourcePropertyManager.setExecutionDetailMessage("Invalid result returned from target data service " + serviceURL);
                    resourcePropertyManager.setTargetServiceConnectionStatusException(serviceURL, exception);
                } catch (InternalErrorFault ex) {
                    handleInternalError(ex);
                } catch (ResourceException ex) {
                    handleResourceException(ex);
                }
            }

            private void handleInternalError(InternalErrorFault ex) {
                ex.printStackTrace();
                setProcessingException(ex);
            }

            private void handleResourceException(ResourceException ex) {
                ex.printStackTrace();
                setProcessingException(ex);
            }

            public void queryResultsGenerated(DCQLQueryResultsCollection results) {
                queryResults = results;
            }

            public void queryProcessingException(FederatedQueryProcessingException ex) {
                setProcessingException(ex);
            }
        };
        return listener;
    }
}


text:
'use strict';

angular
    .module('erebus')
    .factory('logGroup', logGroup);

logGroup.$inject = ['CONFIG'];

function logGroup(CONFIG) {

    var logGroup = function() {
        this.groupDuplicates = true;
        this.maxSize = 10; // CONFIG.max_log_size
        this.entries = []
        this.groupSize = 0;
    };

    logGroup.prototype.add = function(entry) {
        var i, duplicate = -1;

        if(this.groupDuplicates) {
            // Look for duplicates in existing entries
            for(i in this.entries) {
                if(entry.isDuplicateOf(this.entries[i])) {
                    duplicate = i;
                    break;
                }
            }
            if(duplicate != -1) {
                // Found duplicate
                this.entries[duplicate].addDuplicate(entry);
            } else {
                this.entries.unshift(entry);
                this.groupSize += 1;
            }
        } else {
            this.entries.unshift(entry);
            this.groupSize += 1;
        }

        while(this.groupSize > this.maxSize) {
            this.pop();
        }
    };

    logGroup.prototype.pop = function() {
        var lastEntry = this.entries[this.groupSize-1];
        if(lastEntry.numDuplicates() == 0) {
            this.entries.pop();
            this.groupSize -= 1;
        } else {
            lastEntry.removeDuplicate();
        }
    };

    // Get all entries in a readable format
    // {message, type, time, count}
    logGroup.prototype.getAll = function() {
        var i, entry, entries = [];
        for(i in this.entries) {
            entry = this.entries[i].getEntry();
            entry.count = this.entries[i].numDuplicates();
            entries.push(entry);
        }
        return entries;
    };

    logGroup.prototype.emptyLog = function() {
        this.entries = [];
        this.groupSize = 0;
    };

    logGroup.prototype.showDuplicates = function() {
        var i, j, entry, dedup_entries = [], dup_entries = [];

        this.groupDuplicates = false;
        // Get all entries and their duplicates
        for(i in this.entries) {
            entry = this.entries[i];
            // Push duplicates
            if(entry.numDuplicates() > 0) {
                dedup_entries = entry.popDuplicates();
                for(j in dedup_entries) {
                    dup_entries.push(dedup_entries[j]);
                }
            }
            // Push original entry to deduplicated list
            dup_entries.push(entry);
        }
        // Drop all log entries
        this.emptyLog();
        // Refill
        for(i in dup_entries) {
            this.add(dup_entries[i]);
        }
    };

    // Hide duplicates
    logGroup.prototype.hideDuplicates = function() {
        var i, dup_entries = [];

        this.groupDuplicates = true;

        for(i in this.entries) {
            dup_entries.push(this.entries[i]);
        }
        // Drop all log entries
        this.emptyLog();
        // Refill
        for(i in dup_entries) {
            this.add(dup_entries[i]);
        }
    };

    return logGroup;
}