text:
package com.planet_ink.coffee_mud.Libraries.interfaces;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.core.database.DBConnections;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.GenericBuilder.GenItemCode;
import com.planet_ink.coffee_mud.Libraries.interfaces.GenericBuilder.GenMOBCode;
import com.planet_ink.coffee_mud.Libraries.interfaces.PlayerLibrary.ThinPlayer;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

/**
 * The Player Manager is primarily a cache and lookup
 * utility library for player character mobs and player
 * accounts if the account system is enabled.  It is mostly
 * optimized to cache as few players as possible, providing
 * many methods of getting and changing player character
 * information w/o a permanent load.
 *
 * @author Bo Zimmerman
 *
 */
public interface PlayerLibrary extends CMLibrary
{
	/**
	 * Returns null or an account of the given name if it
	 * exists in the database managed by this player lib.
	 *
	 * @see PlayerLibrary#getLoadAccountByEmail(String)
	 *
	 * @param calledThis the name of the account
	 * @return the account found, or null
	 */
	public PlayerAccount getLoadAccount(String calledThis);
	/**
	 * Returns null or an account of the given email addy if it
	 * exists in the database managed by this player lib.
	 *
	 * @see PlayerLibrary#getLoadAccount(String)
	 *
	 * @param email the email of the account
	 * @return the account found, or null
	 */
	public PlayerAccount getLoadAccountByEmail(String email);

	/**
	 * Returns null or an account of the given name if it
	 * exists in the cache managed by this player lib.
	 *
	 * @see PlayerLibrary#getAccountAllHosts(String)
	 *
	 * @param calledThis the name of the account
	 * @return the account found, or null
	 */
	public PlayerAccount getAccount(String calledThis);

	/**
	 * Returns null or an account of the given name if it
	 * exists in the cache managed by this player lib. If
	 * not found, all other player libraries are consulted
	 * if they share the same map as this one.
	 *
	 * @see PlayerLibrary#getAccount(String)
	 *
	 * @param calledThis the name of the account
	 * @return the account found, or null
	 */
	public PlayerAccount getAccountAllHosts(String calledThis);

	/**
	 * Adds a new account to this player manager, for
	 * caching only.
	 *
	 * @param acct the new account
	 */
	public void addAccount(PlayerAccount acct);

	/**
	 * Returns whether an account of the given name exists
	 * in the database managed by this player lib.
	 *
	 * @see PlayerLibrary#accountExistsAllHosts(String)
	 *
	 * @param name the name of the account
	 * @return true if the account exists
	 */
	public boolean accountExists(String name);

	/**
	 * Returns whether an account of the given name exists
	 * in the database managed by this player lib.  If
	 * not found, all other player libraries are consulted
	 * if they share the same map as this one.
	 *
	 * @see PlayerLibrary#accountExists(String)
	 *
	 * @param name the name of the account
	 * @return true if the account exists
	 */
	public boolean accountExistsAllHosts(String name);

	/**
	 * Returns an enumeration of all player account objects
	 *
	 * @see PlayerLibrary#accounts(String, Map)
	 *
	 * @return an enumeration of all player account objects
	 */
	public Enumeration<PlayerAccount> accounts();

	/**
	 * Returns an enumeration of all account objects, with optional sort field,
	 * and optional cache so that subsequent calls are faster.
	 * The sort field is a AcctThinSortCode name.
	 * The cache is a map that can contain a field called "ACCOUNTLISTVECTOR" plus
	 * the sort field, and would be the vector of accounts that can be
	 * enumerated over again.
	 *
	 * @see PlayerLibrary#accounts()
	 *
	 * @param sort null, or AcctThinSortCode name
	 * @param cache map that can contain a cashed enum vector
	 * @return the enum of ALL player accounts
	 */
	public Enumeration<PlayerAccount> accounts(String sort, Map<String, Object> cache);

	/**
	 * Given two player characters, this will return whether they either
	 * share an account.
	 *
	 * @see PlayerLibrary#isSameAccount(MOB, MOB)
	 * @see PlayerLibrary#isSameAccountIP(MOB, MOB)
	 *
	 * @param player1 the first player mob
	 * @param player2 the second player mob
	 * @return whether they are on the same account
	 */
	public boolean isSameAccount(final MOB player1, final MOB player2);

	/**
	 * Given two player characters, this will return whether they either
	 * share an account, or the same ip address.
	 *
	 * @see PlayerLibrary#isSameAccount(MOB, MOB)
	 * @see PlayerLibrary#isSameAccountIP(MOB, MOB)
	 *
	 * @param player1 the first player mob
	 * @param player2 the second player mob
	 * @return whether they are probably the same person
	 */
	public boolean isSameAccountIP(final MOB player1, final MOB player2);

	/**
	 * Removes the given player account from the list of protected
	 * names, and then deletes the account from the manager cache, from
	 * the database, and from the world.  It does not delete the
	 * players in the account, like, at all, so it should be done
	 * last in that process.
	 *
	 * @param deadAccount the account to obliterate
	 */
	public void obliterateAccountOnly(PlayerAccount deadAccount);

	/**
	 * Returns the number of player character mobs currently
	 * cached by this manager.
	 *
	 * @see PlayerLibrary#delPlayer(MOB)
	 * @see PlayerLibrary#addPlayer(MOB)
	 * @see PlayerLibrary#players()
	 *
	 * @return the number of cached players
	 */
	public int numPlayers();

	/**
	 * Adds a reference to the given player char mob to this
	 * manager cache.
	 *
	 * @see PlayerLibrary#delPlayer(MOB)
	 * @see PlayerLibrary#numPlayers()
	 * @see PlayerLibrary#players()
	 *
	 * @param newOne the player mob to add
	 */
	public void addPlayer(MOB newOne);

	/**
	 * Deletes a reference to a player character mob from the
	 * cache.  This does not completely remove the mob from
	 * the game itself, or all their stuff, and is thus
	 * somewhat dangerous to call.
	 *
	 * @see PlayerLibrary#addPlayer(MOB)
	 * @see PlayerLibrary#numPlayers()
	 * @see PlayerLibrary#players()
	 *
	 * @param oneToDel the player char mob to remove from the cache
	 */
	public void delPlayer(MOB oneToDel);

	/**
	 * Returns an enumeration of all cached players in this
	 * manager.
	 *
	 * @see PlayerLibrary#delPlayer(MOB)
	 * @see PlayerLibrary#addPlayer(MOB)
	 * @see PlayerLibrary#numPlayers()
	 *
	 * @return the enumeration of cached player mobs
	 */
	public Enumeration<MOB> players();

	/**
	 * Given a player character name, this will search the list
	 * of cached player mobs and return the one with that name.
	 *
	 *  @see PlayerLibrary#getPlayerAllHosts(String)
	 *
	 * @param calledThis the cached player to get
	 * @return null if not cached, or the player char mob
	 */
	public MOB getPlayer(String calledThis);

	/**
	 * Given a player character name, this will search the list
	 * of cached player mobs and return the one with that name.
	 * If not found in this player manager, it will search all
	 * others that share the same map.
	 *
	 *  @see PlayerLibrary#getPlayer(String)
	 *
	 * @param calledThis the cached player to get
	 * @return null if not cached, or the player char mob
	 */
	public MOB getPlayerAllHosts(String calledThis);

	/**
	 * Given a player name, or substring for searching,
	 * this will return a player character object that is presently
	 * online and in the game.
	 *
	 * @param srchStr the name, or substring if Not exact only
	 * @param exactOnly true to only search full names, false for substring
	 * @return null, or the found online player
	 */
	public MOB findPlayerOnline(final String srchStr, final boolean exactOnly);

	/**
	 * Finds a player character who has the given unique name,
	 * first checking the manager cache, and if not found, goes
	 * to the associated database and loads the character into
	 * the cache and then returns it.
	 *
	 * @see PlayerLibrary#getLoadPlayerByEmail(String)
	 * @see PlayerLibrary#getLoadPlayerAllHosts(String)
	 *
	 * @param last the character name
	 * @return null, or the character found
	 */
	public MOB getLoadPlayer(String last);

	/**
	 * Finds a player character who has the given unique name,
	 * first checking the manager cache, and if not found, goes
	 * to the associated database and loads the character into
	 * the cache and then returns it.  If not found there, it
	 * checks all other player managers who share a map with
	 * this one.
	 *
	 * @see PlayerLibrary#getLoadPlayerByEmail(String)
	 * @see PlayerLibrary#getLoadPlayer(String)
	 *
	 * @param last the character name
	 * @return null, or the character found
	 */
	public MOB getLoadPlayerAllHosts(final String last);

	/**
	 * Finds a player character who has the given email address
	 * (possibly from their account), and loads that character
	 * into the player manager cache and then returns it.  It
	 * will check the cache first, of course.
	 *
	 * @see PlayerLibrary#getLoadPlayer(String)
	 * @see PlayerLibrary#getLoadPlayerAllHosts(String)
	 *
	 * @param email email address to find a player for
	 * @return null, or the player char mob found
	 */
	public MOB getLoadPlayerByEmail(String email);

	/**
	 * Returns a list of all player char names
	 * in the database.
	 *
	 * @see PlayerLibrary#getPlayerListsAllHosts()
	 *
	 * @return list of all player names
	 */
	public List<String> getPlayerLists();

	/**
	 * Returns a list of all player char names from all
	 * databases connected to the same map as this
	 * player manager.
	 *
	 * @see PlayerLibrary#getPlayerLists()
	 *
	 * @return list of all player names
	 */
	public List<String> getPlayerListsAllHosts();

	/**
	 * Returns whether the given player char mob is currently
	 * cached by this player manager.
	 *
	 * @see PlayerLibrary#isLoadedPlayer(String)
	 *
	 * @param M the player char
	 * @return true if cached, false otherwise
	 */
	public boolean isLoadedPlayer(final MOB M);

	/**
	 * Returns whether the given player char name is currently
	 * cached by this player manager.
	 *
	 * @see PlayerLibrary#isLoadedPlayer(MOB)
	 *
	 * @param mobName the player char name
	 * @return true if cached, false otherwise
	 */
	public boolean isLoadedPlayer(final String mobName);

	/**
	 * Given a player name, this will attempt to find them and
	 * return whether they actually exist regardless of whether
	 * they've been cached or not.
	 *
	 * @see PlayerLibrary#playerExistsAllHosts(String)
	 *
	 * @param name the player name
	 * @return true if the player exists anywhere
	 */
	public boolean playerExists(String name);

	/**
	 * Given a player name, this will attempt to find them and
	 * return whether they actually exist regardless of whether
	 * they've been cached or not, and checking all user
	 * databases that share a map with the caller.
	 *
	 * @see PlayerLibrary#playerExists(String)
	 *
	 * @param name the player name
	 * @return true if the player exists anywhere
	 */
	public boolean playerExistsAllHosts(String name);

	/**
	 * Given a player name, this will attempt to find the name of the
	 * liege of this player, regardless of whether they've been cached
	 * or not, and checking all user databases that share a map with
	 * the caller.
	 *
	 * @param userName the player char name
	 * @return "", or the name of the player's liege
	 */
	public String getLiegeOfUserAllHosts(final String userName);

	/**
	 * Obliterates a cached loaded player character from the
	 * database, from the cache, from everything.  Deletes a character
	 * completely and forever.
	 *
	 * @param deadMOB the player char mob object
	 * @param deleteAssets true to send retirement msg to the world and kill player data
	 * @param quiet true to do this silently, false otherwise
	 */
	public void obliteratePlayer(MOB deadMOB, boolean deleteAssets, boolean quiet);

	/**
	 * Renaming a player is quite involved, as there are so many tables and
	 * objects index by the players names.  Calling this method attempts
	 * to take care of as much as possible.  To use it, first set the mob
	 * objects new name, then call this with the old one.
	 *
	 * @param mob the player char who has been renamed
	 * @param oldName the previous name
	 */
	public void renamePlayer(MOB mob, String oldName);

	/**
	 * Given a player char mob object, this will ensure that
	 * the char is indeed not currently in the game and, if
	 * so, remove them from the player cache without saving
	 * them.
	 *
	 * @param mob the player char to unload
	 */
	public void unloadOfflinePlayer(final MOB mob);

	/**
	 * Saves all cached players.  If the INI file does not
	 * support the player cache, this will throw out players who
	 * are offline, but otherwise leave them cached.
	 *
	 * @return the number of players saved
	 */
	public int savePlayers();

	/**
	 * Factory method for a ThinnerPlayer object, so that
	 * new features can be added in the future w/o having
	 * to change many files.
	 *
	 * @see PlayerLibrary.ThinnerPlayer
	 *
	 * @return a ThinnerPlayer object you can modify
	 */
	public PlayerLibrary.ThinnerPlayer newThinnerPlayer();

	/**
	 * Given a player name, this will construct a ThinPlayer
	 * object if the player char is already cached, or
	 * a new one from the database if not.
	 *
	 * @see PlayerLibrary.ThinPlayer
	 * @see PlayerLibrary#newThinnerPlayer()
	 * @see PlayerLibrary#thinPlayers(String, Map)
	 *
	 * @param mobName the char name
	 * @return the ThinPlayer
	 */
	public ThinPlayer getThinPlayer(final String mobName);

	/**
	 * Given a possible player sort code string, and an optional cache of
	 * pre-loaded key pairs, one of which might be "PLAYERLISTVECTOR"+sort,
	 * pointing to a vector of pre-loaded thinplayers, this will return
	 * an enumeration of all players in the game.
	 *
	 * @see PlayerLibrary.PlayerSortCode
	 * @see PlayerLibrary.ThinPlayer
	 * @see PlayerLibrary#getThinPlayer(String)
	 * @see PlayerLibrary#newThinnerPlayer()
	 *
	 * @param sort "", or a player sort code name
	 * @param cache null, or a map that might have a prior list
	 * @return an enumeration of all players, as thin-ones
	 */
	public Enumeration<ThinPlayer> thinPlayers(String sort, Map<String, Object> cache);

	/**
	 * Given a possible sort code name, and now exact of a match you want,
	 * this might return a player sort code match.
	 *
	 * @see PlayerLibrary.PlayerSortCode
	 * @see PlayerLibrary.ThinPlayer
	 * @see PlayerLibrary#getSortValue(MOB, PlayerSortCode)
	 * @see PlayerLibrary#getThinSortValue(ThinPlayer, PlayerSortCode)
	 * @see PlayerLibrary#getThinPlayer(String)
	 *
	 * @param codeName the possible code name
	 * @param loose true for startswith matches, false for exact
	 * @return null or the player sort code
	 */
	public PlayerSortCode getCharThinSortCode(String codeName, boolean loose);

	/**
	 * Given a player character thinplayer obj, and a sort code, this will
	 * return the sortable string value of that attribute,
	 *
	 * @see PlayerLibrary.PlayerSortCode
	 * @see PlayerLibrary.ThinPlayer
	 * @see PlayerLibrary#getSortValue(MOB, PlayerSortCode)
	 * @see PlayerLibrary#getCharThinSortCode(String, boolean)
	 * @see PlayerLibrary#getThinPlayer(String)
	 *
	 * @param player the character thinplayer obj
	 * @param code the code for the value to return
	 * @return the value of the code from the character
	 */
	public Object getThinSortValue(ThinPlayer player, PlayerSortCode code);

	/**
	 * Given a player character mob, and a sort code, this will
	 * return the sortable string value of that attribute,
	 *
	 * @see PlayerLibrary.PlayerSortCode
	 * @see PlayerLibrary#getThinSortValue(ThinPlayer, PlayerSortCode)
	 * @see PlayerLibrary#getCharThinSortCode(String, boolean)
	 *
	 * @param player the character mob
	 * @param code the code for the value to return
	 * @return the value of the code from the character
	 */
	public String getSortValue(MOB player, PlayerSortCode code);

	/**
	 * Given a player name, and code representing an attribute of the player
	 * character, this will fetch the value on the player, regardless of
	 * whether they are online or no. See PlayerCode enum for information
	 * on proper object type for the return value.
	 *
	 * @see PlayerLibrary.PlayerCode
	 * @see PlayerLibrary#setPlayerValue(String, PlayerCode, Object)
	 *
	 * @param playerName player character name
	 * @param code PlayerCode to fetch
	 * @return value the character value
	 */
	public Object getPlayerValue(final String playerName, final PlayerCode code);

	/**
	 * Given a player name, and code representing an attribute of the player
	 * character, and a new value appropriate to that code, this will change
	 * the value on the player, regardless of whether they are online or no.
	 * See PlayerCode enum for information on proper object type for
	 * the value.
	 *
	 * @see PlayerLibrary.PlayerCode
	 * @see PlayerLibrary#getPlayerValue(String, PlayerCode)
	 *
	 * @param playerName player character name
	 * @param code PlayerCode to change
	 * @param value the new value
	 */
	public void setPlayerValue(final String playerName, final PlayerCode code, final Object value);

	/**
	 * Sometimes the list of players in a given room needs to be
	 * determined rather instantly.  This method helps do that
	 * by returning all player chars in the given room,
	 * or null.
	 *
	 * @see PlayerLibrary#changePlayersLocation(MOB, Room)
	 *
	 * @param room the room curious about
	 * @return the set of chars, or null
	 */
	public Set<MOB> getPlayersHere(Room room);

	/**
	 * Sometimes the list of players in a given room needs to be
	 * determined rather instantly.  This method helps do that
	 * by keeping a double-hash reference of players to their
	 * rooms.
	 *
	 * @see PlayerLibrary#getPlayersHere(Room)
	 *
	 * @param mob the player to keep tracking
	 * @param room the room the player is in, or null to remove him altogther
	 */
	public void changePlayersLocation(MOB mob, Room room);

	/**
	 * Causes the pride stats list to be reloaded from the
	 * player database.
	 *
	 * @see PlayerLibrary#getTopPrideAccounts(com.planet_ink.coffee_mud.Common.interfaces.TimeClock.TimePeriod, com.planet_ink.coffee_mud.Common.interfaces.AccountStats.PrideStat)
	 * @see PlayerLibrary#getTopPridePlayers(com.planet_ink.coffee_mud.Common.interfaces.TimeClock.TimePeriod, com.planet_ink.coffee_mud.Common.interfaces.AccountStats.PrideStat)
	 * #see PlayerLibrary#bumpPrideStat(MOB, com.planet_ink.coffee_mud.Common.interfaces.AccountStats.PrideStat, int)
	 * @see PlayerLibrary#parsePrideStats(String[], String[])
	 */
	public void resetAllPrideStats();

	/**
	 * Given an array of timestamps indexed by period ordinals, and previous
	 * pride stat values similarly indexed, this will generate an array
	 * of pairs representing the data.
	 *
	 * @see PlayerLibrary#getTopPrideAccounts(com.planet_ink.coffee_mud.Common.interfaces.TimeClock.TimePeriod, com.planet_ink.coffee_mud.Common.interfaces.AccountStats.PrideStat)
	 * @see PlayerLibrary#getTopPridePlayers(com.planet_ink.coffee_mud.Common.interfaces.TimeClock.TimePeriod, com.planet_ink.coffee_mud.Common.interfaces.AccountStats.PrideStat)
	 * #see PlayerLibrary#bumpPrideStat(MOB, com.planet_ink.coffee_mud.Common.interfaces.AccountStats.PrideStat, int)
	 * @see PlayerLibrary#resetAllPrideStats()
	 *
	 * @param nextPeriods the timestamps by period
	 * @param prideStats the previous stat values by period
	 * @return the array of pairs
	 */
	public Pair<Long,int[]>[] parsePrideStats(final String[] nextPeriods, final String[] prideStats);

	/**
	 * Given a player who did something that triggers a change in a pride stat, the pride
	 * stat that changed, and the amount it changed by, this will update the pride lists
	 * and return the given value.
	 *
	 * @see PlayerLibrary#getTopPrideAccounts(com.planet_ink.coffee_mud.Common.interfaces.TimeClock.TimePeriod, com.planet_ink.coffee_mud.Common.interfaces.AccountStats.PrideStat)
	 * @see PlayerLibrary#getTopPridePlayers(com.planet_ink.coffee_mud.Common.interfaces.TimeClock.TimePeriod, com.planet_ink.coffee_mud.Common.interfaces.AccountStats.PrideStat)
	 * @see PlayerLibrary#parsePrideStats(String[], String[])
	 * @see PlayerLibrary#resetAllPrideStats()
	 *
	 * @param mob the player char who did something
	 * @param stat the pride stat reflecting what they did
	 * @param amt the amount to change the stat by + or -
	 * @return the give amt, or 0
	 */
	public int bumpPrideStat(final MOB mob, final AccountStats.PrideStat stat, final int amt);

	/**
	 * Returns the top winning character names and the associated values that got them there, for the given time
	 * period and given pridestat.
	 *
	 * @see PlayerLibrary#getTopPrideAccounts(com.planet_ink.coffee_mud.Common.interfaces.TimeClock.TimePeriod, com.planet_ink.coffee_mud.Common.interfaces.AccountStats.PrideStat)
	 * #see PlayerLibrary#bumpPrideStat(MOB, com.planet_ink.coffee_mud.Common.interfaces.AccountStats.PrideStat, int)
	 * @see PlayerLibrary#parsePrideStats(String[], String[])
	 * @see PlayerLibrary#resetAllPrideStats()
	 *
	 * @param period the time period to get the top character for
	 * @param stat the pridestat to find winners for
	 * @return the list of top winners
	 */
	public List<Pair<String,Integer>> getTopPridePlayers(TimeClock.TimePeriod period, AccountStats.PrideStat stat);

	/**
	 * Returns the top winning account names and the associated values that got them there, for the given time
	 * period and given pridestat.
	 *
	 * @see PlayerLibrary#getTopPridePlayers(com.planet_ink.coffee_mud.Common.interfaces.TimeClock.TimePeriod, com.planet_ink.coffee_mud.Common.interfaces.AccountStats.PrideStat)
	 * #see PlayerLibrary#bumpPrideStat(MOB, com.planet_ink.coffee_mud.Common.interfaces.AccountStats.PrideStat, int)
	 * @see PlayerLibrary#parsePrideStats(String[], String[])
	 * @see PlayerLibrary#resetAllPrideStats()
	 *
	 * @param period the time period to get the top accounts for
	 * @param stat the pridestat to find winners for
	 * @return the list of top winners
	 */
	public List<Pair<String,Integer>> getTopPrideAccounts(TimeClock.TimePeriod period, AccountStats.PrideStat stat);

	/**
	 * For systems that list users and allow sorting, here
	 * is an enum of the popular sort codes, along with
	 * popular alias for the code names.
	 *
	 * @author Bo Zimmerman
	 */
	public enum PlayerSortCode
	{
		NAME("CHARACTER"),
		CLASS("CHARCLASS"),
		RACE("RACE"),
		LEVEL("LVL"),
		AGE("HOURS"),
		LAST("DATE"),
		EMAIL("EMAILADDRESS"),
		IP("LASTIP")
		;
		public String altName;
		private PlayerSortCode(final String ln)
		{
			this.altName=ln;
		}
	}

	/**
	 * The player library can query individual fields from player
	 * characters regardless of whether the player is cached or
	 * not.  These are the fields that are available for direct
	 * reading, along with the format of their values
	 *
	 * @author Bo Zimmerman
	 *
	 */
	public enum PlayerCode
	{
		/**
		 * String
		 */
		NAME,
		/**
		 * String
		 */
		PASSWORD,
		/**
		 * CharClass
		 */
		CHARCLASS,
		/**
		 * Race
		 */
		RACE,
		/**
		 * Integer
		 */
		HITPOINTS,
		/**
		 * Integer
		 */
		LEVEL,
		/**
		 * Integer
		 */
		MANA,
		/**
		 * Integer
		 */
		MOVES,
		/**
		 * String
		 */
		DESCRIPTION,
		/**
		 * Integer
		 */
		ALIGNMENT,
		/**
		 * Integer
		 */
		EXPERIENCE,
		/**
		 * String
		 */
		DEITY,
		/**
		 * Integer
		 */
		PRACTICES,
		/**
		 * Integer
		 */
		TRAINS,
		/**
		 * Long
		 */
		AGE,
		/**
		 * List<Coin>
		 */
		MONEY,
		/**
		 * Integer
		 */
		WIMP,
		/**
		 * Integer
		 */
		QUESTPOINTS,
		/**
		 * String
		 */
		LOCATION,
		/**
		 * String
		 */
		STARTROOM,
		/**
		 * Long
		 */
		LASTDATE,
		/**
		 * Integer
		 */
		CHANNELMASK,
		/**
		 * Integer
		 */
		ATTACK,
		/**
		 * Integer
		 */
		ARMOR,
		/**
		 * Integer
		 */
		DAMAGE,
		/**
		 * Integer
		 */
		MATTRIB,
		/**
		 * String
		 */
		LEIGE,
		/**
		 * Integer
		 */
		HEIGHT,
		/**
		 * Integer
		 */
		WEIGHT,
		/**
		 * String
		 */
		COLOR,
		/**
		 * String
		 */
		LASTIP,
		/**
		 * String
		 */
		EMAIL,
		/**
		 * List<Tattoo>
		 */
		TATTS,
		/**
		 * List<String>
		 */
		EXPERS,
		/**
		 * String
		 */
		ACCOUNT,
		/**
		 * List<Pair<String,Integer>> (factionid, value)
		 */
		FACTIONS,
		/**
		 * String[] (dbid, item class, item txt, loID, worn, uses, lvl, abilty, heit)
		 */
		INVENTORY,
		/**
		 * List<Ability>
		 */
		ABLES,
		/**
		 * List<CMObject> (behavior and ability objects)
		 */
		AFFBEHAV,
		/**
		 * List<Clan,Integer>
		 */
		CLANS
	}

	/**
	 * Sometimes the system does not need the entire mob object
	 * and all associated attributes to make decisions about
	 * a particular player char.  In cases like these, a smaller
	 * and more light-weight view of the char is available
	 * through this interface.
	 *
	 * @author Bo Zimmerman
	 *
	 */
	public static interface ThinPlayer
	{
		/**
		 * Return the char name
		 * @return the char name
		 */
		public String name();

		/**
		 * Return the char char Class
		 * @return the char char Class
		 */
		public String charClass();

		/**
		 * Return the char race
		 * @return the char race
		 */
		public String race();

		/**
		 * Return the char level
		 * @return the char level
		 */
		public int level();

		/**
		 * Return the char age/hrs/mins
		 * @return the char age/hrs/mins
		 */
		public int age();

		/**
		 * Return the last date
		 * @return the last date
		 */
		public long last();

		/**
		 * Return the char email
		 * @return the char email
		 */
		public String email();

		/**
		 * Return the last ip
		 * @return the last ip
		 */
		public String ip();

		/**
		 * Return the char experience
		 * @return the char experience
		 */
		public int exp();

		/**
		 * Return the char experience next lvl
		 * @return the char experience next lvl
		 */
		public int expLvl();

		/**
		 * Return the char liege/mate
		 * @return the char liege/mate
		 */
		public String liege();

		/**
		 * Return the char worship/deity
		 * @return the char worship/deity
		 */
		public String worship();
	}

	/**
	 * The absolute smallest whole view of a player char
	 * is the ThinnerPlayer interface, which requires
	 * the least work pulling from the database,
	 * short of pulling only a single field.
	 *
	 * @author Bo Zimmerman
	 *
	 */
	public static interface ThinnerPlayer
	{
		/**
		 * Get the character name
		 * @return the character name
		 */
		public String name();

		/**
		 * Builder to change the character name
		 * @param name the character name
		 * @return this
		 */
		ThinnerPlayer name(String name);

		/**
		 * Get the char password
		 * @return the char password
		 */
		public String password();

		/**
		 * Builder to change the char password
		 * @param password the char password
		 * @return this
		 */
		ThinnerPlayer password(String password);

		/**
		 * Get the char/acct expiration date
		 * @return the char/acct expiration date
		 */
		public long expiration();

		/**
		 * Builder to change the char/acct expiration date
		 * @param expiration the char/acct expiration date
		 * @return this
		 */
		ThinnerPlayer expiration(long expiration);

		/**
		 * Get the account name
		 * @return the account name
		 */
		public String accountName();

		/**
		 * Builder to change the account name
		 * @param accountName the account name
		 * @return this
		 */
		ThinnerPlayer accountName(String accountName);

		/**
		 * Get the char/acct email
		 * @return the char/acct email
		 */
		public String email();

		/**
		 * Builder to change the char/acct email
		 * @param email the char/acct email
		 * @return this
		 */
		ThinnerPlayer email(String email);
		/**
		 * Get the actual mob object
		 * @return the actual mob object
		 */
		public MOB loadedMOB();

		/**
		 * Builder to change the actual mob object
		 * @param mob the actual mob object
		 * @return this
		 */
		ThinnerPlayer loadedMOB(MOB mob);
	}
}


text:
/**
 * @fileoverview
 * @author Yannick Lagger <lagger.yannick@gmail.com>
 */
YUI.add('wegas-pmg-tablepopup', function(Y) {
    "use strict";

    var Wegas = Y.Wegas, Tablepopup;

    /**
     *  @class add a popup on a table column
     *  @name Y.Plugin.Tablepopup
     *  @extends Y.Plugin.Base
     *  @constructor
     */
    Tablepopup = Y.Base.create("wegas-pmg-tablepopup", Y.Plugin.Base, [Wegas.Plugin, Wegas.Editable], {
        /** @lends Y.Plugin.Tablepopup */
        /**
         * Lifecycle methods
         * @function
         * @private
         */
        initializer: function() {
            this.handlers = [];
            this.menuDetails = new Wegas.Menu({
                width: this.get("width"),
                points: ["tl", "tr"]
            });
            this.bind();
            this.onceAfterHostEvent("render", this.sync);
            this.afterHostMethod("syncUI", this.sync);
            this.get("host").datatable.after("sort", this.sync, this);
        },
        bind: function() {
            Y.log("bind()", "log", "Wegas.Tablepopup");
            var descriptor, field = this.get("field"),
                dt = this.get("host").datatable;

            this.handlers.push(dt.delegate("mouseover", function(e) {
                descriptor = dt.getRecord(e.currentTarget).get("descriptor");
                this.menuDetails.attachTo(e.currentTarget);

                if (descriptor.get(field)) {
                    this.display(descriptor.get(field));
                } else {
                    this.request(descriptor);
                }
            }, ".popup", this));
            this.handlers.push(dt.delegate("mouseout", this.menuDetails.hide, ".popup", this.menuDetails));
        },
        sync: function() {
            var i, dt = this.get("host").datatable;
            for (i = 0; i < dt.get("data").size(); i++) {
                dt.getCell([i, this.get("column")]).addClass("popup");
            }
        },
        request: function(descriptor) {
            Wegas.Facade.Variable.cache.getWithView(descriptor, "Extended", {// Retrieve the object from the server in Export view
                on: Wegas.superbind({
                    success: function(e) {
                        var field = this.get("field"),
                            val = e.response.entity.get(this.get("field"));
                        if (val) {
                            descriptor.set(field, val);
                            this.display(val);
                        } else {
                            this.get("host").showMessage("error", "This information does not exist");
                        }
                    },
                    failure: function() {
                        this.get("host").showMessage("error", "An error occured");
                    }
                }, this)
            });
        },
        display: function(value) {
            this.menuDetails.show();
            this.menuDetails.get("contentBox").setHTML('

' + value + '

');
        },
        /**
         * Destructor methods.
         * @function
         * @private
         */
        destructor: function() {
            for (var i = 0; i < this.handlers.length; i++) {
                this.handlers[i].detach();
            }
        }
    }, {
        ATTRS: {
            width: {
                type: "string",
                value: "250px"
            },
            field: {
                type: "string",
                value: "description"
            },
            column: {
                value: 1,
                _inputex: {
                    _type: "integer",
                    label: "popup on column"
                }
            }
        },
        NS: "tablepopup"
    });
    Y.Plugin.Tablepopup = Tablepopup;
});

redpajama_set_name: RedPajamaGithub


text:
package com.intellij.execution.services;

import org.jetbrains.annotations.NotNull;

public interface ServiceViewProvidingContributor<T, S> extends ServiceViewContributor<T> {
  @NotNull
  S asService();
}


text:
namespace Apache.Ignite
{
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Linq;
    using System.ServiceProcess;
    using System.Threading;
    using Apache.Ignite.Config;
    using Apache.Ignite.Core;
    using Apache.Ignite.Service;

    /// <summary>
    /// Runner class.
    /// </summary>
    public static class IgniteRunner
    {
        /** Help commands. */
        private static readonly IList<string> Help = new List<string> { "/help", "-help", "--help" };

        /** Argument meaning that this is service call. */
        internal static readonly string Svc = "/service";

        /** Service install command. */
        internal static readonly string SvcInstall = "/install";

        /** Service uninstall command. */
        internal static readonly string SvcUninstall = "/uninstall";

        /// <summary>
        /// Application entry point.
        /// </summary>
        internal static void Main(string[] args)
        {
            bool svc = false;
            bool install = false;

            try
            {
                // Check for special cases.
                if (args.Length > 0)
                {
                    string first = args[0].ToLowerInvariant();

                    if (Help.Contains(first))
                    {
                        ConsoleUtils.PrintHelp("Apache.Ignite.exe", true);

                        return;
                    }

                    if (Svc.Equals(first))
                    {
                        args = RemoveFirstArg(args);

                        svc = true;
                    }

                    else if (SvcInstall.Equals(first))
                    {
                        args = RemoveFirstArg(args);

                        install = true;
                    }
                    else if (SvcUninstall.Equals(first))
                    {
                        IgniteService.Uninstall();

                        return;
                    }
                }

                if (!svc)
                {
                    // Pick application configuration first, command line arguments second.
                    var allArgs = AppSettingsConfigurator.GetArgs(ConfigurationManager.AppSettings)
                        .Concat(ArgsConfigurator.GetArgs(args)).ToArray();

                    if (install)
                        IgniteService.DoInstall(allArgs);
                    else
                    {
                        var ignite = Ignition.Start(Configurator.GetConfiguration(allArgs));

                        // Wait until stopped.
                        var evt = new ManualResetEventSlim(false);
                        ignite.Stopped += (s, a) => evt.Set();
                        evt.Wait();
                    }

                    return;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("ERROR: " + e);

                Environment.Exit(-1);
            }

            // If we are here, then this is a service call.
            // Use only arguments, not app.config.
            var cfg = Configurator.GetConfiguration(ArgsConfigurator.GetArgs(args).ToArray());

            ServiceBase.Run(new IgniteService(cfg));
        }

        /// <summary>
        /// Remove the first argument.
        /// </summary>
        /// <param name="args">Arguments.</param>
        /// <returns>New arguments.</returns>
        private static string[] RemoveFirstArg(string[] args)
        {
            return args.Skip(1).ToArray();
        }
    }
}


text: export * from './UsersScene'


text:
<?php

class cloneAndSendCampaignResponse
{

  /**
   *
   * @var int $return
   * @access public
   */
  public $return;

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ch3
{
    class Program
    {
        static void Main(string[] args)
        {
            Counter c1 = new Counter();
            c1++;
            Counter c2 = c1;
            Counter c3 = new Counter();
            c3++;

            Console.WriteLine(c1.Count);
            Console.WriteLine(c2.Count);
            Console.WriteLine(c3.Count);
            Console.WriteLine(c1 == c2);
            Console.WriteLine(c1 == c3);
            Console.WriteLine(c2 == c3);
            Console.WriteLine(object.ReferenceEquals(c1, c2));
            Console.WriteLine(object.ReferenceEquals(c1, c3));
            Console.WriteLine(object.ReferenceEquals(c2, c3));
        }
    }
}


text:
import { take, call, put, select } from 'redux-saga/effects';
import agenda from '../agenda.saga';
import expect from 'expect';

const saga = agenda();

describe('agenda Saga', () => {

});


text:
/**
 *
 */
package com.googlecode.flickrjandroid.photos;

import com.googlecode.flickrjandroid.SearchResultList;
import com.googlecode.flickrjandroid.people.User;

/**
 * Represents the photo favourites result
 *
 * @author yayu
 */
public class PhotoFavouriteUserList extends SearchResultList<User> {

	/**
	 *
	 */
	private static final long serialVersionUID = 8033993738089756037L;
	private String secret;
	private int farm = -1;
	private String server;

	/**
	 *
	 */
	public PhotoFavouriteUserList() {
		super();
	}

	/**
	 * @return the secret
	 */
	public String getSecret() {
		return secret;
	}

	/**
	 * @param secret the secret to set
	 */
	public void setSecret(String secret) {
		this.secret = secret;
	}

	/**
	 * @return the farm
	 */
	public int getFarm() {
		return farm;
	}

	/**
	 * @param farm the farm to set
	 */
	public void setFarm(int farm) {
		this.farm = farm;
	}

	/**
	 * @return the server
	 */
	public String getServer() {
		return server;
	}

	/**
	 * @param server the server to set
	 */
	public void setServer(String server) {
		this.server = server;
	}

}


text:
{% block messages_content %}

Success message

Error message

Info message

Warn message

{% endblock %}


text:
zrequire('timerender');
zrequire('muting');
zrequire('stream_data');
set_global('XDate', zrequire('XDate', 'xdate'));
set_global('page_params', {});

run_test('edge_cases', () => {
    // private messages
    assert(!muting.is_topic_muted(undefined, undefined));
});

const design = {
    stream_id: 100,
    name: 'design',
};

const devel = {
    stream_id: 101,
    name: 'devel',
};

const office = {
    stream_id: 102,
    name: 'office',
};

const social = {
    stream_id: 103,
    name: 'social',
};

const unknown = {
    stream_id: 999,
    name: 'whatever',
};

stream_data.add_sub(design);
stream_data.add_sub(devel);
stream_data.add_sub(office);
stream_data.add_sub(social);

run_test('basics', () => {
    assert(!muting.is_topic_muted(devel.stream_id, 'java'));
    muting.add_muted_topic(devel.stream_id, 'java');
    assert(muting.is_topic_muted(devel.stream_id, 'java'));

    // test idempotentcy
    muting.add_muted_topic(devel.stream_id, 'java');
    assert(muting.is_topic_muted(devel.stream_id, 'java'));

    muting.remove_muted_topic(devel.stream_id, 'java');
    assert(!muting.is_topic_muted(devel.stream_id, 'java'));

    // test idempotentcy
    muting.remove_muted_topic(devel.stream_id, 'java');
    assert(!muting.is_topic_muted(devel.stream_id, 'java'));

    // test unknown stream is harmless too
    muting.remove_muted_topic(unknown.stream_id, 'java');
    assert(!muting.is_topic_muted(unknown.stream_id, 'java'));
});

run_test('get_and_set_muted_topics', () => {
    assert.deepEqual(muting.get_muted_topics(), []);
    muting.add_muted_topic(office.stream_id, 'gossip', 1577836800);
    muting.add_muted_topic(devel.stream_id, 'java', 1577836800);
    assert.deepEqual(muting.get_muted_topics().sort(), [
        {
            date_muted: 1577836800000,
            date_muted_str: 'Jan 01',
            stream: devel.name,
            stream_id: devel.stream_id,
            topic: 'java',
        },
        {
            date_muted: 1577836800000,
            date_muted_str: 'Jan 01',
            stream: office.name,
            stream_id: office.stream_id,
            topic: 'gossip',
        }]);

    blueslip.expect('warn', 'Unknown stream in set_muted_topics: BOGUS STREAM');

    page_params.muted_topics = [
        ['social', 'breakfast', 1577836800],
        ['design', 'typography', 1577836800],
        ['BOGUS STREAM', 'whatever', 1577836800],
    ];
    muting.initialize();

    assert.deepEqual(muting.get_muted_topics().sort(), [
        {
            date_muted: 1577836800000,
            date_muted_str: 'Jan 01',
            stream: social.name,
            stream_id: social.stream_id,
            topic: 'breakfast',
        },
        {
            date_muted: 1577836800000,
            date_muted_str: 'Jan 01',
            stream: design.name,
            stream_id: design.stream_id,
            topic: 'typography',
        }]);
});

run_test('case_insensitivity', () => {
    muting.set_muted_topics([]);
    assert(!muting.is_topic_muted(social.stream_id, 'breakfast'));
    muting.set_muted_topics([
        ['SOCial', 'breakfast'],
    ]);
    assert(muting.is_topic_muted(social.stream_id, 'breakfast'));
    assert(muting.is_topic_muted(social.stream_id, 'breakFAST'));
});


text:
import argparse, fnmatch, os, subprocess, sys

def try_which(program):
    if os.path.dirname(program):
        if os.path.isfile(program) and os.access(program, os.X_OK):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            file_exe = os.path.join(path.strip('\'').strip('\"'), program)
            if os.path.isfile(file_exe) and os.access(file_exe, os.X_OK):
                return file_exe

def which(program):
    exes = []
    if sys.platform.startswith("win") and not program.lower().endswith(".exe"):
        exes.extend(["exe", "exE", "eXe", "eXE", "Exe", "ExE", "EXe", "EXE"])
    if not exes: return try_which(program)
    for exe in exes:
        if try_which(program + '.' + exe): return program
    return None
kSignCMDAvailable = which("kSignCMD")
codsignAvailable = which("codesign")

def getPFXFile():
    file = os.path.join(os.path.expanduser('~'), "certificate.pfx")
    return None if not os.path.isfile(file) else file
PFXFile = getPFXFile()

def getPFXPass():
    file = os.path.join(os.path.expanduser('~'), "certificate.txt")
    if not os.path.isfile(file): return None
    with open(file, 'r') as file: return file.readline().strip()
PFXPass = getPFXPass()

def getIdentity():
    file = os.path.join(os.path.expanduser('~'), "identity.txt")
    if not os.path.isfile(file): return None
    with open(file, 'r') as file: return file.readline().strip()
identity = getIdentity()

def signFile(file):
    if sys.platform.startswith("win"):
        if kSignCMDAvailable and PFXFile and PFXPass:
            if not subprocess.call(["kSignCMD",
            "/f", PFXFile, "/p", PFXPass, file.replace("/", "\\")]):
                print "Success"
            else:
                print "Failure"
                raise
        else: print "Skipping"
        return
    elif sys.platform == "darwin":
        if codsignAvailable and identity:
            if not subprocess.call(["codesign",
            "-s", identity, file]):
                print "Success"
            else:
                print "Failure"
                raise
        else: print "Skipping"
        return
    print "Success"

def try_signFile(file):
    print "Signing %s..." % file,
    try: signFile(file)
    except:
        print "Trying again...",
        try: signFile(file)
        except:
            sys.exit("Failed to sign %s." % file)

def main():
    __folder__ = os.path.dirname(os.path.abspath(__file__))
    parser = argparse.ArgumentParser(description = "Sign Script")
    parser.add_argument("target", help = "File or Directory")
    args = parser.parse_args()

    target = args.target
    if not os.path.isabs(target):
        target = os.path.abspath(target)

    if os.path.isfile(target): try_signFile(target)
    else:

        extensions = ["*.[rR][uU][nN]", "*.[sS][oO]"]
        if sys.platform.startswith("win"):
            extensions = ["*.[eE][xX][eE]", "*.[dD][lL][lL]"]
        elif sys.platform == "darwin":
            extensions = ["*.[aA][pP][pP]", "*.[dD][yY][lL][iI][bB]"]

        for dirpath, dirnames, filenames in os.walk(target):
            paths = dirnames + filenames
            for extension in extensions:
                for path in fnmatch.filter(paths, extension):
                    try_signFile(os.path.join(dirpath, path))

if __name__ == "__main__":
    main()


text:
@implementation ExpandableCellModel

- (instancetype)initWithContent:(id)content level:(NSInteger)level {
    if (self = [super init]) {
        self.level = level;
        self.content = content;
        self.subLevelNodes = [@[] mutableCopy];

    }
    return self;
}

- (instancetype)init {
    if (self = [self initWithContent:nil level:-1]) {

    }
    return self;
}

- (void)setSuperLevelNode:(ExpandableCellModel *)superLevelNode {
    _superLevelNode = superLevelNode;
    [_superLevelNode.subLevelNodes addObject:self];
}

- (void)setIsSelected:(BOOL)isSelected {
    _isSelected = isSelected;
    for (ExpandableCellModel *subModel in self.subLevelNodes) {
        subModel.isVisible = _isSelected;
    }
}

- (void)setIsVisible:(BOOL)isVisible {
    _isVisible = isVisible;

    // ignore section node
    if (!self.level) {
        return;
    }
    // set all subNodes's isVisible
    if (!isVisible) {
        for (ExpandableCellModel *subModel in self.subLevelNodes) {
            subModel.isVisible = isVisible;
        }
    }
}

@end


text:
<?php

/**
 * Factory for the different code rank strategies.
 *
 * @category   QualityAssurance
 * @package    PHP_Depend
 * @subpackage Metrics
 * @author     Manuel Pichler <mapi@pdepend.org>
 * @copyright  2008-2012 Manuel Pichler. All rights reserved.
 * @license    http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @version    Release: @package_version@
 * @link       http://pdepend.org/
 */
class PHP_Depend_Metrics_CodeRank_StrategyFactory
{
    /**
     * The identifier for the inheritance strategy.
     */
    const STRATEGY_INHERITANCE = 'inheritance';

    /**
     * The identifier for the property strategy.
     */
    const STRATEGY_PROPERTY = 'property';

    /**
     * The identifier for the method strategy.
     */
    const STRATEGY_METHOD = 'method';

    /**
     * The default strategy.
     *
     * @var string
     */
    private $defaultStrategy = self::STRATEGY_INHERITANCE;

    /**
     * List of all valid properties.
     *
     * @var array(string)
     */
    private $validStrategies = array(
        self::STRATEGY_INHERITANCE,
        self::STRATEGY_METHOD,
        self::STRATEGY_PROPERTY
    );

    /**
     * Creates the default code rank strategy.
     *
     * @return PHP_Depend_Metrics_CodeRank_CodeRankStrategyI
     */
    public function createDefaultStrategy()
    {
        return $this->createStrategy($this->defaultStrategy);
    }

    /**
     * Creates a code rank strategy for the given identifier.
     *
     * @param string $strategyName The strategy identifier.
     *
     * @return PHP_Depend_Metrics_CodeRank_CodeRankStrategyI
     * @throws InvalidArgumentException If the given <b>$id</b> is not valid or
     *                                  no matching class declaration exists.
     */
    public function createStrategy($strategyName)
    {
        if (in_array($strategyName, $this->validStrategies) === false) {
            throw new InvalidArgumentException(
                sprintf('Cannot load file for identifier "%s".', $strategyName)
            );
        }

        // Prepare identifier
        $name = ucfirst(strtolower($strategyName));

        $fileName  = "PHP/Depend/Metrics/CodeRank/{$name}Strategy.php";
        $className = "PHP_Depend_Metrics_CodeRank_{$name}Strategy";

        include_once $fileName;

        return new $className();
    }
}


text: Data Cleansing: Human Activity Recognition Using Smartphones


text:
#pragma once

#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>

#ifdef __cplusplus
extern "C" {
#endif

typedef uint32_t warp_pool_id_t;
#define WARP_POOL_ID_INVALID 0
#define WARP_POOL_MAX_COUNT 0xffff

typedef struct warp_pool warp_pool_t;

warp_pool_t *warp_pool_create
    (size_t max_items_count, size_t item_size, void (*item_deinit)(void *));
void warp_pool_destroy(warp_pool_t *pool);

/* Each pool has it's name (gloabl identifier). Name of the pool is used to
 * mark item IDs owned by the pool (this prevents using IDs generate by one
 * pool with another). This function allows to set name of the pool to
 * predefined value as a mean to overwrite this mechanism. */
void warp_pool_set_name(warp_pool_t *pool, uint16_t name);

size_t warp_pool_get_count(const warp_pool_t *pool);
size_t warp_pool_get_capacity(const warp_pool_t *pool);
bool warp_pool_is_id_valid(const warp_pool_t *pool, warp_pool_id_t id);

void warp_pool_map
    (const warp_pool_t *pool, void (*f)(void *, void *), void *context);

warp_pool_id_t warp_pool_create_item(warp_pool_t *pool);
void *warp_pool_get_data(const warp_pool_t *pool, warp_pool_id_t id);

/* This one is intended to be used by warp_pool_get macro */
void *warp_pool_get_data_and_check_size
        (const warp_pool_t *pool, warp_pool_id_t id, size_t item_size);

bool warp_pool_destroy_item(warp_pool_t *pool, warp_pool_id_t id);
/* TODO: remove this one */
bool warp_pool_destroy_item_deprecated(warp_pool_t *pool, void *item);
void warp_pool_clear(warp_pool_t *pool);

/* pool iteration: */
typedef struct warp_pool_it warp_pool_it_t;

warp_pool_it_t *warp_pool_iterate(warp_pool_t *pool);
warp_pool_it_t *warp_pool_it_next(warp_pool_it_t *it);
void *warp_pool_it_get_data(warp_pool_it_t *it);
warp_pool_id_t warp_pool_it_to_id(warp_pool_t *pool, warp_pool_it_t *it);

/* some helpers: */
#define warp_pool_create_typed(type, capacity, element_deinit) \
    warp_pool_create(capacity, sizeof (type), element_deinit)

#define warp_pool_get(type, pool, id) \
    ((type *)warp_pool_get_data_and_check_size(pool, id, sizeof (type)))

#define warp_pool_it_get(type, it) ((type *)warp_pool_it_get_data(it))

#ifdef __cplusplus
}
#endif

#ifdef WARP_DROP_PREFIX
typedef warp_pool_id_t pool_id_t;
typedef warp_pool_t pool_t;
typedef warp_pool_it_t pool_it_t;

#define pool_create(...) warp_pool_create(__VA_ARGS__)
#define pool_destroy(...) warp_pool_destroy(__VA_ARGS__)
#define pool_set_name(...) warp_pool_set_name(__VA_ARGS__)
#define pool_get_count(...) warp_pool_get_count(__VA_ARGS__)
#define pool_get_capacity(...) warp_pool_get_capacity(__VA_ARGS__)
#define pool_is_id_valid(...) warp_pool_is_id_valid(__VA_ARGS__)
#define pool_map(...) warp_pool_map(__VA_ARGS__)
#define pool_destroy_item(...) warp_pool_destroy_item(__VA_ARGS__)
#define pool_clear(...) warp_pool_clear(__VA_ARGS__)
#define pool_create_item(...) warp_pool_create_item(__VA_ARGS__)
#define pool_get_data(...) warp_pool_get_data(__VA_ARGS__)
#define pool_iterate(...) warp_pool_iterate(__VA_ARGS__)
#define pool_it_next(...) warp_pool_it_next(__VA_ARGS__)
#define pool_it_get(...) warp_pool_it_get(__VA_ARGS__)
#define pool_it_to_id(...) warp_pool_it_to_id(__VA_ARGS__)

#define pool_create_typed(...) warp_pool_create_typed(__VA_ARGS__)
#define pool_get(...) warp_pool_get(__VA_ARGS__)
#endif


text:
// Copyright 2017 Google LLC. All Rights Reserved.
//
// 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 com.google.monitoring.metrics;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.time.Instant;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Unit tests for {@link StoredMetric}. */
@RunWith(JUnit4.class)
public class StoredMetricTest {

  @Test
  public void testGetCardinality_reflectsCurrentCardinality() {
    StoredMetric<Boolean> smallMetric =
        new StoredMetric<>("/metric", "description", "vdn", ImmutableSet.of(), Boolean.class);
    assertThat(smallMetric.getCardinality()).isEqualTo(0);

    smallMetric.set(true);

    assertThat(smallMetric.getCardinality()).isEqualTo(1);

    StoredMetric<Boolean> dimensionalMetric =
        new StoredMetric<>(
            "/metric",
            "description",
            "vdn",
            ImmutableSet.of(LabelDescriptor.create("foo", "bar")),
            Boolean.class);

    dimensionalMetric.set(true, "test_value1");
    dimensionalMetric.set(true, "test_value2");

    assertThat(dimensionalMetric.getCardinality()).isEqualTo(2);
  }

  @Test
  public void testSet_wrongNumberOfLabels_throwsException() {
    StoredMetric<Boolean> dimensionalMetric =
        new StoredMetric<>(
            "/metric",
            "description",
            "vdn",
            ImmutableSet.of(
                LabelDescriptor.create("label1", "bar"), LabelDescriptor.create("label2", "bar")),
            Boolean.class);

    IllegalArgumentException thrown =
        assertThrows(IllegalArgumentException.class, () -> dimensionalMetric.set(true, "foo"));
    assertThat(thrown)
        .hasMessageThat()
        .contains(
            "The count of labelValues must be equal to the underlying Metric's count of labels.");
  }

  @Test
  public void testSet_setsValue() {
    StoredMetric<Boolean> metric =
        new StoredMetric<>(
            "/metric",
            "description",
            "vdn",
            ImmutableSet.of(LabelDescriptor.create("label1", "bar")),
            Boolean.class);

    assertThat(metric.getTimestampedValues()).isEmpty();

    metric.set(true, ImmutableList.of("test_value1"));
    assertThat(metric.getTimestampedValues(Instant.ofEpochMilli(1337)))
        .containsExactly(
            MetricPoint.create(
                metric, ImmutableList.of("test_value1"), Instant.ofEpochMilli(1337), true));

    metric.set(false, ImmutableList.of("test_value1"));
    metric.set(true, ImmutableList.of("test_value2"));
    assertThat(metric.getTimestampedValues(Instant.ofEpochMilli(1338)))
        .containsExactly(
            MetricPoint.create(
                metric, ImmutableList.of("test_value1"), Instant.ofEpochMilli(1338), false),
            MetricPoint.create(
                metric, ImmutableList.of("test_value2"), Instant.ofEpochMilli(1338), true));
  }
}


text:
/

typedef struct
{
	U32 face;    ///< index of face to modify.
	U32 corner;  ///< which corner of the face to modify.
	U32 newUp;   ///< new vertex index to use when increasing the resolution.
	U32 newDown; ///< new vertex index to use when decreasing the resolution.
} IFXFaceUpdate;

/**
With IFXMesh a single resolution change may involve more than one vertex.
*/
class IFXResolutionChange
{
public:
	IFXResolutionChange() { deltaVerts = 0; deltaFaces = 0; numFaceUpdates = 0; };
	U32 deltaVerts;	  ///< number of vertices added or removed.
	U32 deltaFaces;	  ///< number of faces added or removed.
	U32 numFaceUpdates;	 ///< number of faces that need to be modified because of resolution change.
};

/**
Just as IFXMeshGroup contains IFXMeshes, IFXUpdatesGroup contains IFXUpdates.
Each IFXMesh in an IFXMeshGroup has a corresponding IFXUpdates object
in the IFXUpdateGroup object.
*/
class IFXUpdates
{

public:

    /**Class constructor. */
	IFXUpdates();
	/**Class destructor. */
	~IFXUpdates();

	/**
		Allocates resolution change and updates number.

		@param	rc	Resolution change number
		@param	fu	Face update number

		@return	IFXResult
	 */

	IFXRESULT Allocate(U32 rc, U32 fu);

	U32 numResChanges;
	IFXResolutionChange *pResChanges;

	U32 numFaceUpdates;
	IFXFaceUpdate *pFaceUpdates;
};

IFXINLINE IFXUpdates::IFXUpdates()
{
    numResChanges = 0;
    numFaceUpdates = 0;
    pResChanges = NULL;
    pFaceUpdates = NULL;
}

IFXINLINE IFXUpdates::~IFXUpdates()
{
    if (pFaceUpdates)
    {
        delete[] pFaceUpdates;
        pFaceUpdates = NULL;
    }

    if (pResChanges)
    {
        delete[] pResChanges;
        pResChanges = NULL;
    }
}

/*
IFXINLINE IFXRESULT IFXUpdates::Allocate()
{
    if (pResChanges)
    {
        delete pResChanges;
        pResChanges = NULL;
    }
	pResChanges = new IFXResolutionChange[numResChanges];

    if (pFaceUpdates)
    {
        delete pFaceUpdates;
        pFaceUpdates = NULL;
    }
	pFaceUpdates = new IFXFaceUpdate[numFaceUpdates];

    if (pResChanges && pFaceUpdates)
		return IFX_OK;
	else
		return IFX_E_OUT_OF_MEMORY;
};
*/

IFXINLINE IFXRESULT IFXUpdates::Allocate(U32 rc, U32 fu)
{
	IFXRESULT returnCode = IFX_OK;
    if (pResChanges)
    {
        delete [] pResChanges;
        pResChanges = NULL;
    }
    if (pFaceUpdates)
    {
        delete [] pFaceUpdates;
        pFaceUpdates = NULL;
    }

	pResChanges     = new IFXResolutionChange[rc];
	pFaceUpdates    = new IFXFaceUpdate[fu];

	if(pResChanges && pFaceUpdates)
    {
//		memset(pResChanges,0,rc*sizeof(IFXResolutionChange));
//		memset(pFaceUpdates,0,fu*sizeof(IFXFaceUpdate));
		numResChanges = rc;
		numFaceUpdates = fu;
	}
	else
	{
		if (pResChanges)
		{
			delete [] pResChanges;
			pResChanges = NULL;
		}
		if (pFaceUpdates)
		{
			delete [] pFaceUpdates;
			pFaceUpdates = NULL;
		}

		returnCode = IFX_E_OUT_OF_MEMORY;
	}
	return returnCode;
}

#endif


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="co.infinum.https.MainActivity" >

    <item android:id="@+id/action_apache"
        android:title="@string/apache_request"
        app:showAsAction="never" />

    <item android:id="@+id/action_retrofit"
        android:title="@string/retrofit_request"
        app:showAsAction="never" />

    <item android:id="@+id/action_not_allowed"
        android:title="@string/action_other"
        android:orderInCategory="100"
        app:showAsAction="never" />
</menu>


text:
package net.sf.javaml.distance;

import net.sf.javaml.core.Instance;

/**
 * Specialized similarity that takes the maximum product of two feature values.
 * If this value is zero, the similarity is undefined. This similarity measure
 * is used mainly with features extracted from cluster models.
 *
 * @author Michael Wurst
 * @author Thomas Abeel
 */
public class MaxProductSimilarity extends AbstractSimilarity {
    /**
     *
     */
    private static final long serialVersionUID = 3737968543405527283L;

    /**
     * XXX doc
     */
    public double measure(Instance x, Instance y) {

        double max = Double.NEGATIVE_INFINITY;

        for (int i = 0; i < x.noAttributes(); i++) {

            double v = x.value(i) * y.value(i);

            if (v > max)
                max = v;

        }

        if (max > 0.0)
            return max;
        else
            return Double.NaN;
    }

}


text:
<?php
/**
 * Index model
 */
class IndexModel extends Model
{
	public function __construct()
	{
		parent::__construct();
	}
}


text:
Name:        Cookie
Description: Recipes dealing with Laravel's Cookie component.
Id:          12
Position:    8
---


text:
package com.planet_ink.coffee_mud.Abilities.Properties;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class Prop_ShortEffects extends Property
{
	@Override
	public String ID()
	{
		return "Prop_ShortEffects";
	}

	@Override
	public String name()
	{
		return "Short Effects";
	}

	@Override
	protected int canAffectCode()
	{
		return Ability.CAN_MOBS;
	}

	@Override
	public String accountForYourself()
	{
		return "";
	}

	protected volatile int					lastNumEffects	= 0;
	protected int							maxTicks		= 3;
	protected MaskingLibrary.CompiledZMask	mask			= null;

	@Override
	public void setMiscText(String newMiscText)
	{
		super.setMiscText(newMiscText);
		int x=newMiscText.indexOf(';');
		maxTicks=3;
		mask=null;
		if((x>0)&&(CMath.isInteger(newMiscText.substring(0,x).trim())))
		{
			maxTicks = CMath.s_int(newMiscText.substring(0,x).trim());
			newMiscText=newMiscText.substring(x+1).trim();
		}
		if(newMiscText.trim().length()>0)
			mask=CMLib.masking().getPreCompiledMask(newMiscText);
	}

	@Override
	public boolean tick(final Tickable ticking, final int tickID)
	{
		final Physical affected = this.affected;
		if(affected != null)
		{
			if(affected.numEffects() != this.lastNumEffects)
			{
				this.lastNumEffects = affected.numEffects();
				final Set<MOB> badInvokers = new HashSet<MOB>();
				if((affected instanceof Item)
				&&(((Item)affected).owner() instanceof MOB))
					badInvokers.add((MOB)((Item)affected).owner());
				else
				if(affected instanceof MOB)
					((MOB)affected).getGroupMembers(badInvokers);
				for(final Enumeration<Ability> a=affected.effects();a.hasMoreElements();)
				{
					final Ability A=a.nextElement();
					if((A!=null)
					&&(A.canBeUninvoked())
					&&((A.invoker()==null)||(!badInvokers.contains(A.invoker())))
					&&((mask==null)||(CMLib.masking().maskCheck(mask, A, true))))
					{
						if(CMath.s_int(A.getStat("TICKDOWN"))>maxTicks)
							A.setStat("TICKDOWN", ""+maxTicks);
					}
				}
			}
		}
		return super.tick(ticking,tickID);
	}
}


text:
use irl_tests;
select * from a order by a.id;


text:
using System.Collections.Generic;
using Umbraco.Core.Models.Rdbms;

namespace Umbraco.Core.Persistence.Relators
{
    internal class UserGroupSectionRelator
    {
        internal UserGroupDto Current;

        internal UserGroupDto Map(UserGroupDto a, UserGroup2AppDto p)
        {
            // Terminating call.  Since we can return null from this function
            // we need to be ready for PetaPoco to callback later with null
            // parameters
            if (a == null)
                return Current;

            // Is this the same object as the current one we're processing
            if (Current != null && Current.Id == a.Id)
            {
                if (p.AppAlias.IsNullOrWhiteSpace() == false)
                {
                    // Yes, just add this to the current item's collection
                    Current.UserGroup2AppDtos.Add(p);
                }

                // Return null to indicate we're not done with this User yet
                return null;
            }

            // This is a different object to the current one, or this is the
            // first time through and we don't have one yet

            // Save the current instance
            var prev = Current;

            // Setup the new current instance
            Current = a;
            Current.UserGroup2AppDtos = new List<UserGroup2AppDto>();
            //this can be null since we are doing a left join
            if (p.AppAlias.IsNullOrWhiteSpace() == false)
            {
                Current.UserGroup2AppDtos.Add(p);
            }

            // Return the now populated previous user group (or null if first time through)
            return prev;
        }
    }
}


text:
package org.springframework.build.aws.ant;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.FileSet;
import org.jets3t.service.S3Service;
import org.jets3t.service.ServiceException;
import org.jets3t.service.model.S3Bucket;

/**
 * A member of the S3 ANT task for dealing with Amazon S3 delete behavior. This operation will use the credentials setup
 * in its parent S3 task tag.
 *
 * @author Ben Hale
 */
public class Delete extends AbstractS3Operation {

    private String file;

    private final List<FileSet> fileSets = new ArrayList<FileSet>(1);

    /**
     * Optional parameter that corresponds to the source object key in S3
     *
     * @param file The source object key in S3
     */
    public void setFile(String file) {
        this.file = file;
    }

    /**
     * Adds an optional fileSet to read delete from.
     *
     * @param fileSet The set of files to delete
     */
    public void addFileSet(FileSet fileSet) {
        this.fileSets.add(fileSet);
    }

    /**
     * Verify that required parameters have been set
     */
    public void init() {
        if (this.bucketName == null) {
            throw new BuildException("bucketName must be set");
        }
        if ((this.file != null) && (this.fileSets.size() > 0)) {
            throw new BuildException("Only one of file and <fileset> may be set");
        }
        if ((this.file == null) && (this.fileSets.size() == 0)) {
            throw new BuildException("At least one of file and <fileset> must be set");
        }
    }

    public void execute(S3Service service) throws ServiceException, IOException {
        if (this.file != null) {
            processFile(service);
        } else if (this.fileSets.size() > 0) {
            processSet(service);
        }
    }

    private void processFile(S3Service service) throws ServiceException {
        deleteFile(service, getOperationBucket(), this.file);
    }

    private void processSet(S3Service service) throws IOException, ServiceException {
        S3Bucket bucket = getOperationBucket();
        for (FileSet fileSet : this.fileSets) {
            S3Scanner scanner = getS3Scanner(bucket, fileSet.mergePatterns(this.project), getS3SafeDirectory(fileSet.getDir()));
            List<String> keys = scanner.getQualifiyingKeys(service);
            for (String key : keys) {
                deleteFile(service, bucket, key);
            }
        }
    }

    private void deleteFile(S3Service service, S3Bucket bucket, String key) throws ServiceException {
        service.deleteObject(bucket, key);
        this.project.log("Deleted s3://" + bucket.getName() + "/" + key, Project.MSG_INFO);
    }
}


text:
@extends('admin.templates.app')

@section('content')

{{ $user->name }}

                usn) }}" type="submit" class="btn btn-success btn-xs'">Edit User

	@if($user->privilege != 'Dean')
                @if ($user->active === 1)
                <form action={!! route('admin-block-user', $user->usn) !!} method="POST">
                    {{csrf_field()}}
                    <button type="submit" class="btn btn-danger btn-xs'">Block</button>
                </form>
                @else
                <form action={!! route('admin-unblock-user', $user->usn) !!} method="POST">
                    {{ method_field('PATCH') }}
                    {{csrf_field()}}
                    <button type="submit" class="btn btn-info btn-xs'">Unblock</button>
                </form>
                @endif
	@endif

                @if ($user->privilege == 'Student')

                            Grades

                                            USN
                                            Name
                                            Course
                                            Subject
                                            Section
                                            Grade
                                            Final Mark
                                            Academic Term

                @endif

                            Schedule this semester

@endsection

@push('admin-css')
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.13/r-2.1.1/datatables.min.css"/>
      <link href="{{ asset('dist/plugins/fullcalendar/fullcalendar.min.css') }}" rel="stylesheet">

@endpush

@push('admin-js')

@endpush


text:
Ubicar los links a los gdoc y otros recursos web aquí con el siguiente **formato**

## GitHub tricks
[Sintaxis de archivos .md](https://help.github.com/articles/markdown-basics)

[Markdown Cheat Sheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)

## Roadmap
[Roadmap de investigación, general y por subgrupo](https://docs.google.com/spreadsheets/d/1ZKLpWA_RVWShLlEoccXwNpd-vAta9xmPdP-1avtj2go/edit)

## Referecia bibliográfica
[E-books](https://drive.google.com/?tab=mo&authuser=0#folders/0B6zTFMqBdW-0VXJpaE5SYjlxUlk)

## Vagrant
[Vagrant](http://www.vagrantup.com/) es una herramienta para la creación y configuración de ambientes virtuales, es una muy buena forma de que todos compartamos ambientes equivalentes.
Hay versiones para linux, windows y mac y también hay para elegir si usamos VBox o VMWare.

Provee formas muy faciles de fowaredear puertos, compartir carpetas, manejar los ambientes, etc.
Dejo [Vagrant 101](http://codehero.co/como-instalar-y-configurar-vagrant/) y el [getting started](http://docs.vagrantup.com/v2/getting-started/index.html) oficial

## MongoDB

[MongoDB](http://www.mongodb.org/) es un sistema de base de datos NoSQL orientado a documentos. En vez de guardar los datos en tablas como se hace en las base de datos relacionales, MongoDB guarda estructuras de datos en documentos tipo JSON con un esquema dinámico, haciendo que la integración de los datos en ciertas aplicaciones sea más fácil y rápida.

Les dejo una serie de post que ya habia mandado por mail, como para arrancar:

- [MongoDB: que es, como funciona, y cuando usarlo o no](http://www.genbetadev.com/bases-de-datos/mongodb-que-es-como-funciona-y-cuando-podemos-usarlo-o-no)
- [Insertando datos](http://www.genbetadev.com/bases-de-datos/mongodb-empezando-por-el-principio-insertando-datos)
- [Operaciones de actualizacion simples](http://www.genbetadev.com/bases-de-datos/mongodb-la-vida-cambia-tus-datos-tambien-operaciones-de-actualizacion-simples)
- [Actualizando subdocumentos y arrays](http://www.genbetadev.com/bases-de-datos/mongodb-la-vida-cambia-tus-datos-tambien-actualiza-subdocumentos-y-anade-datos-a-un-array)
- [Eliminando elementos de arrays y documentos completos](http://www.genbetadev.com/bases-de-datos/mongodb-la-vida-cambia-tus-datos-tambien-eliminando-elementos-de-un-array-y-documentos-completos)

Ademas la documentacion de algunos drivers que nos puede llegar a servir:

- [Java](http://docs.mongodb.org/ecosystem/drivers/java/)
- [Node.js](http://docs.mongodb.org/ecosystem/drivers/node-js/)
- [Python](http://docs.mongodb.org/ecosystem/drivers/python/)


text:
{% extends '_pymchild.html' %}

{% block head_stuff %}
	{{ CSS.push('less/location.less') }}
	{{ CSS.render('css/rendered/location.min.css') }}
{% endblock %}

{% block body %}

		← back to list
		Tracking ID: {{ location.id }}

{{ location.location_name }}

		{% include '_abandonware.html' %}
		{% if status %}

status: {{status.color}}

				{{ status.status|urlize }}
				Last updated: {{ status.date }} {{ status.time }}

		{% else %}

last status: unknown

This location has no known status. Please contribute status information by following the instructions at this link.

		{% endif %}

Location information:

Owner:

{{location.location_owner }}

Address:

<address>
					{{ location.address }}

					{{ location.city }}, {{ location.state }}, {{ location.zip|format_zip }}
				</address>

Phone:

				{% if location.phone %}

{{ location.phone }}

				{% else %}

This location has no known phone number. Please contribute one by following the instructions at this link.

				{% endif %}

			{% if location.mpn %}

Medicare Provider Number

{{ location.mpn }}

			{% endif %}

All status updates:

				{% for status in history %}

						{{ status.date }}
						{{ status.time }}
						{{status.color}}
						{{ status.status|urlize }}

				{% else %}

This location has no known status. Please contribute status information by following the instructions at this link.

				{% endfor %}

	{{ COPY.content.table_footer }}

{% endblock %}


text:
str_to_int = {
    'unknown': 0,
    'saccade': 1,
    'fixation': 2
}

int_to_str = [
    'unknown',
    'saccade',
    'fixation'
]

class ClassError(Exception):
    pass

def convert_to_integers(stringclasses):
    for s in stringclasses:
        if s in str_to_int:
            yield str_to_int[s]
        else:
            raise ClassError('Invalid class string')

def convert_to_strings(intclasses):
    for i in intclasses:
        if i >= 0 and i < len(int_to_str):
            yield int_to_str[i]
        else:
            raise ClassError('Invalid class integer')


text:
%MIT License

%Copyright (c) 2017 Alaa Alassi

%Permission is hereby granted, free of charge, to any person obtaining a copy
%of this software and associated documentation files (the "Software"), to deal
%in the Software without restriction, including without limitation the rights
%to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
%copies of the Software, and to permit persons to whom the Software is
%furnished to do so, subject to the following conditions:

%The above copyright notice and this permission notice shall be included in all
%copies or substantial portions of the Software.

%THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
%IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
%FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
%AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
%LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
%OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
%SOFTWARE.

function [ Force ] = Constain3D(Pos,Borders,stiffness)

 if ~isequal([1 3], size(Borders)),
    error('E:Constain3D','Borders must be 1 x 3 Vector');
 end

 if ~isequal([3 1], size(Pos)),
    error('E:Constain3D','Pos must be 3 x 1 Vector');
 end

 Force = zeros(3,1);

for i=1:3
    if(Pos(i) < Borders(i))
        Force(i) = -(Pos(i)-Borders(i))*stiffness;
    else
    Force(i) = 0;
    end
end

end


text:
namespace views {

class StyledLabelTest : public testing::Test, public StyledLabelListener {
 public:
  StyledLabelTest() {}
  virtual ~StyledLabelTest() {}

  // StyledLabelListener implementation.
  virtual void StyledLabelLinkClicked(const ui::Range& range,
                                      int event_flags) OVERRIDE {}

 protected:
  StyledLabel* styled() { return styled_.get(); }

  void InitStyledLabel(const std::string& ascii_text) {
    styled_.reset(new StyledLabel(ASCIIToUTF16(ascii_text), this));
  }

  int StyledLabelContentHeightForWidth(int w) {
    return styled_->GetHeightForWidth(w) - styled_->GetInsets().height();
  }

 private:
  scoped_ptr<StyledLabel> styled_;

  DISALLOW_COPY_AND_ASSIGN(StyledLabelTest);
};

TEST_F(StyledLabelTest, NoWrapping) {
  const std::string text("This is a test block of text");
  InitStyledLabel(text);
  Label label(ASCIIToUTF16(text));
  const gfx::Size label_preferred_size = label.GetPreferredSize();
  EXPECT_EQ(label_preferred_size.height(),
            StyledLabelContentHeightForWidth(label_preferred_size.width() * 2));
}

TEST_F(StyledLabelTest, BasicWrapping) {
  const std::string text("This is a test block of text");
  InitStyledLabel(text);
  Label label(ASCIIToUTF16(text.substr(0, text.size() * 2 / 3)));
  gfx::Size label_preferred_size = label.GetPreferredSize();
  EXPECT_EQ(label_preferred_size.height() * 2,
            StyledLabelContentHeightForWidth(label_preferred_size.width()));

  // Also respect the border.
  styled()->set_border(Border::CreateEmptyBorder(3, 3, 3, 3));
  styled()->SetBounds(
      0,
      0,
      styled()->GetInsets().width() + label_preferred_size.width(),
      styled()->GetInsets().height() + 2 * label_preferred_size.height());
  styled()->Layout();
  ASSERT_EQ(2, styled()->child_count());
  EXPECT_EQ(3, styled()->child_at(0)->bounds().x());
  EXPECT_EQ(3, styled()->child_at(0)->bounds().y());
  EXPECT_EQ(styled()->bounds().height() - 3,
            styled()->child_at(1)->bounds().bottom());
}

TEST_F(StyledLabelTest, CreateLinks) {
  const std::string text("This is a test block of text.");
  InitStyledLabel(text);
  styled()->AddLink(ui::Range(0, 1));
  styled()->AddLink(ui::Range(1, 2));
  styled()->AddLink(ui::Range(10, 11));
  styled()->AddLink(ui::Range(12, 13));

  styled()->SetBounds(0, 0, 1000, 1000);
  styled()->Layout();
  ASSERT_EQ(7, styled()->child_count());
}

TEST_F(StyledLabelTest, DontBreakLinks) {
  const std::string text("This is a test block of text, ");
  const std::string link_text("and this should be a link");
  InitStyledLabel(text + link_text);
  styled()->AddLink(ui::Range(text.size(), text.size() + link_text.size()));

  Label label(ASCIIToUTF16(text + link_text.substr(0, link_text.size() / 2)));
  gfx::Size label_preferred_size = label.GetPreferredSize();
  int pref_height = styled()->GetHeightForWidth(label_preferred_size.width());
  EXPECT_EQ(label_preferred_size.height() * 2,
            pref_height - styled()->GetInsets().height());

  styled()->SetBounds(0, 0, label_preferred_size.width(), pref_height);
  styled()->Layout();
  ASSERT_EQ(2, styled()->child_count());
  EXPECT_EQ(0, styled()->child_at(0)->bounds().x());
  EXPECT_EQ(0, styled()->child_at(1)->bounds().x());
}

TEST_F(StyledLabelTest, HandleEmptyLayout) {
  const std::string text("This is a test block of text, ");
  InitStyledLabel(text);
  styled()->Layout();
  ASSERT_EQ(0, styled()->child_count());
}

}  // namespace


text:
namespace MassTransit.RetryPolicies
{
    using System;

    public class RetryConsumerConsumeContext<TConsumer> :
        RetryConsumeContext,
        ConsumerConsumeContext<TConsumer>
        where TConsumer : class
    {
        readonly ConsumerConsumeContext<TConsumer> _context;

        public RetryConsumerConsumeContext(ConsumerConsumeContext<TConsumer> context, IRetryPolicy retryPolicy, RetryContext retryContext)
            : base(context, retryPolicy, retryContext)
        {
            _context = context;
        }

        public TConsumer Consumer => _context.Consumer;

        public override TContext CreateNext<TContext>(RetryContext retryContext)
        {
            return new RetryConsumerConsumeContext<TConsumer>(_context, RetryPolicy, retryContext) as TContext
                ?? throw new ArgumentException($"The context type is not valid: {TypeCache<TContext>.ShortName}");
        }
    }
}