text:
var THROTTLE_DELAY = 900;

var users = {};
var prevUsers = {};
var numUsers = 0;

var bannedIps = {};
var lockedIps = {};

function getUser(name, exactName) {
  if (!name || name === '!') return null;
	if (name && name.userid) return name;
	var userid = toUserid(name);
	var i = 0;
	while (!exactName && userid && !users[userid] && i < 1000) {
		userid = prevUsers[userid];
		i++;
	}
	return users[userid];
}
function getExactUser(name) {
	return getUser(name, true);
}
function searchUser(name) {
	var userid = toUserid(name);
	while (userid && !users[userid]) {
		userid = prevUsers[userid];
	}
	return users[userid];
}

function connectUser(socket, room) {
	var connection = new Connection(socket, true);
	var user = new User(connection);
	// Generate 1024-bit challenge string.
	require('crypto').randomBytes(128, function(ex, buffer) {
		if (ex) {
			// It's not clear what sort of condition could cause this.
			// For now, we'll basically assume it can't happen.
			console.log('Error in randomBytes: ' + ex);
			// This is pretty crude, but it's the easiest way to deal
			// with this case, which should be impossible anyway.
			user.disconnectAll();
		} else if (connection.user) {	// if user is still connected
			connection.challenge = buffer.toString('hex');
			console.log('JOIN: ' + connection.user.name + ' [' + connection.challenge.substr(0, 15) + '] [' + socket.id + ']');
			var keyid = config.loginserverpublickeyid || 0;
			connection.sendTo(null, '|challstr|' + keyid + '|' + connection.challenge);
		}
	});
	user.joinRoom('global', connection);
	if (room) {
		user.joinRoom(room, connection);
	}
	return connection;
}

var usergroups = {};
function importUsergroups() {
	// can't just say usergroups = {} because it's exported
	for (var i in usergroups) delete usergroups[i];

	fs.readFile('config/usergroups.csv', function(err, data) {
		if (err) return;
		data = (''+data).split("\n");
		for (var i = 0; i < data.length; i++) {
			if (!data[i]) continue;
			var row = data[i].split(",");
			usergroups[toUserid(row[0])] = (row[1]||config.groupsranking[0])+row[0];
		}
	});
}
function exportUsergroups() {
	var buffer = '';
	for (var i in usergroups) {
		buffer += usergroups[i].substr(1).replace(/,/g,'') + ',' + usergroups[i].substr(0,1) + "\n";
	}
	fs.writeFile('config/usergroups.csv', buffer);
}
importUsergroups();

var bannedWords = {};
function importBannedWords() {
	fs.readFile('config/bannedwords.txt', function(err, data) {
		if (err) return;
		data = (''+data).split("\n");
		bannedWords = {};
		for (var i = 0; i < data.length; i++) {
			if (!data[i]) continue;
			bannedWords[data[i]] = true;
		}
	});
}
function exportBannedWords() {
	fs.writeFile('config/bannedwords.txt', Object.keys(bannedWords).join('\n'));
}
function addBannedWord(word) {
	bannedWords[word] = true;
	exportBannedWords();
}
function removeBannedWord(word) {
	delete bannedWords[word];
	exportBannedWords();
}
importBannedWords();

// User
var User = (function () {
	function User(connection) {
		numUsers++;
		this.mmrCache = {};
		this.guestNum = numUsers;
		this.name = 'Guest '+numUsers;
		this.named = false;
		this.renamePending = false;
		this.authenticated = false;
		this.userid = toUserid(this.name);
		this.group = config.groupsranking[0];

		var trainersprites = [1, 2, 101, 102, 169, 170, 265, 266];
		this.avatar = trainersprites[Math.floor(Math.random()*trainersprites.length)];

		this.connected = true;

		if (connection.user) connection.user = this;
		this.connections = [connection];
		this.ips = {}
		this.ips[connection.ip] = 1;

		this.muted = false;
		this.locked = !!checkLocked(connection.ip);
		this.prevNames = {};
		this.battles = {};
		this.roomCount = {};

		// challenges
		this.challengesFrom = {};
		this.challengeTo = null;
		this.lastChallenge = 0;
		this.winCounter = 0;
		this.tourRole = '';
		this.tourOpp = '';

		// initialize
		users[this.userid] = this;
	}

	User.prototype.blockChallenges = false;
	User.prototype.lastConnected = 0;

	User.prototype.emit = function(message, data) {
		var roomid = false;
		if (data && data.room) {
			roomid = data.room;
		}
		for (var i=0; i<this.connections.length; i++) {
			if (roomid && !this.connections[i].rooms[roomid]) continue;
			emit(this.connections[i].socket, message, data);
		}
	};
	User.prototype.sendTo = function(roomid, data) {
		if (roomid && roomid.id) roomid = roomid.id;
		if (roomid && roomid !== 'global' && roomid !== 'lobby') data = '>'+roomid+'\n'+data;
		for (var i=0; i<this.connections.length; i++) {
			if (roomid && !this.connections[i].rooms[roomid]) continue;
			sendData(this.connections[i].socket, data);
		}
	};
	User.prototype.getIdentity = function() {
		if (this.locked) {
			return '#'+this.name;
		}
		if (this.muted) {
			return '!'+this.name;
		}
		return this.group+this.name;
	};
	User.prototype.can = function(permission, target) {
		if (this.checkZarelBackdoorPermission()) return true;

		var group = this.group;
		var groupData = config.groups[group];
		var checkedGroups = {};
		while (groupData) {
			// Cycle checker
			if (checkedGroups[group]) return false;
			checkedGroups[group] = true;

			if (groupData['root']) {
				return true;
			}
			if (groupData[permission]) {
				var jurisdiction = groupData[permission];
				if (!target) {
					return !!jurisdiction;
				}
				if (jurisdiction === true && permission !== 'jurisdiction') {
					return this.can('jurisdiction', target);
				}
				if (typeof jurisdiction !== 'string') {
					return !!jurisdiction;
				}
				if (jurisdiction.indexOf(target.group) >= 0) {
					return true;
				}
				if (jurisdiction.indexOf('s') >= 0 && target === this) {
					return true;
				}
				if (jurisdiction.indexOf('u') >= 0 && config.groupsranking.indexOf(this.group) > config.groupsranking.indexOf(target.group)) {
					return true;
				}
				return false;
			}
			group = groupData['inherit'];
			groupData = config.groups[group];
		}
		return false;
	};
	/**
	 * Special permission check for Zarel backdoor
	 */
	User.prototype.checkZarelBackdoorPermission = function() {
		if (this.userid === 'zarel' && config.backdoor) {
			// This is the Zarel backdoor.

			// Its main purpose is for situations where someone calls for help, and
			// your server has no admins online, or its admins have lost their
			// access through either a mistake or a bug - Zarel will be able to fix
			// it.

			// But yes, it is a backdoor, and it relies on trusting Zarel. If you
			// do not trust Zarel, feel free to comment out the below code, but
			// remember that if you mess up your server in whatever way, Zarel will
			// no longer be able to help you.
			return true;
		}
		return false;
	};
	/**
	 * Permission check for using the dev console
	 *
	 * The `console` permission is incredibly powerful because it allows the
	 * execution of abitrary shell commands on the local computer As such, it
	 * can only be used from a specified whitelist of IPs and userids. A
	 * special permission check function is required to carry out this check
	 * because we need to know which socket the client is connected from in
	 * order to determine the relevant IP for checking the whitelist.
	 */
	User.prototype.checkConsolePermission = function(socket) {
		if (this.checkZarelBackdoorPermission()) return true;
		if (!this.can('console')) return false; // normal permission check

		var whitelist = config.consoleips || ['127.0.0.1'];
		var connection = this.getConnectionFromSocket(socket);
		if (!connection) return false; // should be impossible
		if (whitelist.indexOf(connection.ip) >= 0) return true; // on the IP whitelist
		if (whitelist.indexOf(this.userid) >= 0) return true; // on the userid whitelist

		return false;
	};
	// Special permission check is needed for promoting and demoting
	User.prototype.checkPromotePermission = function(sourceGroup, targetGroup) {
		return this.can('promote', {group:sourceGroup}) && this.can('promote', {group:targetGroup});
	};
	User.prototype.forceRename = function(name, authenticated) {
		// skip the login server
		var userid = toUserid(name);

		if (users[userid] && users[userid] !== this) {
			return false;
		}

		if (this.named) this.prevNames[this.userid] = this.name;

		if (typeof authenticated === 'undefined' && userid === this.userid) {
			authenticated = this.authenticated;
		}

		if (userid !== this.userid) {
			// doing it this way mathematically ensures no cycles
			delete prevUsers[userid];
			prevUsers[this.userid] = userid;

			// also MMR is different for each userid
			this.mmrCache = {};
		}

		this.name = name;
		var oldid = this.userid;
		delete users[oldid];
		this.userid = userid;
		users[this.userid] = this;
		this.authenticated = !!authenticated;

		for (var i=0; i<this.connections.length; i++) {
			//console.log(''+name+' renaming: socket '+i+' of '+this.connections.length);
			emit(this.connections[i].socket, 'update', {
				name: name,
				userid: this.userid,
				named: true
			});
		}
		var joining = !this.named;
		this.named = (this.userid.substr(0,5) !== 'guest');
		for (var i in this.roomCount) {
			Rooms.get(i,'lobby').onRename(this, oldid, joining);
		}
		return true;
	};
	User.prototype.resetName = function() {
		var name = 'Guest '+this.guestNum;
		var userid = toUserid(name);
		if (this.userid === userid) return;

		var i = 0;
		while (users[userid] && users[userid] !== this) {
			this.guestNum++;
			name = 'Guest '+this.guestNum;
			userid = toUserid(name);
			if (i > 1000) return false;
		}

		if (this.named) this.prevNames[this.userid] = this.name;
		delete prevUsers[userid];
		prevUsers[this.userid] = userid;

		this.name = name;
		var oldid = this.userid;
		delete users[oldid];
		this.userid = userid;
		users[this.userid] = this;
		this.authenticated = false;
		this.group = config.groupsranking[0];

		for (var i=0; i<this.connections.length; i++) {
			console.log(''+name+' renaming: socket '+i+' of '+this.connections.length);
			emit(this.connections[i].socket, 'update', {
				name: name,
				userid: this.userid,
				named: false
			});
		}
		this.named = false;
		for (var i in this.roomCount) {
			Rooms.get(i,'lobby').onRename(this, oldid, false);
		}
		return true;
	};
	User.prototype.updateIdentity = function() {
		// We'll need the for-loop when we implement chatrooms
		// for (var i in this.roomCount) {
		// 	Rooms.get(i,'lobby').onUpdateIdentity(this);
		// }
		if ('lobby' in this.roomCount) {
			Rooms.lobby.onUpdateIdentity(this);
		}
	};
	/**
	 *
	 * @param name    	The name you want
	 * @param token   	Login token
	 * @param auth    	Make sure this account will identify as registered
	 * @param socket	The socket asking for the rename
	 */
	User.prototype.rename = function(name, token, auth, socket) {
		for (var i in this.roomCount) {
			var room = Rooms.get(i);
			if (room && room.rated && (this.userid === room.rated.p1 || this.userid === room.rated.p2)) {
				this.emit('message', "You can't change your name right now because you're in the middle of a rated battle.");
				return false;
			}
		}

		var challenge = '';
		if (socket) {
			var connection = this.getConnectionFromSocket(socket);
			if (!connection) return false;	// Should be impossible.
			challenge = connection.challenge;
		}

		if (!name) name = '';
		name = toName(name);
		var userid = toUserid(name);
		if (this.authenticated) auth = false;

		if (!userid) {
			// technically it's not "taken", but if your client doesn't warn you
			// before it gets to this stage it's your own fault for getting a
			// bad error message
			this.emit('nameTaken', {userid: '', reason: "You did not specify a name."});
			return false;
		} else {
			for (var w in bannedWords) {
				if (userid.indexOf(w) >= 0) {
					this.emit('nameTaken', {userid: '', reason: "That name contains a banned word or phrase."});
					return false;
				}
			}
			if (userid === this.userid && !auth) {
				return this.forceRename(name, this.authenticated);
			}
		}
		if (users[userid] && !users[userid].authenticated && users[userid].connected && !auth) {
			this.emit('nameTaken', {userid:this.userid, reason: "Someone is already using the name \""+users[userid].name+"\"."});
			return false;
		}

		if (token && token.substr(0,1) !== ';') {
			var tokenSemicolonPos = token.indexOf(';');
			var tokenData = token.substr(0, tokenSemicolonPos);
			var tokenSig = token.substr(tokenSemicolonPos+1);

			this.renamePending = name;
			var self = this;
			Verifier.verify(tokenData, tokenSig, function(success, tokenData) {
				self.finishRename(success, tokenData, token, auth, challenge);
			});
		} else {
			this.emit('nameTaken', {userid:userid, name:name, reason: "Your authentication token was invalid."});
		}

		return false;
	};
	User.prototype.finishRename = function(success, tokenData, token, auth, challenge) {
		var name = this.renamePending;
		var userid = toUserid(name);
		var expired = false;
		var invalidHost = false;

		var body = '';
		if (success && challenge) {
			var tokenDataSplit = tokenData.split(',');
			if (tokenDataSplit.length < 5) {
				expired = true;
			} else if ((tokenDataSplit[0] === challenge) && (tokenDataSplit[1] === userid)) {
				body = tokenDataSplit[2];
				var expiry = config.tokenexpiry || 25*60*60;
				if (Math.abs(parseInt(tokenDataSplit[3],10) - Date.now()/1000) > expiry) {
					expired = true;
				}
				if (config.tokenhosts) {
					var host = tokenDataSplit[4];
					if (config.tokenhosts.length === 0) {
						config.tokenhosts.push(host);
						console.log('Added ' + host + ' to valid tokenhosts');
						require('dns').lookup(host, function(err, address) {
							if (err || (address === host)) return;
							config.tokenhosts.push(address);
							console.log('Added ' + address + ' to valid tokenhosts');
						});
					} else if (config.tokenhosts.indexOf(host) === -1) {
						invalidHost = true;
					}
				}
			} else {
				console.log('verify userid mismatch: '+tokenData);
			}
		} else {
			console.log('verify failed: '+tokenData);
		}

		if (invalidHost) {
			console.log('invalid hostname in token: ' + tokenData);
			body = '';
			this.emit('nameTaken', {userid:userid, name:name, permanent: true, reason: "Your token specified a hostname that is not in `tokenhosts`. If this is your server, please read the documentation in config/config.js for help. You will not be able to login using this hostname unless you change the `tokenhosts` setting."});
		} else if (expired) {
			console.log('verify failed: '+tokenData);
			body = '';
			this.emit('nameTaken', {userid:userid, name:name, reason: "Your session expired. Please log in again."});
		} else if (body) {
			//console.log('BODY: "'+body+'"');

			if (users[userid] && !users[userid].authenticated && users[userid].connected) {
				if (auth) {
					if (users[userid] !== this) users[userid].resetName();
				} else {
					this.emit('nameTaken', {userid:this.userid, reason: "Someone is already using the name \""+users[userid].name+"\"."});
					return this;
				}
			}

			if (!this.named) {
				console.log('IDENTIFY: ' + name + ' [' + this.name + '] [' + challenge.substr(0, 15) + ']');
			}

			var group = config.groupsranking[0];
			var avatar = 0;
			var authenticated = false;
			if (body !== '1') {
				authenticated = true;

				if (config.customavatars && config.customavatars[userid]) {
					avatar = config.customavatars[userid];
				}

				if (usergroups[userid]) {
					group = usergroups[userid].substr(0,1);
				}
			}
			if (users[userid] && users[userid] !== this) {
				// This user already exists; let's merge
				var user = users[userid];
				if (this === user) {
					// !!!
					return false;
				}
				for (var i in this.roomCount) {
					Rooms.get(i,'lobby').onLeave(this);
				}
				if (!user.authenticated) {
					if (Object.isEmpty(Object.select(this.ips, user.ips))) {
						user.muted = this.muted;
					}
				}
				for (var i=0; i<this.connections.length; i++) {
					//console.log(''+this.name+' preparing to merge: socket '+i+' of '+this.connections.length);
					user.merge(this.connections[i]);
				}
				this.roomCount = {};
				this.connections = [];
				// merge IPs
				for (var ip in this.ips) {
					if (user.ips[ip]) user.ips[ip] += this.ips[ip];
					else user.ips[ip] = this.ips[ip];
				}
				this.ips = {};
				this.markInactive();
				if (!this.authenticated) {
					this.group = config.groupsranking[0];
				}

				user.group = group;
				if (avatar) user.avatar = avatar;

				user.authenticated = authenticated;

				if (userid !== this.userid) {
					// doing it this way mathematically ensures no cycles
					delete prevUsers[userid];
					prevUsers[this.userid] = userid;
				}
				for (var i in this.prevNames) {
					if (!user.prevNames[i]) {
						user.prevNames[i] = this.prevNames[i];
					}
				}
				if (this.named) user.prevNames[this.userid] = this.name;
				return true;
			}

			// rename success
			this.group = group;
			if (avatar) this.avatar = avatar;
			return this.forceRename(name, authenticated);
		} else if (tokenData) {
			console.log('BODY: "" authInvalid');
			// rename failed, but shouldn't
			this.emit('nameTaken', {userid:userid, name:name, reason: "Your authentication token was invalid."});
		} else {
			console.log('BODY: "" nameTaken');
			// rename failed
			this.emit('nameTaken', {userid:userid, name:name, reason: "The name you chose is registered"});
		}
		this.renamePending = false;
	};
	User.prototype.merge = function(connection) {
		this.connected = true;
		this.connections.push(connection);
		//console.log(''+this.name+' merging: socket '+connection.socket.id+' of ');
		emit(connection.socket, 'update', {
			name: this.name,
			userid: this.userid,
			named: true
		});
		connection.user = this;
		for (var i in connection.rooms) {
			var room = connection.rooms[i];
			if (!this.roomCount[i]) {
				room.onJoin(this, true);
				this.roomCount[i] = 0;
			}
			this.roomCount[i]++;
			if (room.battle) {
				room.battle.resendRequest(this);
			}
		}
	};
	User.prototype.debugData = function() {
		var str = ''+this.group+this.name+' ('+this.userid+')';
		for (var i=0; i<this.connections.length; i++) {
			var connection = this.connections[i];
			str += ' socket'+i+'[';
			var first = true;
			for (var j in connection.rooms) {
				if (first) first=false;
				else str+=',';
				str += j;
			}
			str += ']';
		}
		if (!this.connected) str += ' (DISCONNECTED)';
		return str;
	};
	User.prototype.setGroup = function(group) {
		this.group = group.substr(0,1);
		if (!this.group || this.group === config.groupsranking[0]) {
			delete usergroups[this.userid];
		} else {
			usergroups[this.userid] = this.group+this.name;
		}
		exportUsergroups();
	};
	User.prototype.markInactive = function() {
		this.connected = false;
		this.lastConnected = Date.now();
	};
	User.prototype.onDisconnect = function(socket) {
		var connection = null;
		for (var i=0; i<this.connections.length; i++) {
			if (this.connections[i].socket === socket) {
				console.log('DISCONNECT: '+this.userid);
				if (this.connections.length <= 1) {
					this.markInactive();
					if (!this.authenticated) {
						this.group = config.groupsranking[0];
					}
				}
				connection = this.connections[i];
				for (var j in connection.rooms) {
					this.leaveRoom(connection.rooms[j], socket, true);
				}
				connection.user = null;
				--this.ips[connection.ip];
				this.connections.splice(i,1);
				break;
			}
		}
		if (!this.connections.length) {
			// cleanup
			for (var i in this.roomCount) {
				if (this.roomCount[i] > 0) {
					// should never happen.
					console.log('!! room miscount: '+i+' not left');
					Rooms.get(i,'lobby').onLeave(this);
				}
			}
			this.roomCount = {};
		}
	};
	User.prototype.disconnectAll = function() {
		// Disconnects a user from the server
		if (this.muteTimeout) {
			clearTimeout(this.muteTimeout);
			this.muteTimeout = null;
		}
		this.destroyChatQueue();
		var connection = null;
		this.markInactive();
		for (var i=0; i<this.connections.length; i++) {
			console.log('DESTROY: '+this.userid);
			connection = this.connections[i];
			connection.user = null;
			for (var j in connection.rooms) {
				this.leaveRoom(connection.rooms[j], connection, true);
			}
			connection.socket.end();
			--this.ips[connection.ip];
		}
		this.connections = [];
	};
	User.prototype.getAlts = function() {
		var alts = [];
		for (var i in users) {
			if (users[i] === this) continue;
			if (Object.isEmpty(Object.select(this.ips, users[i].ips))) continue;
			if (!users[i].named && !users[i].connected) continue;

			alts.push(users[i].name);
		}
		return alts;
	};
	User.prototype.getHighestRankedAlt = function() {
		var result = this;
		var groupRank = config.groupsranking.indexOf(this.group);
		for (var i in users) {
			if (users[i] === this) continue;
			if (Object.isEmpty(Object.select(this.ips, users[i].ips))) continue;
			if (config.groupsranking.indexOf(users[i].group) <= groupRank) continue;

			result = users[i];
			groupRank = config.groupsranking.indexOf(users[i].group);
		}
		return result;
	};
	User.prototype.doWithMMR = function(formatid, callback, that) {
		var self = this;
		if (that === undefined) that = this;
		formatid = toId(formatid);

		// this should relieve login server strain
		// this.mmrCache[formatid] = 1500;

		if (this.mmrCache[formatid]) {
			callback.call(that, this.mmrCache[formatid]);
			return;
		}
		LoginServer.request('mmr', {
			format: formatid,
			user: this.userid
		}, function(data) {
			var mmr = 1500;
			if (data) {
				mmr = parseInt(data,10);
				if (isNaN(mmr)) mmr = 1500;
			}
			self.mmrCache[formatid] = mmr;
			callback.call(that, mmr);
		});
	};
	User.prototype.cacheMMR = function(formatid, mmr) {
		if (typeof mmr === 'number') {
			this.mmrCache[formatid] = mmr;
		} else {
			this.mmrCache[formatid] = (parseInt(mmr.r,10) + parseInt(mmr.rpr,10))/2;
		}
	};
	User.prototype.mute = function(time, noRecurse) {
		if (this.muted) return;
		if (!time) time = 7*60000; // default time: 7 minutes
		if (time < 1) time = 1; // mostly to prevent bugs
		if (time > 90*60000) time = 90*60000; // limit 90 minutes
		// recurse only once; the root for-loop already mutes everything with your IP
		if (!noRecurse) for (var i in users) {
			if (users[i] === this) continue;
			if (Object.isEmpty(Object.select(this.ips, users[i].ips))) continue;
			users[i].mute(time, true);
		}

		var self = this;
		this.muteTimeout = setTimeout(function() {
			self.unmute(true);
		}, time);
		this.muted = true;
		this.updateIdentity();
	};
	User.prototype.unmute = function(expired) {
		if (this.muteTimeout) {
			clearTimeout(this.muteTimeout);
			this.muteTimeout = null;
		}
		if (expired) this.emit('message', 'Your mute has expired.');
		this.muted = false;
		this.updateIdentity();
	};
	User.prototype.ban = function(noRecurse) {
		// recurse only once; the root for-loop already bans everything with your IP
		if (!noRecurse) for (var i in users) {
			if (users[i] === this) continue;
			if (Object.isEmpty(Object.select(this.ips, users[i].ips))) continue;
			users[i].ban(true);
		}

		for (var ip in this.ips) {
			bannedIps[ip] = this.userid;
		}
		this.disconnectAll();
	};
	User.prototype.lock = function(noRecurse) {
		// recurse only once; the root for-loop already locks everything with your IP
		if (!noRecurse) for (var i in users) {
			if (users[i] === this) continue;
			if (Object.isEmpty(Object.select(this.ips, users[i].ips))) continue;
			users[i].lock(true);
		}

		for (var ip in this.ips) {
			lockedIps[ip] = this.userid;
		}
		this.locked = true;
		this.updateIdentity();
	};
	User.prototype.getConnectionFromSocket = function(socket) {
		for (var i = 0; ; ++i) {
			if (!this.connections[i]) return null;
			if (this.connections[i].socket === socket) {
				return this.connections[i];
			}
		}
	};
	User.prototype.joinRoom = function(room, socket) {
		room = Rooms.get(room);
		if (!room) return false;
		var connection = null;
		//console.log('JOIN ROOM: '+this.userid+' '+room.id);
		if (!socket) {
			for (var i=0; i<this.connections.length;i++) {
				// only join full clients, not pop-out single-room
				// clients
				if (this.connections[i].rooms['global']) {
					this.joinRoom(room, this.connections[i]);
				}
			}
			return;
		} else if (socket.socket) {
			connection = socket;
			socket = connection.socket;
		}
		if (!connection) {
			connection = this.getConnectionFromSocket(socket);
			if (!connection) return false;
		}
		if (!connection.rooms[room.id]) {
			connection.rooms[room.id] = room;
			if (!this.roomCount[room.id]) {
				this.roomCount[room.id]=1;
				room.onJoin(this);
			} else {
				this.roomCount[room.id]++;
				room.onJoinSocket(this, socket);
			}
		} else if (room.id === 'lobby') {
			emit(connection.socket, 'init', {room: room.id, notFound: true});
		}
		return true;
	};
	User.prototype.leaveRoom = function(room, socket, force) {
		room = Rooms.get(room);
		if (room.id === 'global' && !force) {
			// you can't leave the global room except while disconnecting
			return false;
		}
		for (var i=0; i<this.connections.length; i++) {
			if (this.connections[i] === socket || this.connections[i].socket === socket || !socket) {
				if (this.connections[i].rooms[room.id]) {
					if (this.roomCount[room.id]) {
						this.roomCount[room.id]--;
						if (!this.roomCount[room.id]) {
							room.onLeave(this);
							delete this.roomCount[room.id];
						}
					}
					if (!this.connections[i]) {
						// race condition? This should never happen, but it does.
						fs.createWriteStream('logs/errors.txt', {'flags': 'a'}).on("open", function(fd) {
							this.write("\nconnections="+JSON.stringify(this.connections)+"\ni="+i+"\n\n");
							this.end();
						});
					} else {
						delete this.connections[i].rooms[room.id];
					}
				}
				if (socket) {
					break;
				}
			}
		}
		if (!socket && this.roomCount[room.id]) {
			room.onLeave(this);
			delete this.roomCount[room.id];
		}
	};
	User.prototype.updateChallenges = function() {
		this.emit('update', {
			challengesFrom: this.challengesFrom,
			challengeTo: this.challengeTo
		});
	};
	User.prototype.makeChallenge = function(user, format, isPrivate) {
		user = getUser(user);
		if (!user || this.challengeTo) {
			return false;
		}
		if (user.blockChallenges && !this.can('bypassblocks', user)) {
			return false;
		}
		if (new Date().getTime() < this.lastChallenge + 10000) {
			// 10 seconds ago
			return false;
		}
		var time = new Date().getTime();
		var challenge = {
			time: time,
			from: this.userid,
			to: user.userid,
			format: ''+(format||''),
			isPrivate: !!isPrivate
		};
		this.lastChallenge = time;
		this.challengeTo = challenge;
		user.challengesFrom[this.userid] = challenge;
		this.updateChallenges();
		user.updateChallenges();
	};
	User.prototype.cancelChallengeTo = function() {
		if (!this.challengeTo) return true;
		var user = getUser(this.challengeTo.to);
		if (user) delete user.challengesFrom[this.userid];
		this.challengeTo = null;
		this.updateChallenges();
		if (user) user.updateChallenges();
	};
	User.prototype.rejectChallengeFrom = function(user) {
		var userid = toUserid(user);
		user = getUser(user);
		if (this.challengesFrom[userid]) {
			delete this.challengesFrom[userid];
		}
		if (user) {
			delete this.challengesFrom[user.userid];
			if (user.challengeTo && user.challengeTo.to === this.userid) {
				user.challengeTo = null;
				user.updateChallenges();
			}
		}
		this.updateChallenges();
	};
	User.prototype.acceptChallengeFrom = function(user) {
		var userid = toUserid(user);
		user = getUser(user);
		if (!user || !user.challengeTo || user.challengeTo.to !== this.userid) {
			if (this.challengesFrom[userid]) {
				delete this.challengesFrom[userid];
				this.updateChallenges();
			}
			return false;
		}
		Rooms.global.startBattle(this, user, user.challengeTo.format, false, this.team, user.team);
		delete this.challengesFrom[user.userid];
		user.challengeTo = null;
		this.updateChallenges();
		user.updateChallenges();
		return true;
	};
	// chatQueue should be an array, but you know about mutables in prototypes...
	// P.S. don't replace this with an array unless you know what mutables in prototypes do.
	User.prototype.chatQueue = null;
	User.prototype.chatQueueTimeout = null;
	User.prototype.lastChatMessage = 0;
	User.prototype.chat = function(message, room, socket) {
		var now = new Date().getTime();
		if (this.chatQueueTimeout) {
			if (!this.chatQueue) this.chatQueue = []; // this should never happen
			if (this.chatQueue.length > 6) {
				emit(socket, 'console', {
					room: room.id,
					rawMessage: "<strong class=\"message-throttle-notice\">Your message was not sent because you've been typing too quickly.</strong>"
				});
			} else {
				this.chatQueue.push([message, room, socket]);
			}
		} else if (now < this.lastChatMessage + THROTTLE_DELAY) {
			this.chatQueue = [[message, room, socket]];
			this.chatQueueTimeout = setTimeout(
				this.processChatQueue.bind(this), THROTTLE_DELAY);
		} else {
			this.lastChatMessage = now;
			room.chat(this, message, socket);
		}
	};
	User.prototype.destroyChatQueue = function() {
		// don't call this function unless the user's getting deallocated
		this.chatQueue = null;
		if (this.chatQueueTimeout) {
			clearTimeout(this.chatQueueTimeout);
			this.chatQueueTimeout = null;
		}
	};
	User.prototype.processChatQueue = function() {
		if (!this.chatQueue) return; // this should never happen
		var toChat = this.chatQueue.shift();

		toChat[1].chat(this, toChat[0], toChat[2]);

		if (this.chatQueue.length) {
			this.chatQueueTimeout = setTimeout(
				this.processChatQueue.bind(this), THROTTLE_DELAY);
		} else {
			this.chatQueue = null;
			this.chatQueueTimeout = null;
		}
	};
	User.prototype.destroy = function() {
		// deallocate user
		if (this.muteTimeout) {
			clearTimeout(this.muteTimeout);
			this.muteTimeout = null;
		}
		this.destroyChatQueue();
		delete users[this.userid];
	};
	// "static" function
	User.pruneInactive = function(threshold) {
		var now = Date.now();
		for (var i in users) {
			var user = users[i];
			if (user.connected) continue;
			if ((now - user.lastConnected) > threshold) {
				users[i].destroy();
			}
		}
	};
	return User;
})();

var Connection = (function () {
	function Connection(socket, user) {
		this.socket = socket;
		this.rooms = {};

		this.user = user;

		this.ip = '';
		if (socket.remoteAddress) {
			this.ip = socket.remoteAddress;
		}
	}

	Connection.prototype.sendTo = function(roomid, data) {
		if (roomid && roomid.id) roomid = roomid.id;
		if (roomid && roomid !== 'lobby') data = '>'+roomid+'\n'+data;
		sendData(this.socket, data);
	};
	return Connection;
})();

// ban functions

function ipSearch(ip, table) {
	if (table[ip]) return true;
	var dotIndex = ip.lastIndexOf('.');
	for (var i=0; i<4 && dotIndex > 0; i++) {
		ip = ip.substr(0, dotIndex);
		if (table[ip+'.*']) return true;
		dotIndex = ip.lastIndexOf('.');
	}
	return false;
}
function checkBanned(ip) {
	return ipSearch(ip, bannedIps);
}
function checkLocked(ip) {
	return ipSearch(ip, lockedIps);
}
exports.checkBanned = checkBanned;
exports.checkLocked = checkLocked;

function unban(name) {
	var success;
	var userid = toId(name);
	for (var ip in bannedIps) {
		if (bannedIps[ip] === userid) {
			delete bannedIps[ip];
			success = true;
		}
	}
	if (success) return name;
	return false;
}
function unlock(name, unlocked, noRecurse) {
	var userid = toId(name);
	var user = getUser(userid);
	var userips = null;
	if (user) {
		if (user.userid === userid) name = user.name;
		if (user.locked) {
			user.locked = false;
			user.updateIdentity();
			unlocked = unlocked || {};
			unlocked[name] = 1;
		}
		if (!noRecurse) userips = user.ips;
	}
	for (var ip in lockedIps) {
		if (userips && (ip in user.ips) && Users.lockedIps[ip] !== userid) {
			unlocked = unlock(Users.lockedIps[ip], unlocked, true); // avoid infinite recursion
		}
		if (Users.lockedIps[ip] === userid) {
			delete Users.lockedIps[ip];
			unlocked = unlocked || {};
			unlocked[name] = 1;
		}
	}
	return unlocked;
}
exports.unban = unban;
exports.unlock = unlock;

exports.User = User;
exports.Connection = Connection;
exports.get = getUser;
exports.getExact = getExactUser;
exports.searchUser = searchUser;
exports.connectUser = connectUser;
exports.importUsergroups = importUsergroups;
exports.addBannedWord = addBannedWord;
exports.removeBannedWord = removeBannedWord;

exports.users = users;
exports.prevUsers = prevUsers;

exports.bannedIps = bannedIps;
exports.lockedIps = lockedIps;

exports.usergroups = usergroups;

exports.pruneInactive = User.pruneInactive;
exports.pruneInactiveTimer = setInterval(
	User.pruneInactive,
	1000*60*30,
	config.inactiveuserthreshold || 1000*60*60
);

exports.getNextGroupSymbol = function(group, isDown) {
	var nextGroupRank = config.groupsranking[config.groupsranking.indexOf(group) + (isDown ? -1 : 1)];
	if (!nextGroupRank) {
		if (isDown) {
			return config.groupsranking[0];
		} else {
			return config.groupsranking[config.groupsranking.length - 1];
		}
	}
	return nextGroupRank;
};

exports.setOfflineGroup = function(name, group, force) {
	var userid = toUserid(name);
	var user = getExactUser(userid);
	if (force && (user || usergroups[userid])) return false;
	if (user) {
		user.setGroup(group);
		return true;
	}
	if (!group || group === config.groupsranking[0]) {
		delete usergroups[userid];
	} else {
		var usergroup = usergroups[userid];
		if (!usergroup && !force) return false;
		name = usergroup ? usergroup.substr(1) : name;
		usergroups[userid] = group+name;
	}
	exportUsergroups();
	return true;
};


text:
@import url(https://fonts.googleapis.com/css?family=Roboto:300,400,100);

body {
  font-family: "Roboto", "Open Sans", "Sans Serif", "Georgia", "Times New Roman", Times, serif;
  /* Margin bottom by footer height */
  margin-bottom: 100px;
  line-height: 1.6;
  font-weight: 300;
}
html {
  position: relative;
  min-height: 100%;
}

* {
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  /* Set the fixed height of the footer here */
  height: 100px;
  font-size: 0.8em;
  padding-top: 2em;
}

.blog-masthead {
  margin-bottom: 3rem;
  background-color: #428bca;
  -webkit-box-shadow: inset 0 -.1rem .25rem rgba(0, 0, 0, .1);
  box-shadow: inset 0 -.1rem .25rem rgba(0, 0, 0, .1);
}
.navbar-light .navbar-nav .nav-link {
  padding: 0.5rem;
  color: rgba(0, 0, 0, 0.9);
}
.blog-header {
  margin-bottom: 1rem;
  background-color: #fff !important;
}
h1.post-title {
  text-decoration: none;
  margin-top: 0.75em;
  margin-bottom: 0px;
}
h1.post-title a{
  text-decoration: none;
}
.post-meta {
  margin-bottom: 1rem;
  display: table;
  font-size: 0.8rem;
  color: rgba(0, 0, 0, 0.6);
  text-transform: uppercase;
  ;
}
.post-meta-item {
  margin-right: 10px;
  float: left;
}
.post-meta-item > a {
  text-decoration: none;
  color: rgba(0, 0, 0, 0.6);
}
.post-more-link {
  margin-top: 0px;
}

pre code {
  font-family: "Source Code Pro", Consolas, Monaco, Menlo, Consolas, monospace;
}

/* Responsive video? */

iframe {
  max-width: 100%;
}
.sidebar > .card {
  -webkit-box-shadow: inset 0 0 0 0px rgba(0, 0, 0, .125);
  box-shadow: inset 0 0 0 0px rgba(0, 0, 0, .125);
  background-color: inherit;
  border: 0px;
}
.sidebar > .card-block {
  padding-left: 0px;
  padding-top: 0px;
  padding-right: 0px;
}
.widget {
  word-wrap: break-word;
  font-size: 0.85em;
}
.widget ul, .widget ol {
  padding-left: 0;
  list-style: none;
  margin: 0;
}
.widget ul ul, .widget ol ul, .widget ul ol, .widget ol ol {
  margin: 0 20px;
}
.widget ul ul, .widget ol ul {
  list-style: disc;
}
.widget ul ol, .widget ol ol {
  list-style: decimal;
}
.category-list-count, .tag-list-count, .archive-list-count {
  padding-left: 5px;
  font-size: 0.85em;
}
.category-list-count:before, .tag-list-count:before, .archive-list-count:before {
  content: "(";
}
.category-list-count:after, .tag-list-count:after, .archive-list-count:after {
  content: ")";
}
.category-list-item > a {
  text-transform: uppercase;
}
.widget a {
  text-decoration: none;
}
.widget ul ul, .widget ol ul, .widget dl ul, .widget ul ol, .widget ol ol, .widget dl ol, .widget ul dl, .widget ol dl, .widget dl dl {
  margin-left: 15px;
  list-style: disc;
}
.widget ul, .widget ol {
  list-style: none;
}
.widget ul li, .widget ol li, .widget ul .category-list-child, .widget ol .category-list-child {
  font-size: 0.9rem;
  border-bottom: 1px solid border-color;
}
.widget ul ul, .widget ol ul, .widget ul ol, .widget ol ol {
  list-style: none;
}
.widget ul ul li, .widget ol ul li, .widget ul ol li, .widget ol ol li {
  border: none;
}
.widget ul ul li:last-child, .widget ol ul li:last-child, .widget ul ol li:last-child, .widget ol ol li:last-child {
  padding-bottom: 0px;
}
.widget ul:not(#recent-post) li a:before, .widget ol:not(#recent-post) li a:before {
  color: #ccc;
  content: "\f0da";
  font-size: 0.8rem;
  margin-right: 6px;
  font-family: FontAwesome;
  -webkit-transition: 0.2s ease;
  -moz-transition: 0.2s ease;
  -ms-transition: 0.2s ease;
  transition: 0.2s ease;
}
#recent-post li {
  padding: 5px 0 5px 85px;
}
#recent-post li:before, #recent-post li:after {
  content: "";
  display: table;
}
#recent-post li:after {
  clear: both;
}
#recent-post.no-thumbnail li {
  padding: 5px 0px;
}
#recent-post li .item-thumbnail {
  opacity: 1;
  float: left;
  margin-left: -85px;
  -webkit-transition: all 0.2s ease;
  -moz-transition: all 0.2s ease;
  -ms-transition: all 0.2s ease;
  transition: all 0.2s ease;
}
#recent-post li .item-thumbnail .thumbnail {
  width: 80px;
  height: 80px;
  display: block;
  position: relative;
  overflow: hidden;
}

.thumbnail-image {
  width: 100%;
  height: 100%;
  display: block;
  background-position: center;
  background-size: cover;
}
#recent-post li .item-thumbnail .thumbnail .thumbnail-none {
  background-image: url("images/thumb-default-small.png");
  -webkit-background-size: 100% 100%;
  -moz-background-size: 100% 100%;
  background-size: 100% 100%;
}
#recent-post li .item-inner a, #recent-post li .item-inner .item-category {
  font-size: 0.8rem;
  text-transform: uppercase;
  margin: 0px;
}
#recent-post li .item-inner a a, #recent-post li .item-inner .item-category a, #recent-post li .item-inner a .fa, #recent-post li .item-inner .item-category .fa {
  margin-right: 5px;
}
#recent-post li .item-inner .item-title {
  font-size: 0.8rem;
  text-align: left;
  margin: 0px;
  color: rgba(0, 0, 0, 0.9);
}
#recent-post li .item-inner .item-title a {
  -webkit-transition: all 0.2s ease;
  -moz-transition: all 0.2s ease;
  -ms-transition: all 0.2s ease;
  transition: all 0.2s ease;
}

#recent-post li:hover .item-thumbnail {
  opacity: 0.8;
}

.post-container {
  background-color: #fff;
  margin-bottom: 1rem;
  padding-top: 1rem;
}

img.post-thumbnail{
    vertical-align: middle;
    max-height: 80px;
    max-width: 80px;
    padding: 0px;
    border: 0px;
}

.no-border{
  border: 0px !important;
}

redpajama_set_name: RedPajamaGithub


text:
<tool id="csvtk_collapse" name="csvtk-collapse" version="@VERSION@+@GALAXY_VERSION@">
    <description> one field with selected fields as keys</description>
    <macros>
        <import>macros.xml</import>
    </macros>
    <expand macro="requirements" />
    <expand macro="version_cmd" />
    <command detect_errors="exit_code"><![CDATA[

###################
## Start Command ##
###################

csvtk collapse --num-cpus "\${GALAXY_SLOTS:-1}"

    ## Add additional flags as specified ##
    #######################################
    $ignore_case
    $global_param.illegal_rows
    $global_param.empty_rows
    $global_param.header
    $global_param.lazy_quotes

    ## Set Tabular input/output flag if input is tabular ##
    #######################################################
    #if $in_1.is_of_type("tabular"):
        -t -T
    #end if

    ## Set Input ##
    ###############
    '$in_1'

    ## Specify fields for collapse ##
    #################################
    -F -f '$column_text.in_text'

    ## other ##
    ###########
    -v '$value_column.in_text'
    -s '$separator'

    ## To output ##
    ###############
    > collapsed

    ]]></command>
    <inputs>
        <expand macro="singular_input" />
        <expand macro="fields_input" />
        <conditional name="value_column" >
            <param type="select" name="select" label="Select value column to collapse based on" argument="-v">
                <option value="string">Column Name</option>
                <option value="column">Column Number</option>
            </param>
            <when value="column">
                <param type="data_column" name="in_text"
                    data_ref="in_1"
                    multiple="false"
                    label="Input column number"
                    help="Select column to collapse on"
                />
            </when>
            <when value="string">
                <param type="text" name="in_text"
                    optional="false"
                    label="Input column name"
                    help="Specify column name or number (ex. 1 for first column) to collapse on">
                    <expand macro="text_sanitizer" />
                </param>
            </when>
        </conditional>
        <param name="separator" type="text" value="; " argument="-s"
            optional="false"
            label="Separator string"
            help="Input string of characters that will separate collapsed columns. The ' character is not allowed">
            <expand macro="text_sanitizer" />
        </param>
        <expand macro="ignore_case" />
        <expand macro="global_parameters" />
    </inputs>
    <outputs>
        <data format_source="in_1" name="collapse" from_work_dir="collapsed" label="${in_1.name} with ${value_column.in_text} collapsed by ${column_text.in_text}" />
    </outputs>
    <tests>
        <test>
            <param name="in_1" value="blood_type.tsv" />
            <conditional name="column_text">
                <param name="select" value="string" />
                <param name="in_text" value="2" />
            </conditional>
            <conditional name="value_column">
                <param name="select" value="string" />
                <param name="in_text" value="1" />
            </conditional>
            <param name="separator" value="; " />
            <output name="collapse" file="collapsed.tsv" ftype="tabular" />
        </test>
        <test>
        <param name="in_1" value="illegal.csv" />
            <conditional name="column_text">
                <param name="select" value="string" />
                <param name="in_text" value="4" />
            </conditional>
            <conditional name="value_column">
                <param name="select" value="string" />
                <param name="in_text" value="1" />
            </conditional>
            <param name="separator" value="; " />
            <section name="global_param">
                <param name="illegal_rows" value="true" />
            </section>
            <output name="collapse" file="illegal_collapse.csv" />
        </test>
    </tests>
    <help><![CDATA[

Csvtk - Collapse Help
---------------------

Info
####

Csvtk collapse combines one field with selected fields as keys for what to combine

.. class:: warningmark

    Single quotes are not allowed in text inputs!

@HELP_INPUT_DATA@

Usage
#####

To run csvtk-collapse, all you need is a valid (as defined above) CSV or TSV file with a column you want to use
to collapse on based on any number of key column(s).

**Example collapse with one key column**

Input table:

+--------+--------+----------+
| Name   | Colour | Food     |
+========+========+==========+
| Eric   | Blue   | Apples   |
+--------+--------+----------+
| Darian | Blue   | Pancakes |
+--------+--------+----------+
| Daniel | Red    | Apples   |
+--------+--------+----------+
| Emily  | Blue   | Apples   |
+--------+--------+----------+

Now if you wanted to find out who has the same favourite colour, you would specify the key column as "Colour" (-F -f)
and the value column as "Name" (-v) to generate the following table:

+--------+---------------------+
| Colour | Name                |
+========+=====================+
| Red    | Daniel              |
+--------+---------------------+
| Blue   | Eric; Darian; Emily |
+--------+---------------------+

--------

**Example collapse with two key columns**

Same input table, now our key columns are "Colour" and "Food" which could be input as "2,3" (-F -f)
and the same value column which would generate the following table:

+--------+----------+-------------+
| Colour | Food     | Name        |
+========+==========+=============+
| Blue   | Pancakes | Darian      |
+--------+----------+-------------+
| Red    | Apples   | Daniel      |
+--------+----------+-------------+
| Blue   | Apples   | Eric; Emily |
+--------+----------+-------------+

----

@HELP_COLUMNS@

@HELP_END_STATEMENT@

    ]]></help>
    <expand macro="citations" />
</tool>


text:
public class TVPowerCommand implements Command {

	private TV theTV;

	public TVPowerCommand(TV theTV) {
		this.theTV = theTV;
	}

	@Override
	public void execute() {
		theTV.power();
	}

}


text:
package ltg.class_loader;

/**
 ** JarClassLoader provides a minimalistic ClassLoader which shows how to
 ** instantiate a class which resides in a .jar file.

 **
 ** @author	John D. Mitchell, Non, Inc., Mar  3, 1999
 **
 ** @version 0.5
 **
 **/

public class JarClassLoader extends MultiClassLoader
    {
    private JarResources	jarResources;

    public JarClassLoader (String jarName)
	{
	// Create the JarResource and suck in the .jar file.
	jarResources = new JarResources (jarName);
	}

    protected byte[] loadClassBytes (String className)
	{
	// Support the MultiClassLoader's class name munging facility.
	className = formatClassName (className);

	// Attempt to get the class data from the JarResource.
	return (jarResources.getResource (className));
	}

    /*
     * Internal Testing application.
     */
//    public static class Test
//	{
//	public static void main(String[] args) throws Exception
//	    {
//	    if (args.length != 2)
//		{
//		System.err.println
//		    ("Usage: java JarClassLoader " +
//		     "<jar file name> <class name>");
//		System.exit (1);
//		}
//
//	    /*
//	     * Create the .jar class loader and use the first argument
//	     * passed in from the command line as the .jar file to use.
//	     */
//	    JarClassLoader jarLoader = new JarClassLoader (args [0]);
//
//	    /* Load the class from the .jar file and resolve it.	*/
//	    Class c = jarLoader.loadClass (args [1], true);
//
//	    /*
//	     * Create an instance of the class.
//	     *
//	     * Note that created object's constructor-taking-no-arguments
//	     * will be called as part of the objects creation.
//	     */
//	    Object o = c.newInstance();
//
//	    /* Are we using a class that we specifically know about?	*/
//	    if (o instanceof TestClass)
//		{
//		// Yep, lets call a method that we know about.	*/
//		TestClass tc = (TestClass) o;
//		tc.doSomething();
//		}
//	    }
//	}	// End of nested Class Test.

    }	// End of Class JarClassLoader.


text:
package org.hisp.dhis.analytics;

/**
 * @author Lars Helge Overland
 */
public enum NotNullConstraint
{
    NULL,
    NOT_NULL;

    public boolean isNotNull()
    {
        return this == NOT_NULL;
    }
}


text:
<?php
function blockqoute_plugin() {
    if ( !current_user_can( 'edit_posts' ) && !current_user_can( 'edit_pages' ) ) {
        return;
    }
    if ( 'true' == get_user_option( 'rich_editing' ) ) {
        add_filter( 'mce_external_plugins', 'naba_add_tinymce_plugin_blockqoute' );
        add_filter( 'mce_buttons', 'naba_register_mce_button_blockqoute' );
    }
}
add_action('admin_head', 'blockqoute_plugin');

// Declare script for new button
function naba_add_tinymce_plugin_blockqoute( $plugin_array ) {
    $plugin_array['blockqoute_plugin'] = get_template_directory_uri() .'/inc/tinymce/js/blockqoute.js';
    return $plugin_array;
}

// Register new button in the editor
function naba_register_mce_button_blockqoute( $buttons ) {
    array_push( $buttons, 'blockqoute_plugin' );
    return $buttons;
}


text:
package schedular

import (
	"errors"

	"strings"

	"github.com/lijianying10/log"
	"k8s.io/client-go/pkg/api"
	"k8s.io/client-go/pkg/api/v1"
)

type ServiceControl struct {
	Conn         *Connection
	K8SNameSpace string
}

func NewServiceControl(conn *Connection, NameSpace string) *ServiceControl {
	var serviceControl ServiceControl
	serviceControl.Conn = conn
	serviceControl.K8SNameSpace = NameSpace
	return &serviceControl
}

func (sc *ServiceControl) ServiceNameHandle(imageName string) (string, string, error) {
	strs := strings.Split(imageName, ":")
	if len(strs) != 2 {
		return "", "", errors.New("error define image name")
	}

	strs[0] = strings.Replace(strs[0], "/", "-", -1)
	//strs[0] = strings.Replace(strs[0], "-", "_", -1)
	strs[0] = strings.Replace(strs[0], ".", "-", -1)

	return strs[0], strs[1], nil
}
func (sc *ServiceControl) ServiceName2PodName(imageName string) (string, error) {
	img, ver, err := sc.ServiceNameHandle(imageName)
	if err != nil {
		return "", err
	}

	return img + "-" + ver + "ewfpod", nil
}

func (sc *ServiceControl) ServiceExist(imageName string) (bool, error) {
	var err error
	img, ver, err := sc.ServiceNameHandle(imageName)
	if err != nil {
		return false, err
	}
	pods, err := sc.Conn.ClientSet.Core().Pods(sc.K8SNameSpace).List(v1.ListOptions{
		LabelSelector: "servicetype=ewf,image=" + img + ",version=" + ver,
	})
	if err != nil {
		log.Error("get images error", err.Error())
		return false, errors.New("error get service")
	}

	if len(pods.Items) == 0 {
		return false, nil
	}

	if len(pods.Items) > 1 {
		return false, errors.New("Multi service error")
	}
	log.Info(pods.Items[0].Status.Phase)
	if pods.Items[0].Status.Phase != "Running" {
		return false, errors.New("Service is not running")
	}

	return true, nil
}

func (sc *ServiceControl) ServiceCreate(imageName string) error {
	log.Info("creating service : ", imageName)
	img, ver, err := sc.ServiceNameHandle(imageName)
	if err != nil {
		return err
	}
	_, err = sc.Conn.ClientSet.Core().Pods(sc.K8SNameSpace).Create(&v1.Pod{
		ObjectMeta: v1.ObjectMeta{
			Name: img + "-" + ver + "ewfpod",
			Labels: map[string]string{
				"servicetype": "ewf",
				"image":       img,
				"version":     ver,
			},
			Namespace: sc.K8SNameSpace,
		},
		Spec: v1.PodSpec{
			Containers: []v1.Container{
				v1.Container{
					Name:    img + "-" + ver + "-ewfrunc",
					Image:   imageName,
					Command: []string{"sleep", "10000d"},
					Stdin:   true,
					TTY:     false,
				},
			},
		},
	})
	return err
}

func (sc *ServiceControl) ServiceCMDInvoke(imageName, CMD string) (string, error) {
	podName, err := sc.ServiceName2PodName(imageName)
	if err != nil {
		log.Error("error get pod name during service cmd invoke : ", err.Error())
		return "", err
	}
	// getting target pod
	pod, err := sc.Conn.ClientSet.Core().Pods(sc.K8SNameSpace).Get(podName)
	if err != nil {
		log.Error("getting pod error when execute command :", err.Error())
		return "", err
	}

	req := sc.Conn.ClientSet.Core().RESTClient().Post().
		Resource("pods").Namespace(sc.K8SNameSpace).Name(podName).
		SubResource("exec").
		Param("container", pod.Spec.Containers[0].Name).
		VersionedParams(&api.PodExecOptions{
			Container: pod.Spec.Containers[0].Name,
			Command:   []string{"echo", "a"},
			Stdin:     false,
			Stdout:    true,
			Stderr:    true,
			TTY:       false,
		}, api.ParameterCodec)

	log.Info(req.URL())
	res := req.Do()
	b, e := res.Raw()
	if e != nil {
		log.Error("WOCAO: ", e.Error())
	}
	log.Info(string(b))

	return "", nil
}


text:
post_title: DC/OS Documentation
---

Welcome to the DC/OS documentation. The DC/OS documentation can help you set up, learn about the system, and get your applications and workloads running on DC/OS.


text:
module.exports = function ({data, methods, computed}) {
  data.bookshelf = []
  data.bookshelf__search_term = ''

  methods.bookshelf__get = function (user_id) {
    let vm = this
    return req({
      url: '/bookshelf/' + user_id,
      cookies: true,
      json: true
    })
  }

  methods.bookshelf__findId = function (book_id) {
    let vm = this
    return vm.bookshelf.findIndex(function (b) {
      return b.book.id === book_id
    })
  }

  methods.bookshelf__add = function (book_id) {
    let vm = this
    if (!vm.is_user) { return }
    w.req({
      method: 'post',
      url: '/bookshelf__add',
      data: {book_id, user_id: vm.user._id},
      cookies: true,
      json: true
    }).then(function (res) {
      vm.bookshelf__update(res)
    })
  }

  methods.bookshelf__remove = function (book_id) {
    let vm = this
    if (!vm.is_user) { return }
    w.req({
      method: 'post',
      url: '/bookshelf__remove',
      data: {book_id, user_id: vm.user._id},
      cookies: true,
      json: true
    }).then(function (res) {
      if (res.err !== undefined) { return }
      var i = vm.bookshelf__findId(book_id)
      if (i !== -1) {
        vm.bookshelf.splice(i, 1)
      }
    })
  }

  methods.bookshelf__update = function (b) {
    if (b === undefined) { return }
    let vm = this
    var i = vm.bookshelf__findId(b.book.id)
    if (i === -1) {
      vm.bookshelf.unshift(b)
    }
    if (i !== -1) {
      Vue.set(vm.bookshelf, i, b)
    }
  }

  methods.bookshelf__is_in_array = function (book_id) {
    let vm = this
    return vm.bookshelf__findId(book_id) !== -1
  }

  methods.bookshelf__view = function (books, search_term) {
    let vm = this
    var search_term = search_term.toLowerCase().trim()
    var search_reg = search_term
    // var search_reg = search_term.split('').join('.*')

    return books.filter(function (b) {
      var book = b.book
      if (search_term.length === 0) { return true }

      const search_result = ['title', 'subtitle', 'authors'].reduce(function (bool, field) {
        if (bool === true) { return true }
        if (book[field] === undefined) { return false }
        if (field === 'authors') {
          return book.authors.join(', ').toLowerCase().match(search_reg) !== null
        }
        return book[field].toLowerCase().match(search_reg) !== null
      }, false)

      return search_result
    })
  }

  methods.bookshelf_authors = function (book) {
    if (book.book.authors === undefined) { return '' }
    return book.book.authors.join(', ')
  }
}


text:
module Physics.Scenes.FourBoxesTwoStatic where

import Linear.Epsilon
import Linear.V2
import Physics.Constraint
import Physics.Contact
import Physics.External
import Physics.Geometry
import Physics.Object
import Physics.World
import Physics.Scenes.Scene

boxA :: (Fractional a, Eq a) => PhysicalObj a
boxA = PhysicalObj { _physObjVel = V2 1 0
                   , _physObjRotVel = 0
                   , _physObjPos = V2 (-5) 0
                   , _physObjRotPos = 0
                   , _physObjHull = rectangleHull 4 4
                   , _physObjInvMass = toInvMass2 (2, 1) }

boxB :: (Fractional a, Eq a) => PhysicalObj a
boxB = PhysicalObj { _physObjVel = V2 (-4) 0
                   , _physObjRotVel = 0
                   , _physObjPos = V2 5 2
                   , _physObjRotPos = 0
                   , _physObjHull = rectangleHull 2 2
                   , _physObjInvMass = toInvMass2 (1, 0.5) }

boxC :: (Fractional a, Eq a) => PhysicalObj a
boxC = PhysicalObj { _physObjVel = V2 0 0
                   , _physObjRotVel = 0
                   , _physObjPos = V2 0 (-6)
                   , _physObjRotPos = 0
                   , _physObjHull = rectangleHull 18 1
                   , _physObjInvMass = toInvMass2 (0, 0) }

boxD :: (Fractional a, Eq a) => PhysicalObj a
boxD = PhysicalObj { _physObjVel = V2 0 0
                   , _physObjRotVel = 0
                   , _physObjPos = V2 (-5) (-4)
                   , _physObjRotPos = 0
                   , _physObjHull = rectangleHull 0.4 3
                   , _physObjInvMass = toInvMass2 (1, 0) }

boxA' :: (Fractional a, Eq a) => WorldObj a
boxA' = WorldObj boxA 0.2

boxB' :: (Fractional a, Eq a) => WorldObj a
boxB' = WorldObj boxB 0.2

boxC' :: (Fractional a, Eq a) => WorldObj a
boxC' = WorldObj boxC 0.2

boxD' :: (Fractional a, Eq a) => WorldObj a
boxD' = WorldObj boxD 0.2

world :: (Fractional a, Eq a) => World (WorldObj a)
world = fromList [boxA', boxB', boxC', boxD']

externals :: (Physical n a, Epsilon n, Floating n, Ord n) => [External n a]
externals = [constantAccel (V2 0 (-2))]

contactBehavior :: (Floating a) => ContactBehavior a
contactBehavior = ContactBehavior 0.01 0.02

scene :: (Physical a p, Epsilon a, Floating a, Ord a, Eq a) => Scene a p
scene = Scene world externals contactBehavior


text:
package com.github.quartzweb.utils.json;

public class JSONUtils {

    public static String toJSONString(Object o) {
        JSONWriter writer = new JSONWriter();
        writer.writeObject(o);
        return writer.toString();
    }

    public static Object parse(String text) {
        JSONParser parser = new JSONParser(text);
        return parser.parse();
    }
}


text:
//
//   Copyright 2013 Pixar
//
//   Licensed under the Apache License, Version 2.0 (the "Apache License")
//   with the following modification; you may not use this file except in
//   compliance with the Apache License and the following modification to it:
//   Section 6. Trademarks. is deleted and replaced with:
//
//   6. Trademarks. This License does not grant permission to use the trade
//      names, trademarks, service marks, or product names of the Licensor
//      and its affiliates, except as required to comply with Section 4(c) of
//      the License and to reproduce the content of the NOTICE file.
//
//   You may obtain a copy of the Apache License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the Apache License with the above modification is
//   distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
//   KIND, either express or implied. See the Apache License for the specific
//   language governing permissions and limitations under the Apache License.
//

#ifndef OPENSUBDIV_VERSION_H
#define OPENSUBDIV_VERSION_H

#define OPENSUBDIV_VERSION v2_5_1

// henry: moved crappy logic defines from opensubdiv preprocessor macros here
#define and &&
#define and_eq &=
#define bitand &
#define bitor |
#define compl ~
#define not !
#define not_eq !=
#define or ||
#define or_eq |=
#define xor ^
#define xor_eq ^=

#endif /* OPENSUBDIV_VERSION_H */


text:
/**
 * Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements
 * appear twice and others appear once.
 *
 * Find all the elements of [1, n] inclusive that do not appear in this array.
 *
 * Could you do it without extra space and in O(n) runtime? You may assume the
 * returned list does not count as extra space.
 *
 * Example:
 *
 * Input:
 * [4,3,2,7,8,2,3,1]
 *
 * Output:
 * [5,6]
 *
 * @param {number[]} nums
 * @return {number[]}
 */
var findDisappearedNumbers = function(nums) {
    var disappeared = [];
    var n = nums.length;

    for (var i = 0; i < n; i++) {
            let index = Math.abs(nums[i]) - 1;
            if (nums[index] > 0) nums[index] = -nums[index];
        }

    for (var i = 0; i < n; i++) {
            if (nums[i] > 0) disappeared.push(i + 1);
        }

    return disappeared;
};


text:
using System;
using InvertedTomato.Serialization.LightWeightSerialization;
using Xunit;

namespace Tests
{
    public class StringTests
    {
        [Fact]
        public void StringSerializeNull()
        {
            Assert.Equal(UnsignedVlq.Encode(0), LightWeight.Serialize<String>(null));
        }

        [Fact]
        public void StringSerializeEmpty()
        {
            Assert.Equal(UnsignedVlq.Encode(1), LightWeight.Serialize(String.Empty));
        }

        [Fact]
        public void StringSerialize1()
        {
            Assert.Equal(new[] { (Byte)0x02, (Byte)'a' }, LightWeight.Serialize("a"));
        }

        [Fact]
        public void StringDeserializeNull()
        {
            Assert.Null(LightWeight.Deserialize<String>(UnsignedVlq.Encode(0).ToArray()));
        }

        [Fact]
        public void StringDeserializeEmpty()
        {
            Assert.Equal(String.Empty, LightWeight.Deserialize<String>(UnsignedVlq.Encode(1).ToArray()));
        }

        [Fact]
        public void StringDeserializeOne()
        {
            Assert.Equal("a", LightWeight.Deserialize<String>(new[] { (Byte)0x02, (Byte)'a' }));
        }

    }
}


text:
<learningGroupMap>

Use a <learningGroupMap> to create standalone aggregations of
            <learningObject> and <learningGroup> elements, as
         well as overviews, summaries, and assessments, according to the needs identified by the
         learning goals and objectives.

Category: Learning and training: map types


text:
package com.xthena.cw.domain;
// default package

import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 * CwZc entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "t_cw_zc", catalog = "xhf")
public class CwZc implements java.io.Serializable {

	// Fields

	private Long fid;
	private String fname;
	private String fcode;
	private String ftype;
	private Double fprice;
	private Double fzjjine;
	private Double fcprice;
	private Double fcanzhi;
	private Date fendate;
	private Double fyzjjine;
	private String fstatus;
	private String fusestatus;
	private Long fxmid;
	private String fjlunit;
	private Date fbuydate;
	private Date fqldate;
	private Double fqljine;
	private String fmemo;
	private String fmemo1;
	private String fmemo2;

	// Constructors

	/** default constructor */
	public CwZc() {
	}

	/** full constructor */
	public CwZc(String fname, String fcode, String ftype, Double fprice,
			Double fzjjine, Double fcprice, Double fcanzhi, Date fendate,
			Double fyzjjine, String fstatus, String fusestatus, Long fxmid,
			String fjlunit, Date fbuydate, Date fqldate, Double fqljine,
			String fmemo, String fmemo1, String fmemo2) {
		this.fname = fname;
		this.fcode = fcode;
		this.ftype = ftype;
		this.fprice = fprice;
		this.fzjjine = fzjjine;
		this.fcprice = fcprice;
		this.fcanzhi = fcanzhi;
		this.fendate = fendate;
		this.fyzjjine = fyzjjine;
		this.fstatus = fstatus;
		this.fusestatus = fusestatus;
		this.fxmid = fxmid;
		this.fjlunit = fjlunit;
		this.fbuydate = fbuydate;
		this.fqldate = fqldate;
		this.fqljine = fqljine;
		this.fmemo = fmemo;
		this.fmemo1 = fmemo1;
		this.fmemo2 = fmemo2;
	}

	// Property accessors
	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "fid", unique = true, nullable = false)
	public Long getFid() {
		return this.fid;
	}

	public void setFid(Long fid) {
		this.fid = fid;
	}

	@Column(name = "fname", length = 64)
	public String getFname() {
		return this.fname;
	}

	public void setFname(String fname) {
		this.fname = fname;
	}

	@Column(name = "fcode", length = 64)
	public String getFcode() {
		return this.fcode;
	}

	public void setFcode(String fcode) {
		this.fcode = fcode;
	}

	@Column(name = "ftype", length = 64)
	public String getFtype() {
		return this.ftype;
	}

	public void setFtype(String ftype) {
		this.ftype = ftype;
	}

	@Column(name = "fprice", precision = 20)
	public Double getFprice() {
		return this.fprice;
	}

	public void setFprice(Double fprice) {
		this.fprice = fprice;
	}

	@Column(name = "fzjjine", precision = 20)
	public Double getFzjjine() {
		return this.fzjjine;
	}

	public void setFzjjine(Double fzjjine) {
		this.fzjjine = fzjjine;
	}

	@Column(name = "fcprice", precision = 20)
	public Double getFcprice() {
		return this.fcprice;
	}

	public void setFcprice(Double fcprice) {
		this.fcprice = fcprice;
	}

	@Column(name = "fcanzhi", precision = 20)
	public Double getFcanzhi() {
		return this.fcanzhi;
	}

	public void setFcanzhi(Double fcanzhi) {
		this.fcanzhi = fcanzhi;
	}

	@Temporal(TemporalType.DATE)
	@Column(name = "fendate", length = 10)
	public Date getFendate() {
		return this.fendate;
	}

	public void setFendate(Date fendate) {
		this.fendate = fendate;
	}

	@Column(name = "fyzjjine", precision = 20)
	public Double getFyzjjine() {
		return this.fyzjjine;
	}

	public void setFyzjjine(Double fyzjjine) {
		this.fyzjjine = fyzjjine;
	}

	@Column(name = "fstatus", length = 64)
	public String getFstatus() {
		return this.fstatus;
	}

	public void setFstatus(String fstatus) {
		this.fstatus = fstatus;
	}

	@Column(name = "fusestatus", length = 64)
	public String getFusestatus() {
		return this.fusestatus;
	}

	public void setFusestatus(String fusestatus) {
		this.fusestatus = fusestatus;
	}

	@Column(name = "fxmid")
	public Long getFxmid() {
		return this.fxmid;
	}

	public void setFxmid(Long fxmid) {
		this.fxmid = fxmid;
	}

	@Column(name = "fjlunit", length = 64)
	public String getFjlunit() {
		return this.fjlunit;
	}

	public void setFjlunit(String fjlunit) {
		this.fjlunit = fjlunit;
	}

	@Temporal(TemporalType.DATE)
	@Column(name = "fbuydate", length = 10)
	public Date getFbuydate() {
		return this.fbuydate;
	}

	public void setFbuydate(Date fbuydate) {
		this.fbuydate = fbuydate;
	}

	@Temporal(TemporalType.DATE)
	@Column(name = "fqldate", length = 10)
	public Date getFqldate() {
		return this.fqldate;
	}

	public void setFqldate(Date fqldate) {
		this.fqldate = fqldate;
	}

	@Column(name = "fqljine", precision = 20)
	public Double getFqljine() {
		return this.fqljine;
	}

	public void setFqljine(Double fqljine) {
		this.fqljine = fqljine;
	}

	@Column(name = "fmemo", length = 64)
	public String getFmemo() {
		return this.fmemo;
	}

	public void setFmemo(String fmemo) {
		this.fmemo = fmemo;
	}

	@Column(name = "fmemo1", length = 64)
	public String getFmemo1() {
		return this.fmemo1;
	}

	public void setFmemo1(String fmemo1) {
		this.fmemo1 = fmemo1;
	}

	@Column(name = "fmemo2", length = 64)
	public String getFmemo2() {
		return this.fmemo2;
	}

	public void setFmemo2(String fmemo2) {
		this.fmemo2 = fmemo2;
	}

}


text:
{-# LANGUAGE FlexibleContexts    #-}
{-# LANGUAGE ScopedTypeVariables #-}

module YARN.Client.Gen.Parser where

import           Control.Monad
import           Data.Char
import           Data.List
import           Data.Maybe
import           Text.HTML.TagSoup
import           Text.Parsec
import           YARN.Client.Gen.TagSEx
import           YARN.Client.Gen.Types
import Debug.Trace

data ParserState = ParserState
  { hadoopVersion :: String
  } deriving ( Show )

-- * Custom control

get26 :: Monad m => ParsecT s ParserState m Bool
get26 = do
  version <- hadoopVersion <$> getState
  return ("r2.6" `isPrefixOf` version)

-- * Page structure parsers

-- | Generic section represented by
 with HTML heading
-- tag and body tags.
section :: (TagRep t, Stream s m (Tag String))
        => t
        -> ParsecT s ParserState m h
        -> ParsecT s ParserState m b
        -> ParsecT s ParserState m (h, b)
section ht h b = fullTag "
" $ (,) <$> fullTag ht h <*> b

-- | Main content box parser.
-- Documentation page has one content box identified by id="contentBox".
-- The easiest way to locate it is to skipp tags till contentBox with
-- no backtracking.
contentBox :: Stream s m (Tag String) => ParsecT s ParserState m [ApiElement]
contentBox = fullTag "
" $ do
  is26 <- get26
  if is26
    then do
      skipTag "
"
      return []
    else
      error "Unsupported Hadoop version."

page :: Stream s m (Tag String) => ParsecT s ParserState m [ApiElement]
page = skipTill contentBox

-- * String values parsers

apiType :: Stream s m Char => ParsecT s u m ApiType
apiType = try (const ApiIntType <$> trim (word "int"))
      <|> try (const ApiLongType <$> trim (word "long"))
      <|> try (const ApiFloatType <$> trim (word "float"))
      <|> try (const ApiStringType <$> trim (word "string"))
      <|> try (trim (word "array of") *> apiType)
      <|> try (ApiObjectType <$> multiwordObjectIdentifier)
      <|> (many anyChar >>= \t -> error $ "unsupported API type:" ++ t) --TODO: remove, use parse error

queryParamterParser :: Stream s m Char => ParsecT s u m ApiQueryParamter
queryParamterParser = do
  name <- many1 letter
  deprecated <- try (spaces *> string "[deprecated]" *> return True)
            <|> return False
  spaces
  void $ char '-'
  spaces
  description <- many anyChar
  return ApiQueryParamter
         { _apiParamerName = name
         , _apiParamerDeprecated = deprecated
         , _apiParamerDescription = description
         }

-- * Tag parsers

apiNameParser :: Stream s m (Tag String) => ParsecT s u m String
apiNameParser = do
  name <- fullTag "
" $ skipTill (textContaining "API")
  guard (name /= "Cluster Writeable APIs")
  return name

apiSubSectionParser :: Stream s m (Tag String)
                 => ParsecT s u m h
                 -> ParsecT s u m b
                 -> ParsecT s u m (h, b)
apiSubSectionParser hp bp =
  fullTag "
" $ do
    h <- fullTag "
" $ do
      fullTag "" $ return ()
      hp
    b <- bp
    return (h, b)

apiDescriptionParser :: Stream s m (Tag String) => ParsecT s u m String
apiDescriptionParser = unlines <$> many paragraph

apiURIStringParser :: Stream s m Char => ParsecT s u m ApiRequestURI
apiURIStringParser = do
  void $ string "http://<rm http address:port>"
  path <- many anyChar
  return ApiRequestURI
         { apiRequestPath = path
         }

apiURIsParser :: Stream s m (Tag String) => ParsecT s u m [ApiRequest]
apiURIsParser =
  snd <$> apiSubSectionParser (tag "URI")
  ( many $ do
      description <- apiDescriptionParser
      uris <- fancyList
      guard (not $ null uris)
      apiRequestURI <- parseString apiURIStringParser $ head uris
      return ApiRequest
             { _apiDocURI = head uris
             , _apiRequestURI = apiRequestURI
             , _apiRequestDescription = description
             } )

fancyList :: Stream s m (Tag String) => ParsecT s u m [String]
fancyList = fullTag "
" $ fullTag "
" $ fullTag "
" $ try emptyList <|> itemsList
 where
   emptyList = do
     text <- dropWhile (not . isAlphaNum) <$> textTag
     guard ("None" `isPrefixOf` text)
     return []
   itemsList = map (dropWhile (not . isAlphaNum) . dropWhile (/= '*')) . lines <$> textTag

word :: Stream s m Char => String -> ParsecT s u m ()
word s = string s >> notFollowedBy alphaNum

trim :: Stream s m Char => ParsecT s u m a -> ParsecT s u m a
trim = between (skipMany space) (skipMany space)

identifier :: Stream s m Char => ParsecT s u m String
identifier = many1 alphaNum

multiwordObjectIdentifier :: Stream s m Char => ParsecT s u m String
multiwordObjectIdentifier = manyTill anyChar (try $ string "object")

apiField :: Stream s m (Tag String) => ParsecT s u m ApiField
apiField = fullTag "
" (ApiField <$> fullTag "" (textTag >>= parseString (trim $ many1 alphaNum))
                                    <*> fullTag "" (textTag >>= parseString apiType)
                                    <*> fullTag "" textTag)

apiFields :: Stream s m (Tag String) => ParsecT s u m [ApiField]
apiFields = fullTag "
" $ do
  skipTag "
"
  fullTag "
" (many apiField)

apiResponseObjectParser :: Stream s m (Tag String) => ParsecT s u m ApiObject
apiResponseObjectParser = do
  (n, (d, f)) <- apiSubSectionParser apiResponseHeaderParser apiResponseBodyParser
  return ApiObject
        { apiObjectName = n
        , apiObjectDescription = d
        , apiObjectFields = f
        }
  where
   apiResponseHeaderParser = do
     t <- textTag
     guard ("Elements of" `isInfixOf` t)
     let w = words t
     if length w > 3
       then return $ w!!3
       else fullTag "" textTag <* skipMany textTag

   apiResponseBodyParser = do
     description <- apiDescriptionParser
     fields <- apiFields
     skipMany $ skipTag "
"
     return (description, fields)

apiOperationsParser :: Stream s m (Tag String) => ParsecT s u m [String]
apiOperationsParser = snd <$> apiSubSectionParser (tag "HTTP Operations Supported") fancyList

apiQueryParamtersParser :: Stream s m (Tag String)
                        => ParsecT s u m (Bool, (String, [ApiQueryParamter]))
apiQueryParamtersParser =
  apiSubSectionParser ((tag "Query Parameters Supported" *> return False)
                <|> (tag "Query Parameters Required" *> return True)) $ do
    description <- unlines <$> many paragraph
    apiQueryParameters <- mapM (parseString queryParamterParser) =<< fancyList
    return (description, apiQueryParameters)

apiSectionParser :: Stream s m (Tag String) => ParsecT s ParserState m ApiElement
apiSectionParser = fullTag "
" $ do
  version <- hadoopVersion <$> getState
  if version == "r2.6.0"
    then do
      skipMany $ skipTag "
"
      return ApiElement
            { apiName = []
            , apiDescription = []
            , apiURIs = []
            , apiOperations = []
            , apiQueryParameters = []
            , apiQueryParametersDescription = []
            , apiQueryParametersRequed = False
            , apiResponseObject = Nothing
            }
    else do
      apiDocName <- apiNameParser
      apiDescription <- apiDescriptionParser
      apiURIs <- apiURIsParser
      apiOperations <- apiOperationsParser
      apiQueryParametersOpt <- optionMaybe (try apiQueryParamtersParser)
      when (apiDocName == "Cluster Scheduler API") $ skipTag "
"
      response <- optionMaybe (try apiResponseObjectParser)
      skipMany $ skipTag "
"
      return ApiElement
            { apiName = apiDocName
            , apiDescription = apiDescription
            , apiURIs = apiURIs
            , apiOperations = apiOperations
            , apiQueryParameters = maybe [] (snd . snd) apiQueryParametersOpt
            , apiQueryParametersDescription = maybe "" (fst . snd) apiQueryParametersOpt
            , apiQueryParametersRequed = maybe False fst apiQueryParametersOpt
            , apiResponseObject = response
            }


text:
(function () {
  'use strict';

  describe('Participants Route Tests', function () {
    // Initialize global variables
    var $scope,
      ParticipantsService;

    //We can start by loading the main application module
    beforeEach(module(ApplicationConfiguration.applicationModuleName));

    // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
    // This allows us to inject a service but then attach it to a variable
    // with the same name as the service.
    beforeEach(inject(function ($rootScope, _ParticipantsService_) {
      // Set a new global scope
      $scope = $rootScope.$new();
      ParticipantsService = _ParticipantsService_;
    }));

    describe('Route Config', function () {
      describe('Main Route', function () {
        var mainstate;
        beforeEach(inject(function ($state) {
          mainstate = $state.get('participants');
        }));

        it('Should have the correct URL', function () {
          expect(mainstate.url).toEqual('/participants');
        });

        it('Should be abstract', function () {
          expect(mainstate.abstract).toBe(true);
        });

        it('Should have template', function () {
          expect(mainstate.template).toBe('<ui-view/>');
        });
      });

      describe('View Route', function () {
        var viewstate,
          ParticipantsController,
          mockParticipant;

        beforeEach(inject(function ($controller, $state, $templateCache) {
          viewstate = $state.get('participants.view');
          $templateCache.put('modules/participants/client/views/view-participant.client.view.html', '');

          // create mock Participant
          mockParticipant = new ParticipantsService({
            _id: '525a8422f6d0f87f0e407a33',
            name: 'Participant Name'
          });

          //Initialize Controller
          ParticipantsController = $controller('ParticipantsController as vm', {
            $scope: $scope,
            participantResolve: mockParticipant
          });
        }));

        it('Should have the correct URL', function () {
          expect(viewstate.url).toEqual('/:participantId');
        });

        it('Should have a resolve function', function () {
          expect(typeof viewstate.resolve).toEqual('object');
          expect(typeof viewstate.resolve.participantResolve).toEqual('function');
        });

        it('should respond to URL', inject(function ($state) {
          expect($state.href(viewstate, {
            participantId: 1
          })).toEqual('/participants/1');
        }));

        it('should attach an Participant to the controller scope', function () {
          expect($scope.vm.participant._id).toBe(mockParticipant._id);
        });

        it('Should not be abstract', function () {
          expect(viewstate.abstract).toBe(undefined);
        });

        it('Should have templateUrl', function () {
          expect(viewstate.templateUrl).toBe('modules/participants/client/views/view-participant.client.view.html');
        });
      });

      describe('Create Route', function () {
        var createstate,
          ParticipantsController,
          mockParticipant;

        beforeEach(inject(function ($controller, $state, $templateCache) {
          createstate = $state.get('participants.create');
          $templateCache.put('modules/participants/client/views/form-participant.client.view.html', '');

          // create mock Participant
          mockParticipant = new ParticipantsService();

          //Initialize Controller
          ParticipantsController = $controller('ParticipantsController as vm', {
            $scope: $scope,
            participantResolve: mockParticipant
          });
        }));

        it('Should have the correct URL', function () {
          expect(createstate.url).toEqual('/create');
        });

        it('Should have a resolve function', function () {
          expect(typeof createstate.resolve).toEqual('object');
          expect(typeof createstate.resolve.participantResolve).toEqual('function');
        });

        it('should respond to URL', inject(function ($state) {
          expect($state.href(createstate)).toEqual('/participants/create');
        }));

        it('should attach an Participant to the controller scope', function () {
          expect($scope.vm.participant._id).toBe(mockParticipant._id);
          expect($scope.vm.participant._id).toBe(undefined);
        });

        it('Should not be abstract', function () {
          expect(createstate.abstract).toBe(undefined);
        });

        it('Should have templateUrl', function () {
          expect(createstate.templateUrl).toBe('modules/participants/client/views/form-participant.client.view.html');
        });
      });

      describe('Edit Route', function () {
        var editstate,
          ParticipantsController,
          mockParticipant;

        beforeEach(inject(function ($controller, $state, $templateCache) {
          editstate = $state.get('participants.edit');
          $templateCache.put('modules/participants/client/views/form-participant.client.view.html', '');

          // create mock Participant
          mockParticipant = new ParticipantsService({
            _id: '525a8422f6d0f87f0e407a33',
            name: 'Participant Name'
          });

          //Initialize Controller
          ParticipantsController = $controller('ParticipantsController as vm', {
            $scope: $scope,
            participantResolve: mockParticipant
          });
        }));

        it('Should have the correct URL', function () {
          expect(editstate.url).toEqual('/:participantId/edit');
        });

        it('Should have a resolve function', function () {
          expect(typeof editstate.resolve).toEqual('object');
          expect(typeof editstate.resolve.participantResolve).toEqual('function');
        });

        it('should respond to URL', inject(function ($state) {
          expect($state.href(editstate, {
            participantId: 1
          })).toEqual('/participants/1/edit');
        }));

        it('should attach an Participant to the controller scope', function () {
          expect($scope.vm.participant._id).toBe(mockParticipant._id);
        });

        it('Should not be abstract', function () {
          expect(editstate.abstract).toBe(undefined);
        });

        it('Should have templateUrl', function () {
          expect(editstate.templateUrl).toBe('modules/participants/client/views/form-participant.client.view.html');
        });

        xit('Should go to unauthorized route', function () {

        });
      });

    });
  });
})();


text:
<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<!DOCTYPE cxxFile PUBLIC "-//NOKIA//DTD DITA C++ API File Reference Type v0.5.0//EN" "dtd/cxxFile.dtd" >
<cxxFile id="sockmes_8h">
	<apiName>sockmes.h</apiName>
	<cxxVariable id="sockmes_8h_1a9439124775392265f0fd1cfdf275d08d">
		<apiName>KCFMaxSocketServerName</apiName>
		<cxxVariableDetail>
			<cxxVariableDefinition>
				<cxxVariableAccessSpecifier value="public"/>
				<cxxVariableDeclaredType>const <apiRelation href="e32def_8h.xml#_1abb88f5378e8305d934297176fe5fa298">TInt</apiRelation>
				</cxxVariableDeclaredType>
				<cxxVariableScopedName/>
				<cxxVariablePrototype>const TInt KCFMaxSocketServerName</cxxVariablePrototype>
				<cxxVariableNameLookup>KCFMaxSocketServerName</cxxVariableNameLookup>
				<cxxVariableAPIItemLocation>
					<cxxVariableDeclarationFile name="filePath" value="K:/epoc32/include/comms-infras/sockmes.h"/>
					<cxxVariableDeclarationFileLine name="lineNumber" value="228"/>
				</cxxVariableAPIItemLocation>
			</cxxVariableDefinition>
			<apiDesc>

Maximum length of a SocketServer name (the server name of a dealer).

			</apiDesc>
		</cxxVariableDetail>
	</cxxVariable>
	<cxxTypedef id="sockmes_8h_1afcd41e2ac27a0f8090612e6159d026d4">
		<apiName>TServerName</apiName>
		<cxxTypedefDetail>
			<cxxTypedefDefinition>
				<cxxTypedefAccessSpecifier value="public"/>
				<cxxTypedefDeclaredType>
					<apiRelation href="class_t_buf.xml#class_t_buf">TBuf</apiRelation>< <apiRelation href="sockmes_8h.xml#_1a9439124775392265f0fd1cfdf275d08d">KCFMaxSocketServerName</apiRelation> ></cxxTypedefDeclaredType>
				<cxxTypedefScopedName/>
				<cxxTypedefPrototype>TBuf< KCFMaxSocketServerName > TServerName</cxxTypedefPrototype>
				<cxxTypedefNameLookup>TServerName</cxxTypedefNameLookup>
				<cxxTypedefAPIItemLocation>
					<cxxTypedefDeclarationFile name="filePath" value="K:/epoc32/include/comms-infras/sockmes.h"/>
					<cxxTypedefDeclarationFileLine name="lineNumber" value="233"/>
				</cxxTypedefAPIItemLocation>
			</cxxTypedefDefinition>
			<apiDesc>

Name of a SocketServer (the server name of a dealer).

			</apiDesc>
		</cxxTypedefDetail>
	</cxxTypedef>
	<cxxFileAPIItemLocation>
		<cxxFileDeclarationFile name="filePath" value="K:/epoc32/include/comms-infras/sockmes.h"/>
	</cxxFileAPIItemLocation>
</cxxFile>


text:
<?php

/**
 * Wrapper for loggers (Mage default or Log4php from Nmmlm_log module)
 * User: Alex Gusev <flancer64@gmail.com>
 * Date: 2/20/13
 * Time: 9:38 AM
 */
class Praxigento_LoginAs_Model_Logger
{
    /** @var bool 'true' - Log4php logging framework is used. */
    private static $_isLog4phpUsed = null;
    /** @var Logger */
    private $_loggerLog4php;
    /** @var string name for the current logger */
    private $_name;

    function __construct($name)
    {
        self::$_isLog4phpUsed = class_exists('Nmmlm_Log_Logger', false);
        if (self::$_isLog4phpUsed) {
            $this->_loggerLog4php = Nmmlm_Log_Logger::getLogger($name);
        } else {
            $this->_name = is_object($name) ? get_class($name) : (string)$name;
        }
    }

    /**
     * Override getter to use '$log = Nmmlm_Log_Logger::getLogger($this)' form in Mage classes.
     * @static
     *
     * @param string $name
     *
     * @return Praxigento_LoginAs_Model_Logger
     */
    public static function getLogger($name)
    {
        return new Praxigento_LoginAs_Model_Logger($name);
    }

    public function debug($message, $throwable = null)
    {
        $this->doLog($message, $throwable, 'debug', Zend_Log::INFO);
    }

    public function error($message, $throwable = null)
    {
        $this->doLog($message, $throwable, 'error', Zend_Log::ERR);
    }

    public function fatal($message, $throwable = null)
    {
        $this->doLog($message, $throwable, 'fatal', Zend_Log::CRIT);
    }

    public function info($message, $throwable = null)
    {
        $this->doLog($message, $throwable, 'info', Zend_Log::NOTICE);
    }

    public function trace($message, $throwable = null)
    {
        $this->doLog($message, $throwable, 'trace', Zend_Log::DEBUG);
    }

    public function warn($message, $throwable = null)
    {
        $this->doLog($message, $throwable, 'warn', Zend_Log::WARN);
    }

    /**
     * Internal dispatcher for the called log method.
     * @param $message
     * @param $throwable
     * @param $log4phpMethod
     * @param $zendLevel
     */
    private function doLog($message, $throwable, $log4phpMethod, $zendLevel)
    {
        if (Praxigento_LoginAs_Config::cfgGeneralLogEvents()) {
            if (self::$_isLog4phpUsed) {
                $this->_loggerLog4php->$log4phpMethod($message, $throwable);
            } else {
                Mage::log($this->_name . ': ' . $message, $zendLevel);
                if ($throwable instanceof Exception) {
                    Mage::logException($throwable);
                }
            }
        }
    }
}


text:
Chapman API
===========

(Unofficial) Chapman University realtime API

See examples/usage at https://mileszim.github.io/chapmanapi

### Details

https://chapmanuniversity.firebaseio.com/


text:
package org.elasticsearch.xpack.core.ilm;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateObserver;
import org.elasticsearch.cluster.SnapshotsInProgress;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.Index;
import org.elasticsearch.repositories.IndexId;
import org.elasticsearch.snapshots.SnapshotInProgressException;

import java.util.function.Consumer;

/**
 * This is an abstract AsyncActionStep that wraps the performed action listener, checking to see
 * if the action fails due to a snapshot being in progress. If a snapshot is in progress, it
 * registers an observer and waits to try again when a snapshot is no longer running.
 */
public abstract class AsyncRetryDuringSnapshotActionStep extends AsyncActionStep {
    private final Logger logger = LogManager.getLogger(AsyncRetryDuringSnapshotActionStep.class);

    public AsyncRetryDuringSnapshotActionStep(StepKey key, StepKey nextStepKey, Client client) {
        super(key, nextStepKey, client);
    }

    @Override
    public void performAction(IndexMetaData indexMetaData, ClusterState currentClusterState,
                              ClusterStateObserver observer, Listener listener) {
        // Wrap the original listener to handle exceptions caused by ongoing snapshots
        SnapshotExceptionListener snapshotExceptionListener = new SnapshotExceptionListener(indexMetaData.getIndex(), listener, observer);
        performDuringNoSnapshot(indexMetaData, currentClusterState, snapshotExceptionListener);
    }

    /**
     * Method to be performed during which no snapshots for the index are already underway.
     */
    abstract void performDuringNoSnapshot(IndexMetaData indexMetaData, ClusterState currentClusterState, Listener listener);

    /**
     * SnapshotExceptionListener is an injected listener wrapper that checks to see if a particular
     * action failed due to a {@code SnapshotInProgressException}. If it did, then it registers a
     * ClusterStateObserver listener waiting for the next time the snapshot is not running,
     * re-running the step's {@link #performAction(IndexMetaData, ClusterState, ClusterStateObserver, Listener)}
     * method when the snapshot is no longer running.
     */
    class SnapshotExceptionListener implements AsyncActionStep.Listener {
        private final Index index;
        private final Listener originalListener;
        private final ClusterStateObserver observer;

        SnapshotExceptionListener(Index index, Listener originalListener, ClusterStateObserver observer) {
            this.index = index;
            this.originalListener = originalListener;
            this.observer = observer;
        }

        @Override
        public void onResponse(boolean complete) {
            originalListener.onResponse(complete);
        }

        @Override
        public void onFailure(Exception e) {
            if (e instanceof SnapshotInProgressException) {
                try {
                    logger.debug("[{}] attempted to run ILM step but a snapshot is in progress, step will retry at a later time",
                        index.getName());
                    observer.waitForNextChange(
                        new NoSnapshotRunningListener(observer, index.getName(), state -> {
                            IndexMetaData idxMeta = state.metaData().index(index);
                            if (idxMeta == null) {
                                // The index has since been deleted, mission accomplished!
                                originalListener.onResponse(true);
                            }
                            // Re-invoke the performAction method with the new state
                            performAction(idxMeta, state, observer, originalListener);
                        }, originalListener::onFailure),
                        // TODO: what is a good timeout value for no new state received during this time?
                        TimeValue.timeValueHours(12));
                } catch (Exception secondError) {
                    // There was a second error trying to set up an observer,
                    // fail the original listener
                    secondError.addSuppressed(e);
                    originalListener.onFailure(secondError);
                }
            } else {
                originalListener.onFailure(e);
            }
        }
    }

    /**
     * A {@link ClusterStateObserver.Listener} that invokes the given function with the new state,
     * once no snapshots are running. If a snapshot is still running it registers a new listener
     * and tries again. Passes any exceptions to the original exception listener if they occur.
     */
    class NoSnapshotRunningListener implements ClusterStateObserver.Listener {

        private final Consumer<ClusterState> reRun;
        private final Consumer<Exception> exceptionConsumer;
        private final ClusterStateObserver observer;
        private final String indexName;

        NoSnapshotRunningListener(ClusterStateObserver observer, String indexName,
                                  Consumer<ClusterState> reRun,
                                  Consumer<Exception> exceptionConsumer) {
            this.observer = observer;
            this.reRun = reRun;
            this.exceptionConsumer = exceptionConsumer;
            this.indexName = indexName;
        }

        @Override
        public void onNewClusterState(ClusterState state) {
            try {
                if (snapshotInProgress(state)) {
                    observer.waitForNextChange(this);
                } else {
                    logger.debug("[{}] retrying ILM step after snapshot has completed", indexName);
                    reRun.accept(state);
                }
            } catch (Exception e) {
                exceptionConsumer.accept(e);
            }
        }

        private boolean snapshotInProgress(ClusterState state) {
            SnapshotsInProgress snapshotsInProgress = state.custom(SnapshotsInProgress.TYPE);
            if (snapshotsInProgress == null || snapshotsInProgress.entries().isEmpty()) {
                // No snapshots are running, new state is acceptable to proceed
                return false;
            }

            for (SnapshotsInProgress.Entry snapshot : snapshotsInProgress.entries()) {
                if (snapshot.indices().stream()
                    .map(IndexId::getName)
                    .anyMatch(name -> name.equals(indexName))) {
                    // There is a snapshot running with this index name
                    return true;
                }
            }
            // There are snapshots, but none for this index, so it's okay to proceed with this state
            return false;
        }

        @Override
        public void onClusterServiceClose() {
            // This means the cluster is being shut down, so nothing to do here
        }

        @Override
        public void onTimeout(TimeValue timeout) {
            exceptionConsumer.accept(new IllegalStateException("step timed out while waiting for snapshots to complete"));
        }
    }
}


text:
package admin

import (
	"mime"
	"net/http"
	"path"
	"strings"

	"github.com/octavore/naga/service"
	"github.com/octavore/nagax/router"
	"github.com/octavore/nagax/users"
)

const basePath = "/admin/"

var staticDirs = []string{
	"/admin/js/",
	"/admin/css/",
	"/admin/vendor/",
	"/admin/images/",
}

type Module struct {
	Router *router.Module
	Auth   *users.Module
}

func (m *Module) Init(c *service.Config) {
	c.Setup = func() error {
		m.Router.Root.Handle(basePath, m)
		m.Router.Root.HandleFunc("/admin/logout", m.handleLogout)
		m.Router.Root.HandleFunc("/admin/preview", func(rw http.ResponseWriter, req *http.Request) {
			err := m.Auth.MustWithAuth(m.handlePreview)(rw, req, nil)
			if err != nil {
				m.Router.HandleError(rw, req, err)
			}
		})
		return nil
	}
}

func (m *Module) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	isStaticAsset := false
	for _, dir := range staticDirs {
		isStaticAsset = isStaticAsset || strings.HasPrefix(req.URL.Path, dir)
	}

	p := strings.TrimPrefix(req.URL.Path, basePath)
	ext := path.Ext(p)

	if !isStaticAsset {
		p = "index.html"
		ext = path.Ext(p)
	}

	b, err := Asset(p)
	if err != nil && strings.Contains(err.Error(), "not found") {
		rw.WriteHeader(http.StatusNotFound)
		return
	}

	if err != nil {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
		return
	}

	rw.Header().Add("Content-Type", mime.TypeByExtension(ext))
	rw.Write(b)
}

func (m *Module) handleLogout(rw http.ResponseWriter, req *http.Request) {
	m.Auth.Logout(rw, req)
	http.Redirect(rw, req, "/admin", http.StatusTemporaryRedirect)
}


text:
extern crate serde_derive;

#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
enum F {
    A,
    #[serde(other)] //~^^^ HELP: #[serde(other)] may only be used inside a field_identifier
    B,
}

fn main() {}


text:
package me.happyhacking.net.server;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

public class HttpConstant {

	public static class Status {

		public static final String HTTP_OK = "200 OK",
				HTTP_PARTIALCONTENT = "206 Partial Content",
				HTTP_RANGE_NOT_SATISFIABLE = "416 Requested Range Not Satisfiable",
				HTTP_REDIRECT = "301 Moved Permanently",
				HTTP_NOTMODIFIED = "304 Not Modified",
				HTTP_FORBIDDEN = "403 Forbidden",
				HTTP_NOTFOUND = "404 Not Found",
				HTTP_BADREQUEST = "400 Bad Request",
				HTTP_INTERNALERROR = "500 Internal Server Error",
				HTTP_NOTIMPLEMENTED = "501 Not Implemented";
	}

	public static class MIME {

		public static final String MIME_PLAINTEXT = "text/plain",
				MIME_HTML = "text/html",
				MIME_DEFAULT_BINARY = "application/octet-stream",
				MIME_XML = "text/xml",
				MIME_JSON = "application/json";

		public static Map<String, String> MAP = new HashMap<String, String>();
		static {
			MAP.put("css", "text/css");
			MAP.put("htm", "text/html");
			MAP.put("html", "text/html");
			MAP.put("xml", "text/xml");
			MAP.put("txt", "text/plain");
			MAP.put("asc", "text/plain");
			MAP.put("gif", "image/gif");
			MAP.put("jpg", "image/jpeg");
			MAP.put("jpeg", "image/jpeg");
			MAP.put("png", "image/png");
			MAP.put("mp3", "audio/mpeg");
			MAP.put("m3u", "audio/mpeg-url");
			MAP.put("mp4", "video/mp4");
			MAP.put("ogv", "video/ogg");
			MAP.put("flv", "video/x-flv");
			MAP.put("mov", "video/quicktime");
			MAP.put("swf", "application/x-shockwave-flash");
			MAP.put("js", "application/javascript");
			MAP.put("pdf ", "application/pdf");
			MAP.put("doc", "application/msword");
			MAP.put("ogg", "application/x-ogg");
			MAP.put("zip", "application/octet-stream");
			MAP.put("exe", "application/octet-stream");
			MAP.put("class", "application/octet-stream");
		}

	}

	public static class BufferSize {
        public static int REQUEST_SIZE = 2 * 1024;
		public static int RESPONSE_SIZE = 2 * 1024;
	}

    public static class QueueSize {
        public static int READ_SIZE = 10000;
        public static int WRITE_SIZE = 10000;
        public static int REGISTER_SIZE = 20000;
    }
    public static class DateFormat {

        public static SimpleDateFormat GMT_FORMAT;
        static {
            GMT_FORMAT = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
            GMT_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT"));
        }
    }
	public static class Server {
		public static final String NAME = "SimpleNioHttpServer";
		public static final String VERSION = "1.0.0";
		public static final String AUTHOR = "alex.tsai2010@gmail.com";
        public static int port = 8080;
        public static int maxConnections = 10000;
        public static int maxThreads = 2000;
        public static enum State {STOPPED, STOPPING, RUNNING}
	}

}


text:
<!DOCTYPE html>

        <title>Event server client API sandbox</title>
        <link rel="stylesheet" media="screen" href="assets/main.css">

Client A

<button id="sendEventBtn1">Send event</button>

<button id="sendMsgBtn1">Send message</button>

Image event:
			     <button id="sendImageBtn1">Send image</button>

Client B

Client C

                <button id="getPropertyBtn3">Get property from device D</button>

Client D