text:
/* *************************************************************************
 *             AliEbyE Analysis for Particle Ratio Fluctuation             *
 *                   Deepika Rathee  | Satyajit Jena                       *
 *                   drathee@cern.ch | sjena@cern.ch                       *
 *                  Date: Wed Jul  9 18:38:30 CEST 2014                    *
 *          New approch to find particle ratio to reduce memory            *
 *                             (Test Only)                                 *
 ***************************************************************************/

AliAnalysisTask *AddEbyEPidRatioTaskV2(const Char_t *name      = "NuDyn", //  0
				     Int_t   isModeDist      = 1,       //  1
				     Int_t   isModeEff       = 0,       //  2
				     Bool_t  isModeDCA       = 0,       //  3
				     Bool_t  isModeQA        = 0,       //  4
				     Int_t   isRatio         = 3,       //  5
				     Bool_t  isModeAOD       = 0,       //  6
				     Bool_t  isSetExt        = 0,       //  7
				     Int_t   aodFilterBit    = 1024,    //  8
				     Float_t gEta            = 0.8,     //  9
				     Int_t   modeCuts        = 0,       // 10
				     Int_t   modePID         =-1,       // 11
				     Float_t gMinPt          = 0.3,     // 12
				     Float_t gMaxPt          = 2.5,     // 13
				     Float_t gMinPtForTof    = 0.21,    // 14
				     Float_t gMaxPtForTPClow = 0.69,    // 15
				     Float_t gMinPtEff       = 0.3,     // 16
				     Float_t gMaxPtEff       = 2.5,     // 17
				     Float_t gSigmaITS       = 4.0,     // 18
				     Float_t gSigmaTOF       = 4.0,     // 19
				     Float_t gSigmaTPC       = 4.0,     // 20
				     Float_t gSigmaTPClow    = 3.0,
				     Bool_t  isPer           = 0,
				     Int_t   nSub            = 25) {   // 21

  TString sName(name);

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskNetParticle", "No analysis manager found.");
    return NULL;
  }

  Bool_t isMC = (mgr->GetMCtruthEventHandler() != NULL);
  if (isMC)
    Info("AddTaskNetParticle", "This task has MC.");

  AliEbyEPidRatioTask *task = new AliEbyEPidRatioTask("EbyEPidRatio");
  if (!task) {
    Error("EbyEPidRatio", "Task could not be created.");
    return NULL;
  }

  if (isMC)
    task->SetIsMC();
  if (isModeEff == 1) {
    task->SetModeEffCreation(1);             // => 1 = on    | 0 = off (default)
  } else if (isModeEff == 2) {
    task->SetModeEffCreation(1);             // => 1 = on    | 0 = off (default)
    task->SetEffExtra();             // => 1 = on    | 0 = off (default)
  }
  if (isModeDCA)
    task->SetModeDCACreation(1);             // => 1 = on    | 0 = off (default)

  if (isModeAOD) {
    task->SetIsAOD(1);                       // => 1 = AOD   | 0 = ESD (default)
    task->SetTrackFilterBit(aodFilterBit);
  }
  if (isModeQA)
    task->SetModeQACreation(1);              // => 1 = on    | 0 = off (default)

  task->SetModeDistCreation(isModeDist);  // 0 nothing, 1 only dist, 2, with qa
  task->SetIsRatio(isRatio);

  Float_t minPt,     maxPt,     minPtEff,     maxPtEff,  minPtForTOF;
  Float_t nSigmaITS, nSigmaTPC, nSigmaTPClow, nSigmaTOF, maxPtForTPClow;
  Float_t etaMax,    etaMaxEff, maxRap;
  Int_t   pidStrategy;

  minPtForTOF    = 0.69;
  maxPtForTPClow = 0.69;
  minPt          = 0.5;
  maxPt          = 2.0;
  minPtEff       = 0.3;
  maxPtEff       = 2.5;

  maxRap         = 0.5;
  etaMax         = 0.8;

  etaMaxEff      = 0.8;
  nSigmaITS      = 4.0;
  nSigmaTPC      = 4.0;
  nSigmaTPClow   = 3.0;
  nSigmaTOF      = 4.0;

  if (isSetExt) {
    minPt          = gMinPt;
    maxPt          = gMaxPt;
    minPtForTOF    = gMinPtForTof;
    maxPtForTPClow = gMaxPtForTPClow;
    minPtEff       = gMinPtEff;
    maxPtEff       = gMaxPtEff;

    etaMax         = gEta;

    nSigmaITS      = gSigmaITS;
    nSigmaTPC      = gSigmaTPC;
    nSigmaTPClow   = gSigmaTPClow;
    nSigmaTOF      = gSigmaTOF;
  }

  if (modePID    == -1) { // default
    pidStrategy   = 7;         // 7: ITS + TPC + TOF (using minPtForTOF)
    if (modeCuts == 1)
      pidStrategy = 5;       // 5: TPC + TOF (using minPtForTOF)
  }
  else
    pidStrategy = modePID;

  AliEbyEPidRatioHelper *helper = new AliEbyEPidRatioHelper;
  if (!helper) {
    Error("AddTaskNetParticle", "Helper could not be created.");
    delete task;
    return NULL;
  }

  task->SetESDTrackCutMode(modeCuts);       // => 0 = normal | 1 = LF
  task->SetEtaMax(etaMax);                  // eta cut
  task->SetEtaMaxEff(etaMaxEff);            // eta cut for efficiency
  task->SetPtRange(minPt, maxPt);           // pt cut range for the analysis
  task->SetPtRangeEff(minPtEff, maxPtEff);  // pt cut range for the correction / efficiency / contamination creation
  if (isPer) task->SetIsPer();  //

  helper->SetVertexZMax(10.);
  helper->SetCentralityBinMax(11);
  helper->SetRapidityMax(maxRap);
  helper->SetMinTrackLengthMC(70.);
  helper->SetNSigmaMaxCdd(0.);              //  3. ||   ->> Turn off sigmaDCA cuts for now
  helper->SetNSigmaMaxCzz(0.);              //  3. ||   ->> Turn off sigmaDCA cuts for now
  helper->SetPhiRange(0., 3.88);            //  Only used if requested in task - default is TwoPi
  helper->SetPIDStrategy(pidStrategy);
  helper->SetNSigmaMaxITS(nSigmaITS);
  helper->SetNSigmaMaxTPC(nSigmaTPC);
  helper->SetNSigmaMaxTPClow(nSigmaTPClow);
  helper->SetNSigmaMaxTOF(nSigmaTOF);
  helper->SetMinPtForTOFRequired(minPtForTOF);
  helper->SetMaxPtForTPClow(maxPtForTPClow);
  helper->SetNSubSamples(nSub);

  task->SetNetParticleHelper(helper);
  mgr->AddTask(task);

  AliAnalysisDataContainer *cinput  = mgr->GetCommonInputContainer();
  TString outputFileName   = Form("%s:%s", AliAnalysisManager::GetCommonFileName(), name);
  TString outputQAFileName = Form("%s:%s", AliAnalysisManager::GetCommonFileName(), name);

  AliAnalysisDataContainer *coutput     = mgr->CreateContainer(name, TList::Class(),  AliAnalysisManager::kOutputContainer, outputFileName);
  AliAnalysisDataContainer *coutputEff  = mgr->CreateContainer(Form("%s_eff",  name), TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName);
  AliAnalysisDataContainer *coutputCont = mgr->CreateContainer(Form("%s_cont", name), TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName);
  AliAnalysisDataContainer *coutputDca  = mgr->CreateContainer(Form("%s_dca",  name), TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName);

  AliAnalysisDataContainer *coutputQA   = mgr->CreateContainer(Form("%sQA",    name), TList::Class(), AliAnalysisManager::kOutputContainer, outputQAFileName);

  mgr->ConnectInput  (task,  0, cinput );
  mgr->ConnectOutput (task,  1, coutput);
  mgr->ConnectOutput (task,  2, coutputEff);
  mgr->ConnectOutput (task,  3, coutputCont);
  mgr->ConnectOutput (task,  4, coutputDca);
  mgr->ConnectOutput (task,  5, coutputQA);

  return task;
}

redpajama_set_name: RedPajamaGithub


text:
import os
import io
import sys
import gzip
from struct import *

class BinaryReader:
	def __init__(self, data):
		if isinstance(data,str):
			self.base_stream = open(data,'rb')
		else:
			self.base_stream = data

	def tell(self):
		return self.base_stream.tell()

	def seek(self,*args):
		return self.base_stream.seek(*args)

	def Length(self):
		cur_pos = self.base_stream.tell()
		self.base_stream.seek(0,2)
		length = self.base_stream.tell()
		self.base_stream.seek(cur_pos)
		return length

	def setPosition(self,pos):
		self.seek(pos,os.SEEK_SET)

	def unpack(self, fmt, length = 1):
		return unpack(fmt, self.base_stream.read(length))[0]

	def load(self,fmt,length):
		return unpack(fmt, self.base_stream.read(length))

	def skip(self,length):
		self.readBytes(length)

	def readByte(self):
		return self.base_stream.read(1)

	def readBytes(self, length):
		return self.base_stream.read(length)

	def readChar(self):
		return self.unpack('b')

	def readUChar(self):
		return self.unpack('B')

	def readBool(self):
		return self.unpack('?')

	def readInt16(self):
		return self.unpack('h', 2)

	def readUInt16(self):
		return self.unpack('H', 2)

	def readInt32(self):
		return self.unpack('i', 4)

	def readUInt32(self):
		return self.unpack('I', 4)

	def readInt64(self):
		return self.unpack('q', 8)

	def readUInt64(self):
		return self.unpack('Q', 8)

	def readFloat(self):
		return self.unpack('f', 4)

	def readDouble(self):
		return self.unpack('d', 8)

	def readString(self):
		length = self.readUInt16()
		return self.unpack(str(length) + 's', length)

	def readUTF(self):
		leng =  self.unpack('>H',2)
		return self.readBytes(leng).decode('u8')

class BinaryWriter:

	def __init__(self, filename):
		self.base_stream = open(filename,'wb')

	def tell(self):
		return self.base_stream.tell()

	def seek(self,*args):
		return self.base_stream.seek(*args)

	def Length(self):
		cur_pos = self.base_stream.tell()
		self.base_stream.seek(0,2)
		length = self.base_stream.tell()
		self.base_stream.seek(cur_pos)
		return length

	def writeBytes(self, value):
		self.base_stream.write(value)

	def writeChar(self, value):
		self.pack('c', value)

	def writeUChar(self, value):
		self.pack('C', value)

	def writeBool(self, value):
		self.pack('?', value)

	def writeInt16(self, value):
		self.pack('h', value)

	def writeUInt16(self, value):
		self.pack('H', value)

	def writeInt32(self, value):
		self.pack('i', value)

	def writeUInt32(self, value):
		self.pack('I', value)

	def writeInt64(self, value):
		self.pack('q', value)

	def writeUInt64(self, value):
		self.pack('Q', value)

	def writeFloat(self, value):
		self.pack('f', value)

	def writeDouble(self, value):
		self.pack('d', value)

	def writeString(self, value):
		length = len(value)
		self.writeUInt16(length)
		self.pack(str(length) + 's', value)

	def pack(self, fmt, data):
		return self.writeBytes(pack(fmt, data))

	def unpack(self, fmt, length = 1):
		return unpack(fmt, self.base_stream.read(length))[0]

class BigEndianBinaryReader(BinaryReader):

	def readInt16(self):
		return self.unpack('>h', 2)

	def readUInt16(self):
		return self.unpack('>H', 2)

	def readInt32(self):
		return self.unpack('>i', 4)

	def readUInt32(self):
		return self.unpack('>I', 4)

	def readInt64(self):
		return self.unpack('>q', 8)

	def readUInt64(self):
		return self.unpack('>Q', 8)

	def readFloat(self):
		return self.unpack('>f', 4)

	def readDouble(self):
		return self.unpack('>d', 8)

	def readUTF(self):
		leng =  self.unpack('>H',2)
		bytes = self.readBytes(leng)
		return bytes.decode('u8')

class NBTBase:

	def __init__(self,name):
		self.name = name

	def setName(self,name = ""):
		self.name = name

	def getName(self):
		return self.name if self.name else ""

class NBTTagEnd(NBTBase):

	def __init__(self,name = ""):
		super().__init__(name)

	def __str__(self):
		return 'END'

	def getId(self):
		return '\x00'

class NBTTagByte(NBTBase):

	def __init__(self,name = "", data = None):
		super().__init__(name)
		self.data = data

	def load(self,binaryReader):
		self.data = binaryReader.readByte()

	def write(self,binaryWriter):
		binaryWriter.write(self.data)

	def getId(self):
		return '\x01'

	def __str__(self):
		return str(self.data)

class NBTTagShort(NBTBase):

	def __init__(self,name = "", data = None):
		super().__init__(name)
		self.data = data

	def load(self,binaryReader):
		self.data = binaryReader.readInt16()

	def write(self,binaryWriter):
		binaryWriter.write(self.data)

	def getId(self):
		return '\x02'

	def __str__(self):
		return str(self.data)

class NBTTagInt(NBTBase):

	def __init__(self,name = "", data = None):
		super().__init__(name)
		self.data = data

	def load(self,binaryReader):
		self.data = binaryReader.readInt32()

	def write(self,binaryWriter):
		binaryWriter.write(self.data)

	def getId(self):
		return '\x03'

	def __str__(self):
		return str(self.data)

class NBTTagLong(NBTBase):

	def __init__(self,name = "", data = None):
		super().__init__(name)
		self.data = data

	def load(self,binaryReader):
		self.data = binaryReader.readInt64()

	def write(self,binaryWriter):
		binaryWriter.write(self.data)

	def getId(self):
		return '\x04'

	def __str__(self):
		return str(self.data)

class NBTTagFloat(NBTBase):

	def __init__(self,name = "", data = None):
		super().__init__(name)
		self.data = data

	def load(self,binaryReader):
		self.data = binaryReader.readFloat()

	def write(self,binaryWriter):
		binaryWriter.write(self.data)

	def getId(self):
		return '\x05'

	def __str__(self):
		return str(self.data)

class NBTTagDouble(NBTBase):

	def __init__(self,name = "", data = None):
		super().__init__(name)
		self.data = data

	def load(self,binaryReader):
		self.data = binaryReader.readDouble()

	def write(self,binaryWriter):
		binaryWriter.write(self.data)

	def getId(self):
		return '\x06'

	def __str__(self):
		return str(self.data)

class NBTTagByteArray(NBTBase):

	def __init__(self,name = "", data = None):
		super().__init__(name)
		self.data = data
		self.byteArray = b""

	def load(self,binaryReader):
		length = binaryReader.readInt32()
		self.byteArray = binaryReader.readBytes(length)

	def write(self,binaryWriter):
		binaryWriter.write(self.data)

	def getId(self):
		return '\x07'

	def __str__(self):
		return str(self.data)

class NBTTagString(NBTBase):

	def __init__(self,name = "", data = None):
		super().__init__(name)
		self.data = data

	def load(self,binaryReader):
		self.data = binaryReader.readUTF()

	def write(self,binaryWriter):
		binaryWriter.write(self.data)

	def getId(self):
		return '\x08'

	def __str__(self):
		return str(self.data)

class NBTTagList(NBTBase):

	def __init__(self,name = "", data = None):
		super().__init__(name)
		self.data = data

		self.tagList = []
		self.tagType = '\x00'

	def __getitem__(self,idx):
		return self.tagList[idx]

	def __len__(self):
		return len(self.tagList)

	def load(self,binaryReader):
		self.tagType = binaryReader.readByte()
		length = binaryReader.readInt32()
		self.tagList = []
		for i in range(length):
			tag = NBTFactory.newTag(self.tagType,"")
			tag.load(binaryReader)
			self.tagList.append(tag)

	def write(self,binaryWriter):
		binaryWriter.write(self.data)

	def getId(self):
		return '\x09'

	def __str__(self):
		return str(self.data)

class NBTTagCompound(NBTBase):

	def __init__(self,name = "", data = None):
		super().__init__(name)
		self.data = data
		self.tagMap = {}

	def load(self,binaryReader):
		self.tagMap = {}

		while True:
			tag = NBTFactory.readNamedTag(binaryReader)
			if ord(tag.getId()) == 0:
				break
			self.tagMap[tag.getName()] = tag

	def __getitem__(self,key):
		if key in self.tagMap:
			tag = self.tagMap[key]
			if isinstance(tag,(NBTTagCompound,NBTTagList)):
				return tag
			elif isinstance(tag, NBTTagByteArray):
				return tag.byteArray
			elif isinstance(tag, NBTTagIntArray):
				return tag.intArray
			else:
				return tag.data
		else:
			raise Exception("DUDE,WHY DO U DO THIS")

	def write(self,binaryWriter):
		binaryWriter.write(self.data)

	def getId(self):
		return '\x0a'

	def getCompoundTag(self,name):
		try: return self.tagMap[name]
		except: return NBTTagCompound(name)
	def getByte (self,name):
		try: return self.tagMap[name].data
		except: return b""
	def getShort(self,name):
		try: return self.tagMap[name].data
		except: return 0
	def getInteger(self,name):
		try: return self.tagMap[name].data
		except: return 0
	def getLong(self,name):
		try: return self.tagMap[name].data
		except: return 0
	def getFloat(self,name):
		try: return self.tagMap[name].data
		except: return 0.0
	def getDouble(self,name):
		try: return self.tagMap[name].data
		except: return 0.0
	def getString(self,name):
		try: return self.tagMap[name].data
		except: return ""
	def getByteArray(self,name):
		try: return self.tagMap[name].byteArray
		except: return b""
	def getIntArray(self,name):
		try: return self.tagMap[name].intArray
		except: return []
	def getTagList (self,name):
		try: return self.tagMap[name]
		except: return NBTTagList(name)
	def getBoolean(self,name):
		try: return ord(self.getByte(name)) != 0
		except: return False

	def hasKey(self,key):
		return key in self.tagMap

	def __str__(self):
		return str(self.data)

class NBTTagIntArray(NBTBase):

	def __init__(self,name = "", data = None):
		super().__init__(name)
		self.data = data
		self.intArray = []

	def load(self,binaryReader):
		length = binaryReader.readInt32()
		self.intArray = []
		for i in range(length):
			self.intArray.append(binaryReader.readInt32())

	def write(self,binaryWriter):
		binaryWriter.write(self.data)

	def getId(self):
		return '\x0b'

	def __str__(self):
		return str(self.data)

class NBTFactory:

	TAGCLASS = 	[
		NBTTagEnd,
		NBTTagByte,
		NBTTagShort,
		NBTTagInt,
		NBTTagLong,
		NBTTagFloat,
		NBTTagDouble,
		NBTTagByteArray,
		NBTTagString,
		NBTTagList,
		NBTTagCompound,
		NBTTagIntArray
	]
	TAGNAME = [
		"TAG_End",
		"TAG_Byte",
		"TAG_Short",
		"TAG_Int",
		"TAG_Long",
		"TAG_Float",
		"TAG_Double",
		"TAG_Byte_Array",
		"TAG_String",
		"TAG_List",
		"TAG_Compound",
		"TAG_Int_Array"
	]
	@classmethod
	def readFromString(cls,data):
		return cls.readFromStream(io.BytesIO(data))

	@classmethod
	def readCompressed(cls,filename):
		return cls.readFromStream(gzip.GzipFile(filename,'rb'))

	@classmethod
	def readFromStream(cls,stream):
		return cls.readNamedTag(BigEndianBinaryReader(stream))

	@classmethod
	def readNamedTag(cls,binaryReader):
		typ = binaryReader.readByte()
		if ord(typ) == 0:
			return NBTTagEnd()
		else:
			val = binaryReader.readUTF()
			tag = cls.newTag(typ,val)
			tag.load(binaryReader)
			return tag

	@classmethod
	def newTag(cls,typ,val):
		return cls.TAGCLASS[ord(typ)](val)

	@classmethod
	def getTagName(cls,typ):
		return cls.TAGNAME[ord(typ)]

if __name__ == '__main__':
	nbt = NBTFactory.readCompressed()


text:
require 'generators/devise/views_generator'

module DevisePhone
  module Generators
    class ViewsGenerator < Devise::Generators::ViewsGenerator
      source_root File.expand_path("../../../../app/views/devise", __FILE__)
      desc 'Copies all DevisePhone views to your application.'

      def generate_view
      	directory 'phone', "#{target_path}/phone"
      	# directory 'path_to_install_directory', 'path_to_source_directory'
      end

      def target_path
        @target_path ||= "app/views/#{scope || :devise}"
      end

    end
  end
end


text:
namespace MIFUtils
{
	// City block generation data, used by city generation. The order of data is tightly coupled
	// with the original generation algorithm.
	const std::array<std::string, 7> CityBlockCodes = { "EQ", "MG", "NB", "TP", "TV", "TS", "BS" };
	const std::array<int, 7> CityBlockVariations = { 13, 11, 10, 12, 15, 11, 20 };
	const std::array<std::string, 4> CityBlockRotations = { "A", "B", "C", "D" };
}

bool MIFUtils::isChasm(int textureID)
{
	return (textureID == MIFUtils::DRY_CHASM) || (textureID == MIFUtils::WET_CHASM) ||
		(textureID == MIFUtils::LAVA_CHASM);
}

Double2 MIFUtils::convertStartPointToReal(const OriginalInt2 &startPoint)
{
	return Double2(
		static_cast<double>(startPoint.x) / MIFUtils::ARENA_UNITS,
		static_cast<double>(startPoint.y) / MIFUtils::ARENA_UNITS);
}

std::string MIFUtils::makeMainQuestDungeonMifName(int dungeonX, int dungeonY, int provinceID)
{
	uint32_t mifID = (dungeonY << 16) + dungeonX + provinceID;
	mifID = static_cast<uint32_t>(-static_cast<int32_t>(Bytes::rol(mifID, 5)));

	DOSUtils::FilenameBuffer buffer;
	std::snprintf(buffer.data(), buffer.size(), "%d.MIF", mifID);
	return std::string(buffer.data());
}

int MIFUtils::getCityBlockCodeCount()
{
	return static_cast<int>(CityBlockCodes.size());
}

int MIFUtils::getCityBlockVariationsCount()
{
	return static_cast<int>(CityBlockVariations.size());
}

int MIFUtils::getCityBlockRotationCount()
{
	return static_cast<int>(CityBlockRotations.size());
}

const std::string &MIFUtils::getCityBlockCode(int index)
{
	DebugAssertIndex(CityBlockCodes, index);
	return CityBlockCodes[index];
}

int MIFUtils::getCityBlockVariations(int index)
{
	DebugAssertIndex(CityBlockVariations, index);
	return CityBlockVariations[index];
}

const std::string &MIFUtils::getCityBlockRotation(int index)
{
	DebugAssertIndex(CityBlockRotations, index);
	return CityBlockRotations[index];
}

std::string MIFUtils::makeCityBlockMifName(const char *blockCode, int variation,
	const char *rotation)
{
	DOSUtils::FilenameBuffer buffer;
	std::snprintf(buffer.data(), buffer.size(), "%sBD%d%s.MIF", blockCode, variation, rotation);
	return std::string(buffer.data());
}

std::string MIFUtils::makeCityBlockMifName(BlockType blockType, ArenaRandom &random)
{
	const int blockIndex = static_cast<int>(blockType) - 2;
	const std::string &blockCode = MIFUtils::getCityBlockCode(blockIndex);
	const std::string &rotation = MIFUtils::getCityBlockRotation(
		random.next() % MIFUtils::getCityBlockRotationCount());
	const int variationCount = MIFUtils::getCityBlockVariations(blockIndex);
	const int variation = std::max(random.next() % variationCount, 1);
	return MIFUtils::makeCityBlockMifName(blockCode.c_str(), variation, rotation.c_str());
}

MIFUtils::BlockType MIFUtils::generateRandomBlockType(ArenaRandom &random)
{
	const uint32_t randVal = random.next();
	if (randVal <= 0x7333)
	{
		return BlockType::Houses;
	}
	else if (randVal <= 0xA666)
	{
		return BlockType::Tavern;
	}
	else if (randVal <= 0xCCCC)
	{
		return BlockType::Equipment;
	}
	else if (randVal <= 0xE666)
	{
		return BlockType::Temple;
	}
	else
	{
		return BlockType::NobleHouse;
	}
}


text:
package io.rancher.type;

import io.rancher.base.AbstractType;
import java.util.Map;

public class ProcessExecution extends AbstractType {

    private String created;

    private Map<String, Object> log;

    private String processInstanceId;

    private String uuid;

    public String getCreated() {
        return this.created;
    }

    public void setCreated(String created) {
      this.created = created;
    }

    public Map<String, Object> getLog() {
        return this.log;
    }

    public void setLog(Map<String, Object> log) {
      this.log = log;
    }

    public String getProcessInstanceId() {
        return this.processInstanceId;
    }

    public void setProcessInstanceId(String processInstanceId) {
      this.processInstanceId = processInstanceId;
    }

    public String getUuid() {
        return this.uuid;
    }

    public void setUuid(String uuid) {
      this.uuid = uuid;
    }

}


text:
package org.oep.core.processmgt.service.base;

import org.oep.core.processmgt.service.DossierStepServiceUtil;

import java.util.Arrays;

/**
 * @author trungdk
 * @generated
 */
public class DossierStepServiceClpInvoker {
	public DossierStepServiceClpInvoker() {
		_methodName108 = "getBeanIdentifier";

		_methodParameterTypes108 = new String[] {  };

		_methodName109 = "setBeanIdentifier";

		_methodParameterTypes109 = new String[] { "java.lang.String" };
	}

	public Object invokeMethod(String name, String[] parameterTypes,
		Object[] arguments) throws Throwable {
		if (_methodName108.equals(name) &&
				Arrays.deepEquals(_methodParameterTypes108, parameterTypes)) {
			return DossierStepServiceUtil.getBeanIdentifier();
		}

		if (_methodName109.equals(name) &&
				Arrays.deepEquals(_methodParameterTypes109, parameterTypes)) {
			DossierStepServiceUtil.setBeanIdentifier((java.lang.String)arguments[0]);

			return null;
		}

		throw new UnsupportedOperationException();
	}

	private String _methodName108;
	private String[] _methodParameterTypes108;
	private String _methodName109;
	private String[] _methodParameterTypes109;
}


text:
package entidades;

/**
 * Clase Nodo de Pila.
 */
public class NodoDePila {

    /** Atributo x. */
    private int x;
    /** Atributo y. */
    private int y;
    /** Atributo ptrSiguiente. */
    private NodoDePila ptrSiguiente;

    /**
     * Constructor de la clase Nodo de Pila.
     *
     * @param xValue
     *            valor de x donde esta el personaje
     * @param yValue
     *            valor de y donde esta el personaje
     */
    public NodoDePila(final int xValue, final int yValue) {
        this.x = xValue;
        this.y = yValue;
        ptrSiguiente = null;
    }

    /**
     * Pide el siguiente.
     *
     * @return devuelve un nodo de pila con el siguiente
     */
    public final NodoDePila obtenerSiguiente() {
        return ptrSiguiente;
    }

    /**
     * Setea el siguiente.
     *
     * @param nodo
     *            nuevo nodo a setear
     */
    public final void establecerSiguiente(final NodoDePila nodo) {
        ptrSiguiente = nodo;
    }

    /**
     * Pide el valor de X.
     *
     * @return devuelve el valor de X
     */
    public final int obtenerX() {
        return x;
    }

    /**
     * Pide el valor de Y.
     *
     * @return devuelve el valor de Y
     */
    public final int obtenerY() {
        return y;
    }

}


text:
package org.openmrs.module.sync;

import java.util.Comparator;

/**
 * Sync point: abstract concept representing a point in a continuous series. As a result, all it
 * needs to establish is order based on type T. Practically T is either Long (to represent sequence)
 * or timestamp.
 */
public class SyncPoint<T> implements Comparator<T> {

	private T value;

	public SyncPoint() {
	}

	public SyncPoint(T value) {
		this.value = value;
	}

	public T getValue() {
		return value;
	}

	public void setValue(T value) {
		this.value = value;
	}

	public int compare(T v1, T v2) {
		if (v1 instanceof Long && v2 instanceof Long) {
			if ((Long) v1 < (Long) v2)
				return -1;
			else if ((Long) v1 > (Long) v2)
				return 1;
			else
				return 0;
		} else
			throw new ClassCastException();
	}

}


text:
package org.zstack.header.identity.role.api;

import org.springframework.http.HttpMethod;
import org.zstack.header.identity.PolicyVO;
import org.zstack.header.identity.role.RoleVO;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.APIParam;
import org.zstack.header.rest.RestRequest;

@RestRequest(path = "/identities/policies/{policyUuid}/roles/{roleUuid}", method = HttpMethod.POST, responseClass = APIAttachPolicyToRoleEvent.class)
public class APIAttachPolicyToRoleMsg extends APIMessage implements RoleMessage {
    @APIParam(resourceType = RoleVO.class, checkAccount = true, operationTarget = true)
    private String roleUuid;
    @APIParam(resourceType = PolicyVO.class, checkAccount = true, operationTarget = true)
    private String policyUuid;

    public String getRoleUuid() {
        return roleUuid;
    }

    public void setRoleUuid(String roleUuid) {
        this.roleUuid = roleUuid;
    }

    public String getPolicyUuid() {
        return policyUuid;
    }

    public void setPolicyUuid(String policyUuid) {
        this.policyUuid = policyUuid;
    }

    public static APIAttachPolicyToRoleMsg __example__() {
        APIAttachPolicyToRoleMsg msg = new APIAttachPolicyToRoleMsg();

        msg.setRoleUuid(uuid());
        msg.setPolicyUuid(uuid());

        return msg;
    }
}


text:
Basically CRUD is a simple class that create a Database Abstraction Layer (DBAL) helping creating basic CRUD systems/applications, making them maintainable and secure against SQL injection.

To start using it, create an object passing the path to DB.ini file, and you're done. Now you can execute SQL queries. However, I created it with these two concepts in mind:
 * DI (Dependency Injection)
 * Law of Demeter (a.k.a tell, don't ask.)

So make sure to use it this way:
In your class, declare a dependency of this class in the constructor (or using set method...etc) and start using methods of this class in your class.

For more information checkout the example.


text:
from __future__ import annotations

from typing import TYPE_CHECKING

from django import forms
from django.core.exceptions import ValidationError
from django.http import HttpRequest

from .models import AccessToken
from .settings import PERIMETER_SESSION_KEY

if TYPE_CHECKING:
    from .models import AccessTokenUse

class TokenGatewayForm(forms.Form):
    """Form used to process a perimeter request."""

    token = forms.CharField(required=True, max_length=100)

    def clean_token(self) -> AccessToken:
        """Validate the token against existing tokens."""
        try:
            _token = AccessToken.objects.get(token=self.cleaned_data.get("token"))
            if _token.has_expired:
                raise ValidationError("Token has expired", code="expired")
            if not _token.is_active:
                raise ValidationError("Token is inactive", code="invalid")
        except AccessToken.DoesNotExist:
            raise ValidationError("Token not found", code="invalid")
        else:
            self._token = _token
            return _token

    def save_token(self, request: HttpRequest) -> AccessTokenUse:
        """Record use of the token."""
        request.session[PERIMETER_SESSION_KEY] = self._token.token
        return self._token.record(
            user_email=self.cleaned_data.get("email"),
            user_name=self.cleaned_data.get("name"),
            client_ip=request.META.get("REMOTE_ADDR", "unknown"),
            client_user_agent=request.META.get("HTTP_USER_AGENT", "unknown"),
        )

    def save(self, request: HttpRequest) -> AccessTokenUse:
        """Create a new AccessTokenUse object from the form."""
        if getattr(self, "_token", None) is None:
            raise ValueError("Form token attr is not set")
        return self.save_token(request)

class UserGatewayForm(TokenGatewayForm):
    """Form used to process a perimeter request with user info."""

    email = forms.EmailField(required=True)
    name = forms.CharField(required=True, max_length=100)


text:
<?php
namespace frontend\controllers;

use Yii;
use yii\web\Controller;

class BaseController extends Controller{

    public function actions()
    {

        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

}


text:
module Project::Operation
  class Index < Base::Operation::Base
    step :check_user!
    fail :process_absence
    step :model
    step Policy::Pundit(ProjectPolicy, :index?)

    def check_user!(_ctx, current_user:, **)
      current_user
    end

    def model(ctx, current_user:, **)
      ctx[:model] = scope(user: current_user, res: Project)
    end

    def process_absence(ctx, current_user:, **)
      ctx['result.notify'] = 'user not present'
    end
  end
end


text:
#include <config.h>

/* Specification.  */
#include "xvasprintf.h"

#include <errno.h>
#include <limits.h>
#include <string.h>
#include <stdio.h>

#include "xalloc.h"

/* Checked size_t computations.  */
#include "xsize.h"

static char *
xstrcat (size_t argcount, va_list args)
{
  char *result;
  va_list ap;
  size_t totalsize;
  size_t i;
  char *p;

  /* Determine the total size.  */
  totalsize = 0;
  va_copy (ap, args);
  for (i = argcount; i > 0; i--)
    {
      const char *next = va_arg (ap, const char *);
      totalsize = xsum (totalsize, strlen (next));
    }
  va_end (ap);

  /* Test for overflow in the summing pass above or in (totalsize + 1) below.
     Also, don't return a string longer than INT_MAX, for consistency with
     vasprintf().  */
  if (totalsize == SIZE_MAX || totalsize > INT_MAX)
    {
      errno = EOVERFLOW;
      return NULL;
    }

  /* Allocate and fill the result string.  */
  result = XNMALLOC (totalsize + 1, char);
  p = result;
  for (i = argcount; i > 0; i--)
    {
      const char *next = va_arg (args, const char *);
      size_t len = strlen (next);
      memcpy (p, next, len);
      p += len;
    }
  *p = '\0';

  return result;
}

char *
xvasprintf (const char *format, va_list args)
{
  char *result;

  /* Recognize the special case format = "%s...%s".  It is a frequently used
     idiom for string concatenation and needs to be fast.  We don't want to
     have a separate function xstrcat() for this purpose.  */
  {
    size_t argcount = 0;
    const char *f;

    for (f = format;;)
      {
        if (*f == '\0')
          /* Recognized the special case of string concatenation.  */
          return xstrcat (argcount, args);
        if (*f != '%')
          break;
        f++;
        if (*f != 's')
          break;
        f++;
        argcount++;
      }
  }

  if (vasprintf (&result, format, args) < 0)
    {
      if (errno == ENOMEM)
        xalloc_die ();
      return NULL;
    }

  return result;
}


text:
namespace Tests.Caliburn.Fakes.UI
{
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;

    public class UIBoundToCustomerWithStyleAndTriggers : UserControl
    {
        public UIBoundToCustomerWithStyleAndTriggers()
        {
            var stack = new StackPanel();
            Content = stack;

            var textBlock = new TextBlock();
            textBlock.SetBinding(TextBlock.TextProperty, new Binding("FirstName"));
            stack.Children.Add(textBlock);

            textBlock = new TextBlock();
            textBlock.SetBinding(TextBlock.TextProperty, new Binding("LastName"));
            textBlock.Style = CreateStyle();

            stack.Children.Add(textBlock);
        }

        Style CreateStyle()
        {
            var style = new Style();

            var trigger = new DataTrigger();
            trigger.Binding = new Binding("Cty"); //misspelling
            trigger.Value = "Tallahassee";

            style.Triggers.Add(trigger);

            return style;
        }
    }
}


text:
module.exports = ensureHeader
function ensureHeader (headers, key, value) {
  var lower = key.toLowerCase()
  if (!headers[key] && !headers[lower]) {
    headers[key] = value
  }
}


text:
package se.svennesson.authserver.resources;

import com.codahale.metrics.annotation.Timed;
import io.dropwizard.auth.Auth;
import se.svennesson.authserver.models.BasicCredentials;
import se.svennesson.authserver.models.User;
import se.svennesson.authserver.services.LoginAttemptsService;
import se.svennesson.authserver.services.UserService;

import javax.validation.Valid;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.net.URI;

@Path("users")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class UserResource {

    @Context
    private UriInfo uriInfo;

    private final UserService userService;
    private final LoginAttemptsService loginAttemptsService;

    public UserResource(UserService userService, LoginAttemptsService loginAttemptsService) {
        this.userService = userService;
        this.loginAttemptsService = loginAttemptsService;
    }

    @POST
    @Timed
    @Path("register")
    public Response registerUser(@Valid User user) {
        final User registeredUser = userService.registerUser(user);
        final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
        final URI userUri = uriBuilder
                .path("users/")
                .path(String.valueOf(registeredUser.getId()))
                .build();

        return Response.created(userUri).entity(registeredUser).build();
    }

    @POST
    @Timed
    @Path("login")
    public Response loginUser(@Valid BasicCredentials credentials) {
        return Response.ok(userService.loginUser(credentials)).build();
    }

    @GET
    @Timed
    @Path("attempts/success")
    public Response getLatestSuccessLoginAttempts(@Auth User user) {
        return Response.ok(loginAttemptsService.getLatestSuccessfulAttempts(user.getId())).build();
    }
}


text:
package com.anji_ahni.neat;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Arrays;
import java.util.Iterator;
import java.util.TreeMap;
import java.util.Vector;

import org.apache.log4j.Logger;
import org.jgapcustomised.BulkFitnessFunction;
import org.jgapcustomised.Chromosome;
import org.jgapcustomised.Genotype;
import org.jgapcustomised.Species;
import org.jgapcustomised.event.GeneticEvent;

import com.anji_ahni.integration.*;
import com.anji_ahni.nn.*;
import com.anji_ahni.persistence.Persistence;
import com.anji_ahni.run.Run;
import com.anji_ahni.util.*;

/**
 * Configures and performs an ANJI evolutionary run.
 *
 * @author Philip Tucker
 */
public class Evolver implements Configurable {

	private static Logger logger = Logger.getLogger(Evolver.class);

	/**
	 * properties key, # generations in run
	 */
	public static final String NUM_GENERATIONS_KEY = "num.generations";

	public static final String PERFORMANCE_TARGET_TYPE_KEY = "performance.target.type";
	public static final String PERFORMANCE_TARGET_KEY = "performance.target";

	/**
	 * properties key, fitness function class
	 */
	public static final String FITNESS_FUNCTION_CLASS_KEY = "fitness_function";

	// private static final String FITNESS_THRESHOLD_KEY = "fitness.threshold";

	private static final String RESET_KEY = "run.reset";

	private static final String HIBERNATE_ENABLE_KEY = "hibernate.enable";

	private static final String LOGGING_ENABLE_KEY = "logging.enable";

	private static final String LOAD_GENOTYPE_KEY = "persist.load.genotype";

	public static final String PERSIST_ENABLE_KEY = "persist.enable";

	private static final String PRESENTATION_GENERATE_KEY = "presentation.generate";

	private static final String LOG_PER_GENERATIONS_KEY = "log.pergenerations";

	// /**
	// * properties key, target fitness value - after reaching this run will halt
	// */
	// public static final String FITNESS_TARGET_KEY = "fitness.target";

	private NeatConfiguration config = null;
	private Properties props = null;

	private Chromosome fittest = null;
	private Chromosome bestPerforming = null;

	private Genotype genotype = null;

	private int numEvolutions = 0;

	// private double targetFitness = 0;

	// private double thresholdFitness = 0;

	private double targetPerformance = 1;

	private Persistence db = null;

	private boolean loadGenotypeFromDB = false;

	static final Runtime runtime = Runtime.getRuntime();

	private BulkFitnessFunction bulkFitnessFunc;

	private int logPerGenerations = 1;

	double[] bestPerformance;
	double[] bestFitness;
	double[] bestPC;

	/**
	 * ctor; must call init() before using this object
	 */
	public Evolver() {
		super();
	}

	/**
	 * Construct new evolver with given properties. See Parameter
	 * Details  for specific property settings.
	 *
	 * @see com.anji_ahni.util.Configurable#init(com.anji_ahni.util.Properties)
	 */
	public void init(Properties props) throws Exception {
		boolean doReset = props.getBooleanProperty(RESET_KEY, false);
		if (doReset) {
			// logger.warn( "Resetting previous run !!!" );
			Reset resetter = new Reset(props);
			resetter.setUserInteraction(false);
			resetter.reset();
		}

		this.props = props;
		config = new NeatConfiguration(props);

		// fitness function
		bulkFitnessFunc = (BulkFitnessFunction) props.singletonObjectProperty(FITNESS_FUNCTION_CLASS_KEY);
		config.setBulkFitnessFunction(bulkFitnessFunc);

		// peristence
		db = (Persistence) props.singletonObjectProperty(Persistence.PERSISTENCE_CLASS_KEY);

		loadGenotypeFromDB = props.getBooleanProperty(LOAD_GENOTYPE_KEY);

		numEvolutions = props.getIntProperty(NUM_GENERATIONS_KEY);
		targetPerformance = props.getFloatProperty(PERFORMANCE_TARGET_KEY, 1);
		// targetFitness = props.getFloatProperty(FITNESS_TARGET_KEY, 1);
		// thresholdFitness = props.getFloatProperty(FITNESS_THRESHOLD_KEY, targetFitness);
		logPerGenerations = props.getIntProperty(LOG_PER_GENERATIONS_KEY, 1);

		//
		// event listeners
		//

		// run
		// TODO - hibernate
		Run run = (Run) props.singletonObjectProperty(Run.class);
		if (props.getBooleanProperty(HIBERNATE_ENABLE_KEY, true)) {
			db.startRun(run.getName());
			config.getEventManager().addEventListener(GeneticEvent.GENOTYPE_EVALUATED_EVENT, run);
		}

		if (props.getBooleanProperty(LOGGING_ENABLE_KEY, true)) {
			// logging
			LogEventListener logListener = new LogEventListener(config);
			config.getEventManager().addEventListener(GeneticEvent.GENOTYPE_EVOLVED_EVENT, logListener);
			config.getEventManager().addEventListener(GeneticEvent.GENOTYPE_EVALUATED_EVENT, logListener);
		}

		// persistence
		if (props.getBooleanProperty(PERSIST_ENABLE_KEY, false)) {
			System.out.println("\n\nhere2\n");
			PersistenceEventListener dbListener = new PersistenceEventListener(config, run);
			dbListener.init(props);
			config.getEventManager().addEventListener(GeneticEvent.GENOTYPE_START_GENETIC_OPERATORS_EVENT, dbListener);
			config.getEventManager().addEventListener(GeneticEvent.GENOTYPE_FINISH_GENETIC_OPERATORS_EVENT, dbListener);
			config.getEventManager().addEventListener(GeneticEvent.GENOTYPE_EVALUATED_EVENT, dbListener);
		}
		// else {
		// config.load();
		// }

		// presentation
		if (props.getBooleanProperty(PRESENTATION_GENERATE_KEY, false)) {
			PresentationEventListener presListener = new PresentationEventListener(run);
			presListener.init(props);
			config.getEventManager().addEventListener(GeneticEvent.GENOTYPE_EVALUATED_EVENT, presListener);
			config.getEventManager().addEventListener(GeneticEvent.RUN_COMPLETED_EVENT, presListener);
		}
	}

	/**
	 * command line usage
	 */
	private static void usage() {
		System.err.println("usage: <cmd> <properties-file>");
	}

	/**
	 * Perform a single run.
	 *
	 * @throws Exception
	 */
	public double[] run() throws Exception {

		DecimalFormat nf4 = new DecimalFormat("0.0000");
		DecimalFormat nf3 = new DecimalFormat("0.000");
		DecimalFormat nf1 = new DecimalFormat("0.0");

		bestPerformance = new double[numEvolutions];
		bestFitness = new double[numEvolutions];
		bestPC = new double[numEvolutions];

		if (loadGenotypeFromDB) {
			// load population, either from previous run or random
			genotype = db.loadGenotype(config);
			if (genotype != null) {
				// logger.info( "genotype from previous run" );
			} else {
				genotype = Genotype.randomInitialGenotype(props, config);
				// logger.info( "random genotype (unable to load from DB)" );
			}
		} else {
			genotype = Genotype.randomInitialGenotype(props, config);
			// logger.info( "random genotype" );
		}

		// run start time
		Date runStartDate = Calendar.getInstance().getTime();
		// logger.info( "----- Run start -----  (RAM: total: " +
		// (runtime.totalMemory() / (1024*1024)) + "  free: " +
		// (runtime.freeMemory() / (1024*1024)) + "  used: " +
		// ((runtime.totalMemory() - runtime.freeMemory()) / (1024*1024)) +
		// ")");
		//DateFormat fmt = new SimpleDateFormat("HH:mm:ss");

		// System.out.println("targetFitness = " + targetFitness);
		// System.out.println("maxFitness = " + maxFitness);

		// initialize result data
		int generationOfFirstSolution = -1;
		fittest = genotype.getFittestChromosome();

		File dirFile = new File(props.getProperty("output.dir"));
		if (!dirFile.exists())
			dirFile.mkdirs();
		BufferedWriter speciesInfoWriter = new BufferedWriter(new FileWriter(props.getProperty("output.dir") + "species-history-size.csv"));
		StringBuffer output = new StringBuffer();
		output.append("Gen,\tTSE,\tTS,\tNew,\tExt");
		for (int i = 0; i < 100; i++)
			output.append(",\t" + i);
		output.append("\n");
		speciesInfoWriter.write(output.toString());
		speciesInfoWriter.flush();

		double avgGenTime = 0;
		int previousSpeciesCount = 0;
		int generation;
		TreeMap<Long, Species> allSpeciesEver = new TreeMap<Long, Species>();
		long start = System.currentTimeMillis();

		// for (generation = 0; (generation < numEvolutions && (adjustedFitness < targetFitness ||
		// genotype.preventRunEnd())); ++generation) {
		for (generation = 0; generation < numEvolutions && !bulkFitnessFunc.endRun(); ++generation) {
			previousSpeciesCount = genotype.getSpecies().size();

			// generation start time
			// Date generationStartDate = Calendar.getInstance().getTime();
			// logger.info( "Generation " + generation + ": start" );

			// nextSequence generation
			fittest = genotype.evolve();

			bestPerforming = genotype.getBestPerforming();

			// result data
			// if (bestPerforming.getPerformanceValue() >= targetPerformance && generationOfFirstSolution == -1)
			if (bulkFitnessFunc.endRun())
				generationOfFirstSolution = generation;

			// champFitnesses[generation] = adjustedFitness;

			bestPerformance[generation] = bestPerforming.getPerformanceValue();
			bestFitness[generation] = fittest.getFitnessValue();

			int numSpecies = genotype.getSpecies().size();
			int minSpeciesSize = Integer.MAX_VALUE;
			int maxSpeciesSize = 0;
			int numSpeciesWithNewBestPerforming = 0;
			int numNewSpecies = 0;
			int maxSpeciesAge = 0;
			int minSpeciesAge = Integer.MAX_VALUE;
			double avgBestSpeciesPerformance = 0;
			Iterator<Species> speciesIter = genotype.getSpecies().iterator();
			while (speciesIter.hasNext()) {
				Species species = speciesIter.next();

				if (species.originalSize > maxSpeciesSize)
					maxSpeciesSize = species.originalSize;
				if (species.originalSize < minSpeciesSize)
					minSpeciesSize = species.originalSize;

				if (species.getAge() > maxSpeciesAge)
					maxSpeciesAge = species.getAge();
				if (species.getAge() < minSpeciesAge)
					minSpeciesAge = species.getAge();

				if (species.getBestPerforming() != null)
					avgBestSpeciesPerformance += species.getBestPerforming().getPerformanceValue();

				Long speciesKey = new Long(species.getID());
				if (allSpeciesEver.containsKey(speciesKey)) { // if existing species
					if (species.getBestPerforming() != species.getPreviousBestPerforming())
						numSpeciesWithNewBestPerforming++;
				} else {
					numNewSpecies++;
					allSpeciesEver.put(speciesKey, species);
				}
			}
			avgBestSpeciesPerformance /= numSpecies;
			int numExtinctSpecies = previousSpeciesCount - numSpecies + numNewSpecies;

			// write out some info about species history
			speciesIter = allSpeciesEver.values().iterator();
			output = new StringBuffer(generation + ",\t" + allSpeciesEver.size() + ",\t" + numSpecies + ",\t" + numNewSpecies + ",\t" + numExtinctSpecies);
			while (speciesIter.hasNext()) {
				Species species = speciesIter.next();
				// output += ",\t" + species.getID() + ":" + species.size();
				output.append(",\t");
				output.append(species.originalSize);
			}
			output.append("\n");
			speciesInfoWriter.write(output.toString());
			speciesInfoWriter.flush();

			if (generation % logPerGenerations == 0) {
				double speciationCompatThreshold = genotype.getParameters().getSpeciationThreshold();

				long memTotal = Math.round(runtime.totalMemory() / 1048576);
				long memFree = Math.round(runtime.freeMemory() / 1048576);
				long memUsed = memTotal - memFree;

				long duration = (System.currentTimeMillis() - start) / 1000;
				if (avgGenTime == 0)
					avgGenTime = duration;
				else
					avgGenTime = avgGenTime * 0.9 + duration * 0.1;
				int eta = (int) Math.round(avgGenTime * (numEvolutions - generation));

				// System.out.print(generation+"(" + (int)(adjustedFitness*100) + "," + genotype.getSpecies().size() +
				// "), ");
				// System.out.println(generation + "(" + nf.format((double)fittest.getFitnessValue() /
				// bulkFitnessFunc.getMaxFitnessValue()) + ", " + nf.format(bestPerformance[generation]) + ", " +
				// duration + "s, " + memUsed + "M), ");
				// System.out.print((int)(adjustedFitness*100)+",");
				// System.out.println(generation+"(" + (int)(adjustedFitness*100) + " : " + champ.getFitnessValue() +
				// "), ");

				logger.info("Gen: " + generation + "  Fittest: " + fittest.getId() + "  (F: " + nf4.format(fittest.getFitnessValue()) + "  P: " + nf4.format(fittest.getPerformanceValue()) + ")" + "  Best perf: " + bestPerforming.getId() + "  (F: " + nf4.format(bestPerforming.getFitnessValue()) + "  P: " + nf4.format(bestPerforming.getPerformanceValue()) + ")" + "  ABSP: " + nf4.format(avgBestSpeciesPerformance) + "  S: " + numSpecies + "  NS/ES: " + numNewSpecies + "/" + numExtinctSpecies + "  SCT: " + nf1.format(speciationCompatThreshold) + "  Min/Max SS: " + minSpeciesSize + "/" + maxSpeciesSize + "  Min/Max SA: " + minSpeciesAge + "/" + maxSpeciesAge + "  SNB: " + numSpeciesWithNewBestPerforming + "  Time: " + duration + "s  ETA: " + Misc.formatTimeInterval(eta) + "  Mem: " + memUsed + "MB");

				start = System.currentTimeMillis();
			}

			// generation finish
			// Date generationEndDate = Calendar.getInstance().getTime();
			// long durationMillis = generationEndDate.getTime() -
			// generationStartDate.getTime();
			// logger.info( "Generation " + generation + ": end [" + fmt.format(
			// generationStartDate ) + " - " + fmt.format( generationEndDate ) +
			// "] [" + durationMillis + "]" );
		}
		System.out.println();

		speciesInfoWriter.close();

		// if evolution was terminated before the max number of gens was
		// performed (eg because solution was found sooner)
		if (generation != numEvolutions) {
			// fill in rest of array with last fitness and performance values (for stats generation later)
			double lastPerf = bestPerformance[generation - 1];
			for (int i = generation; i < numEvolutions; i++)
				bestPerformance[i] = lastPerf;

			double lastFitness = bestFitness[generation - 1];
			for (int i = generation; i < numEvolutions; i++)
				bestFitness[i] = lastFitness;

			double lastPC = bestPC[generation - 1];
			for (int i = generation; i < numEvolutions; i++)
				bestPC[i] = lastPC;

		}

		// run finish
		config.getEventManager().fireGeneticEvent(new GeneticEvent(GeneticEvent.RUN_COMPLETED_EVENT, genotype));
		logConclusion(generationOfFirstSolution, fittest);
		//Date runEndDate = Calendar.getInstance().getTime();
		//long durationMillis = runEndDate.getTime() - runStartDate.getTime();
		// logger.info( "Run: end [" + fmt.format( runStartDate ) + " - " +
		// fmt.format( runEndDate ) + "] [" + durationMillis +
		// "]  Best fitness: " + adjustedFitness);

		System.out.println();
		System.out.println();
		System.out.println("Best performance for this run (average per 10 gens): ");
		double v;
		int i;
		for (generation = 0; generation < numEvolutions;) {
			v = 0;
			for (i = 0; i < 10 && generation < numEvolutions; i++, generation++)
				v += bestPerformance[generation];
			v /= i;
			System.out.print(nf3.format(v) + ", ");
		}
		System.out.println();
		System.out.println("Best fitness for this run (average per 10 gens): ");
		for (generation = 0; generation < numEvolutions;) {
			v = 0;
			for (i = 0; i < 10 && generation < numEvolutions; i++, generation++)
				v += bestFitness[generation];
			v /= i;
			System.out.print(nf3.format(v) + ", ");
		}
		System.out.println();
		System.out.println();
		System.out.println();

		return bestPerformance;
	}

	public double[] getBestFitness() {
		return bestFitness;
	}

	public double[] getBestPerformance() {
		return bestPerformance;
	}

	public double[] getBestPC() {
		return bestPC;
	}

	/**
	 * Log summary data of run including generation in which the first solution occurred, and the champion of the final
	 * generation.
	 *
	 * @param generationOfFirstSolution
	 * @param champ
	 */
	private void logConclusion(int generationOfFirstSolution, Chromosome champ) {
		logger.info("    generation of first solution: " + generationOfFirstSolution);
		logger.info("    champ # connections: " + NeatChromosomeUtility.getConnectionList(champ.getAlleles()).size());
		logger.info("    champ # hidden nodes: " + NeatChromosomeUtility.getNeuronList(champ.getAlleles(), NeuronType.HIDDEN).size());
		logger.info("    final species compat threshold: " + config.getSpeciationParms().getSpeciationThreshold());
	}

	/**
	 * Main program used to perform an evolutionary run.
	 *
	 * @param args command line arguments; args[0] used as properties file
	 * @throws Throwable
	 */
	public static void main(String[] args) throws Throwable {
		try {
			// System.out.println( Copyright.STRING );
			if (args.length != 1) {
				usage();
				System.exit(-1);
			}

			Properties props = new Properties(args[0]);
			Evolver evolver = new Evolver();
			evolver.init(props);
			evolver.run();

			// HyperNEATTranscriber transcriber = new HyperNEATTranscriber(props);
			// GridNet net =transcriber.newGridNet(evolver.getChamp());
			// System.out.println("Champ weights:");
			// System.out.println(net.toString());

			// NeatActivator na = new NeatActivator();
			// na.init( props );
			// logger.info( "\n" + na.displayActivation( "" +evolver.getChamp().getId() ) );

			System.exit(0);
		} catch (Throwable th) {
			logger.error("", th);
			throw th;
		}
	}

	/**
	 * @return champion of last generation
	 */
	public Chromosome getChamp() {
		return fittest;
	}

	/**
	 * Fitness of current champ, 0 ... 1
	 *
	 * @return maximum fitness value
	 */
	public double getChampAdjustedFitness() {
		return (fittest == null) ? 0 : fittest.getFitnessValue();
	}

	/**
	 * @return target fitness value, 0 ... 1
	 */
	public double getTargetPerformance() {
		return targetPerformance;
	}

	// /**
	// * @return threshold fitness value, 0 ... 1
	// */
	// public double getThresholdFitness() {
	// return thresholdFitness;
	// }

	public void dispose() {
		bulkFitnessFunc.dispose();
	}

}


text:
.SUFFIXES:
#---------------------------------------------------------------------------------

ifeq ($(strip $(DEVKITARM)),)
$(error "Please set DEVKITARM in your environment. export DEVKITARM=<path to>devkitARM")
endif

include $(DEVKITARM)/ds_rules

#---------------------------------------------------------------------------------
# TARGET is the name of the output
# BUILD is the directory where object files & intermediate files will be placed
# SOURCES is a list of directories containing source code
# INCLUDES is a list of directories containing extra header files
# DATA is a list of directories containing binary files embedded using bin2o
# GRAPHICS is a list of directories containing image files to be converted with grit
# AUDIO is a list of directories containing audio to be converted by maxmod
# ICON is the image used to create the game icon, leave blank to use default rule
# NITRO is a directory that will be accessible via NitroFS
#---------------------------------------------------------------------------------
TARGET   := $(shell basename $(CURDIR))
BUILD    := build
SOURCES  := source
INCLUDES := source
DATA     := data
GRAPHICS := gfx
AUDIO    :=
ICON     :=

# specify a directory which contains the nitro filesystem
# this is relative to the Makefile
NITRO    :=

# These set the information text in the nds file
GAME_TITLE     := rxTools
GAME_SUBTITLE1 := MSET ROP Installer
GAME_SUBTITLE2 := Roxas75

#---------------------------------------------------------------------------------
# options for code generation
#---------------------------------------------------------------------------------
ARCH := -marm -mthumb-interwork -march=armv5te -mtune=arm946e-s

CFLAGS   := -Wno-multichar -g -Wall -O3\
            $(ARCH) $(INCLUDE) -DARM9
CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions
ASFLAGS  := -g $(ARCH)
LDFLAGS   = -specs=ds_arm9.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map)

#---------------------------------------------------------------------------------
# any extra libraries we wish to link with the project (order is important)
#---------------------------------------------------------------------------------
LIBS := -lfat -lnds9

# automatigically add libraries for NitroFS
ifneq ($(strip $(NITRO)),)
LIBS := -lfilesystem -lfat $(LIBS)
endif
# automagically add maxmod library
ifneq ($(strip $(AUDIO)),)
LIBS := -lmm9 $(LIBS)
endif

#---------------------------------------------------------------------------------
# list of directories containing libraries, this must be the top level containing
# include and lib
#---------------------------------------------------------------------------------
LIBDIRS := $(LIBNDS) $(PORTLIBS)

#---------------------------------------------------------------------------------
# no real need to edit anything past this point unless you need to add additional
# rules for different file extensions
#---------------------------------------------------------------------------------
ifneq ($(BUILD),$(notdir $(CURDIR)))
#---------------------------------------------------------------------------------
export TOOLS := ../../tools
export OUTPUT := $(CURDIR)

export VPATH := $(CURDIR)/$(subst /,,$(dir $(ICON)))\
                $(foreach dir,$(SOURCES),$(CURDIR)/$(dir))\
                $(foreach dir,$(DATA),$(CURDIR)/$(dir))\
                $(foreach dir,$(GRAPHICS),$(CURDIR)/$(dir))

export DEPSDIR := $(CURDIR)/$(BUILD)

CFILES   := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
SFILES   := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))
PNGFILES := $(foreach dir,$(GRAPHICS),$(notdir $(wildcard $(dir)/*.png)))
BINFILES := mset4x.bin mset6x.bin

# prepare NitroFS directory
ifneq ($(strip $(NITRO)),)
  export NITRO_FILES := $(CURDIR)/$(NITRO)
endif

# get audio list for maxmod
ifneq ($(strip $(AUDIO)),)
  export MODFILES	:=	$(foreach dir,$(notdir $(wildcard $(AUDIO)/*.*)),$(CURDIR)/$(AUDIO)/$(dir))

  # place the soundbank file in NitroFS if using it
  ifneq ($(strip $(NITRO)),)
    export SOUNDBANK := $(NITRO_FILES)/soundbank.bin

  # otherwise, needs to be loaded from memory
  else
    export SOUNDBANK := soundbank.bin
    BINFILES += $(SOUNDBANK)
  endif
endif

#---------------------------------------------------------------------------------
# use CXX for linking C++ projects, CC for standard C
#---------------------------------------------------------------------------------
ifeq ($(strip $(CPPFILES)),)
#---------------------------------------------------------------------------------
  export LD := $(CC)
#---------------------------------------------------------------------------------
else
#---------------------------------------------------------------------------------
  export LD := $(CXX)
#---------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------

export OFILES   := $(addsuffix .o,$(BINFILES))\
                   $(PNGFILES:.png=.o)\
                   $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)
export INCLUDE  := $(foreach dir,$(INCLUDES),-iquote $(CURDIR)/$(dir))\
                   $(foreach dir,$(LIBDIRS),-I$(dir)/include)\
                   -I$(CURDIR)/$(BUILD)
export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib)

ifeq ($(strip $(ICON)),)
  icons := $(wildcard *.bmp)

  ifneq (,$(findstring $(TARGET).bmp,$(icons)))
    export GAME_ICON := $(CURDIR)/$(TARGET).bmp
  else
    ifneq (,$(findstring icon.bmp,$(icons)))
      export GAME_ICON := $(CURDIR)/icon.bmp
    endif
  endif
else
  ifeq ($(suffix $(ICON)), .grf)
    export GAME_ICON := $(CURDIR)/$(ICON)
  else
    export GAME_ICON := $(CURDIR)/$(BUILD)/$(notdir $(basename $(ICON))).grf
  endif
endif

.PHONY: $(BUILD) clean all

#---------------------------------------------------------------------------------
all: data/mset4x.bin data/mset6x.bin $(BUILD)

data/mset4x.bin: rop/mset4x.s
	@mkdir -p data
	@armips $<

data/mset6x.bin: rop/mset6x.s
	@mkdir -p data
	@armips $<

$(BUILD):
	@mkdir -p $@
	@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
	@rm $(OUTPUT).elf

#---------------------------------------------------------------------------------
clean:
	@echo clean ...
	@rm -fr $(BUILD) $(TARGET).elf $(TARGET).nds $(SOUNDBANK) data/*.bin

#---------------------------------------------------------------------------------
else

#---------------------------------------------------------------------------------
# main targets
#---------------------------------------------------------------------------------
$(OUTPUT).nds: $(OUTPUT).elf $(GAME_ICON)
$(OUTPUT).elf: $(OFILES)

# need to build soundbank first
$(OFILES): $(SOUNDBANK)

#---------------------------------------------------------------------------------
# rule to build solution from music files
#---------------------------------------------------------------------------------
$(SOUNDBANK) : $(MODFILES)
#---------------------------------------------------------------------------------
	mmutil $^ -d -o$@ -hsoundbank.h

#---------------------------------------------------------------------------------
%.bin.o: %.bin
#---------------------------------------------------------------------------------
	@echo $(notdir $<)
	$(bin2o)

#---------------------------------------------------------------------------------
# This rule creates assembly source files using grit
# grit takes an image file and a .grit describing how the file is to be processed
# add additional rules like this for each image extension
# you use in the graphics folders
#---------------------------------------------------------------------------------
%.s %.h: %.png %.grit
#---------------------------------------------------------------------------------
	grit $< -fts -o$*

#---------------------------------------------------------------------------------
# Convert non-GRF game icon to GRF if needed
#---------------------------------------------------------------------------------
$(GAME_ICON): $(notdir $(ICON))
#---------------------------------------------------------------------------------
	@echo convert $(notdir $<)
	@grit $< -g -gt -gB4 -gT FF00FF -m! -p -pe 16 -fh! -ftr

-include $(DEPSDIR)/*.d

#---------------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------------


text:
package org.ocpsoft.rewrite.util;

/**
 * General purpose visitor interface
 *
 * @author Christian Kaltepoth
 */
public interface Visitor<E>
{

   /**
    * Visit the supplied object
    */
   void visit(E e);

}


text:
namespace elena_lang
{
   constexpr auto INDEX_STEP = 0x100;
   constexpr auto INDEX_ORDER = 8;

   // --- FormatterInfo ---
   struct FormatterInfo
   {
      pos_t  style;
      bool   lookAhead;
      text_c state;
   };

   // --- ReaderInfo ---
   struct ReaderInfo
   {
      pos_t style;
      pos_t step;

      int   row;

      bool  newLine;
      bool  bandStyle;
   };

   struct Marker
   {
      pos_t style;

      bool operator ==(const Marker& m)
      {
         return style == m.style;
      }
   };
   typedef Map<int, Marker>   MarkerList;

   // --- TextFormatterBase ---
   class TextFormatterBase
   {
   public:
      virtual void start(FormatterInfo& info) = 0;

      virtual bool next(text_c ch, FormatterInfo& info, pos_t& lastStyle) = 0;
   };

   // --- LexicalFormatter ---
   class LexicalFormatter : public TextWatcherBase
   {
      Text*                _text;
      MarkerList*          _markers;
      MemoryDump           _indexes;
      MemoryDump           _lexical;

      TextFormatterBase*   _formatter;

      pos_t retrievePosition(pos_t position)
      {
         position >>= INDEX_ORDER;

         MemoryReader reader(&_indexes, position * sizeof(pos_t));

         return reader.getPos();
      }

      bool checkMarker(ReaderInfo& info);
      void format();

   public:
      void onUpdate(size_t position) override;
      void onInsert(size_t position, size_t length, text_t line) override;
      void onErase(size_t position, size_t length, text_t line) override;

      pos_t proceed(pos_t position, ReaderInfo& info);

      LexicalFormatter(Text* text, TextFormatterBase* formatter, MarkerList* markers);
      virtual ~LexicalFormatter();
   };

   // --- DocumentNotifier ---
   class DocumentNotifier
   {
   public:
      virtual void onDocumentUpdate() = 0;
   };

   typedef List<DocumentNotifier*> DocumentNotifiers;

   // --- Document ---
   class DocumentView : public TextWatcherBase
   {
   public:
      struct LexicalReader : ReaderInfo
      {
         Rectangle     region;

         DocumentView* docView;
         TextBookmark  bm;

         void seekCurrentLine();
         bool readCurrentLine(TextWriter<text_c>& writer, pos_t length);

         void readFirst(TextWriter<text_c>& writer, pos_t length);
         bool readNext(TextWriter<text_c>& writer, pos_t length);

         LexicalReader(DocumentView* docView)
         {
            this->docView = docView;
            this->step = this->style = 0;
            this->row = 0;
            this->newLine = false;
            this->bandStyle = false;

            this->bm.invalidate();
         }
      };

      struct Status
      {
         bool caretChanged;
         bool maxColChanged;
         bool frameChanged;
         bool selelectionChanged;
         bool formatterChanged;
         bool readOnly;
         bool modifiedMode;
         bool unnamed;
         bool overwriteMode;

         bool oldModified;
         bool oldOvewrite;

         int  rowDifference;

         bool isModeChanged()
         {
            bool changed = (modifiedMode != oldModified) || (overwriteMode != oldOvewrite);

            oldModified = modifiedMode;
            oldOvewrite = overwriteMode;

            return changed;
         }

         bool isViewChanged(bool reset = true)
         {
            bool flag = formatterChanged | frameChanged | selelectionChanged;

            if (reset)
               formatterChanged = frameChanged = selelectionChanged = false;

            return flag;
         }

         void reset()
         {
            caretChanged = false;
            maxColChanged = false;
            frameChanged = false;
            oldModified = modifiedMode = false;
            selelectionChanged = false;
            formatterChanged = false;
            readOnly = false;
            unnamed = false;
            overwriteMode = false;
            oldOvewrite = true;     // to trigger mode change

            rowDifference = 0;
         }

         Status()
         {
            reset();
         }
      };

      friend struct LexicalReader;

   protected:
      Text*             _text;
      TextHistory       _undoBuffer;
      LexicalFormatter  _formatter;

      Point             _size;
      TextBookmark      _frame;
      TextBookmark      _caret;
      int               _selection;

      int               _maxColumn;

      MarkerList        _markers;
      DocumentNotifiers _notifiers;

      pos_t format(LexicalReader& reader);

      void onInsert(size_t position, size_t length, text_t line) override;
      void onUpdate(size_t position) override;
      void onErase(size_t position, size_t length, text_t line) override;

   public:
      Status status;

      void attachNotifier(DocumentNotifier* notifier)
      {
         _notifiers.add(notifier);
      }

      void removeNotifier(DocumentNotifier* notifier)
      {
         _notifiers.cut(notifier);
      }

      void addMarker(int row, pos_t style, bool instanteMode)
      {
         _markers.add(row, { style });

         status.formatterChanged = true;
      }
      void removeMarker(int row, pos_t style)
      {
         _markers.erase(row, { style });

         status.formatterChanged = true;
      }

      virtual void resize(Point size);

      bool hasSelection() const { return (_selection != 0); }
      disp_t getSelectionLength();

      TextBookmark getCaretBookmark() { return _caret; }

      Point getFrame() const { return _frame.getCaret(); }
      Point getCaret(bool virtualOne = true) const { return _caret.getCaret(virtualOne); }
      Point getSize() const { return _size; }

      int getRowCount() const { return _text->getRowCount(); }
      int getMaxColumn() const { return _maxColumn; }

      void setCaret(int column, int row, bool selecting);
      void setCaret(Point caret, bool selecting)
      {
         setCaret(caret.x, caret.y, selecting);
      }

      void vscroll(int offset);
      void hscroll(int offset);

      void moveRight(bool selecting);
      void moveLeft(bool selecting);
      void moveUp(bool selecting);
      void moveDown(bool selecting);

      void moveRightToken(bool selecting, bool trimWhitespace = false);
      void moveLeftToken(bool selecting);
      void moveFrameUp();
      void moveFrameDown();
      void moveHome(bool selecting);
      void moveEnd(bool selecting);
      void moveFirst(bool selecting);
      void moveLast(bool selecting);

      void moveToFrame(int column, int row, bool selecting);

      virtual void tabbing(text_c space, size_t count, bool indent);

      void insertNewLine();
      void insertChar(text_c ch)
      {
         insertChar(ch, 1);
      }
      void insertChar(text_c ch, size_t number);
      void insertLine(text_t text, disp_t length);

      void eraseChar(bool moveback);
      bool eraseSelection();

      void copySelection(text_c* text);

      void undo();
      void redo();

      void notifyOnChange();

      void save(path_t path);

      DocumentView(Text* text, TextFormatterBase* formatter);
      virtual ~DocumentView();
   };
}

#endif


text:
package net.anotheria.moskito.core.config.plugins;

import org.configureme.annotations.Configure;
import org.configureme.annotations.ConfigureMe;

import java.io.Serializable;

/**
 * Config element that describes a single plugin.
 *
 * @author lrosenberg
 * @since 19.03.13 15:48
 */
@ConfigureMe
public class PluginConfig implements Serializable {
	/**
	 * SerialVersionUID.
	 */
	private static final long serialVersionUID = -5682152228778301153L;

	/**
	 * Name of the plugin. This allows to have multiple copies of same plugin in the runtime instance.
	 */
	@Configure
	private String name;
	/**
	 * Name of the plugin class. It must implement net.anotheria.moskito.core.plugins.MoskitoPlugin.
	 */
	@Configure
	private String className;
	/**
	 * Name of the configuration for the plugin. It will be passed to the plugin after creation.
	 */
	@Configure
	private String configurationName;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getClassName() {
		return className;
	}

	public void setClassName(String className) {
		this.className = className;
	}

	public String getConfigurationName() {
		return configurationName;
	}

	public void setConfigurationName(String configurationName) {
		this.configurationName = configurationName;
	}

	@Override public String toString(){
		return "PluginConfig ("+getName()+", "+getClassName()+", "+getConfigurationName()+ ')';
	}
}


text:
BrainFuckedBotsForBattling - A Brainfuck Tournament
===================================================

All bots at the battle arena suddenly got brainfucked and no one can explain why. But who cares as long as they are still able to fight - although Brainfuck is the only language they understand anymore.

---

Scoreboard
----------

    |       Owner        |          Bot            Score |
    |--------------------|-------------------------------|
    | LymiaAluysia       | NyurokiMagicalFantasy -  600  |
    | Sylwester          | LethalLokeV2.1        -  585  |
    | weston             | MickeyV4              -  584  |
    | Sp3000             | YandereBot            -  538  |
    | Comintern          | CounterPunch          -  512  |
    | Sylwester          | BurlyBalderV3         -  507  |
    | LymiaAluysia       | NestDarwin            -  493  |
    | IstvanChung        | Bigger                -  493  |
    | Manu               | DecoyMaster           -  489  |
    | archaephyrryx      | Wut                   -  478  |
    | DLosc              | LightfootPlodder      -  475  |
    | archaephyrryx      | 99BottlesOfBats       -  461  |
    | Sylwester          | TerribleThorV2        -  458  |
    | MikaLammi          | WallE2.0              -  443  |
    | Mikescher          | MultiVAC              -  441  |
    | archaephyrryx      | Twitcher              -  439  |
    | Timtech            | MetalDetector         -  438  |
    | AndoDaan           | BeatYouMate           -  433  |
    | csarchon           | TheWallmaster         -  427  |
    | Sparr              | SeeSawRush            -  412  |
    | archaephyrryx      | Stitcher              -  406  |
    | PhiNotPi           | RandomOscillator      -  403  |
    | ccarton            | AnybodyThere          -  398  |
    | Comintern          | 2BotsOneCup           -  392  |
    | kaine              | SternBot              -  387  |
    | PhiNotPi           | EvoBot2               -  385  |
    | PhiNotPi           | EvoBot1               -  381  |
    | Brilliand          | TimedAttack           -  373  |
    | Sylwester          | ReluctantRanV2        -  373  |
    | AndoDaan           | PrimesAndWonders      -  359  |
    | Nax                | TruthBot              -  357  |
    | DLosc              | Plodder               -  356  |
    | weston             | FastTrapClearBot      -  345  |
    | MikaLammi          | PolarBearMkII         -  340  |
    | Sp3000             | ParanoidBot           -  336  |
    | Moop               | Alternator            -  319  |
    | TestBot            | FastClearBot          -  302  |
    | icedvariables      | PyBot                 -  293  |
    | TestBot            | DecoyBot              -  293  |
    | kaine              | BestOffense           -  291  |
    | Geobits            | Backtracker           -  289  |
    | bornSwift          | ScribeBot             -  280  |
    | IngoBuerk          | Geronimo              -  268  |
    | flawr              | CropCircleBot         -  239  |
    | plannapus          | CleanUpOnAisleSix     -  233  |
    | frederick          | ConBot                -  230  |
    | frederick          | 128Bot                -  222  |
    | AndoDaan           | EndTitled             -  219  |
    | PhiNotPi           | CloakingDeviceBot     -  215  |
    | AndoDaan           | GetOffMate            -  206  |
    | DLosc              | ScaredyBot            -  205  |
    | isaacg             | CleverAndDetermined   -  202  |
    | PhiNotPi           | CantTouchThis         -  202  |
    | Moop               | StubbornBot           -  174  |
    | Cruncher           | StallBot              -  168  |
    | IngoBuerk          | Gambler               -  157  |
    | BetaDecay          | RussianRoulette       -  129  |
    | flawr              | DoNothingBot          -  123  |
    | SebastianLamerichs | Dumbot                -  115  |
    | mmphilips          | PacifistBot           -  112  |
    | SeanD              | DontUnderstand        -  92   |
    | proudHaskeller     | PatientBot            -  83   |
    | frederick          | Dumberbot             -  70   |
    | flawr              | MetaJSRandomBot       -  68   |
    | Darkgamma          | TheRetard             -  61   |
    | BetaDecay          | Roomba                -  61   |
    | BetaDecay          | PrussianRoulette      -  31   |
    | frederick          | Dumbestbot            -  0    |

_Scores from 09.10.2014 - Next update maybe in the far future with more bots_

__EDIT6__: Discarded logs due to extreme size and runtime. You can generate them yourself by uncommenting the lines in `RunThisTournament.py`.

__EDIT5__: Implemented Abbreviation handling into the controller, no huge runtimes anymore. __This has the side effect that numbers and parentheses are not treated as comments anymore.__ You can still use them if you want to provide an annotated version, but it would be very helpful if there would be __also an uncommented version of your code__, so I don't need to remove the comments manually. Thanks!

__EDIT4__: Changed the title, because the tournament got removed from the hot network questions. Thanks to @Geobits for pointing this out!

__EDIT3__: Removed comments in bf programs, due to an unexpected result, should be fixed now. If anyone has a problem with removing his comments, please report.

__EDIT2__: Since it caused an arcane runtime on my quite slow computer, I reduced the timeout limit from 100000 cycles to 10000 cycles. Not that anyone has turned the resultof a running game beyond this point anyway.

__EDIT1__: Fixed a bug in the convert script causing the interpreter to not ignore numbers in commented programs.

---

Description
-----------

This is a [Brainfuck](http://esolangs.org/wiki/Brainfuck) tournament inspired by [BF Joust](http://esolangs.org/wiki/BF_Joust). Two bots (Brainfuck programs) are fighting each other in an arena which is represented by a memory tape. Each cell can hold values from -127 up to 128 and wrap at their limits (so 128 + 1 = -127).

Valid instructions are similiar to regular Brainfuck, which means:

    + : Increment cell at your pointer's location by 1
    - : Decrement cell at your pointer's location by 1
    > : Move your memory pointer by 1 cell towards the enemy flag
    < : Move your memory pointer by 1 cell away from the enemy flag
    [ : Jump behind the matching ']'-bracket if the cell at your pointer's location equals 0
    ] : Jump behind the matching '['-bracket if the cell at your pointer's location is not 0
    . : Do nothing

The arena has a size of 10 to 30 cells which is pseudorandomly chosen each battle. At both ends is a 'flag' located which has an initial value of 128, while all other cells are zeroed. Your bot's goal is to zero the enemy's flag for 2 consecutive cycles before he zeroes your own flag.

Each bot starts at his own flag, which is cell [0] from his own perspective. The opponent is located on the other side of the tape.

	[ 128 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 128 ]
	   ^											 ^
	my bot										 other bot

Both bots execute their action simultaneously, this is considered one cycle. The game ends after 10000 cycles or as soon as one of the winning conditions is reached. If one of the programs reaches its end, it simply stops doing anthing until the end of the game, but can still win.

---

Winning conditions
------------------

Your bot wins under one of the following conditions:

* Your enemy's flag is zeroed before yours
* Your enemy moves his pointer out of the tape (executes `>` on your flag or `<` on his own)
* Your flag's value is more far away from 0 than the value of your opponent's flag after 10000 cycles

---

Rules
-----

Your post should contain a name for your bot and its code.

* You can use the following abbreviation syntax to make your code more readable:
 * e.g. `(+)*4` is the same as `++++`, this is valid for any instruction __except unmatched brackets in parentheses__ since the loop logic collides with the abbreviation logic. Please use `[-[-[-` instead of `([-)*3`
* Every other character than `+-><[].` is a comment and therefore ignored, except `()*` for abbreviations

Bots which do not follow the rules will excluded from the tournament.

* Only basic Brainfuck is allowed, no other variants which supports procedures or arithmetic operations
* Your bot's source code should not contain unmatched brackets

You may inform yourself about [basic strategies](http://esolangs.org/wiki/BF_Joust_strategies) but do __not__ use another one's code for your own bot.

---

Scoring
-------

A bot's score is determined by the number of wins against all other bots.
An encounter between 2 bots consists of 10 matches with different memory tape lengths, which results in a maximum score of 10 points per encounter.
A draw results in no points for this match.

---

Control program
---------------

You can find the [control program](https://github.com/redevined/brainfuck/tree/master/BrainFuckedBotsForBattling) on github, along with the full logs from the battles.
The leaderboard will be posted here once it is generated.

Feel free to clone the repository and try your bot against the others on your own. Use `python Arena.py yourbot.bf otherbot.bf` to run a match. You can modify the conditions with the command-line flags `-m` and `-t`. If your terminal does not support ANSI escape sequences, use the `--no-color` flag to disable colored output.

---

Example bots
------------

FastClearBot.bf

	(>)*9		Since the tape length is at least 10, the first 9 cells can be easily ignored
	([			Find a non-zero cell
	+++			Increment at first, since it could be a decoy
	[-]			Set the cell to zero
	]>			Move on to the next cell
	)*21		Repeat this 21 times

DecoyBot.bf

	>(+)*10		Set up a large defense in front of your flag
	>(-)*10		Set up another one with different polarity
	(>+>-)*3	Create some small decoys
	(>[-]		Move on and set the next cell to zero
	.			Wait one round, in case it is the enemy's flag
	)*21		Repeat this 21 times

The DecoyBot will win every match with a tape length greater than ten, since the FastClearBot can avoid the small decoys, but not the larger ones. The only situation in which the FastClearBot can win against DecoyBot, is when it is fast enough to reach the enemy's flag before his opponent has built up large decoys.


text:
/*
 * Validation JS
 *
 * - Initializes validation on selector (forms)
 * - Adds/removes rules on elements contained in var wptoolsetValidationData
 * - Checks if elements are hidden by conditionals
 *
 * @see class WPToolset_Validation
 *
 * $HeadURL: https://www.onthegosystems.com/misc_svn/common/tags/Views-1.6.4-CRED-1.3.2-Types-1.6.4-Acces-1.2.3/toolset-forms/js/validation.js $
 * $LastChangedDate: 2014-09-12 09:57:24 +0000 (Fri, 12 Sep 2014) $
 * $LastChangedRevision: 27017 $
 * $LastChangedBy: francesco $
 *
 */
//var wptValidationData = {};

var wptValidationForms = [];
var wptValidation = (function($) {
    function init() {
        /**
         * add extension to validator method
         */
        $.validator.addMethod("extension", function(value, element, param) {
            param = typeof param === "string" ? param.replace(/,/g, "|") : param;
            return this.optional(element) || value.match(new RegExp(".(" + param + ")$", "i"));
        });

        /**
         * add extension to validator method require
         */
        $.validator.addMethod("required", function(value, element, param) {
                // check if dependency is met
                if ( !this.depend(param, element) )
                        return "dependency-mismatch";
                switch( element.nodeName.toLowerCase() ) {
                case 'select':
                        var val = $(element).val();
                        //Fix https://icanlocalize.basecamphq.com/projects/7393061-toolset/todo_items/189231348/comments
                        // we have data-types-value that in select contains the exactly value
                        $(element).find('option').each(function(index, option){
                            if ($(option).val()==value) {
	                        //if $(option).data('typesValue') is undefined i am in backend side
                                val = ($(option).data('typesValue')!=undefined)?$(option).data('typesValue'):val;
                                return;
                            }
                        });
                        //#########################################################################
                        return val && $.trim(val).length > 0;
                case 'input':
                        if ( this.checkable(element) )
                                return this.getLength(value, element) > 0;
                default:
                        return $.trim(value).length > 0;
                }
        });

        /**
         * Add validation method for datepicker adodb_xxx format for date fields
         */
        $.validator.addMethod(
            "dateADODB_STAMP",
            function(a,b){
                return this.optional(b)||/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(a) &&  -12219292800 < a && a < 32535215940
            },
            "Please enter a valid date"
        );
        _.each(wptValidationForms, function(formID) {
            _initValidation(formID);
            applyRules(formID);
        });
    }

    function _initValidation(formID) {
        var $form = $(formID);
        $form.validate({
            // :hidden is kept because it's default value.
            // All accepted by jQuery.not() can be added.
            ignore: 'input[type="hidden"]:not(.js-wpt-date-auxiliar),:not(.js-wpt-validate)',
            errorPlacement: function(error, element) {
                error.insertBefore(element);
            },
            highlight: function(element, errorClass, validClass) {
                // Expand container
                $(element).parents('.collapsible').slideDown();
                if (formID == '#post') {
                    var box = $(element).parents('.postbox');
                    if (box.hasClass('closed')) {
                        $('.handlediv', box).trigger('click');
                    }
                }
                // $.validator.defaults.highlight(element, errorClass, validClass); // Do not add class to element
            },
            unhighlight: function(element, errorClass, validClass) {
                $("input#publish, input#save-post").removeClass("button-primary-disabled").removeClass("button-disabled");
                // $.validator.defaults.unhighlight(element, errorClass, validClass);
            },
            invalidHandler: function(form, validator) {
                if (formID == '#post') {
                    $('#publishing-action .spinner').css('visibility', 'hidden');
                    $('#publish').bind('click', function() {
                        $('#publishing-action .spinner').css('visibility', 'visible');
                    });
                    $("input#publish").addClass("button-primary-disabled");
                    $("input#save-post").addClass("button-disabled");
                    $("#save-action .ajax-loading").css("visibility", "hidden");
                    $("#publishing-action #ajax-loading").css("visibility", "hidden");
                }
            },
//            submitHandler: function(form) {
//                // Remove failed conditionals
//                $('.js-wpt-remove-on-submit', $(form)).remove();
//                form.submit();
//            },
            errorClass: 'wpt-form-error'
        });
        $form.on('submit', function() {
            if ( $form.valid() ) {
                $('.js-wpt-remove-on-submit', $(this)).remove();
            }
        });
    }

    function isIgnored($el) {
        var ignore = $el.parents('.js-wpt-field').hasClass('js-wpt-validation-ignore') ||  // Individual fields
                        $el.parents('.js-wpt-remove-on-submit').hasClass('js-wpt-validation-ignore'); // Types group of fields
        return ignore;
    }

    function applyRules(container) {
        $('[data-wpt-validate]', $(container)).each(function() {
            _applyRules($(this).data('wpt-validate'), this, container);
        });
    }

    function _applyRules(rules, selector, container) {
        var element = $(selector, $(container));
        if (element.length > 0) {
            if (isIgnored(element)) {
                element.rules('remove');
                element.removeClass('js-wpt-validate');
            } else if (!element.hasClass('js-wpt-validate')) {
                _.each(rules, function(value, rule) {
                    var _rule = {messages: {}};
                    _rule[rule] = value.args;
                    if (value.message !== 'undefined') {
                        _rule.messages[rule] = value.message;
                    }
                    element.rules('add', _rule);
                    element.addClass('js-wpt-validate');
                });
            }
        }
    }

    return {
        init: init,
        applyRules: applyRules,
        isIgnored: isIgnored,
    };

})(jQuery);

jQuery(document).ready(function(){
    wptCallbacks.reset.add(function() {
        wptValidation.init();
    });
    wptCallbacks.addRepetitive.add(function(container) {
        wptValidation.applyRules(container);
    });
    wptCallbacks.removeRepetitive.add(function(container) {
        wptValidation.applyRules(container);
    });
    wptCallbacks.conditionalCheck.add(function(container) {
        wptValidation.applyRules(container);
    });
});