text:
//-------1---------2---------3---------4---------5---------6---------7---------8
package org.myrobotlab.gp;

import java.awt.Rectangle;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Observable;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.slf4j.Logger;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;

import org.myrobotlab.framework.Service;

public class GP extends Observable implements Runnable {

	public final static Logger log = LoggerFactory.getLogger(GP.class.getCanonicalName());

	public Number populationSize;
	public Number maxDepthForNewIndividuals;
	public Number maxDepthForIndividualsAfterCrossover;
	public Number maxDepthForNewSubtreesInMutants;
	public Number crossoverFraction;
	public Number fitnessProportionateReproFraction;
	public Number mutationFraction;
	public Choices methodOfGeneration;
	public Choices methodOfSelection;
	public Points fitnessCases;
	public SetData terminalSet;
	public SetData functionSet;

	public Service myService = null;

	Thread thread = null;
	Individual[] population;
	int currentGeneration = 0;
	Individual bestOfRunIndividual = null;
	int generationOfBestOfRunIndividual = 0;
	static final int MAX_GENERATIONS = 1000;

	/**
	 * Each GP has its own random number generator.
	 */
	static final int SEED = 12345;
	static Random random = new Random(SEED);

	public GP(Service s) {
		//
		// All the parameters that the user can change are wrapped up with
		// a user interface component. Let's construct these components here.
		// This will preset their text labels, default values, initial
		// selections and value ranges.
		// To use these components, add them to a dialog.
		//
		myService = s;

		populationSize = new Number("Population size", 100, 10, 1000);
		maxDepthForNewIndividuals = new Number("Max. depth for new individuals", 6, 1, 10);
		maxDepthForIndividualsAfterCrossover = new Number("Max. depth for individuals after crossover", 20, 5, 20);
		maxDepthForNewSubtreesInMutants = new Number("Max. depth for new subtrees in mutants", 4, 1, 7);
		crossoverFraction = new Number("Crossover fraction", 80, 1, 100);
		fitnessProportionateReproFraction = new Number("Reproduction fraction", 0, 0, 100);
		mutationFraction = new Number("Mutation fraction", 20, 0, 100);
		fitnessCases = new Points("Fitness cases", makeDefaultFitnessCases());

		ProgramChoice[] terminalChoices = { new ProgramChoice("Random constant", new RandomConstant().getClass()), new ProgramChoice("Variable x", new Variable().getClass()) };
		int[] terminalSelections = { 0, 1 };
		terminalSet = new SetData("Terminal set", terminalChoices, terminalSelections);

		ProgramChoice[] functionChoices = { new ProgramChoice("+ (add)", new Addition(myService).getClass()), new ProgramChoice("- (sub)", new Subtraction(myService).getClass()),
				new ProgramChoice("* (mul)", new Multiplication(myService).getClass()), new ProgramChoice("/ (div)", new Division(myService).getClass()),
				new ProgramChoice("sin", new Sine(myService).getClass()), new ProgramChoice("cos", new Cosine(myService).getClass()),
				new ProgramChoice("exp", new Exp(myService).getClass()), new ProgramChoice("sleep", new Sleep(myService).getClass()),
				new ProgramChoice("moveHip", new MoveHip(myService).getClass()), new ProgramChoice("moveKnee", new MoveKnee(myService).getClass()) };
		int[] functionSelections = { 0, 1, 2, 3, 8, 9 };
		// int[] functionSelections = {0, 1, 3, 7, 8};
		functionSet = new SetData("Function set", functionChoices, functionSelections);

		MethodOfGeneration[] generationChoices = { new MethodOfGeneration("Grow", MethodOfGeneration.GROW), new MethodOfGeneration("Full", MethodOfGeneration.FULL),
				new MethodOfGeneration("Ramped half and half", MethodOfGeneration.RAMPED_HALF_AND_HALF) };
		methodOfGeneration = new Choices("Method of generation", generationChoices, 2);

		MethodOfSelection[] selectionChoices = { new MethodOfSelection("Fitness proportionate", MethodOfSelection.FITNESS_PROPORTIONATE),
				new MethodOfSelection("Tournament", MethodOfSelection.TOURNAMENT) };
		methodOfSelection = new Choices("Method of selection", selectionChoices, 1);
	}

	/**
	 * Should be called after any of the settings have changed, will addListener
	 * any observers of the changes.
	 */
	public void settingsChanged() {
		notifyObservers(new GPMessageFitnessCasesSet(fitnessCases.get()));
	}

	/**
	 * After the construction of a GP object, you should call the init() method;
	 * this will addListener any observers that the initial settings are now
	 * established. Don't do it in the constructor, because Observer-Observable
	 * relationships are yet not established during construction.
	 */
	public void init() {
		settingsChanged();
	}

	/**
	 * Starts the GP algorithm running in its own thread. The priority is set
	 * lower than normal, so that a user interface thread with normal priority
	 * can surely preempt the GP thread.
	 */
	public synchronized void start() {
		thread = new Thread(this);
		thread.setPriority(Thread.NORM_PRIORITY - 1);
		thread.start();
		state = STARTED;
		log.info("STARTED");
		notifyObservers(new GPMessageStateChanged(state, ""));
	}

	/**
	 * Suspends the GP thread.
	 */
	public synchronized void suspend() {
		if (thread != null && thread.isAlive()) {
			state = SUSPENDED;
			log.info("SUSPENDED");
			notifyObservers(new GPMessageStateChanged(state, ""));
			thread.suspend();
		}
	}

	/**
	 * Resumes a suspended GP thread.
	 */
	public synchronized void resume() {
		if (thread != null && thread.isAlive()) {
			thread.resume();
			state = RESUMED;
			log.info("RESUMED");
			notifyObservers(new GPMessageStateChanged(state, ""));
		}
	}

	/**
	 * Stops a running GP thread and kills it.
	 */
	public synchronized void stop() {
		// Note that the GP thread may call stop() to kill itself.
		// Therefore, any code following thread.stop() below would
		// never be executed.
		if (thread != null && thread.isAlive()) {
			state = STOPPED;
			log.info("STOPPED");
			notifyObservers(new GPMessageStateChanged(state, ""));
			thread.stop();
		}
	}

	/**
	 * Aborts a running GP thread and notifies any observers with a diagnostic
	 * message. This method is tyically called from an exception handler if the
	 * GP algorithm crashes unexpectedly.
	 */
	public synchronized void crash() {
		log.info("CRASH " + currentGeneration);
		if (thread != null && thread.isAlive()) {
			state = STOPPED;
			notifyObservers(new GPMessageStateChanged(state, "The genetic algorithm crashed\n" + "in generation " + currentGeneration + ".\n" + "Sorry."));
			thread.stop();
		}
	}

	public static final int IDLE = 0;
	public static final int STARTED = 1;
	public static final int SUSPENDED = 2;
	public static final int RESUMED = 3;
	public static final int STOPPED = 4;

	private int state = IDLE;
	private int oldState = IDLE;

	/**
	 * @return the execution state of the GP thread
	 */
	public int getState() {
		return state;
	}

	/**
	 * freeze() and thaw() are useful if the GP is running in an applet. A
	 * well-behaved applet should stop running when the user moves to another
	 * page and it should start again when he returns to the (still loaded)
	 * applet. freeze() and thaw() may thus be called from the applet's start()
	 * and stop() methods to pause the GP while its applet is not visible.
	 */
	public synchronized void freeze() {
		log.info("FREEZE " + currentGeneration);
		oldState = getState();
		if (thread != null && thread.isAlive() && (oldState == STARTED || oldState == RESUMED)) { // i.e.
																									// running
			thread.suspend();
		}
	}

	/**
	 * freeze() and thaw() are useful if the GP is running in an applet. A
	 * well-behaved applet should stop running when the user moves to another
	 * page and it should start again when he returns to the (still loaded)
	 * applet. freeze() and thaw() may thus be called from the applet's start()
	 * and stop() methods to pause the GP while its applet is not visible.
	 */
	public synchronized void thaw() {
		log.info("THAW " + currentGeneration);
		if (thread != null && thread.isAlive() && (oldState == STARTED || oldState == RESUMED)) {
			thread.resume();
		}
	}

	/**
	 * @return a terminal, randomly chosen from the terminal set
	 */
	Terminal chooseFromTerminalSet() {
		Terminal choice;
		log.info("chooseFromTerminalSet " + currentGeneration);
		try {
			int index = random.nextInt(terminalSet.countSelections());
			Class cls = ((ProgramChoice) terminalSet.getSelectedItem(index)).value();
			choice = (Terminal) (cls.newInstance());
		} catch (Exception e) {
			choice = null;
		}
		return choice;
	}

	/**
	 * Creates arguments for a function
	 */
	void createArgumentsForFunction(Function function, int allowableDepth, boolean fullP) {
		log.info("createArgumentsForFunction " + currentGeneration);

		for (int i = 0; i < function.arg.length; i++) {
			function.arg[i] = createIndividualProgram(allowableDepth, false, fullP);
		}
	}

	/**
	 * Creates a program recursively using functions and terminals from the
	 * respective sets.
	 *
	 * @param allowableDepth
	 *            the remaining depth of the tree we can create, when we hit
	 *            zero we will only select terminals
	 * @param topNodeP
	 *            is true only when we are being called as the top node in the
	 *            tree. This allows us to make sure that we always put a
	 *            function at the top of the tree.
	 * @param fullP
	 *            indicates whether this individual is to be maximally bushy or
	 *            not
	 */
	Program createIndividualProgram(int allowableDepth, boolean topNodeP, boolean fullP) {
		Program p;
		int choice;
		Function function;

		// log.warn("createIndividualProgram " + currentGeneration);

		if (allowableDepth <= 0) {
			// We've reached maxdepth, so just pack a terminal.
			p = chooseFromTerminalSet();
		} else {
			if (fullP || topNodeP) {
				// We are the top node or are a full tree, so pick only a
				// function.
				choice = random.nextInt(functionSet.countSelections());
				try {
					Class cls = ((ProgramChoice) functionSet.getSelectedItem(choice)).value();
					Constructor mc = cls.getConstructor(new Class[] { Service.class });
					function = (Function) mc.newInstance(myService);

				} catch (Exception e) {
					Logging.logException(e);
					function = null;
				}
				createArgumentsForFunction(function, allowableDepth - 1, fullP);
				p = function;
			} else {
				// Choose one from the bag of functions and terminals.
				choice = random.nextInt(terminalSet.countSelections() + functionSet.countSelections());
				if (choice < functionSet.countSelections()) {
					// We chose a function, so pick it out and go on creating
					// the tree down from here.
					try {
						// Class cls =
						// ((ProgramChoice)functionSet.getSelectedItem(choice)).value();
						// function = (Function)cls.newInstance();

						Class cls = ((ProgramChoice) functionSet.getSelectedItem(choice)).value();
						Constructor mc = cls.getConstructor(new Class[] { Service.class });
						function = (Function) mc.newInstance(myService);

					} catch (Exception e) {
						function = null;
					}
					createArgumentsForFunction(function, allowableDepth - 1, fullP);
					p = function;
				} else {
					// We chose an atom, so pick it out.
					p = chooseFromTerminalSet();
				}
			}
		}
		return p;
	}

	/**
	 * Creates the initial population. This is an array of individuals. Its size
	 * is sizeOfPopulation. The program slot of each individual is initialized
	 * to a suitable random program.
	 */
	void createPopulation() {

		log.warn("createPopulation " + currentGeneration);

		int allowableDepth;
		boolean fullP;
		Hashtable generation0UniquifierTable = new Hashtable();

		population = new Individual[populationSize.intValue()];
		int minimumDepthOfTrees = 1;
		boolean fullCycleP = false;
		int maxDepthForNewIndivs = maxDepthForNewIndividuals.intValue();
		int attemptsAtThisIndividual = 0;
		int individualIndex = 0;
		while (individualIndex < population.length) {
			switch (((MethodOfGeneration) methodOfGeneration.getSelection()).getValue()) {
			case MethodOfGeneration.FULL:
				allowableDepth = maxDepthForNewIndivs;
				fullP = true;
				break;
			case MethodOfGeneration.GROW:
				allowableDepth = maxDepthForNewIndivs;
				fullP = false;
				break;
			case MethodOfGeneration.RAMPED_HALF_AND_HALF:
				// With each new individual, the allowed depth is ramped up
				// until it reaches the maximum. Then it is reset to the minimum
				// depth again.
				// At this time, we toggle between full trees and grown trees,
				// so that half of the trees are full and the other half grown.
				// Note that the switch occurs only at the first attempt to
				// create
				// a new tree. This is to avoid unecessary toggling when several
				// attempts are necessary for the same individual.
				allowableDepth = minimumDepthOfTrees + (individualIndex % (maxDepthForNewIndivs - minimumDepthOfTrees + 1));
				if (attemptsAtThisIndividual == 0 && individualIndex % (maxDepthForNewIndivs - minimumDepthOfTrees + 1) == 0) {
					fullCycleP = !fullCycleP;
				}
				fullP = fullCycleP;
				break;
			default:
				allowableDepth = maxDepthForNewIndivs;
				fullP = false;
				break;
			}

			Program newProgram = createIndividualProgram(allowableDepth, true, fullP);

			// Check if we have already created this program.
			// If not then store it and move on.
			// If we have then try again.
			// The easiest way to compare two programs is to
			// look at their printed representation:
			//
			String hashKey = newProgram.toString(0);
			if (!generation0UniquifierTable.containsKey(hashKey)) {
				population[individualIndex] = new Individual(newProgram);
				individualIndex++;
				generation0UniquifierTable.put(hashKey, newProgram);
				attemptsAtThisIndividual = 0;
			} else {
				attemptsAtThisIndividual++;
				if (attemptsAtThisIndividual > 20) {
					// This depth has probably filled up, so bump the
					// depth counter and keep the max depth in line with
					// the new minimum:
					//
					minimumDepthOfTrees++;
					maxDepthForNewIndivs = Math.max(maxDepthForNewIndivs, minimumDepthOfTrees);
					attemptsAtThisIndividual = 0;
				}
			}
		}
	}

	static final Condition isProgram = new IsProgram();
	static final Condition isFunction = new IsFunction();

	/**
	 * Produces two new individuals by crossing two parents. First, a crossover
	 * point is selected randomly in each parent. Experience shows that it is
	 * more useful to select inner nodes (functions, not terminals) as crossover
	 * points. The ratio of cuts at inner points vs. cuts at terminals is fixed
	 * in this function. Then the two parents are cut at their crossover points,
	 * giving two tree fragments and two cut-off subtrees. The two subtrees are
	 * swapped and spliced with the fragments again. We have to make sure that
	 * the newly formed trees do not exceed a certain depth. If they do, one of
	 * the parents is used as offspring.
	 */
	Program[] crossover(Program male, Program female) {
		double CrossoverAtFunctionFraction = 0.9;
		boolean crossoverAtFunction;
		// Make copies of the parents first, because they will be destructively
		// modified:
		Program[] offspring = new Program[2];
		offspring[0] = (Program) male.clone();
		offspring[1] = (Program) female.clone();

		int malePoint, femalePoint;
		TreeHook maleHook, femaleHook;
		crossoverAtFunction = (random.nextDouble() < CrossoverAtFunctionFraction);
		if (crossoverAtFunction) {
			malePoint = random.nextInt(male.countNodes(isFunction));
			maleHook = getSubtree(offspring[0], malePoint, isFunction);
		} else {
			malePoint = random.nextInt(male.countNodes());
			maleHook = getSubtree(offspring[0], malePoint, isProgram);
		}
		crossoverAtFunction = (random.nextDouble() < CrossoverAtFunctionFraction);
		if (crossoverAtFunction) {
			femalePoint = random.nextInt(female.countNodes(isFunction));
			femaleHook = getSubtree(offspring[1], femalePoint, isFunction);
		} else {
			femalePoint = random.nextInt(female.countNodes());
			femaleHook = getSubtree(offspring[1], femalePoint, isProgram);
		}

		// Modify the new individuals by smashing in the (copied) subtree from
		// the old individual.
		if (maleHook.parent == null) {
			offspring[0] = femaleHook.subtree;
		} else {
			maleHook.parent.arg[maleHook.childIndex] = femaleHook.subtree;
		}
		if (femaleHook.parent == null) {
			offspring[1] = maleHook.subtree;
		} else {
			femaleHook.parent.arg[femaleHook.childIndex] = maleHook.subtree;
		}

		// Make sure that the new individuals aren't too big.
		validateCrossover(male, female, offspring);

		// log.warn("returning offspring " + currentGeneration);

		return offspring;
	}

	/**
	 * @return the depth of the deepest branch of the tree
	 */
	int maxDepthOfTree(Program tree) {
		int maxDepth = 0;
		if (tree instanceof Function) {
			for (int a = 0; a < ((Function) tree).arg.length; a++) {
				Program s = ((Function) tree).arg[a];
				int depth = maxDepthOfTree(s);
				maxDepth = Math.max(maxDepth, depth);
			}
			return (1 + maxDepth);
		} else {
			return 0;
		}
	}

	/**
	 * Given the parents and two offsprings from a crossover operation check to
	 * see whether we have exceeded the maximum allowed depth. If a new
	 * individual has exceeded the maximum depth then one of the parents is
	 * used.
	 */
	void validateCrossover(Program male, Program female, Program[] offspring) {
		int depth;
		for (int i = 0; i < offspring.length; i++) {
			if (offspring[i] == null) {
				depth = 0;
			} else {
				depth = maxDepthOfTree(offspring[i]);
			}
			if (depth < 1 || depth > maxDepthForIndividualsAfterCrossover.intValue()) {
				int whichParent = random.nextInt(2);
				if (whichParent == 0) {
					offspring[i] = (Program) male.clone();
				} else {
					offspring[i] = (Program) female.clone();
				}
			}
		}
	}

	/**
	 * Mutates the argument program by picking a random point in the tree and
	 * substituting in a brand new subtree created in the same way that we
	 * create the initial random population.
	 *
	 * @return a mutated copy of the original program
	 */
	Program mutate(Program program) {
		// log.warn("mutate " + currentGeneration);

		// Pick the mutation point.
		int mutationPoint = random.nextInt(program.countNodes());
		// Create a brand new subtree.
		Program newSubtree = createIndividualProgram(maxDepthForNewSubtreesInMutants.intValue(), true, false);
		Program newProgram = (Program) program.clone();
		// Smash in the new subtree.
		TreeHook hook = getSubtree(program, mutationPoint, isProgram);
		if (hook.parent == null) {
			newProgram = hook.subtree;
		} else {
			hook.parent.arg[hook.childIndex] = newSubtree;
		}
		return newProgram;
	}

	/**
	 * Controls the actual breeding of the new population. Loops through the
	 * population executing each operation (e.g., crossover,
	 * fitness-proportionate reproduction, mutation) until it has reached the
	 * specified fraction. The new programs that are created are stashed in
	 * newPrograms until we have exhausted the population, then we copy the new
	 * individuals into the old ones.
	 */
	void breedNewPopulation() {
		log.warn("breedNewPopulation " + currentGeneration);

		Program[] newPrograms;
		double fraction;
		int index;
		Individual individual1, individual2;
		double sumOfFractions = this.crossoverFraction.doubleValue() + this.fitnessProportionateReproFraction.doubleValue() + this.mutationFraction.doubleValue();
		double crossoverFraction = this.crossoverFraction.doubleValue() / sumOfFractions;
		double reproductionFraction = this.fitnessProportionateReproFraction.doubleValue() / sumOfFractions;
		// double mutationFraction = this.mutationFraction.get() /
		// sumOfFractions;

		newPrograms = new Program[population.length];
		fraction = 0.0;
		index = 0;

		// A hint from Jorg Frohlich: keep the best individual all the time:
		newPrograms[index] = (Program) bestOfRunIndividual.program.clone();
		index++;

		while (index < population.length) {
			fraction = (double) index / (double) population.length;
			individual1 = findIndividual();
			if (fraction < crossoverFraction) {
				individual2 = findIndividual();
				Program[] offspring = crossover(individual1.program, individual2.program);
				newPrograms[index] = offspring[0];
				index++;
				if (index < population.length) {
					newPrograms[index] = offspring[1];
					index = index++;
				}
			} else {
				if (fraction < reproductionFraction + crossoverFraction) {
					newPrograms[index] = (Program) individual1.program.clone();
					index++;
				} else {
					newPrograms[index] = mutate(individual1.program);
					index++;
				}
			}
		}
		for (index = 0; index < population.length; index++) {
			population[index].program = newPrograms[index];
		}
	}

	/**
	 * Clean out the statistics in each individual in the population.
	 */
	void zeroizeFitnessMeasuresOfPopulation() {
		log.info("zeroizeFitnessMeasuresOfPopulation " + currentGeneration);

		for (int i = 0; i < population.length; i++) {
			population[i].standardizedFitness = 0.0;
			population[i].adjustedFitness = 0.0;
			population[i].normalizedFitness = 0.0;
			population[i].hits = 0;
		}
	}

	/**
	 * Loops over the individuals in the population evaluating and recording the
	 * fitness and hits.
	 */
	void evaluateFitnessOfPopulation() {
		log.warn("evaluateFitnessOfPopulation " + currentGeneration + " population length " + population.length);

		for (int i = 0; i < population.length; i++) {
			fitnessFunction(population[i], i); // TODO - Over-rideable fitness
												// function
			// log.warn(population[i].program);
		}

	}

	/**
	 * Computes the normalized and adjusted fitness of each individual in the
	 * population.
	 */
	void normalizeFitnessOfPopulation() {
		log.warn("normalizeFitnessOfPopulation " + currentGeneration);

		double sumOfAdjustedFitnesses = 0.0;
		for (int i = 0; i < population.length; i++) {
			// Set the adjusted fitness.
			population[i].adjustedFitness = 1.0 / (population[i].standardizedFitness + 1.0);
			// Add up the adjusted fitnesses so that we can normalize them.
			sumOfAdjustedFitnesses = sumOfAdjustedFitnesses + population[i].adjustedFitness;
			log.warn(i + " " + population[i].adjustedFitness);
		}
		log.warn("normalized ----");
		// Loop through population normalizing the adjusted fitness.
		for (int i = 0; i < population.length; i++) {
			population[i].normalizedFitness = population[i].adjustedFitness / sumOfAdjustedFitnesses;
			log.warn(i + " " + population[i].normalizedFitness);
		}
	}

	/**
	 * Uses a quicksort to sort the population destructively into descending
	 * order of normalized fitness.
	 */
	private void sort(int low, int high) {
		// log.info("sort " + currentGeneration);

		int index1, index2;
		double pivot;
		Individual temp;

		index1 = low;
		index2 = high;
		pivot = population[(low + high) / 2].normalizedFitness;
		do {
			while (population[index1].normalizedFitness > pivot) {
				index1++;
			}
			while (population[index2].normalizedFitness < pivot) {
				index2--;
			}
			if (index1 <= index2) {
				temp = population[index2];
				population[index2] = population[index1];
				population[index1] = temp;
				index1++;
				index2--;
			}
		} while (index1 <= index2);
		if (low < index2) {
			sort(low, index2);
		}
		if (index1 < high) {
			sort(index1, high);
		}
	}

	/**
	 * Sorts the population according to normalized fitness. The population
	 * array is destructively modified.
	 */
	void sortPopulationByFitness() {
		log.info("sortPopulationByFitness " + currentGeneration);

		sort(0, population.length - 1);

		for (int i = 0; i < population.length; i++) {
			log.warn(i + " " + population[i].normalizedFitness);
		}

	}

	/**
	 * This function has to evaluate the fitness for a specific individual. As a
	 * side-effect, it notfies any observers of the GP that an individual has
	 * been evaluated and supplies the test cases.
	 */
	void fitnessFunction(Individual ind, int individualNr) {
		// log.warn("fitnessFunction " + currentGeneration + " individual " +
		// ind);

		double rawFitness = 0.0;
		ind.hits = 0;
		RealPoint[] testCases = new RealPoint[fitnessCases.get().length];
		RealPoint valueFromProgram = null;

		log.warn("ind " + ind.program.toString(0));
		initializeState();
		for (int index = 0; index < fitnessCases.get().length; index++) { // fitness
																			// cases
																			// represents
																			// the
																			// 20
																			// point
																			// originally
																			// wanted
			double x = fitnessCases.get()[index].x;
			double y = fitnessCases.get()[index].y; // get "fitness point" from
													// gate input
			// double valueFromProgram = ind.program.eval(x); // TODO - does
			// eval(x) BUT gets the valueFromProgram from a call back with
			// coordinates
			double t = ind.program.eval(x);
			try {
				Thread.sleep(20);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			Rectangle r = waitValidForData();
			// Rectangle r = new Rectangle(30,30,10,10);
			valueFromProgram = new RealPoint(r.x + r.width / 2, r.y + r.height / 2);
			// log.error(valueFromProgram);
			double deltaX = valueFromProgram.x - x;
			double deltaY = valueFromProgram.y - y;
			double difference = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
			rawFitness = rawFitness + difference;
			log.error("input " + x + " " + valueFromProgram.x + "," + valueFromProgram.y + " d " + (int) difference);
			// if (difference < 0.01) {
			if (difference < 10) {
				ind.hits++;
			}
			// testCases[index] = new RealPoint(x, valueFromProgram);
			testCases[index] = valueFromProgram;
		}
		// log.warn("ind " + ind.program.toString(0));
		try {
			outfile.write(individualNr + " " + (int) valueFromProgram.x + "," + (int) valueFromProgram.y + " " + rawFitness + "\n");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		myService.invoke("publishInd", new GPMessageEvaluatingIndividual(currentGeneration, individualNr, testCases, ind.standardizedFitness, rawFitness));

		ind.standardizedFitness = rawFitness;
		log.warn("generation " + currentGeneration + " individualNr " + individualNr);

		// notifyObservers(new GPMessageEvaluatingIndividual(
		// currentGeneration, individualNr, testCases));
	}

	boolean interrupted = false;
	BlockingQueue<Rectangle> footData = new LinkedBlockingQueue<Rectangle>();

	public Rectangle waitValidForData() {
		Rectangle r1 = null;
		Rectangle r0 = null;

		try {
			footData.clear(); // clear the data for next sample
			// get two sample points
			// if they are the same - we have stabilized

			while (!interrupted) {
				r0 = footData.take();
				r1 = footData.take();

				if (r1.x == r0.x && r1.y == r0.y && r1.width == r0.width && r1.height == r0.height) {
					return r1;
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		return null;
	}

	public void evalCallBack(Rectangle r) {
		try {
			footData.put(r);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	void initializeState() {
		myService.send("knee", "moveTo", 62);
		myService.send("hip", "moveTo", 82);
		try {
			Thread.sleep(20);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @returns <code>true</code> if the GP algorithm should terminate
	 */
	boolean terminationPredicate() {
		log.info("terminationPredicate " + currentGeneration);
		return currentGeneration >= MAX_GENERATIONS;
	}

	FileWriter outfile = null;

	/**
	 * Breeds a new population from an old one, thus stepping from one
	 * generation to the next.
	 */
	void evolve() {
		log.warn("EVOLVE ! " + currentGeneration);

		try {
			outfile = new FileWriter("data.txt");
			Individual bestOfGeneration;
			if (currentGeneration > 0) {
				breedNewPopulation();
			}
			zeroizeFitnessMeasuresOfPopulation();
			evaluateFitnessOfPopulation();
			outfile.close();
			// outfile = new FileWriter("data.1.txt");
			// evaluateFitnessOfPopulation();
			// outfile.close();
			normalizeFitnessOfPopulation();
			// Sort the population so that the roulette wheel selection is easy:
			sortPopulationByFitness();

			// Keep track of best-of-run individual:
			bestOfGeneration = population[0];
			if (bestOfRunIndividual == null || // IF THIS IS THE NEW BEST - IT
												// WILL EVAL IT HERE!
					bestOfRunIndividual.standardizedFitness > bestOfGeneration.standardizedFitness) {
				bestOfRunIndividual = bestOfGeneration.copy();
				generationOfBestOfRunIndividual = currentGeneration;
				RealPoint[] testCases = new RealPoint[fitnessCases.get().length];
				initializeState();
				for (int i = 0; i < fitnessCases.get().length; i++) {
					double x = fitnessCases.get()[i].x;
					// double y = bestOfRunIndividual.program.eval(x); // TODO -
					// eval is the evaluation - this needs feedback from other
					// systems
					double t = bestOfRunIndividual.program.eval(x);
					try {
						Thread.sleep(20);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					Rectangle r = waitValidForData();
					// Rectangle r = new Rectangle(30,30,10,10);
					RealPoint valueFromProgram = new RealPoint(r.x + r.width / 2, r.y + r.height / 2);

					testCases[i] = valueFromProgram;
				}

				log.warn(bestOfRunIndividual.program.toString(0));

				// TODO deprecate all addListener Observers - change to publish
				// message
				GPMessageBestFound gpm = new GPMessageBestFound(currentGeneration, bestOfRunIndividual.program.toString(0), testCases, bestOfRunIndividual.adjustedFitness,
						bestOfRunIndividual.standardizedFitness);
				myService.invoke("publish", gpm);
				/*
				 * notifyObservers(new GPMessageBestFound(currentGeneration,
				 * bestOfRunIndividual.program.toString(0), testCases,
				 * bestOfRunIndividual.adjustedFitness));
				 */
			}

			double[] fitness = new double[population.length];
			for (int i = 0; i < fitness.length; i++) {
				fitness[i] = population[i].adjustedFitness;
			}

			log.error("fitness " + fitness);
			notifyObservers(new GPMessageEvaluatingPopulation(currentGeneration, fitness));

			currentGeneration++;
			// log.info()
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * @return an individual in the specified population whose normalized
	 *         fitness is greater than the specified value.
	 */
	Individual findFitnessProportionateIndividual(double afterThisFitness) {
		// All we need to do is count along the population from the
		// beginning adding up the fitness until we get past the
		// specified point:
		log.info("findFitnessProportionateIndividual " + currentGeneration);

		int indexOfSelectedIndividual;
		double sumOfFitness = 0.0;
		int index = 0;
		while (index < population.length && sumOfFitness < afterThisFitness) {
			// Sum up the fitness values.
			sumOfFitness = sumOfFitness + population[index].normalizedFitness;
			index++;
		}
		if (index >= population.length) {
			indexOfSelectedIndividual = population.length - 1;
		} else {
			indexOfSelectedIndividual = index - 1;
		}
		return population[indexOfSelectedIndividual];
	}

	/**
	 * @return picks some individuals from the population at random and returns
	 *         the best one.
	 */
	Individual findIndividualUsingTournamentSelection() {

		log.info("findIndividualUsingTournamentSelection " + currentGeneration);

		int TournamentSize = Math.min(population.length, 7);

		Hashtable table = new Hashtable();
		while (table.size() < TournamentSize) {
			int key = random.nextInt(population.length);
			table.put(new Integer(key), population[key]);
		}
		Enumeration e = table.elements();
		Individual best = (Individual) e.nextElement();
		double bestFitness = best.standardizedFitness;
		while (e.hasMoreElements()) {
			Individual individual = (Individual) e.nextElement();
			double thisFitness = individual.standardizedFitness;
			if (thisFitness < bestFitness) {
				best = individual;
				bestFitness = thisFitness;
			}
		}
		return best;
	}

	/**
	 * @return finds an individual in the population according to the defined
	 *         selection method.
	 */
	Individual findIndividual() {
		log.info("findIndividual " + currentGeneration);

		Individual ind = null;
		switch (((MethodOfSelection) methodOfSelection.getSelection()).getValue()) {
		case MethodOfSelection.TOURNAMENT:
			ind = findIndividualUsingTournamentSelection();
			break;
		case MethodOfSelection.FITNESS_PROPORTIONATE:
			ind = findFitnessProportionateIndividual(random.nextDouble());
			break;
		}
		return ind;
	}

	/**
	 * @return some initial fitness cases, in text form, as pairs of x-y values
	 */
	String makeDefaultFitnessCases() {
		log.info("makeDefaultFitnessCases " + currentGeneration);

		// int NrOfFitnessCases = 20;
		// int NrOfFitnessCases = 4;
		String s = "// the data \n";
		s += "123 164\n";
		s += "249 164\n";
		s += "218 142\n";
		s += "130 142\n";
		/*
		 * for (int i = 0; i < NrOfFitnessCases; i++) { int x = i * 4; int y =
		 * x;
		 *
		 * double x = (double)i / (NrOfFitnessCases - 1); if (x == 0.0) { x =
		 * 1.0e-7; } double y = 1.0 + (-3.0)*x + (3.0)*x*x*x*x; // The stream
		 * tokenizer does not handle numbers with an exponent. // Therefore,
		 * clamp small numbers like 1.2e-6 to 0: if (Math.abs(x) < 1.0e-5) { x =
		 * 0; }; if (Math.abs(y) < 1.0e-5) { y = 0; };
		 *
		 * s = s + x + "  " + y + "\n"; }
		 */
		return s;
	}

	/**
	 * This is the body of the GP thread. It will be called by the thread's
	 * start() method.
	 */
	public void run() {
		log.info("run " + currentGeneration);

		// Prime the random generator with the same seed for each run,
		// so that we get reproducible results:
		random.setSeed(SEED);

		notifyObservers(new GPMessageFitnessCasesSet(fitnessCases.get()));

		generationOfBestOfRunIndividual = 0;
		bestOfRunIndividual = null;
		createPopulation();
		currentGeneration = 0;

		while (!terminationPredicate()) {
			try {
				evolve();
				thread.sleep(1);
				// thread.sleep() or thread.yield()?
				// I'm not sure about this. The JDK tutorial suggests yielding
				// so that other threads get a chance to run on host systems
				// without built-in thread support. In my experience with
				// Windows 95 and NT, user interface response got much worse
				// with yield()ing. I have to wait for feedback from users on
				// other platforms to get a clue.
			} catch (Exception e) {
				crash();
			}
		}
		// stop() will addListener any Observers that the GP has come to an end:
		stop();
	}

	/**
	 * @return the index'th subtree satisfying a specific condition, for example
	 *         the 3rd terminal of a tree. Subtrees are numbered from left to
	 *         right, depth first. The test function of the condition is applied
	 *         to all nodes of the tree. It must evaluate to true for the
	 *         desired kind of subtrees. getSubtree() returns not only a pointer
	 *         to the specified subtree, but also a pointer to the subtree's
	 *         parent and and index for its position in the list of the parent's
	 *         children. If the subtree is not found, the function returns null.
	 */
	TreeHook getSubtree(Program tree, int index, Condition cond) {
		log.info("getSubtree " + currentGeneration);

		// Hack: I need a global counter across the recursive calls to Walk().
		// In a Wirthian language, a VAR parameter would be fine.
		// In Java, I misuse a single-element array:
		int[] count = { index };
		return Walk(tree, count, cond, null, -1);
	}

	/**
	*
	*/
	private TreeHook Walk(Program tree, int[] count, Condition cond, Function parent, int childIndex) {
		log.info("Walk " + currentGeneration);

		if (cond.test(tree) && count[0] == 0) {
			return new TreeHook(tree, parent, childIndex);
		} else {
			TreeHook hook = null;
			if (tree instanceof Function) {
				Function func = (Function) tree;
				for (int a = 0; a < func.arg.length && count[0] > 0; a++) {
					if (cond.test(func.arg[a])) {
						count[0]--;
					}
					hook = Walk(func.arg[a], count, cond, func, a);
				}
			}
			return hook;
		}
	}

	/**
	 * Notifies any observers of changes in the GP algorithm's state. Observers
	 * must register with this Observable.
	 */
	public void notifyObservers(Object arg) {
		// Why should I call notifyObservers if nothing has changed?
		// I change the semantics of notifyObservers() here and always
		// set the 'changed' flag first:
		setChanged();
		super.notifyObservers(arg);
	}

}

/**
 * An extension of the built-in random generator to supply random integers as
 * well
 */
class Random extends java.util.Random {
	Random(int seed) {
		super(seed);
	}

	/**
	 * @return a random integer in the range 0 to n-1
	 */
	public int nextInt(int n) {
		return (int) (nextDouble() * n);
	}
}

/**
 * Just a data structure to hold the pointer to a subtree as well as to its
 * parent. This is needed to splice trees.
 */
class TreeHook {
	TreeHook(Program subtree, Function parent, int childIndex) {
		this.subtree = subtree;
		this.parent = parent;
		this.childIndex = childIndex;
	}

	Program subtree;
	Function parent;
	int childIndex;
}

/**
 * Just a helper class.
 */
abstract class Condition {
	abstract boolean test(Program p);
}

/**
*
*/
class IsProgram extends Condition {
	boolean test(Program p) {
		return (p instanceof Program);
	}
}

/**
*
*/
class IsFunction extends Condition {
	boolean test(Program p) {
		return (p instanceof Function);
	}
}

/**
 * This is the base class for all kinds of tree nodes.
 */
abstract class Program implements Cloneable {

	/**
	 * @param level
	 *            the current recursion level when descending a subtree
	 * @return the text representation of the subtree
	 */
	public abstract String toString(int level);

	/**
	 * @return a text description of the node. While toString() prints the value
	 *         of a subtree, getName() returns something like the class name of
	 *         this very node. getName() can be used to preset the choice lists
	 *         for the function and terminal sets.
	 */
	abstract String getName();

	/**
	 * @return a series of blanks proportional to the recursion level
	 */
	String indent(int level) {
		String s = new String();
		for (int i = 0; i < level; i++) {
			s = s + "  ";
		}
		return s;
	}

	/**
	 * @return the value of the subtree, evaluated at x, i.e. y = f(x)
	 */
	abstract double eval(double x);

	/**
	 * @return the number of nodes in this subtree
	 */
	abstract int countNodes();

	/**
	 * @return the number of nodes in this subtree satisfying a certain
	 *         condition
	 */
	abstract int countNodes(Condition cond);

	/**
	 * @return a deep copy of the subtree
	 */
	abstract protected Object clone();
}

/**
 * This is the base class for all kinds of terminal nodes.
 */
abstract class Terminal extends Program {

	int countNodes() {
		return 1;
	}

	int countNodes(Condition cond) {
		return (cond.test(this)) ? 1 : 0;
	}

}

/**
*
*/
class RandomConstant extends Terminal {
	// static final double MIN = -4.0;
	// static final double MAX = +4.0;
	static final double MIN = 0.0;
	static final double MAX = 180.0;
	double value;

	RandomConstant() {
		value = GP.random.nextDouble() * (MAX - MIN) + MIN;
	}

	private RandomConstant(double value) {
		this.value = value;
	}

	public String toString(int level) {
		return indent(level) + value;
	}

	protected Object clone() {
		return new RandomConstant(this.value);
	};

	String getName() {
		return "Random Constant";
	}

	double eval(double x) {
		return value;
	}

}

/**
*
*/
class Variable extends Terminal {

	public String toString(int level) {
		return indent(level) + "x";
	}

	protected Object clone() {
		return new Variable();
	}

	String getName() {
		return "x";
	}

	double eval(double x) {
		return x;
	}

}

/**
 * This is the base class for all kinds of function nodes (i.e. non-terminals).
 * Each kind of function can have a different number of arguments (i.e.
 * subtrees).
 */
abstract class Function extends Program {

	protected Program[] arg;
	public Service myService = null;

	public Function(Service s) {
		// TODO - not the most graceful WHAM WHAM WHAM! - I guess that'll work
		// and provide access to all Service fns
		myService = s;
	}

	public String toString(int level) {
		// Just to please the eye: If all arguments of the function
		// are terminals, I print a single line instead of spreading the
		// stuff tree-like.
		boolean allArgsAreTerminals = true;
		for (int a = 0; a < arg.length; a++) {
			allArgsAreTerminals = allArgsAreTerminals && (arg[a] instanceof Terminal);
		}
		String s = new String();
		if (!allArgsAreTerminals) {
			s = indent(level) + getName() + "(\n";
			int i = 0;
			while (i < arg.length - 1) {
				s = s + arg[i].toString(level + 1) + ",\n";
				i++;
			}
			if (i < arg.length) {
				s = s + arg[i].toString(level + 1) + "\n";
			}
			s = s + indent(level) + ")";
		} else {
			s = indent(level) + getName() + "(";
			int i = 0;
			while (i < arg.length - 1) {
				s = s + arg[i].toString(0) + ",";
				i++;
			}
			if (i < arg.length) {
				s = s + arg[i].toString(0);
			}
			s = s + ")";
		}
		return s;
	}

	protected Object clone() {
		Function temp = null;
		try {
			// temp = (Function)getClass().newInstance();

			Class cls = getClass();
			Constructor mc = cls.getConstructor(new Class[] { Service.class });
			temp = (Function) mc.newInstance(myService);

			for (int i = 0; i < arg.length; i++) {
				temp.arg[i] = (Program) arg[i].clone();
			}
		} catch (Exception e) {
		}
		return temp;
	}

	int countNodes() {
		int count = 1;
		for (int a = 0; a < arg.length; a++) {
			count = count + arg[a].countNodes();
		}
		return count;
	}

	int countNodes(Condition cond) {
		int count = (cond.test(this) ? 1 : 0);
		for (int a = 0; a < arg.length; a++) {
			count = count + arg[a].countNodes(cond);
		}
		return count;
	}

}

class Addition extends Function {

	public Addition(Service s) {
		super(s);
		arg = new Program[2];
	}

	public String getName() {
		return "add";
	}

	public double eval(double x) {
		return arg[0].eval(x) + arg[1].eval(x);
	}

}

class Subtraction extends Function {

	public Subtraction(Service s) {
		super(s);
		arg = new Program[2];
	}

	public String getName() {
		return "sub";
	}

	public double eval(double x) {
		return arg[0].eval(x) - arg[1].eval(x);
	}

}

class Multiplication extends Function {

	public Multiplication(Service s) {
		super(s);
		arg = new Program[2];
	}

	public String getName() {
		return "mul";
	}

	public double eval(double x) {
		return arg[0].eval(x) * arg[1].eval(x);
	}

}

class Division extends Function {

	public Division(Service s) {
		super(s);
		arg = new Program[2];
	}

	public String getName() {
		return "div";
	}

	public double eval(double x) {
		double divisor = arg[1].eval(x);
		return (divisor == 0 ? 1 : arg[0].eval(x) / divisor);
	}

}

class Sine extends Function {

	public Sine(Service s) {
		super(s);
		arg = new Program[1];
	}

	public String getName() {
		return "sin";
	}

	public double eval(double x) {
		return Math.sin(arg[0].eval(x));
	}

}

class Cosine extends Function {

	public Cosine(Service s) {
		super(s);
		arg = new Program[1];
	}

	public String getName() {
		return "cos";
	}

	public double eval(double x) {
		return Math.cos(arg[0].eval(x));
	}

}

class Exp extends Function {

	public Exp(Service s) {
		super(s);
		arg = new Program[1];
	}

	public String getName() {
		return "exp";
	}

	public double eval(double x) {
		double v = arg[0].eval(x);
		if (v > 100) {
			v = 100;
		} else if (v < -100) {
			v = -100;
		}
		return Math.exp(v);
	}

}

class MoveHip extends Function {

	public MoveHip(Service s) {
		super(s);
		arg = new Program[1];
	}

	public String getName() {
		return "hip";
	}

	public double eval(double x) {
		// return Math.cos(arg[0].eval(x));

		int X = (int) arg[0].eval(x);
		// Log.error("moveHip " + X);
		myService.send("hip", "moveTo", X);
		return x;
	}

}

class MoveKnee extends Function {

	public MoveKnee(Service s) {
		super(s);
		arg = new Program[1];
	}

	public String getName() {
		return "knee";
	}

	public double eval(double x) {
		// return Math.cos(arg[0].eval(x));
		int X = (int) arg[0].eval(x);
		// Log.error("moveKnee " + X);
		myService.send("knee", "moveTo", X);
		return x;
	}

}

class Sleep extends Function {

	public Sleep(Service s) {
		super(s);
		arg = new Program[1];
	}

	public String getName() {
		return "sleep";
	}

	public double eval(double x) {
		// return Math.cos(arg[0].eval(x));
		int X = (int) arg[0].eval(x);
		try {
			Thread.sleep(X);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return x;
	}

}

class First extends Function {

	public First(Service s) {
		super(s);
		arg = new Program[2];
	}

	public String getName() {
		return "first";
	}

	public double eval(double x) {
		return arg[0].eval(x);
	}

}

class Second extends Function {

	public Second(Service s) {
		super(s);
		arg = new Program[2];
	}

	public String getName() {
		return "second";
	}

	public double eval(double x) {
		return arg[1].eval(x);
	}

}

/**
 * This class combines a program and its computed fitness values.
 */
class Individual {
	public Program program;
	double standardizedFitness;
	double adjustedFitness;
	double normalizedFitness;
	int hits;

	Individual(Program p) {
		program = (Program) p.clone();
		standardizedFitness = 0.0;
		adjustedFitness = 0.0;
		normalizedFitness = 0.0;
		hits = 0;
	}

	Individual copy() {
		Individual newInd = new Individual(this.program);
		newInd.standardizedFitness = this.standardizedFitness;
		newInd.adjustedFitness = this.adjustedFitness;
		newInd.normalizedFitness = this.normalizedFitness;
		newInd.hits = this.hits;
		return newInd;
	}

}

/**
 * Just a helper class: it combines the class template and its text description
 * of a node. It is used to build the choice lists for function and terminal
 * sets.
 */
class ProgramChoice {
	private Class cls;
	private String text;

	ProgramChoice(String text, Class cls) {
		this.cls = cls;
		this.text = text;
	}

	public String toString() {
		return text;
	}

	Class value() {
		return cls;
	}
}

/**
 * Just a helper class: it combines the enumeration value and its text
 * description of a generation method. It is used to build the choice list for
 * the generation method menu.
 */
class MethodOfGeneration {
	static final int GROW = 0;
	static final int FULL = 1;
	static final int RAMPED_HALF_AND_HALF = 2;

	private String text;
	private int value;

	MethodOfGeneration(String text, int value) {
		this.text = text;
		this.value = value;
	}

	int getValue() {
		return this.value;
	}

	public String toString() {
		return this.text;
	}
}

/**
 * Just a helper class: it combines the enumeration value and its text
 * description of a selection method. It is used to build the choice list for
 * the selection method menu.
 */
class MethodOfSelection {
	static final int FITNESS_PROPORTIONATE = 0;
	static final int TOURNAMENT = 1;

	private String text;
	private int value;

	MethodOfSelection(String text, int value) {
		this.text = text;
		this.value = value;
	}

	public int getValue() {
		return this.value;
	}

	public String toString() {
		return this.text;
	}
}


text:
package org.jbpm.console.ng.pr.forms.display.process.api;

import java.util.Map;

import org.jbpm.console.ng.ga.forms.display.GenericFormDisplayer;
import org.jbpm.console.ng.ga.forms.display.view.FormContentResizeListener;
import org.jbpm.console.ng.pr.model.ProcessDefinitionKey;

/**
 *
 * @author salaboy
 */
public interface StartProcessFormDisplayer extends GenericFormDisplayer<ProcessDefinitionKey> {

    void startProcessFromDisplayer();

    void startProcess(Map<String, Object> params);

    void addResizeFormContent(FormContentResizeListener resizeListener);
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>libCSColorPicker</title>
  <base target="_top">
  <link rel="stylesheet" type="text/css" href="../resources/css/style.css" />
  <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="format-detection" content="telephone=no">

  <panel>
    <fieldset class="iosver">

Supports iOS > 9.0

    </fieldset>
    Info
    <fieldset>

A simplistic color picker for use in PreferenceLoader preference bundles. Supports iOS 9 & 10, other iOS versions
          have not been tested

Screenshots

    </fieldset>

    Changelog
    <fieldset>

Changelog

    </fieldset>

    Other
    <fieldset>

Donate

Contact Me

    </fieldset>

  </panel>


text:
define(['ash', 'game/vos/ItemBonusVO'], function (Ash, ItemBonusVO) {

	var ItemVO = Ash.Class.extend({

		id: "",
		name: "",
		type: "",
		level: 1,
		bonus: null,
		icon: "",
		description: "",
		requiredCampOrdinal: 1,
		maximumCampOrdinal: -1,
		isSpecialEquipment: false,

		scavengeRarity: -1,
		localeRarity: -1,
		tradeRarity: -1,
		investigateRarity: -1,

		equippable: false,
		craftable: false,
		repairable: false,
		useable: false,

		// item specific data (not saved on instances)
		configData: {},

		// instance data (varies between instances)
		itemID: -1,
		equipped: false,
		carried: false,
		broken: false,
		foundPosition: null,

		constructor: function (id, name, type, level, requiredCampOrdinal, maximumCampOrdinal, equippable, craftable, repairable, useable, bonuses, icon, description, isSpecialEquipment) {
			this.id = id;
			this.name = name;
			this.type = type;
			this.level = level;
			this.bonus = new ItemBonusVO(bonuses);
			this.equippable = equippable;
			this.craftable = craftable;
			this.repairable = repairable;
			this.useable = useable;
			this.icon = icon;
			this.description = description;
			this.requiredCampOrdinal = typeof requiredCampOrdinal != 'undefined' ? requiredCampOrdinal : 1;
			this.maximumCampOrdinal = typeof maximumCampOrdinal != 'undefined' ? maximumCampOrdinal : 0;
			this.isSpecialEquipment = isSpecialEquipment || false;

			this.scavengeRarity = -1;
			this.localeRarity = -1;
			this.tradeRarity = -1;
			this.investigateRarity = -1;

			this.configData = {};

			this.itemID = Math.floor(Math.random() * 100000);
			this.equipped = false;
			this.carried = false;
			this.broken = false;
			this.foundPosition = null;
		},

		getBaseTotalBonus: function () {
			return this.bonus.getTotal();
		},

		getCurrentTotalBonus: function () {
			let result = 0;
			if (this.bonus) {
				for (let key in this.bonus.bonuses) {
					let value = this.bonus.getBonus(key);
					if (this.broken && this.isBonusAffectedByBrokenStatus(key)) value = Math.floor(value / 2);
					result += value;
				}
			}
			return result;
		},

		getBaseBonus: function (bonusType) {
			return this.bonus ? this.bonus.getBonus(bonusType) : 0;
		},

		getCurrentBonus: function (bonusType) {
			let result = this.getBaseBonus(bonusType);
			if (this.broken && this.isBonusAffectedByBrokenStatus(bonusType)) result = Math.floor(result / 2);
			return result;
		},

		isBonusAffectedByBrokenStatus: function (bonusType) {
			// TODO refer to ItemConstants here / move whole function
			if (bonusType == "spd") return false;
			return true;
		},

		getCustomSaveObject: function () {
			var clone = this.clone();

			// add instance data
			clone.itemID = this.itemID;
			clone.equipped = this.equipped ? 1 : 0;
			clone.carried = this.carried ? 1 : 0;
			clone.broken = this.broken ? 1 : 0;

			// delete static data
			delete clone.name;
			delete clone.nameShort;
			delete clone.bonus;
			delete clone.icon;
			delete clone.description;
			delete clone.requiredCampOrdinal;
			delete clone.isSpecialEquipment;
			delete clone.scavengeRarity;
			delete clone.localeRarity;
			delete clone.tradeRarity;
			delete clone.investigateRarity;
			delete clone.craftable;
			delete clone.repairable;
			delete clone.useable;
			delete clone.type;
			delete clone.level;
			delete clone.equippable;
			delete clone.balancingData;
			delete clone.configData;
			delete clone.maximumCampOrdinal;

			if (this.foundPosition == null)
				delete clone.foundPosition;

			return clone;
		},

		clone: function () {
			var clone = new ItemVO(this.id, this.name, this.type, this.level, this.requiredCampOrdinal, this.maximumCampOrdinal, this.equippable, this.craftable, this.repairable, this.useable, this.bonus.bonuses, this.icon, this.description, this.isSpecialEquipment);
			clone.scavengeRarity = this.scavengeRarity;
			clone.localeRarity = this.localeRarity;
			clone.tradeRarity = this.tradeRarity;
			clone.investigateRarity = this.investigateRarity;
			clone.tradePrice = this.tradePrice;
			clone.broken = this.broken;
			return clone;
		}
	});

	return ItemVO;
});


text:
	<li <?php echo $this->uri->segment(5) == '' ? 'class="active"' : '' ?>>
		<a href="<?php echo site_url(SITE_AREA .'/content/contact/contact_mail') ?>" id="list"><?php echo lang('contact_list'); ?>

	<?php if ($this->auth->has_permission('Contact.Content.Create')) : ?>

	<?php endif; ?>


text:
/*-*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*  Monkey HTTP Server
 *  ==================
 *  Copyright 2001-2017 Eduardo Silva <eduardo@monkey.io>
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#ifndef MK_GETOPT_H
#define MK_GETOPT_H

#include "mk_core_info.h"

#ifdef __GNUC__      /* Heaven */
#include <getopt.h>
#else                /* Not Heaven */
#include "external/wingetopt.h"
#endif

#endif


text:
<?php

namespace Foodsquare\CommonBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="Comment")
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks()
 */
class Comment
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * Thread of this comment
     *
     * @var Thread
     * @ORM\ManyToOne(targetEntity="Foodsquare\CommonBundle\Entity\CommentThread")
     */
    protected $thread;

    /**
     *
     * @ORM\ManyToOne(targetEntity="Foodsquare\CommonBundle\Entity\Users")
     * @var Users
     */
    protected $commenter;

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

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

    /**
     * Constructor
     */
    function __construct(){
        $this->date = new \DateTime();
    }

    /**
     * @ORM\prePersist
     */
    public function increase()
    {
        $this->thread->incrementNumComments();
    }

    /**
     * @ORM\preRemove
     */
    public function decrease()
    {
      $this->thread->decrementNumComments();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set thread
     *
     * @param \Foodsquare\CommonBundle\Entity\CommentThread $thread
     * @return Comment
     */
    public function setThread(\Foodsquare\CommonBundle\Entity\CommentThread $thread = null)
    {
        $this->thread = $thread;

        return $this;
    }

    /**
     * Get thread
     *
     * @return \Foodsquare\CommonBundle\Entity\CommentThread
     */
    public function getThread()
    {
        return $this->thread;
    }

    /**
     * Set commenter
     *
     * @param \Foodsquare\CommonBundle\Entity\Users $commenter
     * @return Commenter
     */
    public function setCommenter(\Foodsquare\CommonBundle\Entity\Users $commenter = null)
    {
        $this->commenter = $commenter;

        return $this;
    }

    /**
     * Get commenter
     *
     * @return \Foodsquare\CommonBundle\Entity\Users
     */
    public function getCommenter()
    {
        return $this->commenter;
    }

    /**
     * Set comment
     *
     * @param string $comment
     * @return Comment
     */
    public function setComment($comment)
    {
        $this->comment = $comment;

        return $this;
    }

    /**
     * Get comment
     *
     * @return string
     */
    public function getComment()
    {
        return $this->comment;
    }

    /**
     * Set date
     *
     * @param \DateTime $date
     * @return Comment
     */
    public function setDate($date)
    {
        $this->date = $date;

        return $this;
    }

    /**
     * Get date
     *
     * @return \DateTime
     */
    public function getDate()
    {
        return $this->date;
    }
}


text:
package com.intellij.diagnostic.logging;

import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;
import java.util.regex.Pattern;

/**
 * @author Eugene.Kudelevsky
 */
public abstract class LogFilterModel {
  private Pattern myCustomPattern;

  public void updateCustomFilter(String filter) {
    myCustomPattern = null;
  }

  public abstract String getCustomFilter();

  @Nullable
  private Pattern getCustomPattern() {
    String customFilter = getCustomFilter();
    if (myCustomPattern == null && customFilter != null) {
      final StringBuilder buf = new StringBuilder(customFilter.length());
      for (int i = 0; i < customFilter.length(); i++) {
        final char c = customFilter.charAt(i);
        if (Character.isLetterOrDigit(c)) {
          buf.append(Character.toUpperCase(c));
        }
        else {
          buf.append("\\").append(c);
        }
      }
      myCustomPattern = Pattern.compile(".*" + buf + ".*", Pattern.DOTALL);
    }
    return myCustomPattern;
  }

  public abstract void addFilterListener(LogFilterListener listener);

  public abstract void removeFilterListener(LogFilterListener listener);

  public boolean isApplicable(String line) {
    if (getCustomFilter() != null) {
      final Pattern pattern = getCustomPattern();
      if (pattern != null && !pattern.matcher(StringUtil.toUpperCase(line)).matches()) return false;
    }
    return true;
  }

  public abstract List<? extends LogFilter> getLogFilters();

  public abstract boolean isFilterSelected(LogFilter filter);

  public abstract void selectFilter(LogFilter filter);

  @NotNull
  public abstract MyProcessingResult processLine(String line);

  public void processingStarted() {
  }

  public static class MyProcessingResult {
    private final Key myKey;
    private final boolean myApplicable;
    private final String myMessagePrefix;

    public MyProcessingResult(@Nullable Key key,
                               boolean applicable,
                               @Nullable String messagePrefix) {
      myKey = key;
      myApplicable = applicable;
      myMessagePrefix = messagePrefix;
    }

    @Nullable
    public Key getKey() {
      return myKey;
    }

    public boolean isApplicable() {
      return myApplicable;
    }

    @Nullable
    public String getMessagePrefix() {
      return myMessagePrefix;
    }
  }
}


text:
package io.rong.app.model;

import io.rong.imlib.model.MessageContent;

/**
 * Created by zhjchen on 8/12/15.
 */
public class RongEvent {

    /**
     * 有人加入实时位置共享
     */
    public static class RealTimeLocationMySelfJoinEvent {
        String userId;

        RealTimeLocationMySelfJoinEvent(String userId) {
            this.userId = userId;
        }

        public static RealTimeLocationMySelfJoinEvent obtain(String userId) {

            return new RealTimeLocationMySelfJoinEvent(userId);
        }

        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }
    }

    /**
     * 有人加入实时位置共享
     */
    public static class RealTimeLocationJoinEvent {
        String userId;

        RealTimeLocationJoinEvent(String userId) {
            this.userId = userId;
        }

        public static RealTimeLocationJoinEvent obtain(String userId) {

            return new RealTimeLocationJoinEvent(userId);
        }

        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }
    }

    /**
     * 有人退出实时位置共享
     */
    public static class RealTimeLocationQuitEvent {
        String userId;

        RealTimeLocationQuitEvent(String userId) {
            this.userId = userId;
        }

        public static RealTimeLocationQuitEvent obtain(String userId) {
            return new RealTimeLocationQuitEvent(userId);
        }

        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }
    }

    /**
     * 接收某人的实时位置共享
     */
    public static class RealTimeLocationReceiveEvent {
        String userId;
        double latitude;
        double longitude;

        RealTimeLocationReceiveEvent(String userId, double latitude, double longitude) {
            this.userId = userId;
            this.latitude = latitude;
            this.longitude = longitude;
        }

        public static RealTimeLocationReceiveEvent obtain(String userId, double latitude, double longitude) {
            return new RealTimeLocationReceiveEvent(userId, latitude, longitude);
        }

        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }

        public double getLatitude() {
            return latitude;
        }

        public void setLatitude(double latitude) {
            this.latitude = latitude;
        }

        public double getLongitude() {
            return longitude;
        }

        public void setLongitude(double longitude) {
            this.longitude = longitude;
        }
    }

    public static class RealTimeLocationStatusChangeEvent {

        public RealTimeLocationStatusChangeEvent obtain(double latitude, double longitude, String userId) {

            return null;
        }
    }
}


text:
package org.intellij.lang.regexp;

import com.intellij.lang.BracePair;
import com.intellij.lang.PairedBraceMatcher;
import com.intellij.psi.PsiFile;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class RegExpBraceMatcher implements PairedBraceMatcher {
  @Override
  public BracePair @NotNull [] getPairs() {
    return new BracePair[]{
      new BracePair(RegExpTT.GROUP_BEGIN, RegExpTT.GROUP_END, true),
      new BracePair(RegExpTT.SET_OPTIONS, RegExpTT.GROUP_END, true), new BracePair(RegExpTT.NON_CAPT_GROUP, RegExpTT.GROUP_END, true),
      new BracePair(RegExpTT.ATOMIC_GROUP, RegExpTT.GROUP_END, true),
      new BracePair(RegExpTT.POS_LOOKAHEAD, RegExpTT.GROUP_END, true), new BracePair(RegExpTT.NEG_LOOKAHEAD, RegExpTT.GROUP_END, true),
      new BracePair(RegExpTT.POS_LOOKBEHIND, RegExpTT.GROUP_END, true), new BracePair(RegExpTT.NEG_LOOKBEHIND, RegExpTT.GROUP_END, true),
      new BracePair(RegExpTT.PYTHON_NAMED_GROUP, RegExpTT.GROUP_END, true),
      new BracePair(RegExpTT.PYTHON_NAMED_GROUP_REF, RegExpTT.GROUP_END, true),
      new BracePair(RegExpTT.PCRE_RECURSIVE_NAMED_GROUP_REF, RegExpTT.GROUP_END, true),
      new BracePair(RegExpTT.CONDITIONAL, RegExpTT.GROUP_END, true),
      new BracePair(RegExpTT.PCRE_BRANCH_RESET, RegExpTT.GROUP_END, true),
      new BracePair(RegExpTT.RUBY_NAMED_GROUP, RegExpTT.GROUP_END, true),
      new BracePair(RegExpTT.RUBY_QUOTED_NAMED_GROUP, RegExpTT.GROUP_END, true),
      new BracePair(RegExpTT.RUBY_NAMED_GROUP_REF, RegExpTT.GT, true),
      new BracePair(RegExpTT.RUBY_QUOTED_NAMED_GROUP_REF, RegExpTT.QUOTE, true),
      new BracePair(RegExpTT.RUBY_NAMED_GROUP_CALL, RegExpTT.GT, true),
      new BracePair(RegExpTT.RUBY_QUOTED_NAMED_GROUP_CALL, RegExpTT.QUOTE, true),
      new BracePair(RegExpTT.CLASS_BEGIN, RegExpTT.CLASS_END, false), new BracePair(RegExpTT.LBRACE, RegExpTT.RBRACE, false),
      new BracePair(RegExpTT.QUOTE_BEGIN, RegExpTT.QUOTE_END, false),
      new BracePair(RegExpTT.BRACKET_EXPRESSION_BEGIN, RegExpTT.BRACKET_EXPRESSION_END, false)};
  }

  @Override
  public boolean isPairedBracesAllowedBeforeType(@NotNull IElementType lbraceType, @Nullable IElementType contextType) {
    return false;
  }

  @Override
  public int getCodeConstructStart(PsiFile file, int openingBraceOffset) {
    return openingBraceOffset;
  }
}


text:
//// Via http://www.roxlu.com/2014/046/rendering-text-with-pango--cairo-and-freetype
// No folor with FT2 renderer?

/*

 Text layouting and rendering with Pango
 ---------------------------------------

 This code snippet shows how to create a cairo surface and
 render some text into it using Pango. We store the generated
 pixels in a png file.

 n.b. this file was created for testing not production.

 */

#include <cairo.h>
#include <freetype2/ftbitmap.h>
#include <pango/pangocairo.h>
#include <pango/pangoft2.h>
#include <stdio.h>
#include <stdlib.h>

// static
// list fonts
// add font

// invalidating
// set anti-aliasing
// set pixel format
// Set font
// set justification
// set size
// set color
// set render mode (native or freetype)

// Render

int main() {
	const bool grayscale = false;
	const bool native = false;

	if (native) {
		setenv("PANGOCAIRO_BACKEND", "coretext", 0);
	} else {
		setenv("PANGOCAIRO_BACKEND", "fontconfig", 0); // this fixes some font issues on  mac
	}

	/* ------------------------------------------------------------ */
	/*                   I N I T I A L I Z E                        */
	/* ------------------------------------------------------------ */

	// measure
	PangoFontMap *font_map = NULL;
	font_map = pango_cairo_font_map_new();
	if (font_map == NULL) {
		printf("+ error: cannot create the pango font map.\n");
		exit(EXIT_FAILURE);
	}

	PangoContext *context = NULL;
	context = pango_font_map_create_context(font_map);
	if (NULL == context) {
		printf("+ error: cannot create pango font context.\n");
		exit(EXIT_FAILURE);
	}

	/* create layout object. */
	PangoLayout *layout = NULL;
	layout = pango_layout_new(context);

	if (NULL == layout) {
		printf("+ error: cannot create the pango layout.\n");
		exit(EXIT_FAILURE);
	}

	/* create the font description @todo the reference does not tell how/when to free this */
	PangoFontDescription *font_desc = NULL;
	font_desc = pango_font_description_from_string("Times 35");
	pango_layout_set_font_description(layout, font_desc);
	pango_font_map_load_font(font_map, context, font_desc);
	pango_font_description_free(font_desc);

	/* set the width around which pango will wrap */
	pango_layout_set_width(layout, 200 * PANGO_SCALE);
	pango_layout_set_alignment(layout, PANGO_ALIGN_LEFT);

	/* write using the markup feature */
	const gchar *text = ""
											""
											"bold is nicé "
											""
											"<tt> hello </tt>"
											" SANS"
											" colored"
											"";

	// Measure
	pango_layout_set_markup(layout, text, -1);

	int pixelWidth = 0;
	int pixelHeight = 0;
	pango_layout_get_pixel_size(layout, &pixelWidth, &pixelHeight);

	printf("Width: %i Height: %i\n", pixelWidth, pixelHeight);

	// draw into cairo
	_cairo_format cairoFormat = grayscale ? CAIRO_FORMAT_A8 : CAIRO_FORMAT_ARGB32;

	cairo_surface_t *surf = NULL;
	surf = cairo_image_surface_create(cairoFormat, pixelWidth, pixelHeight);

	if (CAIRO_STATUS_SUCCESS != cairo_surface_status(surf)) {
		printf("+ error: couldn't create the surface.\n");
		exit(EXIT_FAILURE);
	}

	/* create our cairo context object that tracks state. */
	cairo_t *cr = cairo_create(surf);
	if (CAIRO_STATUS_NO_MEMORY == cairo_status(cr)) {
		printf("+ error: out of memory, cannot create cairo_t*\n");
		exit(EXIT_FAILURE);
	}

	cairo_move_to(cr, 0, 0);
	pango_cairo_update_layout(cr, layout);
	pango_cairo_show_layout(cr, layout);

	/* ------------------------------------------------------------ */
	/*               O U T P U T  A N D  C L E A N U P              */
	/* ------------------------------------------------------------ */

	/* write to png */
	cairo_status_t status;
	status = cairo_surface_write_to_png(surf, "test_font.png");
	if (CAIRO_STATUS_SUCCESS != status) {
		printf("+ error: couldn't write to png\n");
		exit(EXIT_FAILURE);
	}

	// destroy bmp?
	cairo_surface_destroy(surf);
	cairo_destroy(cr);

	g_object_unref(layout);
	g_object_unref(font_map);
	g_object_unref(context);

	return 0;
}

int main2() {
	setenv("PANGOCAIRO_BACKEND", "fontconfig", 0); // this fixes some font issues on  mac

	PangoFontMap *fontMap = pango_cairo_font_map_get_default();
	PangoContext *pangoContext = pango_font_map_create_context(fontMap);
	PangoLayout *pangoLayout = pango_layout_new(pangoContext);

	float maxWidth = 200;

	pango_layout_set_width(pangoLayout, maxWidth * PANGO_SCALE);

	const gchar *text = ""
											""
											"bold is nicé "
											""
											"<tt> hello </tt>"
											" SANS"
											" colored"
											"";

	pango_layout_set_markup(pangoLayout, text, -1);

	int width = 0;
	int height = 0;
	pango_layout_get_pixel_size(pangoLayout, &width, &height);

	printf("Width: %i Height: %i\n", width, height);

	cairo_surface_t *cairoSurface = NULL;
	cairoSurface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height);

	if (CAIRO_STATUS_SUCCESS != cairo_surface_status(cairoSurface)) {
		printf("+ error: couldn't create the surface.\n");
		exit(EXIT_FAILURE);
	}

	/* create our cairo context object that tracks state. */
	cairo_t *cairoContext = NULL;
	cairoContext = cairo_create(cairoSurface);
	if (CAIRO_STATUS_NO_MEMORY == cairo_status(cairoContext)) {
		printf("+ error: out of memory, cannot create cairo_t*\n");
		exit(EXIT_FAILURE);
	}

	cairo_move_to(cairoContext, 0, 0);
	pango_cairo_update_layout(cairoContext, pangoLayout);
	pango_cairo_show_layout(cairoContext, pangoLayout);

	/* write to png */
	cairo_status_t status;
	status = cairo_surface_write_to_png(cairoSurface, "test_font.png");
	if (CAIRO_STATUS_SUCCESS != status) {
		printf("+ error: couldn't write to png\n");
		exit(EXIT_FAILURE);
	}

	// destroy bmp?
	cairo_surface_destroy(cairoSurface);
	cairo_destroy(cairoContext);

	g_object_unref(pangoLayout);
	g_object_unref(fontMap);
	g_object_unref(pangoContext);

	return 0;
}

int main3() {

	setenv("PANGOCAIRO_BACKEND", "fontconfig", 0); // this fixes some font issues on  mac
	// setenv("PANGOCAIRO_BACKEND", "coretext", 0);

	const bool native = true; // deprecated, keep this true
	const bool grayscale = false;

	cairo_surface_t *surf = NULL;
	cairo_t *cr = NULL;
	cairo_status_t status;
	PangoContext *context = NULL;
	PangoLayout *layout = NULL;
	PangoFontDescription *font_desc = NULL;
	PangoFontMap *font_map = NULL;
	FT_Bitmap bmp = {0};

	//	int stride = 0;
	int width = 640;
	int height = 480;

	/* ------------------------------------------------------------ */
	/*                   I N I T I A L I Z E                        */
	/* ------------------------------------------------------------ */

	/* FT buffer */
	//	FT_Bitmap_New(&bmp);
	//	bmp.rows = height;
	//	bmp.width = width;
	//
	//	bmp.buffer = (unsigned char *)malloc(bmp.rows * bmp.width);
	//	if (NULL == bmp.buffer) {
	//		printf("+ error: cannot allocate the buffer for the output bitmap.\n");
	//		exit(EXIT_FAILURE);
	//	}
	//
	//	/* create our "canvas" */
	//	bmp.pitch = (width + 3) & -4;
	//	bmp.pixel_mode = FT_PIXEL_MODE_BGRA; /*< Grayscale*/
	//	stride = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, width);
	//	surf = cairo_image_surface_create_for_data(bmp.buffer, CAIRO_FORMAT_ARGB32, width, height, stride);

	_cairo_format cairoFormat = grayscale ? CAIRO_FORMAT_A8 : CAIRO_FORMAT_ARGB32;

	if (native) {
		surf = cairo_image_surface_create(cairoFormat, width, height);
	} else {
		// TODO

		// FT_Bitmap_Convert?

		FT_Pixel_Mode_ ftFormat = grayscale ? FT_PIXEL_MODE_GRAY : FT_PIXEL_MODE_BGRA;

		int bpp = grayscale ? 1 : 4;
		int pitch = width * bpp + bpp & ~bpp;

		FT_Bitmap_New(&bmp);
		bmp.width = width;
		bmp.rows = height;
		bmp.buffer = (unsigned char *)malloc(pitch * height);
		bmp.pixel_mode = ftFormat;
		if (grayscale) {
			bmp.num_grays = 256;
		}
		bmp.pitch = pitch;

		int stride = cairo_format_stride_for_width(cairoFormat, width);
		surf = cairo_image_surface_create_for_data(bmp.buffer, cairoFormat, width, height, stride);
	}

	if (CAIRO_STATUS_SUCCESS != cairo_surface_status(surf)) {
		printf("+ error: couldn't create the surface.\n");
		exit(EXIT_FAILURE);
	}

	/* create our cairo context object that tracks state. */
	cr = cairo_create(surf);
	if (CAIRO_STATUS_NO_MEMORY == cairo_status(cr)) {
		printf("+ error: out of memory, cannot create cairo_t*\n");
		exit(EXIT_FAILURE);
	}

	/* ------------------------------------------------------------ */
	/*               D R A W   I N T O  C A N V A S                 */
	/* ------------------------------------------------------------ */

	if (native) {
		font_map = pango_cairo_font_map_new();
	} else {
		font_map = pango_ft2_font_map_new();
	}

	if (NULL == font_map) {
		printf("+ error: cannot create the pango font map.\n");
		exit(EXIT_FAILURE);
	}

	context = pango_font_map_create_context(font_map);
	if (NULL == context) {
		printf("+ error: cannot create pango font context.\n");
		exit(EXIT_FAILURE);
	}

	/* create layout object. */
	layout = pango_layout_new(context);

	if (NULL == layout) {
		printf("+ error: cannot create the pango layout.\n");
		exit(EXIT_FAILURE);
	}

	/* create the font description @todo the reference does not tell how/when to free this */
	font_desc = pango_font_description_from_string("Times 35");
	pango_layout_set_font_description(layout, font_desc);
	pango_font_map_load_font(font_map, context, font_desc);
	pango_font_description_free(font_desc);

	/* set the width around which pango will wrap */
	pango_layout_set_width(layout, width * PANGO_SCALE);
	pango_layout_set_alignment(layout, PANGO_ALIGN_LEFT);

	/* write using the markup feature */
	const gchar *text = ""
											""
											"bold is nicé "
											""
											"<tt> hello </tt>"
											" SANS"
											" colored"
											"";

	pango_layout_set_markup(layout, text, -1);

	/* render */

	if (!native) {
		pango_ft2_render_layout(&bmp, layout, 0, 0);
	}

	pango_cairo_update_layout(cr, layout);

	if (native) {
		pango_cairo_show_layout(cr, layout);
	}

	/* ------------------------------------------------------------ */
	/*               O U T P U T  A N D  C L E A N U P              */
	/* ------------------------------------------------------------ */

	/* write to png */
	status = cairo_surface_write_to_png(surf, "test_font.png");
	if (CAIRO_STATUS_SUCCESS != status) {
		printf("+ error: couldn't write to png\n");
		exit(EXIT_FAILURE);
	}

	// destroy bmp?
	cairo_surface_destroy(surf);
	cairo_destroy(cr);

	g_object_unref(layout);
	g_object_unref(font_map);
	g_object_unref(context);

	return 0;
}

//#include <glib.h>
//#include <math.h>
//#include <pango/pangocairo.h>
//
// static void draw_text(cairo_t *cr) {
//#define RADIUS 150
//#define N_WORDS 10
//#define FONT "Gravur Condensed Pro 30"
//
//	PangoLayout *layout;
//	PangoFontDescription *desc;
//	int i;
//
//	/* Center coordinates on the middle of the region we are drawing
//	 */
//	cairo_translate(cr, RADIUS, RADIUS);
//
//	/* Create a PangoLayout, set the font and text */
//
//	pango_layout_set_text(layout, "Text", -1);
//	desc = pango_font_description_from_string(FONT);
//	pango_layout_set_font_description(layout, desc);
//
//	pango_font_description_free(desc);
//
//	//	pango_font_description_free(font_desc);
//
//	/* Draw the layout N_WORDS times in a circle */
//	for (i = 0; i < N_WORDS; i++) {
//		int width, height;
//		double angle = (360. * i) / N_WORDS;
//		double red;
//
//		cairo_save(cr);
//
//		/* Gradient from red at angle == 60 to blue at angle == 240 */
//		red = (1 + cos((angle - 60) * G_PI / 180.)) / 2;
//		cairo_set_source_rgb(cr, red, 0, 1.0 - red);
//
//		cairo_rotate(cr, angle * G_PI / 180.);
//
//		/* Inform Pango to re-layout the text with the new transformation */
//		pango_cairo_update_layout(cr, layout);
//
//		pango_layout_get_size(layout, &width, &height);
//		cairo_move_to(cr, -((double)width / PANGO_SCALE) / 2, -RADIUS);
//		pango_cairo_show_layout(cr, layout);
//
//		cairo_restore(cr);
//	}
//
//	/* free the layout object */
//	g_object_unref(layout);
//}
//
// int main(int argc, char **argv) {
//
//	FcConfig *fontConfig = FcConfigCreate();
//
//	//	const FcChar8 *file = (const FcChar8 *)"/Users/mika/Code/tech-museum-bio.wetlab/WorkbenchTabletOF/bin/data/fonts/GravurCondensedPro-Regular.ttf";
//	const FcChar8 *file = (const FcChar8 *)"/Users/mika/Documents/Fonts/Gravur Condensed Pro/GravurCondensedPro-Regular.ttf";
//	//	const FcChar8 *file = (const FcChar8 *)"/Users/mika/Documents/Fonts/Trade Gothic LT Std/TradeGothicLTStd-Bd2.otf";
//	//
//	FcBool fontAddStatus = FcConfigAppFontAddFile(fontConfig, file);
//
//	if (fontAddStatus) {
//		g_print("added font successfully");
//	}
//
//	FcConfigSetCurrent(fontConfig);
//
//	// Print fonts
//
//	FcFontSet *fonts = FcConfigGetFonts(FcConfigGetCurrent(), FcSetApplication);
//
//	printf("Font count: %i", fonts->nfont);
//
//	FcPatternPrint(fonts->fonts[0]);
//
//	PangoContext *context;
//	cairo_t *cr;
//	char *filename;
//	cairo_status_t status;
//	cairo_surface_t *surface;
//
//	if (argc != 2) {
//		g_printerr("Usage: cairosimple OUTPUT_FILENAME\n");
//		return 1;
//	}
//
//	filename = argv[1];
//
//	surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 2 * RADIUS, 2 * RADIUS);
//	cr = cairo_create(surface);
//
//	cairo_set_source_rgb(cr, 1.0, 1.0, 1.0);
//	cairo_paint(cr);
//	draw_text(cr);
//	cairo_destroy(cr);
//
//	status = cairo_surface_write_to_png(surface, filename);
//	cairo_surface_destroy(surface);
//
//	if (status != CAIRO_STATUS_SUCCESS) {
//		g_printerr("Could not save png to '%s' status %i\n", filename, status);
//		return 1;
//	}
//
//	return 0;
//}


text:
namespace Soloco.Composition.Example.Repositories.Services
{
    public interface IEmployeeRepository : IRepository,
                                           IEmployeeQuerier,
                                           IAllEntiyRetriever<Employee>,
                                           IEntityCounter<Employee>,
                                           IEntityPersister<Employee>,
                                           IEntityDeleter<Employee, int>
    {
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.lee.main.view.actionbar.ActionBarLayout
        android:id="@+id/web_actionbar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true" />

    <WebView
        android:id="@+id/vb_web_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/web_actionbar_layout" />

    <ProgressBar
        android:id="@+id/pb_web_progress"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dimen_web_progress_bar_height"
        android:layout_below="@id/web_actionbar_layout"
        android:progressDrawable="@drawable/drawable_web_progress" />

</RelativeLayout>


text:
package persistance

import (
	"github.com/pkg/errors"
	"gopkg.in/mgo.v2"
)

type DataStore struct {
	master *mgo.Session
}

func NewDataStore(connection string) (*DataStore, error) {
	session, err := mgo.Dial(connection)
	if err != nil {
		return nil, errors.Wrapf(err, "Unable to connect to Mongo DB on '%s'.", connection)
	}
	return &DataStore{session}, nil
}

func (ds *DataStore) Close() {
	ds.master.Close()
}

func (ds *DataStore) Session() *mgo.Session {
	s := ds.master.Copy()
	s.SetMode(mgo.Monotonic, true)
	return s
}


text:
package com.tirthal.learning.model;

import aQute.bnd.annotation.ProviderType;

import com.liferay.expando.kernel.model.ExpandoBridge;

import com.liferay.exportimport.kernel.lar.StagedModelType;

import com.liferay.portal.kernel.model.ModelWrapper;
import com.liferay.portal.kernel.service.ServiceContext;

import java.io.Serializable;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * This class is a wrapper for {@link NewsEntry}.
 * </p>
 *
 * @author Brian Wing Shun Chan
 * @see NewsEntry
 * @generated
 */
@ProviderType
public class NewsEntryWrapper implements NewsEntry, ModelWrapper<NewsEntry> {
	public NewsEntryWrapper(NewsEntry newsEntry) {
		_newsEntry = newsEntry;
	}

	@Override
	public Class<?> getModelClass() {
		return NewsEntry.class;
	}

	@Override
	public String getModelClassName() {
		return NewsEntry.class.getName();
	}

	@Override
	public Map<String, Object> getModelAttributes() {
		Map<String, Object> attributes = new HashMap<String, Object>();

		attributes.put("uuid", getUuid());
		attributes.put("newsId", getNewsId());
		attributes.put("groupId", getGroupId());
		attributes.put("companyId", getCompanyId());
		attributes.put("userId", getUserId());
		attributes.put("userName", getUserName());
		attributes.put("createDate", getCreateDate());
		attributes.put("modifiedDate", getModifiedDate());
		attributes.put("title", getTitle());
		attributes.put("description", getDescription());

		return attributes;
	}

	@Override
	public void setModelAttributes(Map<String, Object> attributes) {
		String uuid = (String)attributes.get("uuid");

		if (uuid != null) {
			setUuid(uuid);
		}

		Long newsId = (Long)attributes.get("newsId");

		if (newsId != null) {
			setNewsId(newsId);
		}

		Long groupId = (Long)attributes.get("groupId");

		if (groupId != null) {
			setGroupId(groupId);
		}

		Long companyId = (Long)attributes.get("companyId");

		if (companyId != null) {
			setCompanyId(companyId);
		}

		Long userId = (Long)attributes.get("userId");

		if (userId != null) {
			setUserId(userId);
		}

		String userName = (String)attributes.get("userName");

		if (userName != null) {
			setUserName(userName);
		}

		Date createDate = (Date)attributes.get("createDate");

		if (createDate != null) {
			setCreateDate(createDate);
		}

		Date modifiedDate = (Date)attributes.get("modifiedDate");

		if (modifiedDate != null) {
			setModifiedDate(modifiedDate);
		}

		String title = (String)attributes.get("title");

		if (title != null) {
			setTitle(title);
		}

		String description = (String)attributes.get("description");

		if (description != null) {
			setDescription(description);
		}
	}

	@Override
	public NewsEntry toEscapedModel() {
		return new NewsEntryWrapper(_newsEntry.toEscapedModel());
	}

	@Override
	public NewsEntry toUnescapedModel() {
		return new NewsEntryWrapper(_newsEntry.toUnescapedModel());
	}

	@Override
	public boolean isCachedModel() {
		return _newsEntry.isCachedModel();
	}

	@Override
	public boolean isEscapedModel() {
		return _newsEntry.isEscapedModel();
	}

	@Override
	public boolean isNew() {
		return _newsEntry.isNew();
	}

	@Override
	public ExpandoBridge getExpandoBridge() {
		return _newsEntry.getExpandoBridge();
	}

	@Override
	public com.liferay.portal.kernel.model.CacheModel<NewsEntry> toCacheModel() {
		return _newsEntry.toCacheModel();
	}

	@Override
	public int compareTo(NewsEntry newsEntry) {
		return _newsEntry.compareTo(newsEntry);
	}

	@Override
	public int hashCode() {
		return _newsEntry.hashCode();
	}

	@Override
	public Serializable getPrimaryKeyObj() {
		return _newsEntry.getPrimaryKeyObj();
	}

	@Override
	public java.lang.Object clone() {
		return new NewsEntryWrapper((NewsEntry)_newsEntry.clone());
	}

	/**
	* Returns the description of this news entry.
	*
	* @return the description of this news entry
	*/
	@Override
	public java.lang.String getDescription() {
		return _newsEntry.getDescription();
	}

	/**
	* Returns the title of this news entry.
	*
	* @return the title of this news entry
	*/
	@Override
	public java.lang.String getTitle() {
		return _newsEntry.getTitle();
	}

	/**
	* Returns the user name of this news entry.
	*
	* @return the user name of this news entry
	*/
	@Override
	public java.lang.String getUserName() {
		return _newsEntry.getUserName();
	}

	/**
	* Returns the user uuid of this news entry.
	*
	* @return the user uuid of this news entry
	*/
	@Override
	public java.lang.String getUserUuid() {
		return _newsEntry.getUserUuid();
	}

	/**
	* Returns the uuid of this news entry.
	*
	* @return the uuid of this news entry
	*/
	@Override
	public java.lang.String getUuid() {
		return _newsEntry.getUuid();
	}

	@Override
	public java.lang.String toString() {
		return _newsEntry.toString();
	}

	@Override
	public java.lang.String toXmlString() {
		return _newsEntry.toXmlString();
	}

	/**
	* Returns the create date of this news entry.
	*
	* @return the create date of this news entry
	*/
	@Override
	public Date getCreateDate() {
		return _newsEntry.getCreateDate();
	}

	/**
	* Returns the modified date of this news entry.
	*
	* @return the modified date of this news entry
	*/
	@Override
	public Date getModifiedDate() {
		return _newsEntry.getModifiedDate();
	}

	/**
	* Returns the company ID of this news entry.
	*
	* @return the company ID of this news entry
	*/
	@Override
	public long getCompanyId() {
		return _newsEntry.getCompanyId();
	}

	/**
	* Returns the group ID of this news entry.
	*
	* @return the group ID of this news entry
	*/
	@Override
	public long getGroupId() {
		return _newsEntry.getGroupId();
	}

	/**
	* Returns the news ID of this news entry.
	*
	* @return the news ID of this news entry
	*/
	@Override
	public long getNewsId() {
		return _newsEntry.getNewsId();
	}

	/**
	* Returns the primary key of this news entry.
	*
	* @return the primary key of this news entry
	*/
	@Override
	public long getPrimaryKey() {
		return _newsEntry.getPrimaryKey();
	}

	/**
	* Returns the user ID of this news entry.
	*
	* @return the user ID of this news entry
	*/
	@Override
	public long getUserId() {
		return _newsEntry.getUserId();
	}

	@Override
	public void persist() {
		_newsEntry.persist();
	}

	@Override
	public void setCachedModel(boolean cachedModel) {
		_newsEntry.setCachedModel(cachedModel);
	}

	/**
	* Sets the company ID of this news entry.
	*
	* @param companyId the company ID of this news entry
	*/
	@Override
	public void setCompanyId(long companyId) {
		_newsEntry.setCompanyId(companyId);
	}

	/**
	* Sets the create date of this news entry.
	*
	* @param createDate the create date of this news entry
	*/
	@Override
	public void setCreateDate(Date createDate) {
		_newsEntry.setCreateDate(createDate);
	}

	/**
	* Sets the description of this news entry.
	*
	* @param description the description of this news entry
	*/
	@Override
	public void setDescription(java.lang.String description) {
		_newsEntry.setDescription(description);
	}

	@Override
	public void setExpandoBridgeAttributes(ExpandoBridge expandoBridge) {
		_newsEntry.setExpandoBridgeAttributes(expandoBridge);
	}

	@Override
	public void setExpandoBridgeAttributes(
		com.liferay.portal.kernel.model.BaseModel<?> baseModel) {
		_newsEntry.setExpandoBridgeAttributes(baseModel);
	}

	@Override
	public void setExpandoBridgeAttributes(ServiceContext serviceContext) {
		_newsEntry.setExpandoBridgeAttributes(serviceContext);
	}

	/**
	* Sets the group ID of this news entry.
	*
	* @param groupId the group ID of this news entry
	*/
	@Override
	public void setGroupId(long groupId) {
		_newsEntry.setGroupId(groupId);
	}

	/**
	* Sets the modified date of this news entry.
	*
	* @param modifiedDate the modified date of this news entry
	*/
	@Override
	public void setModifiedDate(Date modifiedDate) {
		_newsEntry.setModifiedDate(modifiedDate);
	}

	@Override
	public void setNew(boolean n) {
		_newsEntry.setNew(n);
	}

	/**
	* Sets the news ID of this news entry.
	*
	* @param newsId the news ID of this news entry
	*/
	@Override
	public void setNewsId(long newsId) {
		_newsEntry.setNewsId(newsId);
	}

	/**
	* Sets the primary key of this news entry.
	*
	* @param primaryKey the primary key of this news entry
	*/
	@Override
	public void setPrimaryKey(long primaryKey) {
		_newsEntry.setPrimaryKey(primaryKey);
	}

	@Override
	public void setPrimaryKeyObj(Serializable primaryKeyObj) {
		_newsEntry.setPrimaryKeyObj(primaryKeyObj);
	}

	/**
	* Sets the title of this news entry.
	*
	* @param title the title of this news entry
	*/
	@Override
	public void setTitle(java.lang.String title) {
		_newsEntry.setTitle(title);
	}

	/**
	* Sets the user ID of this news entry.
	*
	* @param userId the user ID of this news entry
	*/
	@Override
	public void setUserId(long userId) {
		_newsEntry.setUserId(userId);
	}

	/**
	* Sets the user name of this news entry.
	*
	* @param userName the user name of this news entry
	*/
	@Override
	public void setUserName(java.lang.String userName) {
		_newsEntry.setUserName(userName);
	}

	/**
	* Sets the user uuid of this news entry.
	*
	* @param userUuid the user uuid of this news entry
	*/
	@Override
	public void setUserUuid(java.lang.String userUuid) {
		_newsEntry.setUserUuid(userUuid);
	}

	/**
	* Sets the uuid of this news entry.
	*
	* @param uuid the uuid of this news entry
	*/
	@Override
	public void setUuid(java.lang.String uuid) {
		_newsEntry.setUuid(uuid);
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}

		if (!(obj instanceof NewsEntryWrapper)) {
			return false;
		}

		NewsEntryWrapper newsEntryWrapper = (NewsEntryWrapper)obj;

		if (Objects.equals(_newsEntry, newsEntryWrapper._newsEntry)) {
			return true;
		}

		return false;
	}

	@Override
	public StagedModelType getStagedModelType() {
		return _newsEntry.getStagedModelType();
	}

	@Override
	public NewsEntry getWrappedModel() {
		return _newsEntry;
	}

	@Override
	public boolean isEntityCacheEnabled() {
		return _newsEntry.isEntityCacheEnabled();
	}

	@Override
	public boolean isFinderCacheEnabled() {
		return _newsEntry.isFinderCacheEnabled();
	}

	@Override
	public void resetOriginalValues() {
		_newsEntry.resetOriginalValues();
	}

	private final NewsEntry _newsEntry;
}


text:
<?php namespace spec\Devtools;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Devtools;
use Devtools\Observer;

class FileLoggerSpec extends ObjectBehavior
{
    function let(Devtools\Formatter $formatter)
    {
        $this->beConstructedWith('test.log', $formatter);
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('Devtools\FileLogger');
    }

    function it_writes_to_file($formatter)
    {
        $this->write('Log1')->shouldNotReturn(false);
        $this::write('Log2', true)->shouldNotReturn(false);
        $this::write('Log3', false)->shouldNotReturn(false);

        $formatter->format('Log1', null)->shouldBeCalled();
        $formatter->format('Log2', true)->shouldBeCalled();
        $formatter->format('Log3', false)->shouldBeCalled();
        $formatter->footer()->willreturn('');
    }
}


text:
//===-- Timer.cpp -----------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/Core/Timer.h"

#include <map>
#include <vector>
#include <algorithm>

#include "lldb/Core/Stream.h"
#include "lldb/Host/Mutex.h"

#include <stdio.h>

using namespace lldb_private;

#define TIMER_INDENT_AMOUNT 2
static bool g_quiet = true;
uint32_t Timer::g_depth = 0;
uint32_t Timer::g_display_depth = 0;
FILE * Timer::g_file = NULL;
typedef std::vector<Timer *> TimerStack;
typedef std::map<const char *, uint64_t> TimerCategoryMap;
static pthread_key_t g_key;

static Mutex &
GetCategoryMutex()
{
    static Mutex g_category_mutex(Mutex::eMutexTypeNormal);
    return g_category_mutex;
}

static TimerCategoryMap &
GetCategoryMap()
{
    static TimerCategoryMap g_category_map;
    return g_category_map;
}

static TimerStack *
GetTimerStackForCurrentThread ()
{
    void *timer_stack = ::pthread_getspecific (g_key);
    if (timer_stack == NULL)
    {
        ::pthread_setspecific (g_key, new TimerStack);
        timer_stack = ::pthread_getspecific (g_key);
    }
    return (TimerStack *)timer_stack;
}

void
ThreadSpecificCleanup (void *p)
{
    delete (TimerStack *)p;
}

void
Timer::SetQuiet (bool value)
{
    g_quiet = value;
}

void
Timer::Initialize ()
{
    Timer::g_file = stdout;
    ::pthread_key_create (&g_key, ThreadSpecificCleanup);

}

Timer::Timer (const char *category, const char *format, ...) :
    m_category (category),
    m_total_start (),
    m_timer_start (),
    m_total_ticks (0),
    m_timer_ticks (0)
{
    if (g_depth++ < g_display_depth)
    {
        if (g_quiet == false)
        {
            // Indent
            ::fprintf (g_file, "%*s", g_depth * TIMER_INDENT_AMOUNT, "");
            // Print formatted string
            va_list args;
            va_start (args, format);
            ::vfprintf (g_file, format, args);
            va_end (args);

            // Newline
            ::fprintf (g_file, "\n");
        }
        TimeValue start_time(TimeValue::Now());
        m_total_start = start_time;
        m_timer_start = start_time;
        TimerStack *stack = GetTimerStackForCurrentThread ();
        if (stack)
        {
            if (stack->empty() == false)
                stack->back()->ChildStarted (start_time);
            stack->push_back(this);
        }
    }
}

Timer::~Timer()
{
    if (m_total_start.IsValid())
    {
        TimeValue stop_time = TimeValue::Now();
        if (m_total_start.IsValid())
        {
            m_total_ticks += (stop_time - m_total_start);
            m_total_start.Clear();
        }
        if (m_timer_start.IsValid())
        {
            m_timer_ticks += (stop_time - m_timer_start);
            m_timer_start.Clear();
        }

        TimerStack *stack = GetTimerStackForCurrentThread ();
        if (stack)
        {
            assert (stack->back() == this);
            stack->pop_back();
            if (stack->empty() == false)
                stack->back()->ChildStopped(stop_time);
        }

        const uint64_t total_nsec_uint = GetTotalElapsedNanoSeconds();
        const uint64_t timer_nsec_uint = GetTimerElapsedNanoSeconds();
        const double total_nsec = total_nsec_uint;
        const double timer_nsec = timer_nsec_uint;

        if (g_quiet == false)
        {

            ::fprintf (g_file,
                       "%*s%.9f sec (%.9f sec)\n",
                       (g_depth - 1) *TIMER_INDENT_AMOUNT, "",
                       total_nsec / 1000000000.0,
                       timer_nsec / 1000000000.0);
        }

        // Keep total results for each category so we can dump results.
        Mutex::Locker locker (GetCategoryMutex());
        TimerCategoryMap &category_map = GetCategoryMap();
        category_map[m_category] += timer_nsec_uint;
    }
    if (g_depth > 0)
        --g_depth;
}

uint64_t
Timer::GetTotalElapsedNanoSeconds()
{
    uint64_t total_ticks = m_total_ticks;

    // If we are currently running, we need to add the current
    // elapsed time of the running timer...
    if (m_total_start.IsValid())
        total_ticks += (TimeValue::Now() - m_total_start);

    return total_ticks;
}

uint64_t
Timer::GetTimerElapsedNanoSeconds()
{
    uint64_t timer_ticks = m_timer_ticks;

    // If we are currently running, we need to add the current
    // elapsed time of the running timer...
    if (m_timer_start.IsValid())
        timer_ticks += (TimeValue::Now() - m_timer_start);

    return timer_ticks;
}

void
Timer::ChildStarted (const TimeValue& start_time)
{
    if (m_timer_start.IsValid())
    {
        m_timer_ticks += (start_time - m_timer_start);
        m_timer_start.Clear();
    }
}

void
Timer::ChildStopped (const TimeValue& stop_time)
{
    if (!m_timer_start.IsValid())
        m_timer_start = stop_time;
}

void
Timer::SetDisplayDepth (uint32_t depth)
{
    g_display_depth = depth;
}

/* binary function predicate:
 * - returns whether a person is less than another person
 */
static bool
CategoryMapIteratorSortCriterion (const TimerCategoryMap::const_iterator& lhs, const TimerCategoryMap::const_iterator& rhs)
{
    return lhs->second > rhs->second;
}

void
Timer::ResetCategoryTimes ()
{
    Mutex::Locker locker (GetCategoryMutex());
    TimerCategoryMap &category_map = GetCategoryMap();
    category_map.clear();
}

void
Timer::DumpCategoryTimes (Stream *s)
{
    Mutex::Locker locker (GetCategoryMutex());
    TimerCategoryMap &category_map = GetCategoryMap();
    std::vector<TimerCategoryMap::const_iterator> sorted_iterators;
    TimerCategoryMap::const_iterator pos, end = category_map.end();
    for (pos = category_map.begin(); pos != end; ++pos)
    {
        sorted_iterators.push_back (pos);
    }
    std::sort (sorted_iterators.begin(), sorted_iterators.end(), CategoryMapIteratorSortCriterion);

    const size_t count = sorted_iterators.size();
    for (size_t i=0; i<count; ++i)
    {
        const double timer_nsec = sorted_iterators[i]->second;
        s->Printf("%.9f sec for %s\n", timer_nsec / 1000000000.0, sorted_iterators[i]->first);
    }
}