text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<project basedir="." default="all" name="org.yafra.server.openejb">

    <condition property="drive" value="C:/" else="/">
        <os family="windows" />
    </condition>

	<property environment="env"/>
	<property name="projname" value="org.yafra.server.ejb-openejb" />

	<property name="yafraver" value="${env.YAFRAVER}" />
	<property name="yafrarel" value="${env.YAFRAREL}" />
	<property name="workdir" value="${drive}work" />
	<property name="wsdir" value="${env.JAVANODE}" />

	<property name="prg.dir" value="${wsdir}/${projname}" />
	<property name="prg.src" value="${prg.dir}/ejbModule" />
	<property name="build.dir" value="${env.WORKNODE}/java/${projname}" />
	<property name="deploy.dir" value="${workdir}/classes" />
	<property name="cp.dir" value="${workdir}/classes" />

	<property name="ejbjar" value="${deploy.dir}/org.yafra.server.ejb.jar" />
	<property name="ejbstubsjar" value="${deploy.dir}/org.yafra.server.ejbstubs.jar" />
	<property name="ejbear" value="${deploy.dir}/org.yafra.server.ear-openejb.ear" />

	<property name="temp.dir" value="${build.dir}/deploy" />
	<property name="temp.ear" value="${temp.dir}/ear" />
    <property name="temp.ejb" value="${temp.dir}/ejbjar" />
    <property name="temp.ejbstubs" value="${temp.dir}/ejbstubs" />
	<property name="temp.libs" value="${temp.dir}/libs" />
	<property name="temp.classes" value="${temp.dir}/classes" />

    <property name="debuglevel" value="source,lines,vars"/>
    <property name="target" value="1.7"/>
    <property name="source" value="1.7"/>
    <path id="Apache Tomcat v7.0 [Apache Tomcat v7.0].libraryclasspath">
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/openejb-ejbd-4.5.2.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/tomcat-util.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/xbean-finder-shaded-3.12.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/openjpa-asm-shaded-2.2.0.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/openejb-hsql-4.5.2.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/geronimo-transaction-3.1.1.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/slf4j-jdk14-1.7.2.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/openejb-jstl-1.2.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/tomee-mojarra-1.5.2.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/commons-collections-3.2.1.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/jasper.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/jasper-el.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/openwebbeans-spi-1.1.8.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/javaee-api-6.0-5-tomcat.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/openejb-loader-4.5.2.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/openejb-javaagent.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/tomcat-jdbc.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/bval-jsr303-0.5.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/catalina-ant.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/openejb-http-4.5.2.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/tomee-jdbc-1.5.2.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/commons-logging-1.1.1.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/commons-lang3-3.1.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/commons-codec-1.7.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/commons-beanutils-core-1.8.3.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/openejb-api-4.5.2.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/tomcat-coyote.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/bval-core-0.5.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/hsqldb-2.2.8.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/swizzle-stream-1.6.1.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/openejb-jpa-integration-4.5.2.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/openwebbeans-ee-common-1.1.8.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/myfaces-impl-2.1.10.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/commons-cli-1.2.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/tomcat-api.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/xbean-naming-3.12.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/tomee-catalina-1.5.2.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/tomcat-dbcp.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/tomee-loader-1.5.2.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/openwebbeans-ee-1.1.8.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/tomcat-i18n-fr.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/xbean-bundleutils-3.12.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/quartz-2.1.6.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/tomcat-i18n-es.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/tomee-webapp-1.5.2.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/tomee-myfaces-1.5.2.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/jaxb-impl.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/tomcat-i18n-ja.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/geronimo-javamail_1.4_mail-1.8.2.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/tomee-common-1.5.2.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/openejb-core-4.5.2.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/catalina.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/openwebbeans-impl-1.1.8.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/mbean-annotation-api-4.5.2.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/slf4j-api-1.7.2.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/commons-dbcp-1.4.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/xbean-reflect-3.12.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/commons-digester-1.8.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/xbean-asm-shaded-3.12.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/commons-lang-2.6.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/javassist-3.17.1-GA.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/servlet-api.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/wsdl4j-1.6.2.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/openejb-server-4.5.2.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/serp-1.13.1.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/myfaces-api-2.1.10.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/catalina-ha.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/howl-1.0.1-1.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/commons-pool-1.5.7.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/jsp-api.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/openwebbeans-web-1.1.8.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/openwebbeans-ejb-1.1.8.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/ecj-4.2.1.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/catalina-tribes.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/openejb-client-4.5.2.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/openejb-jee-4.5.2.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/jansi-1.8.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/openwebbeans-jsf-1.1.8.jar"/>
        <pathelement location="../../../../apache-tomee-webprofile-1.5.2/lib/gson-2.1.jar"/>
    </path>
    <filelist id="depjars" dir="${cp.dir}">
        <file name="${cp.dir}/derbyclient.jar"/>
        <file name="${cp.dir}/mysql-connector-java-5.1.21-bin.jar"/>

    	<file name="${cp.dir}/cayenne-server-3.0.2.jar" />
        <file name="${cp.dir}/ashwood-2.0.jar"/>
        <file name="${cp.dir}/commons-collections-3.2.1.jar"/>
        <file name="${cp.dir}/commons-logging-1.1.1.jar"/>
         <file name="${cp.dir}/vpp-2.2.1.jar"/>
        <file name="${cp.dir}/log4j-1.2.17.jar"/>
        <file name="${cp.dir}/org.yafra.utils.jar"/>
        <file name="${cp.dir}/org.yafra.server.core.jar"/>
    </filelist>
    <path id="pathdepjars">
    	<filelist refid="depjars" />
    </path>
    <path id="org.yafra.server.ejb-openejb.classpath">
        <pathelement location="${build.dir}"/>
        <path refid="pathdepjars"/>
        <path refid="Apache Tomcat v7.0 [Apache Tomcat v7.0].libraryclasspath"/>
    </path>

	<target name="all" description="make ejb libs"
		depends="clean, init, ejbear, ejbstub">
	</target>

	<target name="clean">
		<delete file="${ejbjar}" />
		<delete file="${ejbear}" />
		<delete file="${ejbstubsjar}" />
		<delete dir="${build.dir}"/>
		<delete dir="${temp.dir}"/>
	</target>

	<target name="init">
        <echo message="yafra ejb build.xml - ejb init"/>
    	<echo message="${os.name}"/>
		<buildnumber />
		<tstamp />
		<mkdir dir="${build.dir}"/>
        <mkdir dir="${temp.dir}"/>
        <mkdir dir="${temp.libs}/"/>
        <mkdir dir="${temp.classes}/"/>
        <mkdir dir="${temp.ear}/"/>
        <mkdir dir="${temp.ejb}/"/>
        <mkdir dir="${temp.ejbstubs}/"/>
    </target>

	<target name="ejbbuild" depends="init" description="Build ejb server">
        <echo message="yafra ejb build.xml - build server ejb"/>
        <javac debug="true" debuglevel="${debuglevel}" destdir="${temp.classes}" source="${source}" target="${target}">
            <src path="${prg.src}"/>
            <classpath refid="org.yafra.server.ejb-openejb.classpath"/>
        </javac>
    </target>

	<target name="ejbjar" description="build.xml - do ejb server jar" depends="ejbbuild">
        <echo message="yafra ejb build.xml - do ejb server jar"/>
		<copy todir="${temp.ejb}/org/yafra/server">
		    <fileset dir="${temp.classes}/org/yafra/server"/>
		</copy>
		<copy file="${prg.src}/log4j.properties" todir="${temp.ejb}"/>
		<copy todir="${temp.ejb}/META-INF">
		    <fileset dir="${prg.src}/META-INF"/>
		</copy>
		<jar jarfile="${ejbjar}" basedir="${temp.ejb}">
			<manifest>
				<attribute name="Author" value="${user.name}" />

					<attribute name="Title" value="org.yafra.server.ejbclient" />
					<attribute name="Vendor" value="yafra.org" />
					<attribute name="Build" value="${build.number}" />
					<attribute name="Date" value="${TODAY}" />
					<attribute name="Version" value="${yafraver}${yafrarel}" />

					<attribute name="Copy" value="(C) yafra.org 2010" />

			</manifest>
		</jar>
	</target>

	<target name="ejbear" depends="ejbbuild, ejbjar">
        <echo message="yafra ejb build.xml - copy jars to distribution lib"/>
		<copy todir="${temp.ear}/lib">
			<filelist refid="depjars"/>
	      </copy>
		<copy file="${ejbjar}" todir="${temp.ear}"/>
		<ear destfile="${ejbear}" appxml="${prg.dir}/application.xml" basedir="${temp.ear}">
			<manifest>
				<attribute name="Author" value="${user.name}" />
				<attribute name="Class-Path" value="org.yafra.server.ejb.jar" />

					<attribute name="Title" value="org.yafra.server.ejb ear" />
					<attribute name="Vendor" value="yafra.org" />
					<attribute name="Build" value="${build.number}" />
					<attribute name="Date" value="${TODAY}" />
					<attribute name="Version" value="${yafraver}${yafrarel}" />
					<attribute name="Copy" value="yafra.org 2010" />

			</manifest>
		</ear>
	</target>

	<target name="ejbstub" description="build.xml - do ejb stubs jar" depends="ejbbuild">
        <echo message="yafra ejb build.xml - do ejb stubs jar"/>
		<copy todir="${temp.ejbstubs}/org/yafra/server/ejbRemote">
		    <fileset dir="${temp.classes}/org/yafra/server/ejbRemote"/>
		</copy>
		<copy file="${prg.src}/log4j.properties" todir="${temp.ejbstubs}"/>
		<jar jarfile="${ejbstubsjar}" basedir="${temp.ejbstubs}">
			<manifest>
				<attribute name="Author" value="${user.name}" />

					<attribute name="Title" value="org.yafra.server.ejbclient" />
					<attribute name="Vendor" value="yafra.org" />
					<attribute name="Build" value="${build.number}" />
					<attribute name="Date" value="${TODAY}" />
					<attribute name="Version" value="${yafraver}${yafrarel}" />

					<attribute name="Copy" value="(C) yafra.org 2010" />

			</manifest>
		</jar>
	</target>

</project>


text:
package erogenousbeef.bigreactors.common.multiblock.helpers;

import io.netty.buffer.ByteBuf;
import net.minecraft.nbt.NBTTagCompound;
import cpw.mods.fml.common.network.ByteBufUtils;
import erogenousbeef.bigreactors.api.registry.Reactants;
import erogenousbeef.bigreactors.common.BRLog;
import erogenousbeef.bigreactors.common.data.ReactantStack;
import erogenousbeef.bigreactors.common.multiblock.interfaces.IConditionalUpdater;

/**
 * A helper class which allows multiple reactants to sit in one logical
 * container. It acts basically like a single tank containing multiple things,
 * and limiting the amount of stuff which can go into it based on the total
 * amount of stuff contained.
 *
 * @author Erogenous Beef
 */
public abstract class ReactantContainer implements IConditionalUpdater {

	private ReactantStack[] tanks;
	private int capacity;
	private String[] tankNames;

	private int ticksSinceLastUpdate;
	private static final int minimumTicksBetweenUpdates = 60;
	private static final float minimumDevianceForUpdate = 0.05f; // at least 5% difference before we send a fueling update to the client

	int[] levelAtLastUpdate;

	private static final int FORCE_UPDATE = -1000;

	public ReactantContainer(String[] tankNames, int capacity) {
		assert(tankNames != null);
		assert(tankNames.length > 0);

		this.tankNames = tankNames;
		tanks = new ReactantStack[tankNames.length];
		levelAtLastUpdate = new int[tankNames.length];

		for(int i = 0; i < tanks.length; i++) {
			tanks[i] = null;
			levelAtLastUpdate[i] = FORCE_UPDATE;
		}

		this.capacity = capacity;
	}

	public int getCapacity() { return capacity; }

	public void setCapacity(int newCapacity) {
		int oldCapacity = capacity;
		capacity = newCapacity;

		clampContentsToCapacity();
	}

	/// GETTERS
	public String getReactantType(int reactantIdx) {
		assert(reactantIdx >= 0 && reactantIdx < tanks.length);
		return tanks[reactantIdx] == null ? null : tanks[reactantIdx].getName();
	}

	public int getReactantAmount(int reactantIdx) {
		assert(reactantIdx >= 0 && reactantIdx < tanks.length);
		return tanks[reactantIdx] == null ? 0 : tanks[reactantIdx].amount;
	}

	/**
	 * @return Total amount of stuff contained, across all fluid tanks
	 */
	public int getTotalAmount() {
		int amt = 0;
		for(int i = 0; i < tanks.length; i++) {
			amt += getReactantAmount(i);
		}
		return amt;
	}

	/// SETTERS
	public void setReactant(int reactantIdx, ReactantStack newStack ) {
		assert(reactantIdx >= 0 && reactantIdx < tanks.length);
		tanks[reactantIdx] = newStack;
	}

	/// ADD/REMOVE HELPERS
	protected int addToStack(int idx, int fluidAmount) {
		if(tanks[idx] == null) {
			throw new IllegalArgumentException("Cannot add reactant with only an integer when tank is empty!");
		}

		int amtToAdd = Math.min(fluidAmount, getRemainingSpace());

		tanks[idx].amount += amtToAdd;
		return amtToAdd;
	}

	public int fill(int idx, String reactantName, int amount, boolean doFill) {
		assert(idx >= 0 && idx < tanks.length);
		if(reactantName == null || amount <= 0) {
			return 0;
		}

		if(!canAddToStack(idx, reactantName)) {
			return 0;
		}

		int amtToAdd = Math.min(amount, getRemainingSpace());
		if(amtToAdd <= 0) {
			return 0;
		}
		if(!doFill) {
			return amtToAdd;
		}

		if(tanks[idx] == null) {
			tanks[idx] = new ReactantStack(reactantName, amtToAdd);
		}
		else {
			tanks[idx].amount += amtToAdd;
		}

		return amtToAdd;
	}

	/**
	 * Dump everything in a given reactant tank.
	 * @param idx Index of the tank to dump
	 */
	public int dump(int idx) {
		assert(idx >= 0 && idx < tanks.length);

		int amt = tanks[idx] != null ? tanks[idx].amount : 0;
		setReactant(idx, null);

		return amt;
	}

	/**
	 * Remove some amount of reactant, but don't bother returning it.
	 * We're just dumping it into the ether.
	 * @param idx Index of the tank to dump from
	 * @param amount Maximum amount to dump
	 */
	public int dump(int idx, int amount) {
		assert(idx >= 0 && idx < tanks.length);
		if(tanks[idx] != null) {
			if(tanks[idx].amount <= amount) {
				amount = tanks[idx].amount;
				setReactant(idx, null);
			}
			else {
				tanks[idx].amount -= amount;
			}
			return amount;
		}
		else {
			return 0;
		}
	}

	/// VALIDATION HELPERS
	protected abstract boolean isReactantValidForStack(int stackIdx, String reactant);

	protected boolean canAddToStack(int idx, String incoming) {
		if(idx < 0 || idx >= tanks.length || incoming == null) { return false; }
		else if(tanks[idx] == null) {
			return isReactantValidForStack(idx, incoming);
		}
		return tanks[idx].isReactantEqual(incoming);
	}

	public boolean canDrain(int idx, ReactantStack reactant) {
		if(reactant == null || idx < 0 || idx >= tanks.length) { return false; }

		if(tanks[idx] == null) { return false; }

		return tanks[idx].isReactantEqual(reactant) && tanks[idx].amount > 0;
	}

	/// SAVE/LOAD

	protected NBTTagCompound writeToNBT(NBTTagCompound destination) {
		ReactantStack stack;
		for(int i = 0; i < tankNames.length; i++) {
			stack = tanks[i];
			if(stack != null) {
				destination.setTag(tankNames[i], stack.writeToNBT(new NBTTagCompound()));
			}
		}

		return destination;
	}

	protected void readFromNBT(NBTTagCompound data) {
		for(int i = 0; i < tankNames.length; i++) {
			if(data.hasKey(tankNames[i])) {
				tanks[i] = ReactantStack.createFromNBT(data.getCompoundTag(tankNames[i]));
				levelAtLastUpdate[i] = tanks[i] != null ? tanks[i].amount : FORCE_UPDATE;
			}
			else {
				tanks[i] = null;
				levelAtLastUpdate[i] = FORCE_UPDATE;
			}
		}
	}

	public void serialize(ByteBuf buffer) {
		buffer.writeInt(capacity);
		for(int i = 0; i < tankNames.length; i++) {
			boolean hasReactant = getReactantAmount(i) > 0;
			buffer.writeBoolean(hasReactant);
			if(hasReactant) {
				ByteBufUtils.writeUTF8String(buffer, tanks[i].getName());
				buffer.writeInt(tanks[i].amount);
			}
		}
	}

	public void deserialize(ByteBuf buffer) {
		capacity = buffer.readInt();
		for(int i = 0; i < tankNames.length; i++) {
			tanks[i] = null;

			boolean hasReactant = buffer.readBoolean();
			if(hasReactant) {
				String reactantName = ByteBufUtils.readUTF8String(buffer);
				int amount = buffer.readInt();

				if(!Reactants.isKnown(reactantName)) {
					BRLog.warning("Read an unknown reactant <%s> from a network message; tank %s will remain empty", reactantName, tankNames[i]);
				}
				else {
					tanks[i] = new ReactantStack(reactantName, amount);
					levelAtLastUpdate[i] = amount;
				}
			}
		}
	}

	/// MULTIBLOCK HELPERS
	protected void merge(ReactantContainer other) {
		if(other.capacity > capacity) {
			capacity = other.capacity;
			tanks = other.tanks;
		}
	}

	/// Implementation: IConditionalUpdater
	public boolean shouldUpdate() {
		ticksSinceLastUpdate++;

		if(minimumTicksBetweenUpdates < ticksSinceLastUpdate) {
			int dev = 0;
			boolean shouldUpdate = false;
			for(int i = 0; i < tanks.length && !shouldUpdate; i++) {

				if(tanks[i] == null && levelAtLastUpdate[i] > 0) {
					shouldUpdate = true;
				}
				else if(tanks[i] != null) {
					if(levelAtLastUpdate[i] == FORCE_UPDATE) {
						shouldUpdate = true;
					}
					else {
						dev += Math.abs(tanks[i].amount - levelAtLastUpdate[i]);
					}
				}
				// else, both levels are zero, no-op

				float divisor = capacity;
				if(divisor == 0) { divisor = 4000; } // totally arbitrary 4kmb
				if(((float)dev/divisor) >= minimumDevianceForUpdate) {
					// Only update if we're more than 5% off our current amount
					shouldUpdate = true;
				}
			}

			if(shouldUpdate) {
				resetLastSeenLevels();
			}

			ticksSinceLastUpdate = 0;
			return shouldUpdate;
		}

		return false;
	}

	/// DATA HELPERS
	protected void resetLastSeenLevels() {
		for(int i = 0; i < tanks.length; i++) {
			if(tanks[i] == null) {
				levelAtLastUpdate[i] = 0;
			}
			else {
				levelAtLastUpdate[i] = tanks[i].amount;
			}
		}
	}

	/**
	 * @return The amount of space remaining in the container.
	 */
	public int getRemainingSpace() {
		return getCapacity() - getTotalAmount();
	}

	/**
	 * When a container is overfilled, forcibly "spill" some reactants
	 * to return to a non-overfull state.
	 * This is most often useful when dealing with machine merges.
	 */
	protected void clampContentsToCapacity() {
		if(getTotalAmount() > capacity) {
			int diff = getTotalAmount() - capacity;

			// Reduce stuff in the tanks. Start with waste, to be nice to players.
			for(int i = tanks.length - 1; i >= 0 && diff > 0; i--) {
				if(tanks[i] != null) {
					if(diff > tanks[i].amount) {
						diff -= tanks[i].amount;
						tanks[i] = null;
					}
					else {
						tanks[i].amount -= diff;
						diff = 0;
					}
				}
			}
		}
	}

	public String getDebugInfo() {
		StringBuilder sb = new StringBuilder();
		sb.append("Capacity: ").append(Integer.toString(getCapacity()));
		for(int i = 0; i < tanks.length; i++) {
			sb.append("[").append(Integer.toString(i)).append("] ").append(tankNames[i]).append(": ");
			if(tanks[i] == null) {
				sb.append("NULL");
			}
			else {
				sb.append(tanks[i].toString());
			}
			sb.append("\n");
		}
		return sb.toString();
	}
}

redpajama_set_name: RedPajamaGithub


text:
package ai.elimu.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * Stores information about where website visitors are coming from.
 */
public class CookieHelper {

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

    public static String getReferrer(HttpServletRequest request) {
        String referrer = null;
        for (Cookie cookie : request.getCookies()) {
            if ("referrerElimuAi".equals(cookie.getName())) {
                referrer = cookie.getValue();
                logger.info("referrer: " + referrer);
            }
        }
        return referrer;
    }

    public static void storeRefererCookie(HttpServletResponse response, String referrer)  {
        if (referrer.length() > 1000) {
            referrer = referrer.substring(0, 1000);
        }
        logger.info("Storing cookie 'referrerElimuAi': " + referrer);
        Cookie cookie = new Cookie("referrerElimuAi", referrer);
        cookie.setDomain(".elimu.ai");
        cookie.setPath("/");
        cookie.setMaxAge(60 * 60 * 24 * 30 * 8); // 6 months
        response.addCookie(cookie);
    }

    public static String getUtmSource(HttpServletRequest request) {
        String utmSource = null;
        for (Cookie cookie : request.getCookies()) {
            if ("utmSourceElimuAi".equals(cookie.getName())) {
                utmSource = cookie.getValue();
                logger.info("utmSource: " + utmSource);
            }
        }
        return utmSource;
    }

    public static void storeSourceCookie(HttpServletResponse response, String value)  {
        logger.info("Storing cookie 'utmSourceElimuAi': " + value);
        Cookie cookie = new Cookie("utmSourceElimuAi", value);
        cookie.setDomain(".elimu.ai");
        cookie.setPath("/");
        cookie.setMaxAge(60 * 60 * 24 * 30 * 8); // 6 months
        response.addCookie(cookie);
    }

    public static String getUtmMedium(HttpServletRequest request) {
        String utmMedium = null;
        for (Cookie cookie : request.getCookies()) {
            if ("utmMediumElimuAi".equals(cookie.getName())) {
                utmMedium = cookie.getValue();
                logger.info("utmMedium: " + utmMedium);
            }
        }
        return utmMedium;
    }

    public static void storeMediumCookie(HttpServletResponse response, String value)  {
        logger.info("Storing cookie 'utmMediumElimuAi': " + value);
        Cookie cookie = new Cookie("utmMediumElimuAi", value);
        cookie.setDomain(".elimu.ai");
        cookie.setPath("/");
        cookie.setMaxAge(60 * 60 * 24 * 30 * 8); // 6 months
        response.addCookie(cookie);
    }

    public static String getUtmCampaign(HttpServletRequest request) {
        String utmCampaign = null;
        for (Cookie cookie : request.getCookies()) {
            if ("utmCampaignElimuAi".equals(cookie.getName())) {
                utmCampaign = cookie.getValue();
                logger.info("utmCampaign: " + utmCampaign);
            }
        }
        return utmCampaign;
    }

    public static void storeCampaignCookie(HttpServletResponse response, String value)  {
        logger.info("Storing cookie 'utmCampaignElimuAi': " + value);
        Cookie cookie = new Cookie("utmCampaignElimuAi", value);
        cookie.setDomain(".elimu.ai");
        cookie.setPath("/");
        cookie.setMaxAge(60 * 60 * 24 * 30 * 8); // 6 months
        response.addCookie(cookie);
    }

    public static String getUtmTerm(HttpServletRequest request) {
        String utmTerm = null;
        for (Cookie cookie : request.getCookies()) {
            if ("utmTermElimuAi".equals(cookie.getName())) {
                utmTerm = cookie.getValue();
                logger.info("utmTerm: " + utmTerm);
            }
        }
        return utmTerm;
    }

    public static void storeTermCookie(HttpServletResponse response, String value)  {
        logger.info("Storing cookie 'utmTermElimuAi': " + value);
        Cookie cookie = new Cookie("utmTermElimuAi", value);
        cookie.setDomain(".elimu.ai");
        cookie.setPath("/");
        cookie.setMaxAge(60 * 60 * 24 * 30 * 8); // 6 months
        response.addCookie(cookie);
    }

    public static Long getReferralId(HttpServletRequest request) {
        Long referralId = null;
        for (Cookie cookie : request.getCookies()) {
            if ("referralIdElimuAi".equals(cookie.getName())) {
                referralId = Long.valueOf(cookie.getValue());
                logger.info("referralId: " + referralId);
            }
        }
        return referralId;
    }

    public static void storeIdCookie(HttpServletResponse response, String value)  {
        logger.info("Storing cookie 'referralIdElimuAi': " + value);
        Cookie cookie = new Cookie("referralIdElimuAi", value);
        cookie.setDomain(".elimu.ai");
        cookie.setPath("/");
        cookie.setMaxAge(60 * 60 * 24 * 30 * 8); // 6 months
        response.addCookie(cookie);
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Ann. Bot. , Lond. 15: 333 (1901)

#### Original name
Eurotium microsporum Massee & E.S. Salmon, 1901

### Remarks
null


text:
A cross-browser `Blob` that falls back to `BlobBuilder` when appropriate.
If neither is available, it exports `undefined`.

## Installation

``` bash
$ npm install blob
```

## Example

``` js
var Blob = require('blob');
var b = new Blob(['hi', 'constructing', 'a', 'blob']);
```

## License

MIT


text:
'use strict';

// MODULES //

var tape = require( 'tape' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var ind2sub = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.strictEqual( typeof ind2sub, 'function', 'main export is a function' );
	t.end();
});

tape( 'attached to the main export is a method for assigning results to a specified output array', function test( t ) {
	t.strictEqual( hasOwnProp( ind2sub, 'assign' ), true, 'has property' );
	t.strictEqual( typeof ind2sub.assign, 'function', 'has method' );
	t.end();
});


text:
package simpledynamodb

import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient
import com.amazonaws.services.dynamodbv2.model.{AttributeValue, QueryRequest, QueryResult}
import org.specs2.mutable._
import scala.concurrent.duration._
import scala.concurrent.Await

class DynamoDbSpec extends Specification {

  "DynamoDB Query" should {
    "parse string results correctly" in {
      val results = new DynamoDbTable("name", "key", "range", new MockDynamoDbClient()).query("query").perform
      Await.result(results, new DurationInt(100).milliseconds).toList(0)("string").value mustEqual "a string"
    }
    "parse list results correctly" in {
      val results = new DynamoDbTable("name", "key", "range", new MockDynamoDbClient()).query("query").perform
      Await.result(results, new DurationInt(100).milliseconds).toList(0)("list").value mustEqual List("a string", "another string")
    }
  }
}

class MockDynamoDbClient extends AmazonDynamoDBClient {

  import collection.JavaConverters._

  override def query(request: QueryRequest): QueryResult = {
    val result = new QueryResult()
    val items = List(Map("string" -> stringValue("a string"), "list" -> listValue(List("a string", "another string"))).asJava).asJavaCollection
    result.setItems(items)
    result
  }

  def stringValue(x: String) = {
    val value = new AttributeValue()
    value.setS(x)
    value
  }

  def listValue(x: List[String]) = {
    val value = new AttributeValue()
    value.setSS(x.asJava)
    value
  }
}


text:
Credits
-------

* Flag icons provided by [http://entodorm.deviantart.com/art/Flag-s-Pack-193310959](http://entodorm.deviantart.com/art/Flag-s-Pack-193310959)


text:
from nova.virt.baremetal import driver

BareMetalDriver = driver.BareMetalDriver


text:
// LICENSE
package com.forgedui.editor.edit.policy;

import org.eclipse.gef.EditPolicy;

/**
 * @author Dmitry {dmitry.grimm@gmail.com}
 *
 */
public class ChangeConstraintEditPolicy extends
		AbstractConstrainedLayoutEditPolicy {

	public static final String KEY = EditPolicy.LAYOUT_ROLE;

//	/* (non-Javadoc)
//	 * @see ConstrainedLayoutEditPolicy#createChangeConstraintCommand(ChangeBoundsRequest, EditPart, Object)
//	 */
//	protected Command createChangeConstraintCommand(ChangeBoundsRequest request,
//			EditPart child, Object constraint) {
//		if (child instanceof ElementEditPart && constraint instanceof Rectangle
//				&& !(child instanceof ScreenEditPart)
//				&& !(child instanceof WindowEditPart)
//				&& !(child instanceof TitleBarEditPart)) {
//			// return a command that can move and/or resize a Element
//			return new MoveResizeElementCommand(
//					(Element) child.getModel(), request, (Rectangle) constraint);
//		}
//		return super.createChangeConstraintCommand(request, child, constraint);
//	}

}


text:
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="
          http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2
          http://maven.apache.org/xsd/assembly-1.1.2.xsd">
    <id>distribution</id>
    <formats>
        <format>zip</format>
        <format>tar.gz</format>
    </formats>
    <includeBaseDirectory>true</includeBaseDirectory>
    <fileSets>
        <!-- our dependencies -->
        <fileSet>
            <outputDirectory>lib/</outputDirectory>
            <directory>target/lib</directory>
        </fileSet>
        <!-- our jar -->
        <fileSet>
            <directory>target</directory>
            <outputDirectory>.</outputDirectory>
            <includes>
                <include>slack-hello-world.jar</include>
            </includes>
        </fileSet>
    </fileSets>
</assembly>


text:
require('@jymfony/autoloader');
require('./index.js');

const Debug = Jymfony.Component.Debug.Debug;
const Runner = Jymfony.Component.Testing.Framework.Runner;
Debug.enable();

new Runner().run();


text:
package com.flowpowered.engine.util.math;

import com.flowpowered.api.geo.discrete.Point;
import com.flowpowered.api.geo.discrete.Transform;
import com.flowpowered.api.geo.reference.WorldReference;
import com.flowpowered.math.imaginary.Quaternionf;
import com.flowpowered.math.vector.Vector3f;

public class ReactConverter {
    //Flow -> React
    public static org.spout.physics.math.Vector3 toReactVector3(final Vector3f flowVector3) {
        return new org.spout.physics.math.Vector3(flowVector3.getX(), flowVector3.getY(), flowVector3.getZ());
    }

    public static org.spout.physics.math.Vector3 toReactVector3(final float x, final float y, final float z) {
        return new org.spout.physics.math.Vector3(x, y, z);
    }

    public static org.spout.physics.math.Quaternion toReactQuaternion(final Quaternionf flowQuaternion) {
        return new org.spout.physics.math.Quaternion(flowQuaternion.getX(), flowQuaternion.getY(), flowQuaternion.getZ(), flowQuaternion.getW());
    }

    public static org.spout.physics.math.Quaternion toReactQuaternion(final float w, final float x, final float y, final float z) {
        return new org.spout.physics.math.Quaternion(x, y, z, w);
    }

    public static org.spout.physics.math.Transform toReactTransform(final Transform flowTransform) {
        return new org.spout.physics.math.Transform(toReactVector3(flowTransform.getPosition().getVector()), toReactQuaternion(flowTransform.getRotation()));
    }

    //React -> Flow
    public static Vector3f toFlowVector3(final org.spout.physics.math.Vector3 reactVector3) {
        return new Vector3f(reactVector3.getX(), reactVector3.getY(), reactVector3.getZ());
    }

    public static Quaternionf toFlowQuaternion(final org.spout.physics.math.Quaternion reactQuaternion) {
        return new Quaternionf(reactQuaternion.getX(), reactQuaternion.getY(), reactQuaternion.getZ(), reactQuaternion.getW());
    }

    public static Transform toFlowTransform(final org.spout.physics.math.Transform reactTransform, final WorldReference world, final Vector3f scale) {
        return new Transform(new Point(world, toFlowVector3(reactTransform.getPosition())), new Quaternionf(toFlowQuaternion(reactTransform.getOrientation())), scale);
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

module AnagramGameUtilitiesTest {
    requires anagram.util;
}


text:
'use strict';

const EventEmitter = require('../vendor/emitter/EventEmitter');
const NativeEventEmitter = require('../EventEmitter/NativeEventEmitter');

const invariant = require('invariant');
const logError = require('../Utilities/logError');

import NativeAppState from './NativeAppState';

/**
 * `AppState` can tell you if the app is in the foreground or background,
 * and notify you when the state changes.
 *
 * See https://reactnative.dev/docs/appstate.html
 */
class AppState extends NativeEventEmitter {
  _eventHandlers: Object;
  _supportedEvents = ['change', 'memoryWarning', 'blur', 'focus'];
  currentState: ?string;
  isAvailable: boolean;

  constructor() {
    super(NativeAppState);

    this.isAvailable = true;
    this._eventHandlers = this._supportedEvents.reduce((handlers, key) => {
      handlers[key] = new Map();
      return handlers;
    }, {});

    this.currentState = NativeAppState.getConstants().initialAppState;

    let eventUpdated = false;

    // TODO: this is a terrible solution - in order to ensure `currentState`
    // prop is up to date, we have to register an observer that updates it
    // whenever the state changes, even if nobody cares. We should just
    // deprecate the `currentState` property and get rid of this.
    this.addListener('appStateDidChange', appStateData => {
      eventUpdated = true;
      this.currentState = appStateData.app_state;
    });

    // TODO: see above - this request just populates the value of `currentState`
    // when the module is first initialized. Would be better to get rid of the
    // prop and expose `getCurrentAppState` method directly.
    NativeAppState.getCurrentAppState(appStateData => {
      // It's possible that the state will have changed here & listeners need to be notified
      if (!eventUpdated && this.currentState !== appStateData.app_state) {
        this.currentState = appStateData.app_state;
        this.emit('appStateDidChange', appStateData);
      }
    }, logError);
  }

  // TODO: now that AppState is a subclass of NativeEventEmitter, we could
  // deprecate `addEventListener` and `removeEventListener` and just use
  // addListener` and `listener.remove()` directly. That will be a breaking
  // change though, as both the method and event names are different
  // (addListener events are currently required to be globally unique).
  /**
   * Add a handler to AppState changes by listening to the `change` event type
   * and providing the handler.
   *
   * See https://reactnative.dev/docs/appstate.html#addeventlistener
   */
  addEventListener(type: string, handler: Function) {
    invariant(
      this._supportedEvents.indexOf(type) !== -1,
      'Trying to subscribe to unknown event: "%s"',
      type,
    );

    switch (type) {
      case 'change': {
        this._eventHandlers[type].set(
          handler,
          this.addListener('appStateDidChange', appStateData => {
            handler(appStateData.app_state);
          }),
        );
        break;
      }
      case 'memoryWarning': {
        this._eventHandlers[type].set(
          handler,
          this.addListener('memoryWarning', handler),
        );
        break;
      }

      case 'blur':
      case 'focus': {
        this._eventHandlers[type].set(
          handler,
          this.addListener('appStateFocusChange', hasFocus => {
            if (type === 'blur' && !hasFocus) {
              handler();
            }
            if (type === 'focus' && hasFocus) {
              handler();
            }
          }),
        );
      }
    }
  }

  /**
   * Remove a handler by passing the `change` event type and the handler.
   *
   * See https://reactnative.dev/docs/appstate.html#removeeventlistener
   */
  removeEventListener(type: string, handler: Function) {
    invariant(
      this._supportedEvents.indexOf(type) !== -1,
      'Trying to remove listener for unknown event: "%s"',
      type,
    );
    if (!this._eventHandlers[type].has(handler)) {
      return;
    }
    this._eventHandlers[type].get(handler).remove();
    this._eventHandlers[type].delete(handler);
  }
}

function throwMissingNativeModule() {
  invariant(
    false,
    'Cannot use AppState module when native RCTAppState is not included in the build.\n' +
      'Either include it, or check AppState.isAvailable before calling any methods.',
  );
}

class MissingNativeAppStateShim extends EventEmitter {
  // AppState
  isAvailable: boolean = false;
  currentState: ?string = null;

  addEventListener(type: string, handler: Function) {
    throwMissingNativeModule();
  }

  removeEventListener(type: string, handler: Function) {
    throwMissingNativeModule();
  }

  // EventEmitter
  addListener() {
    throwMissingNativeModule();
  }

  removeAllListeners() {
    throwMissingNativeModule();
  }

  removeSubscription() {
    throwMissingNativeModule();
  }
}

// This module depends on the native `RCTAppState` module. If you don't include it,
// `AppState.isAvailable` will return `false`, and any method calls will throw.
// We reassign the class variable to keep the autodoc generator happy.
const AppStateInstance: AppState | MissingNativeAppStateShim = NativeAppState
  ? new AppState()
  : new MissingNativeAppStateShim();

module.exports = AppStateInstance;


text:
from __future__ import unicode_literals

from django.test import TestCase
from django.test.utils import override_settings
from django.db import connection
from .models import Auther, Book
# Create your tests here.

class TestAuthor(TestCase):
    def setUp(self):
        auth = Auther(name='zhangqian', age='23')
        auth.save()
        book = Book()
        book = Book(title='python', publisher='renmingongye')
        book.save()

    @override_settings(DEBUG=True)
    def test_filter(self):
        auth = Auther.objects.all()
        print auth
        book = Book.objects.all()
        print book
        print(connection.queries)


text:
package io.cucumber.spring;

import io.cucumber.core.backend.ObjectFactory;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;

import java.util.concurrent.atomic.AtomicInteger;

import static io.cucumber.spring.CucumberTestContext.SCOPE_CUCUMBER_GLUE;
import static org.junit.jupiter.api.Assertions.assertNotEquals;

class Issue1970 {

    @Test
    public void issue1970() {
        ObjectFactory factory = new SpringFactory();
        factory.addClass(GlueClass.class); // Add glue with Spring configuration
        factory.start();
        GlueClass instance = factory.getInstance(GlueClass.class);
        String response = instance.service.get();
        factory.stop();
        factory.start();
        GlueClass instance2 = factory.getInstance(GlueClass.class);
        String response2 = instance2.service.get();
        factory.stop();

        assertNotEquals(response, response2);
    }

    @CucumberContextConfiguration
    @ContextConfiguration(classes = TestApplicationConfiguration.class)
    public static class GlueClass {

        @Autowired
        ExampleService service;

    }

    @Configuration
    public static class TestApplicationConfiguration {

        @Bean
        public BeanFactoryPostProcessor beanFactoryPostProcessor() {
            return factory -> factory.registerScope(SCOPE_CUCUMBER_GLUE, new CucumberScenarioScope());
        }

        @Bean
        public ExampleService service(ScenarioScopedApi api) {
            return new ExampleService(api);
        }

        @Bean
        @ScenarioScope
        public ScenarioScopedApi api() {
            return new ScenarioScopedApi();
        }

    }

    public static class ExampleService {

        final ScenarioScopedApi api;

        public ExampleService(ScenarioScopedApi api) {
            this.api = api;
        }

        String get() {
            return "Api response: " + api.get();
        }
    }

    public static class ScenarioScopedApi {

        private static final AtomicInteger globalCounter = new AtomicInteger(0);
        private final int instanceId = globalCounter.getAndIncrement();

        public String get() {
            return "instance " + instanceId;
        }

    }

}


text:
@implementation PAYFormTable

- (id)init {
    self = [super init];
    if (self) {
        self.sections = [NSMutableArray new];
        __weak PAYFormTable *weakSelf = self;
        self.completionBlock = ^{
            PAYFormTable *strongSelf = weakSelf;
            if (strongSelf.finishOnLastField) {
                [strongSelf validate];
            }
        };
        self.formFailBlock = PAYFormDefaultErrorHandler.failBlock;
    }
    return self;
}

- (void)validate {
    NSError *error = [self doValidate];
    if (!error) {
        if (self.formSuccessBlock) {
            self.formSuccessBlock();
        }
    } else {
        if ((!self.formFailBlock || !self.formFailBlock(error)) && error.field) {
            [error.field styleForError:error];
        }
    }
}

- (NSError *)doValidate {
    for (PAYFormSection *section in self.sections) {
        NSError *error = [section validate];
        if (error) {
            return error;
        }
    }
    if (self.validationBlock) {
        return self.validationBlock();
    }
    return nil;
}

- (void)initSectionJumpOrder {
    PAYFormSection *previousSection;
    for (PAYFormSection *section in self.sections.reverseObjectEnumerator) {
        BOOL sectionWithActiveField = [section initFieldJumpOrderWithNextSection:previousSection];

        if (sectionWithActiveField) {
            if (!previousSection) {
                // Let last section execute the table's completion block
                __weak PAYFormTable *weakSelf = self;
                section.completionBlock = ^{
                    PAYFormTable *strongSelf = weakSelf;
                    if (strongSelf.completionBlock) {
                        strongSelf.completionBlock();
                    }
                };
            }

            previousSection = section;
        }
    }
}

@end


text:
<?php

class fabriqmodules_module extends FabriqModule {
	public function manage() {
		if (FabriqModules::module('roles')->requiresPermission('manage modules', $this->name)) {
			Fabriq::title('Admin | Manage modules');
			FabriqModules::add_js($this->name, $this->name);
			Fabriq::fabriq_ui_on();

			$modules = new Modules();
			$modules->getAll();

			// get and install any new modules
			$available = $this->scan_modules();
			$toRegister = $this->to_register($modules, $available);
			foreach ($toRegister as $register) {
				FabriqModules::register_module($register);
			}

			// update modules collection
			$modules = new Modules();
			$modules->getAll();

			FabriqModules::set_var($this->name, 'modules', $modules);
		}
	}

	public function enable() {
		Fabriq::render('none');
		header('Content-type:application/json');

		if (FabriqModules::module('roles')->hasRole('administrator')) {
			$module = new Modules(PathMap::arg(2));
			if ($module->module != '') {
				$module->enabled = 1;
				$module->update();
				echo json_encode(array('success' => true));
			} else {
				echo json_encode(array('success' => false));
			}
		} else {
			echo json_encode(array('success' => false, 'notLoggedIn' => true));
		}
	}

	public function disable() {
		Fabriq::render('none');
		header('Content-type:application/json');

		if (FabriqModules::module('roles')->hasRole('administrator')) {
			$module = new Modules(PathMap::arg(2));
			if ($module->module != '') {
				$module->enabled = 0;
				$module->update();
				echo json_encode(array('success' => true));
			} else {
				echo json_encode(array('success' => false));
			}
		} else {
			echo json_encode(array('success' => false, 'notLoggedIn' => true));
		}
	}

	public function install() {
		Fabriq::render('none');
		header('Content-type:application/json');

		if (FabriqModules::module('roles')->hasRole('administrator')) {
			$module = new Modules(PathMap::arg(2));
			if ($module->module != '') {
				$module->installed = 1;
				$module->update();
				FabriqModules::install($module->module);
				echo json_encode(array('success' => true, 'hasConfiguration' => $module->hasconfigs));
			} else {
				echo json_encode(array('success' => false));
			}
		} else {
			echo json_encode(array('success' => false, 'notLoggedIn' => true));
		}
	}

	public function uninstall() {
		Fabriq::render('none');
		header('Content-type:application/json');

		if (FabriqModules::module('roles')->hasRole('administrator')) {
			$module = new Modules(PathMap::arg(2));
			if ($module->module != '') {
				$module->installed = 0;
				$module->update();
				FabriqModules::uninstall($module->module);
				echo json_encode(array('success' => true));
			} else {
				echo json_encode(array('success' => false));
			}
		} else {
			echo json_encode(array('success' => false, 'notLoggedIn' => true));
		}
	}

	public function configure() {
		Fabriq::render('view');

		$module = new Modules(PathMap::arg(2));
		$install_file = "modules/{$module->module}/{$module->module}.install.php";
		if (file_exists('sites/' . FabriqStack::site() . "/{$install_file}")) {
			$install_file = 'sites/' . FabriqStack::site() . "/{$install_file}";
		} else if (!file_exists($install_file)) {
			throw new Exception("Module {$module->module} install file could not be found");
		}
		require_once($install_file);
		eval("\$installer = new {$module->module}_install();");
		$installer->configure();

		FabriqModules::set_var($this->name, 'module', $module);
	}

	private function scan_modules() {
		$modules = array();
		// scan the site's modules directory
		if ($handle = opendir('sites/' . FabriqStack::site() .'/modules')) {
			while (false !== ($file = readdir($handle))) {
				if ((strpos($file, '.') === FALSE) && is_dir('sites/' . FabriqStack::site() .'/modules/' . $file)) {
					$modules[] = $file;
				}
			}
			closedir($handle);
		}
		// scan the common modules directory
		if ($handle = opendir('modules')) {
			while (false !== ($file = readdir($handle))) {
				if ((strpos($file, '.') === FALSE) && is_dir('modules/' . $file)) {
					if (!in_array($file, $modules)) {
						$modules[] = $file;
					}
				}
			}
			closedir($handle);
		}
		return $modules;
	}

	private function to_register($installed, $available) {
		$toInstall = array();

		foreach ($available as $mod) {
			if (!$installed->installed($mod)) {
				$toInstall[] = $mod;
			}
		}

		return $toInstall;
	}
}


text:
% $  Id: conclusion.tex  $
% !TEX root = main.tex

\begin{abstract}
Current practices in software development are anchored in the use of version control systems to
manage the development progress of software projects. Additionally, version control systems can
be used to drive the release process of software products, by managing different variants of the main
product in a repository. Despite the benefits of versioning systems, using such systems requires
developers to interrupt their development work in order to interact with them, affecting their productivity.
This paper presents CollabIDE, a collaborative environment for
distributed development designed for automated versioning and product variant generation. The goal
of CollabIDE is to increase developers' productivity, therefore, we conducted a small empirical study with
users working in distributed teams, measuring the time to complete different tasks using versioning, and
the ease to release different products' functionality based on recorded versions.
\end{abstract}

\endinput


text:
<?php

/**
 * General utility class in Swift Mailer, not to be instantiated.
 *
 * @package Swift
 *
 * @author Chris Corbyn
 */
abstract class Swift
{

  /** Swift Mailer Version number generated during dist release process */
  const VERSION = '@SWIFT_VERSION_NUMBER@';

  /**
   * Internal autoloader for spl_autoload_register().
   *
   * @param string $class
   */
  public static function autoload($class)
  {
    //Don't interfere with other autoloaders
    if (0 !== strpos($class, 'Swift'))
    {
      return false;
    }

    $path = dirname(__FILE__).'/'.str_replace('_', '/', $class).'.php';

    if (!file_exists($path))
    {
      return false;
    }

    require_once $path;
  }

  /**
   * Configure autoloading using Swift Mailer.
   *
   * This is designed to play nicely with other autoloaders.
   */
  public static function registerAutoload()
  {
    spl_autoload_register(array('Swift', 'autoload'));
  }

}


text:
/* eslint-disable no-sync */

'use strict';

// MODULES //

var fs = require( 'fs' );

// FUNCTIONS //

var fcn;
if ( typeof fs.accessSync === 'function' ) {
	fcn = fs.accessSync;
} else {
	fcn = fs.statSync;
}

// MAIN //

/**
* Synchronously tests whether a path exists on the filesystem.
*
* @param {(string|Buffer)} path - path to test
* @returns {boolean} boolean indicating whether the path exists
*
* @example
* var bool = existsSync( __dirname );
* // returns <boolean>
*/
function existsSync( path ) {
	try {
		fcn( path );
	} catch ( err ) { // eslint-disable-line no-unused-vars
		return false;
	}
	return true;
}

// EXPORTS //

module.exports = existsSync;


text:
namespace g{namespace Fuse{namespace Android{struct Helpers;}}}
namespace g{namespace Uno{struct Float4;}}

namespace g{
namespace Fuse{
namespace Android{

// internal static class Helpers :237
// {
uClassType* Helpers_typeof();
void Helpers__EncodeColor_fn(::g::Uno::Float4* c, int* __retval);

struct Helpers : uObject
{
    static int EncodeColor(::g::Uno::Float4 c);
};
// }

}}} // ::g::Fuse::Android


text:
package com.android.services.telephony;

import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.SystemVibrator;
import android.os.Vibrator;
import android.provider.Settings;

/**
 * Plays an emergency tone when placing emergency calls on CDMA devices.
 */
class EmergencyTonePlayer {

    private static final int EMERGENCY_TONE_OFF = 0;
    private static final int EMERGENCY_TONE_ALERT = 1;
    private static final int EMERGENCY_TONE_VIBRATE = 2;

    private static final int ALERT_RELATIVE_VOLUME_PERCENT = 100;

    private static final int VIBRATE_LENGTH_MILLIS = 1000;
    private static final int VIBRATE_PAUSE_MILLIS = 1000;
    private static final long[] VIBRATE_PATTERN =
            new long[] { VIBRATE_LENGTH_MILLIS, VIBRATE_PAUSE_MILLIS};

    private static final AudioAttributes VIBRATION_ATTRIBUTES =
            new AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                .setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
                .build();

    // We don't rely on getSystemService(Context.VIBRATOR_SERVICE) to make sure that this vibrator
    // object will be isolated from others.
    private final Vibrator mVibrator = new SystemVibrator();
    private final Context mContext;
    private final AudioManager mAudioManager;

    private ToneGenerator mToneGenerator;
    private int mSavedInCallVolume;
    private boolean mIsVibrating = false;

    EmergencyTonePlayer(Context context) {
        mContext = context;
        mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    }

    public void start() {
        switch (getToneSetting()) {
            case EMERGENCY_TONE_VIBRATE:
                startVibrate();
                break;
            case EMERGENCY_TONE_ALERT:
                // Only start if we are not in silent mode.
                int ringerMode = mAudioManager.getRingerMode();
                if (ringerMode == AudioManager.RINGER_MODE_NORMAL) {
                    startAlert();
                }
                break;
            case EMERGENCY_TONE_OFF:
                // nothing;
                break;
        }
    }

    public void stop() {
        stopVibrate();
        stopAlert();
    }

    private void startVibrate() {
        if (!mIsVibrating) {
            mVibrator.vibrate(VIBRATE_PATTERN, 0, VIBRATION_ATTRIBUTES);
            mIsVibrating = true;
        }
    }

    private void stopVibrate() {
        if (mIsVibrating) {
            mVibrator.cancel();
            mIsVibrating = false;
        }
    }

    private void startAlert() {
        if (mToneGenerator == null) {
            mToneGenerator = new ToneGenerator(
                    AudioManager.STREAM_VOICE_CALL, ALERT_RELATIVE_VOLUME_PERCENT);

            // Set the volume to max and save the old volume setting.
            mSavedInCallVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
            mAudioManager.setStreamVolume(
                    AudioManager.STREAM_VOICE_CALL,
                    mAudioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL),
                    0);
            mToneGenerator.startTone(ToneGenerator.TONE_CDMA_EMERGENCY_RINGBACK);
        } else {
            Log.d(this, "An alert is already running.");
        }
    }

    private void stopAlert() {
        if (mToneGenerator != null) {
            mToneGenerator.stopTone();
            mToneGenerator.release();
            mToneGenerator = null;

            mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, mSavedInCallVolume, 0);
            mSavedInCallVolume = 0;
        }
    }

    private int getToneSetting() {
       return Settings.Global.getInt(
               mContext.getContentResolver(), Settings.Global.EMERGENCY_TONE, EMERGENCY_TONE_OFF);
    }
}


text:
'use strict';

var get = easyGet;
var set = easySet;

if (document.selection && document.selection.createRange) {
  get = hardGet;
  set = hardSet;
}

function easyGet (el) {
  return {
    start: el.selectionStart,
    end: el.selectionEnd
  };
}

function hardGet (el) {
  var active = document.activeElement;
  if (active !== el) {
    el.focus();
  }

  var range = document.selection.createRange();
  var bookmark = range.getBookmark();
  var original = el.value;
  var marker = getUniqueMarker(original);
  var parent = range.parentElement();
  if (parent === null || !inputs(parent)) {
    return result(0, 0);
  }
  range.text = marker + range.text + marker;

  var contents = el.value;

  el.value = original;
  range.moveToBookmark(bookmark);
  range.select();

  return result(contents.indexOf(marker), contents.lastIndexOf(marker) - marker.length);

  function result (start, end) {
    if (active !== el) { // don't disrupt pre-existing state
      if (active) {
        active.focus();
      } else {
        el.blur();
      }
    }
    return { start: start, end: end };
  }
}

function getUniqueMarker (contents) {
  var marker;
  do {
    marker = '@@marker.' + Math.random() * new Date();
  } while (contents.indexOf(marker) !== -1);
  return marker;
}

function inputs (el) {
  return ((el.tagName === 'INPUT' && el.type === 'text') || el.tagName === 'TEXTAREA');
}

function easySet (el, p) {
  el.selectionStart = parse(el, p.start);
  el.selectionEnd = parse(el, p.end);
}

function hardSet (el, p) {
  var range = el.createTextRange();

  if (p.start === 'end' && p.end === 'end') {
    range.collapse(false);
    range.select();
  } else {
    range.collapse(true);
    range.moveEnd('character', parse(el, p.end));
    range.moveStart('character', parse(el, p.start));
    range.select();
  }
}

function parse (el, value) {
  return value === 'end' ? el.value.length : value || 0;
}

function sell (el, p) {
  if (arguments.length === 2) {
    set(el, p);
  }
  return get(el);
}

module.exports = sell;


text:
<?php
/**
 * Created by PhpStorm.
 * User: whwyy
 * Date: 2016/5/26 0026
 * Time: 18:53
 */

require('BaseInFace.php');

class XFace extends \xface\BaseInFace
{

}
spl_autoload_register(['XFace','autoload'],true,true);
XFace::$classMap = require('classMap.php');
XFace::$container = new xface\di\Container();


text:
import Mongonaut from 'mongonaut'
import path from 'path'
import fs from 'fs-extra'
import chalk from 'chalk'
import { log, exists } from '../utils'

class Inserter {
  constructor (files, callback) {
    this.files = files
    this.cb = callback

    // Don't load this at the beginning of the file. If you do so, the session...
    // ...will start immediately when the user runs a command that loads this task
    this.rope = require('../db').default

    this.rope.on('open', function () {
      this.rope.db.listCollections().toArray(this.checkInput.bind(this))
    }.bind(this))
  }

  checkInput (err, names) {
    if (err) {
      return log(err)
    }

    let files = [],
        walkers = []

    this.collections = names.map(details => {
      return details.name
    })

    for (let thing of this.files) {
      let fullPath = path.resolve(thing),
          details = path.parse(fullPath)

      if (!exists(path.format(details))) {
        log(`The file or directory "${details.base}" doesn\'t exist`)
        this.rope.close(() => process.exit(1))
      }

      if (details.ext) {
        files.push(fullPath)
        continue
      }

      let prom = new Promise((resolve, reject) => {
        let walker = fs.walk(fullPath),
            subFiles = []

        walker.on('data', item => {
          let info = path.parse(item.path)

          if (info.ext) {
            subFiles.push(item.path)
          }
        })

        walker.on('end', () => resolve(subFiles))
        walker.on('error', reject)
      })

      walkers.push(prom)
    }

    this.rope.close()

    if (walkers.length === 0) {
      return this.tryImport(files)
    }

    Promise.all(walkers).then(function (items) {
      files = files.concat(items[0])
      this.tryImport(files)
    }.bind(this)).catch((err, item) => {
      throw err
    })
  }

  tryImport (files) {
    let imports = []

    for (let file of files) {
      let info = path.parse(file)

      // if (this.collections.indexOf(info.name) === -1) {
      //   log(`Collection "${info.name}" doesn\'t exist`)
      //   this.rope.close(() => process.exit(1))
      // }

      imports.push(this.importFile(info))
    }

    Promise.all(imports).then(function (data) {
      log(chalk.green('Successfully imported data!'))
      this.cb(data)
    }.bind(this), reason => {
      log('Not able to insert data! Make sure that your DB is running.')
    })
  }

  importFile (file) {
    let mongonaut = new Mongonaut({
      user: process.env.DB_USER || '',
      pwd: process.env.DB_PASSWORD || '',
      db: process.env.DB_NAME || 'muffin'
    })

    mongonaut.set('collection', file.name)
    return mongonaut.import(path.format(file))
  }
}

export default Inserter


text:
echo 'Starting App'
npm start


text:
#ifndef POLARSSL_HAVEGE_H
#define POLARSSL_HAVEGE_H

#include <string.h>

#define COLLECT_SIZE 1024

/**
 * \brief          HAVEGE state structure
 */
typedef struct
{
    int PT1, PT2, offset[2];
    int pool[COLLECT_SIZE];
    int WALK[8192];
}
havege_state;

#ifdef __cplusplus
extern "C" {
#endif

/**
 * \brief          HAVEGE initialization
 *
 * \param hs       HAVEGE state to be initialized
 */
void havege_init( havege_state *hs );

/**
 * \brief          HAVEGE rand function
 *
 * \param p_rng    A HAVEGE state
 * \param output   Buffer to fill
 * \param len      Length of buffer
 *
 * \return         A random int
 */
int havege_random( void *p_rng, unsigned char *output, size_t len );

#ifdef __cplusplus
}
#endif

#endif /* havege.h */


text:
package at.jku.sea.cloud.rest.client.stream.provider.implementation;

import at.jku.sea.cloud.Artifact;
import at.jku.sea.cloud.Resource;
import at.jku.sea.cloud.rest.client.stream.provider.RestProvider;
import at.jku.sea.cloud.rest.pojo.factory.PojoFactory;
import at.jku.sea.cloud.rest.pojo.stream.provider.PojoProvider;
import at.jku.sea.cloud.rest.pojo.stream.provider.PojoResourceProvider;

public class ResourceProvider extends RestProvider<Artifact> {
  private final Resource resource;

  public ResourceProvider(Resource resource) {
    this.resource = resource;
  }

  public Resource getResource() {
    return resource;
  }

  @Override
  public PojoProvider map(PojoFactory pojoFactory) {
    return new PojoResourceProvider(pojoFactory.createPojo(resource));
  }

}


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

import org.overlord.rtgov.ep.EventProcessor;

public class TestEventProcessor3 extends EventProcessor {

    public java.io.Serializable process(String source, java.io.Serializable event, int retriesLeft) throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

}


text:
{% extends "djadmin2theme_bootstrap3/base.html" %}
{% load i18n admin2_tags %}

{% block title %}{{ object }}{% endblock title %}

{% block page_title %}{{ object }}{% endblock page_title %}

{% block breadcrumbs %}

        {% trans "Home" %}

        {% firstof app_verbose_name app_label|title %}

        {{ model_name_pluralized|title }}

{{ object }}

{% endblock breadcrumbs %}

{% block content %}
    {{ object }}
{% endblock content %}


text:
$(function() {
	$('.social-no-link').removeAttr("target");
	$('.social-no-link').click(function() {
		alert("No page exists on "+$(this).attr("value")+".");
	});
});


text:
package Paws::EMR::ModifyInstanceGroups;
  use Moose;
  has ClusterId => (is => 'ro', isa => 'Str');
  has InstanceGroups => (is => 'ro', isa => 'ArrayRef[Paws::EMR::InstanceGroupModifyConfig]');

  use MooseX::ClassAttribute;

  class_has _api_call => (isa => 'Str', is => 'ro', default => 'ModifyInstanceGroups');
  class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::API::Response');
  class_has _result_key => (isa => 'Str', is => 'ro');
1;

### main pod documentation begin ###

=head1 NAME

Paws::EMR::ModifyInstanceGroups - Arguments for method ModifyInstanceGroups on Paws::EMR

=head1 DESCRIPTION

This class represents the parameters used for calling the method ModifyInstanceGroups on the
Amazon Elastic MapReduce service. Use the attributes of this class
as arguments to method ModifyInstanceGroups.

You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to ModifyInstanceGroups.

As an example:

  $service_obj->ModifyInstanceGroups(Att1 => $value1, Att2 => $value2, ...);

Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.

=head1 ATTRIBUTES

=head2 ClusterId => Str

The ID of the cluster to which the instance group belongs.

=head2 InstanceGroups => ArrayRef[L<Paws::EMR::InstanceGroupModifyConfig>]

Instance groups to change.

=head1 SEE ALSO

This class forms part of L<Paws>, documenting arguments for method ModifyInstanceGroups in L<Paws::EMR>

=head1 BUGS and CONTRIBUTIONS

The source code is located here: https://github.com/pplu/aws-sdk-perl

Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues

=cut


text:
The C++ language track requires that you have the following software
installed on your system:
* a modern C++11 compiler
* the CMake cross-platform build system
* the Boost libraries

Microsoft's Visual Studio IDE and Apple's Xcode IDEs combine the compiler
and the
native build system into a single IDE (integrated development environment).
Linux environments typically expose the compiler and native build system
as separate command-line tools.

### Prerequisite: A Modern C++11 Compiler

This language track assumes [C++11](http://en.wikipedia.org/wiki/C%2B%2B11),
the latest version of the ISO C++ standard that is
[widely supported](http://en.cppreference.com/w/cpp/compiler_support) on all
major platforms (Linux, Windows and MacOS).
[C++14](http://en.wikipedia.org/wiki/C%2B%2B14) has been recently ratified
as the most recent version of the ISO standard.  The language track will
be updated to C++14 once support is sufficiently mature in the development
environments across all major platforms.

Free compilers exist for C++11 on all major platforms, although the version
of the C++ compiler installed on your system may be an older version that
doesn't fully support C++11.  A comparison chart of
[C++ compiler support](http://en.cppreference.com/w/cpp/compiler_support)
and related [discussion](http://en.cppreference.com/w/Talk:cpp/compiler_support)
shows that most of the major features of C++11 are available on all major
platforms.

#### Linux

Linux users will need gcc 4.8 or later or clang 3.4 or later for the compiler
and `make` will be needed for the native build.  Make is pre-installed on most
unix systems, but is available via `sudo apt-get install make` if not present.
Gcc 4.8 supports C++11 with the `-std=c++11` argument and can be installed and
set as the default compiler with the following recipe:

```bash
$ sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test
$ sudo apt-get -qq -d update
$ sudo apt-get -qq install g++-4.8
$ # make g++ 4.8 the default g++ executable
$ sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.8 90
```

#### MacOS

MacOS users can install gcc 4.8 with [Homebrew](http://brew.sh/) via
`brew install gcc`.

#### Windows

Windows users can get
[Visual Studio Community 2013](http://www.visualstudio.com/en-us/products/visual-studio-community-vs),
a free download that will give you the Visual Studio 2013 IDE and the
latest version of the Microsoft Visual C++ compiler.

### Prerequisite: CMake

CMake is an open source cross-platform build system that generates build
scripts for your native build system (`make`, Visual Studio, Xcode, etc.).
Exercism's C++ track uses CMake to give you a ready-made build that:

* compiles the tests
* compiles your solution
* links the test executable
* automatically runs the tests as part of every build
* fails the build if the any tests fail

Using CMake allows exercism to provide a cross-platform build script that
can generate project files for integrated development environments like
Visual Studio and Xcode.  This allows you to focus on the problem and
not worry about setting up a build for each exercise.

Getting a portable build isn't easy and requires access to many kinds of
systems.  If you encounter any problems with the supplied CMake recipe,
please [report the issue](https://github.com/exercism/xcpp/issues) so we can
improve the CMake support.

[CMake 2.8.11 or later](http://www.cmake.org/) is required to use the provided build recipe.

### Prerequisite: Boost

The unit tests use Boost.Test, the unit testing framework included with
[Boost](http://www.boost.org/index.html).  You may find other libraries
in Boost useful to you as you work through the exercises.  In particular,
gcc 4.8 does not have a proper implementation of the standard regular
expression library, but you can find a compatible library in Boost.
You will need to download and install Boost.  As of this writing Boost
1.55 is the current version.  You will need a compiled version of the
boost libraries Boost.Test, Boost.DateTime and Boost.Regex, or you will
need to download from source and build the library yourself.

If you are having difficulties installing Boost for use with exercism,
[ask for help](https://github.com/exercism/xcpp/issues).

#### Linux

Linux users can get pre-built packages with the following recipe:

```bash
$ sudo add-apt-repository -y ppa:boost-latest/ppa
$ sudo apt-get -qq -d update
$ sudo apt-get -qq install libboost1.55-all-dev
```

Note: These prepackaged Linux binaries are not compiled with gcc 4.8 and
some libraries may have issues as a result.  If a pre-built package is
unavailable for your linux distribution, try
[installing Boost from source](http://www.boost.org/doc/libs/release/more/getting_started/index.html).

#### Windows

Windows users can download compiled binaries from [sourceforge](http://sourceforge.net/projects/boost/files/boost-binaries/1.55.0-build2/).
You must download the version appropriate for your compiler.  For recent
versions of Visual Studio, the direct links are provided below:

| Compiler | Download |
|----------|----------|
| Visual Studio Express 2013 for Windows Desktop (32-bit) | [boost_1_55_0-msvc-12.0-32.exe](http://sourceforge.net/projects/boost/files/boost-binaries/1.55.0-build2/boost_1_55_0-msvc-12.0-32.exe/download) |
| Visual Studio 2013 (32-bit) | [boost_1_55_0-msvc-12.0-32.exe](http://sourceforge.net/projects/boost/files/boost-binaries/1.55.0-build2/boost_1_55_0-msvc-12.0-32.exe/download) |
| Visual Studio 2012 (32-bit) | [boost_1_55_0-msvc-11.0-32.exe](http://sourceforge.net/projects/boost/files/boost-binaries/1.55.0-build2/boost_1_55_0-msvc-11.0-32.exe/download) |
| Visual Studio 2010 (32-bit) | [boost_1_55_0-msvc-10.0-32.exe](http://sourceforge.net/projects/boost/files/boost-binaries/1.55.0-build2/boost_1_55_0-msvc-10.0-32.exe/download) |

In this table, 32-bit refers to the kind of code generated by your
compiler and not the operating system.  Code compiled for 32-bit will run
on both 32-bit and 64-bit versions of Windows.  Code compiled for 64-bit
will only run on 64-bit versions of Windows.  The CMake recipes used in
exercism create 32-bit projects for Visual Studio, so download the
appropriate 32-bit version of Boost.

Once you download the compiled binaries, install them into a suitable
location.  The installed location will contain a libraries directory
named similarly to the install executable, such as `lib32-msvc-12.0`.
Rename this directory to `lib` so that CMake can find the precompiled
libraries.  If you don't rename the directory you will see an error
like this when you run CMake:

```
> cmake -DBOOST_INCLUDEDIR:PATH=D:/tmp/boost_1_55_0 ..
-- Building for: Visual Studio 12
-- The CXX compiler identification is MSVC 18.0.30723.0
-- Check for working CXX compiler using: Visual Studio 12
-- Check for working CXX compiler using: Visual Studio 12 -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
CMake Error at C:/Program Files (x86)/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:1106 (message):
  Unable to find the requested Boost libraries.

  Boost version: 1.55.0

  Boost include path: D:/tmp/boost_1_55_0

  The following Boost libraries could not be found:

          boost_unit_test_framework
          boost_date_time
          boost_regex

  No Boost libraries were found.  You may need to set BOOST_LIBRARYDIR to the
  directory containing Boost libraries or BOOST_ROOT to the location of
  Boost.
Call Stack (most recent call first):
  CMakeLists.txt:12 (find_package)

-- Configuring incomplete, errors occurred!
```

#### MacOS

MacOS users can install boost with [Homebrew](http://brew.sh/) via
`brew install boost`.

#### Building from Source

If all else fails you can download the source and build it yourself,
but you should prefer a prebuilt distribution to make things easier.
Bootstrap instructions are on the
[Boost getting started page](http://www.boost.org/doc/libs/release/more/getting_started/index.html).


text:
A progress-tracking tool for people learning an instrument. Allows users to keep a flexible practice schedule regardless of what instrument they're learning.

## Demo

You can no longer see it in action because I currently host all of my applications on a Linux VM and My Routine can only be hosted on a Windows server.

## License

This project is licensed under the MIT License - see the [LICENSE.txt](LICENSE.txt) file for details.


text:
asynctest(
  'browser.tinymce.core.fmt.ExpandRangeTest',
  [
    'ephox.agar.api.Assertions',
    'ephox.agar.api.Chain',
    'ephox.agar.api.GeneralSteps',
    'ephox.agar.api.Logger',
    'ephox.agar.api.Pipeline',
    'ephox.mcagar.api.TinyApis',
    'ephox.mcagar.api.TinyLoader',
    'ephox.sugar.api.dom.Hierarchy',
    'ephox.sugar.api.node.Element',
    'tinymce.core.fmt.ExpandRange',
    'tinymce.themes.modern.Theme'
  ],
  function (Assertions, Chain, GeneralSteps, Logger, Pipeline, TinyApis, TinyLoader, Hierarchy, Element, ExpandRange, ModernTheme) {
    var success = arguments[arguments.length - 2];
    var failure = arguments[arguments.length - 1];

    ModernTheme();

    var cSetRawContent = function (html) {
      return Chain.op(function (editor) {
        editor.getBody().innerHTML = html;
      });
    };

    var cExpandRng = function (startPath, startOffset, endPath, endOffset, format, remove) {
      return Chain.mapper(function (editor) {
        var startContainer = Hierarchy.follow(Element.fromDom(editor.getBody()), startPath).getOrDie();
        var endContainer = Hierarchy.follow(Element.fromDom(editor.getBody()), endPath).getOrDie();

        var rng = editor.dom.createRng();
        rng.setStart(startContainer.dom(), startOffset);
        rng.setEnd(endContainer.dom(), endOffset);

        return ExpandRange.expandRng(editor, rng, format, remove);
      });
    };

    var cAssertRange = function (editor, startPath, startOffset, endPath, endOffset) {
      return Chain.op(function (rng) {
        var startContainer = Hierarchy.follow(Element.fromDom(editor.getBody()), startPath).getOrDie();
        var endContainer = Hierarchy.follow(Element.fromDom(editor.getBody()), endPath).getOrDie();

        Assertions.assertDomEq('Should be expected start container', startContainer, Element.fromDom(rng.startContainer));
        Assertions.assertEq('Should be expected start offset', startOffset, rng.startOffset);
        Assertions.assertDomEq('Should be expected end container', endContainer, Element.fromDom(rng.endContainer));
        Assertions.assertEq('Should be expected end offset', endOffset, rng.endOffset);
      });
    };

    TinyLoader.setup(function (editor, onSuccess, onFailure) {
      var tinyApis = TinyApis(editor);
      var inlineFormat = [{ inline: 'b' }];
      var blockFormat = [{ block: 'div' }];
      var selectorFormat = [{ selector: 'div', classes: 'b' }];
      var selectorFormatCollapsed = [{ selector: 'div', classes: 'b', collapsed: true }];

      Pipeline.async({}, [
        tinyApis.sFocus,
        Logger.t('Expand inline format words', GeneralSteps.sequence([
          Logger.t('In middle of single word in paragraph', Chain.asStep(editor, [
            cSetRawContent('
ab
'),
            cExpandRng([0, 0], 1, [0, 0], 1, inlineFormat, false),
            cAssertRange(editor, [], 0, [], 1)
          ])),
          Logger.t('In middle of single word in paragraph with paragraph siblings', Chain.asStep(editor, [
            cSetRawContent('
a

bc

de
'),
            cExpandRng([1, 0], 1, [1, 0], 1, inlineFormat, false),
            cAssertRange(editor, [], 1, [], 2)
          ])),
          Logger.t('In middle of single word wrapped in b', Chain.asStep(editor, [
            cSetRawContent('
ab
'),
            cExpandRng([0, 0, 0], 1, [0, 0, 0], 1, inlineFormat, false),
            cAssertRange(editor, [], 0, [], 1)
          ])),
          Logger.t('In middle of first word', Chain.asStep(editor, [
            cSetRawContent('
ab cd
'),
            cExpandRng([0, 0], 1, [0, 0], 1, inlineFormat, false),
            cAssertRange(editor, [], 0, [0, 0], 2)
          ])),
          Logger.t('In middle of last word', Chain.asStep(editor, [
            cSetRawContent('
ab cd
'),
            cExpandRng([0, 0], 4, [0, 0], 4, inlineFormat, false),
            cAssertRange(editor, [0, 0], 3, [], 1)
          ])),
          Logger.t('In middle of middle word', Chain.asStep(editor, [
            cSetRawContent('
ab cd ef
'),
            cExpandRng([0, 0], 4, [0, 0], 4, inlineFormat, false),
            cAssertRange(editor, [0, 0], 3, [0, 0], 5)
          ])),
          Logger.t('In middle of word with bold siblings expand to sibling spaces', Chain.asStep(editor, [
            cSetRawContent('
ab cd ef
'),
            cExpandRng([0, 1], 1, [0, 1], 1, inlineFormat, false),
            cAssertRange(editor, [0, 0, 0], 3, [0, 2, 0], 0)
          ])),
          Logger.t('In middle of word with block sibling and inline sibling expand to sibling space to the right', Chain.asStep(editor, [
            cSetRawContent('

ab
cd ef
'),
            cExpandRng([0, 1], 1, [0, 1], 1, inlineFormat, false),
            cAssertRange(editor, [0, 1], 0, [0, 2, 0], 0)
          ])),
          Logger.t('In middle of word with block sibling and inline sibling expand to sibling space to the left', Chain.asStep(editor, [
            cSetRawContent('
ab cd
 ef

'),
            cExpandRng([0, 1], 1, [0, 1], 1, inlineFormat, false),
            cAssertRange(editor, [0, 0, 0], 3, [0, 1], 2)
          ])),
          Logger.t('In middle of middle word separated by nbsp characters', Chain.asStep(editor, [
            cSetRawContent('
ab\u00a0cd\u00a0ef
'),
            cExpandRng([0, 0], 4, [0, 0], 4, inlineFormat, false),
            cAssertRange(editor, [0, 0], 3, [0, 0], 5)
          ])),
          Logger.t('In empty paragraph', Chain.asStep(editor, [
            cSetRawContent('

'),
            cExpandRng([0], 0, [0], 0, inlineFormat, false),
            cAssertRange(editor, [], 0, [], 1)
          ])),
          Logger.t('Fully selected word', Chain.asStep(editor, [
            cSetRawContent('
ab
'),
            cExpandRng([0, 0], 0, [0, 0], 2, inlineFormat, false),
            cAssertRange(editor, [], 0, [], 1)
          ])),
          Logger.t('Partially selected word', Chain.asStep(editor, [
            cSetRawContent('
abc
'),
            cExpandRng([0, 0], 1, [0, 0], 2, inlineFormat, false),
            cAssertRange(editor, [0, 0], 1, [0, 0], 2)
          ])),
          Logger.t('Whole word selected wrapped in multiple inlines', Chain.asStep(editor, [
            cSetRawContent('
c
'),
            cExpandRng([0, 0, 0, 0], 0, [0, 0, 0, 0], 1, inlineFormat, false),
            cAssertRange(editor, [], 0, [], 1)
          ])),
          Logger.t('Whole word inside td', Chain.asStep(editor, [
            cSetRawContent('

a

'),
            cExpandRng([0, 0, 0, 0, 0], 0, [0, 0, 0, 0, 0], 1, inlineFormat, false),
            cAssertRange(editor, [0, 0, 0], 0, [0, 0, 0], 1)
          ])),
          Logger.t('In middle of single word in paragraph (index based)', Chain.asStep(editor, [
            cSetRawContent('
ab
'),
            cExpandRng([0], 0, [0], 1, inlineFormat, false),
            cAssertRange(editor, [], 0, [], 1)
          ])),
          Logger.t('In middle of single word wrapped in bold in paragraph (index based)', Chain.asStep(editor, [
            cSetRawContent('
ab
'),
            cExpandRng([0], 0, [0], 1, inlineFormat, false),
            cAssertRange(editor, [], 0, [], 1)
          ])),
          Logger.t('In middle of word inside bookmark then exclude bookmark', Chain.asStep(editor, [
            cSetRawContent('
ab cd ef
'),
            cExpandRng([0, 0, 0], 3, [0, 0, 0], 5, inlineFormat, false),
            cAssertRange(editor, [], 0, [], 1)
          ]))
        ])),

        Logger.t('Expand inline format words (remove format)', GeneralSteps.sequence([
          Logger.t('In middle of single word in paragraph', Chain.asStep(editor, [
            cSetRawContent('
ab
'),
            cExpandRng([0, 0], 1, [0, 0], 1, inlineFormat, true),
            cAssertRange(editor, [], 0, [], 1)
          ]))
        ])),

        Logger.t('Expand block format', GeneralSteps.sequence([
          Logger.t('In middle word', Chain.asStep(editor, [
            cSetRawContent('
ab cd ef
'),
            cExpandRng([0, 0], 4, [0, 0], 4, blockFormat, false),
            cAssertRange(editor, [], 0, [], 1)
          ])),
          Logger.t('In middle bold word', Chain.asStep(editor, [
            cSetRawContent('
ab cd ef
'),
            cExpandRng([0, 1, 0], 1, [0, 1, 0], 1, blockFormat, false),
            cAssertRange(editor, [], 0, [], 1)
          ])),
          Logger.t('Whole word inside td', Chain.asStep(editor, [
            cSetRawContent('

a

'),
            cExpandRng([0, 0, 0, 0, 0], 0, [0, 0, 0, 0, 0], 1, blockFormat, false),
            cAssertRange(editor, [0, 0, 0], 0, [0, 0, 0], 1)
          ]))
        ])),

        Logger.t('Expand selector format', GeneralSteps.sequence([
          Logger.t('Do not expand if selector does not match', Chain.asStep(editor, [
            cSetRawContent('
ab
'),
            cExpandRng([0, 0], 1, [0, 0], 1, selectorFormat, false),
            cAssertRange(editor, [0, 0], 1, [0, 0], 1)
          ])),
          Logger.t('Expand since selector matches', Chain.asStep(editor, [
            cSetRawContent('
ab
'),
            cExpandRng([0, 0], 1, [0, 0], 1, selectorFormat, false),
            cAssertRange(editor, [], 0, [], 1)
          ])),
          Logger.t('Expand since selector matches non collapsed', Chain.asStep(editor, [
            cSetRawContent('
ab
'),
            cExpandRng([0, 0], 1, [0, 0], 2, selectorFormat, false),
            cAssertRange(editor, [], 0, [], 1)
          ]))
        ])),

        Logger.t('Expand selector format with collapsed property', GeneralSteps.sequence([
          Logger.t('Expand since selector matches collapsed on collapsed format', Chain.asStep(editor, [
            cSetRawContent('
ab
'),
            cExpandRng([0, 0], 1, [0, 0], 1, selectorFormatCollapsed, false),
            cAssertRange(editor, [], 0, [], 1)
          ])),
          Logger.t('Expand since selector matches non collapsed on collapsed format', Chain.asStep(editor, [
            cSetRawContent('
ab
'),
            cExpandRng([0, 0], 1, [0, 0], 2, selectorFormatCollapsed, false),
            cAssertRange(editor, [0, 0], 1, [0, 0], 2)
          ]))
        ]))
      ], onSuccess, onFailure);
    }, {
      plugins: '',
      toolbar: '',
      skin_url: '/project/src/skins/lightgray/dist/lightgray'
    }, success, failure);
  }
);


text:
package com.jpattern.ioc.xml;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

import com.jpattern.ioc.IContextCreator;
import com.jpattern.ioc.exception.ConfigException;

public class EntryMap  implements IEntry  {

        private List<IEntry> entries = new ArrayList<IEntry>();
        private  Key key;

        public EntryMap(Key aKey) {
            key = aKey;
        }

        public Key getKey() {
            return key;
        }

        public void add(Entry aEntry) {
            entries.add(aEntry);
        }

        public List<IEntry> getEntries() {
            return entries;
        }

        public Object typedValue(IContextCreator aContextCreator) throws ConfigException, ClassNotFoundException {
            Map<String, Object> returnedMap = new HashMap<String, Object>();
            ListIterator<IEntry> entriesIterator = getEntries().listIterator();
            IEntry iEntry;
            while (entriesIterator.hasNext()) {
                iEntry = (IEntry)entriesIterator.next();
                returnedMap.put(iEntry.getKey().key(), iEntry.typedValue(aContextCreator));
            }
            return returnedMap;
        }

        public int hashCode() {
            return key.hashCode();
        }

        public boolean equals(Object obj) {
            if ( !(obj instanceof IEntry))
                return false;
            final IEntry other = (IEntry) obj;
            return key.equals( other.getKey() );
        }

}


text:
import * as cd from 'cd-interfaces';
import * as consts from 'cd-common/consts';
import {
  CdComponent,
  CdComponentFactory,
  getComponent,
  DEFAULT_BOARD_STYLES,
} from 'cd-common/models';
import { INNER_LAYOUT_CONFIG, PADDING_CONFIG, OVERFLOW_CONFIG } from '../../shared';
import templateFunction from './board.template';

export class Board extends CdComponent {
  tagName = consts.DIV_TAG;
  title = 'Board';
  icon = consts.LayerIcons.Board;
  childrenAllowed = true;
  autoAddDefaultProperties = false;

  styles = DEFAULT_BOARD_STYLES.base.style;

  properties: cd.IPropertyGroup[] = [
    { type: cd.PropertyType.BoardSize },
    { children: [PADDING_CONFIG] },
    { children: [OVERFLOW_CONFIG] },
    { type: cd.PropertyType.BoardBackground },
    INNER_LAYOUT_CONFIG,
    { type: cd.PropertyType.BoardPreviewVisibility },
  ];

  template = templateFunction;
  factory = BoardFactory;
}

class BoardFactory extends CdComponentFactory implements cd.IBoardProperties {
  elementType: cd.ElementEntitySubType.Board = cd.ElementEntitySubType.Board;

  constructor(public projectId: string, id: string) {
    super(projectId, id, getComponent(cd.ElementEntitySubType.Board) as Board);
    this.assignFrame(800, 600, 40, 40);
  }
}


text:
#include <aws/iotsitewise/model/ExpressionVariable.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace IoTSiteWise
{
namespace Model
{

ExpressionVariable::ExpressionVariable() :
    m_nameHasBeenSet(false),
    m_valueHasBeenSet(false)
{
}

ExpressionVariable::ExpressionVariable(JsonView jsonValue) :
    m_nameHasBeenSet(false),
    m_valueHasBeenSet(false)
{
  *this = jsonValue;
}

ExpressionVariable& ExpressionVariable::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("name"))
  {
    m_name = jsonValue.GetString("name");

    m_nameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("value"))
  {
    m_value = jsonValue.GetObject("value");

    m_valueHasBeenSet = true;
  }

  return *this;
}

JsonValue ExpressionVariable::Jsonize() const
{
  JsonValue payload;

  if(m_nameHasBeenSet)
  {
   payload.WithString("name", m_name);

  }

  if(m_valueHasBeenSet)
  {
   payload.WithObject("value", m_value.Jsonize());

  }

  return payload;
}

} // namespace Model
} // namespace IoTSiteWise
} // namespace Aws