text:
package mg.fishchicken.gamelogic.actions;

import java.io.IOException;

import mg.fishchicken.core.GameObject;
import mg.fishchicken.core.GameState;
import mg.fishchicken.core.configuration.Configuration;
import mg.fishchicken.core.i18n.Strings;
import mg.fishchicken.core.logging.Log;
import mg.fishchicken.core.logging.Log.LogType;
import mg.fishchicken.core.projectiles.OnProjectileHitCallback;
import mg.fishchicken.core.projectiles.Projectile;
import mg.fishchicken.core.projectiles.ProjectileTarget;
import mg.fishchicken.core.projectiles.ProjectileType;
import mg.fishchicken.core.util.MathUtil;
import mg.fishchicken.core.util.Orientation;
import mg.fishchicken.gamelogic.characters.AbstractGameCharacter.State;
import mg.fishchicken.gamelogic.characters.GameCharacter;
import mg.fishchicken.gamelogic.characters.GameCharacter.Skill;
import mg.fishchicken.gamelogic.combat.CombatManager;
import mg.fishchicken.gamelogic.inventory.Inventory;
import mg.fishchicken.gamelogic.inventory.Inventory.ItemSlot;
import mg.fishchicken.gamelogic.inventory.items.InventoryItem;
import mg.fishchicken.gamelogic.inventory.items.Weapon;
import mg.fishchicken.gamestate.Tile;
import mg.fishchicken.gamestate.characters.Stats;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.utils.XmlReader.Element;
import com.badlogic.gdx.utils.XmlWriter;

/**
 * Makes the supplied character attack the other supplied character.
 *
 * Based on the weapons equipped, the attacker will either move
 * to the target and then attack using melee, or he will move to
 * range and use a ranged weapon.
 *

 * Parameters:
 *

 *
targetNpc - NonPlayerCharacter - the NPC to attack
 *

 * @author Annun
 *
 */
public class AttackAction extends MoveToAction implements OnProjectileHitCallback {

	protected GameCharacter character;
	protected GameCharacter target;
	protected boolean attackFinished;
	protected Array<Weapon> attackingWeapons = new Array<Weapon>();
	protected int attackedWeaponCount;

	private Stats stats;
	private String targetId;
	private Tile targetPosition;
	private boolean startedAttack;
	private boolean actionFinished;
	private boolean hasAttacked;
	private boolean rangedAttack;
	private int totalAPCost;
	private ObjectMap<Projectile, Weapon> projetileWeaponMap = new ObjectMap<Projectile, Weapon>();

	public AttackAction() {
	}

	public AttackAction(GameCharacter attacker, GameCharacter target) {
		init(attacker, target);
	}

	@Override
	public void init(ActionsContainer ac, Object... parameters) {
		if (!(ac instanceof GameCharacter)) {
			throw new GdxRuntimeException("AttackAction only works on GameCharacter!");
		}
		startedAttack = false;
		actionFinished = false;
		attackFinished = false;
		hasAttacked = false;
		rangedAttack = false;
		attackedWeaponCount = 0;
		attackingWeapons.clear();
		projetileWeaponMap.clear();
		character = (GameCharacter) ac;
		stats = character.stats();
		targetPosition = null;
		int targetX = -1, targetY = -1;
		if (parameters.length == 1) {
			this.target = (GameCharacter)parameters[0];
		} else if (parameters.length == 2) {
			targetX = (Integer)parameters[0];
			targetY = (Integer)parameters[1];
			this.target = (GameCharacter)character.getMap().getGameObjectAt(targetX, targetY, GameCharacter.class);
		}
		if (target != null) {
			targetId = target.getInternalId();
			targetPosition = target.position().tile();
			targetX = targetPosition.getX();
			targetY = targetPosition.getY();
			target.pauseAllActions();
			rangedAttack = determineAttackingWeapons(character, targetPosition.getX(), targetPosition.getY(), attackingWeapons);
			// check if we cannot perform the attack at all - if we cannot, we are done immediately
			if (isNextToTarget()
					&& rangedAttack
					|| ((!isNextToTarget() && rangedAttack) || (isNextToTarget() && !rangedAttack)) && getAPCostToAttack() > stats.getAPAct()) {
				actionFinished = true;
				attackFinished = true;
			}
		}
		if (targetX > 0 || targetY > 0) {
			super.init(ac, targetX, targetY);
		}
	}

	/**
	 * Returns whether or not the attack of the supplied tile coordinates by the
	 * supplied character will be ranged.
	 *
	 * @param attacker
	 * @param targetX
	 * @param targetY
	 *
	 * @return true if the attack will be ranged, false otherwise
	 */
	public static boolean isRangedAttack(GameCharacter attacker, int targetX, int targetY) {
		return determineAttackingWeapons(attacker, targetX, targetY, null);
	}

	/**
	 * Determines which weapons will the attacker use when attacking the supplied target tile from the attacker's current position.
	 *
	 * It returns whether or not the attack will be ranged.
	 *
	 * @param attacker
	 * @param targetX
	 * @param targetY
	 *
	 * @return true if the attack will be ranged, false otherwise
	 */
	public static boolean determineAttackingWeapons(GameCharacter attacker, int targetX, int targetY, Array<Weapon> attackingWeapons) {
		Tile tile = attacker.position().tile();
		return determineAttackingWeapons(attacker, tile.getX(), tile.getY(), targetX, targetY, attackingWeapons);
	}

	/**
	 * Determines which weapons will the attacker use when attacking the supplied target tile from the supplied from tile.
	 *
	 * It returns whether or not the attack will be ranged.
	 *
	 * @param attacker
	 * @param fromX
	 * @param fromY
	 * @param targetX
	 * @param targetY
	 *
	 * @return true if the attack will be ranged, false otherwise
	 */
	public static boolean determineAttackingWeapons(GameCharacter attacker, int fromX, int fromY, int targetX, int targetY, Array<Weapon> attackingWeapons) {
		boolean returnValue = false;
		Inventory intentory = attacker.getInventory();
		InventoryItem rightEquipped = intentory.getEquipped(ItemSlot.RIGHTHAND);
		InventoryItem leftEquipped = intentory.getEquipped(ItemSlot.LEFTHAND);
		if (attackingWeapons != null) {
			attackingWeapons.clear();
		}

		if (Vector2.dst(fromX, fromY, targetX, targetY) < 2) {
			returnValue = true;
			if (rightEquipped instanceof Weapon && !((Weapon)rightEquipped).isRanged()) {
				if (attackingWeapons != null) {
					attackingWeapons.add((Weapon)rightEquipped);
				}
				returnValue = false;
			}

			if (leftEquipped instanceof Weapon && !((Weapon)leftEquipped).isRanged()) {
				if (attackingWeapons != null) {
					attackingWeapons.add((Weapon)leftEquipped);
				}
				returnValue = false;
			}

			if (!(rightEquipped instanceof Weapon) && !(leftEquipped instanceof Weapon)) {
				returnValue = false;
			}
		} else {
			if (rightEquipped instanceof Weapon && ((Weapon)rightEquipped).isRanged()) {
				if (attackingWeapons != null) {
					attackingWeapons.add((Weapon)rightEquipped);
				}
				returnValue = true;
			}

			if (leftEquipped instanceof Weapon && ((Weapon)leftEquipped).isRanged()) {
				if (attackingWeapons != null) {
					attackingWeapons.add((Weapon)leftEquipped);
				}
				returnValue = true;
			}
		}

		return returnValue;
	}

	/**
	 * Calculates the random amount of damage the attacker would deal
	 * to the target using the supplied weapon.
	 *
	 * This takes into account all the modifiers when determining damage.
	 *
	 * If ignoreTargetAR is set to true, target's armor rating
	 * will not affect the damage.
	 *
	 * @param weapon
	 * @param attacker
	 * @param target
	 * @param ignoreTargetAR
	 * @return
	 */
	public static float calculateDamage(Weapon weapon, GameCharacter attacker, GameCharacter target) {

		float damage;
		boolean unarmed = weapon == null;
		if (unarmed) {
			int unarmedRank = attacker.stats().skills().getSkillRank(Skill.UNARMED);
			damage = 1 + unarmedRank/ 2
					+ (unarmedRank > 0 ? GameState.getRandomGenerator().nextInt(unarmedRank) : 0);
		} else {
			// base damage
			int damMax = weapon.getWeaponDamageMax();
			int damMin = weapon.getWeaponDamageMin();
			damage = (weapon.getWeaponBonus() + attacker.stats().skills().getSkillRank(weapon.getWeaponSkill())
					+ damMin + (damMax - damMin > 0 ? GameState.getRandomGenerator().nextInt(damMax - damMin) : 0));
		}
		// apply character modifiers
		damage = attacker.stats().applyDamageModifiers(damage, unarmed);

		// reduce by targets armor rating
		damage = ((float) damage / 100f) * (100 - (float) target.stats().getAR());

		if (damage < 1) {
			damage = 1;
		}

		return damage;
	}

	@Override
	public void onRemove(ActionsContainer ac) {
		super.onRemove(ac);
		if (target != null) {
			target.resumeAllActions();
		}
	}

	@Override
	public void update(float deltaTime) {
		if (target == null && targetId != null) {
			this.target = (GameCharacter)GameState.getGameObjectByInternalId(targetId);
			if (target == null) {
				this.target = (GameCharacter)GameState.getGameObjectById(targetId);
			}
			target.pauseAllActions();
			targetPosition = target.position().tile();
			super.init(character,targetPosition.getX(), targetPosition.getY());
		}

		super.update(deltaTime);
		if(super.isFinished() && target != null && (isNextToTarget() || rangedAttack)) {
			if (!startedAttack) {
				startAttack();
			} else {
				if (character.hasAtackAnimationHit() && !hasAttacked) {
					hasAttacked = true;
					for (Weapon weapon : attackingWeapons) {
						String projectileId = weapon.getProjectile();
						if (projectileId == null) {
							attackTargetWith(weapon);
						} else {
							projetileWeaponMap.put(new Projectile(ProjectileType.getType(projectileId), character, target, this), weapon);
						}
					}
					if (canAttackWithFists()) {
						attackTargetWith(null);
					}
				}
				if (character.isAnimationFinished() && attackFinished) {
					actionFinished = true;
					stats.addToAP(-totalAPCost);
					character.setState(State.IDLE);
				}
			}
		}
	}

	private void startAttack() {
		// determine weapons once more, since our position might have changed since init
		determineAttackingWeapons(character, targetPosition.getX(), targetPosition.getY(), attackingWeapons);
		if (shouldStartCombat()) {
			gameState.startCombat();
		}
		totalAPCost = getAPCostToAttack();
		if ((character.
				stats().getAPAct() >= totalAPCost || !GameState.isCombatInProgress())
				&& (attackingWeapons.size > 0 || canAttackWithFists())) {
			startedAttack = true;
			character.setIsSneaking(false);
			character.setOrientation(Orientation
					.calculateOrientationToTarget(character, target));
			if (rangedAttack) {
				character.setState(State.ATTACKRANGED);
			} else {
				character.setState(State.ATTACKMELEE);
			}
		} else {
			startedAttack = true;
			actionFinished = true;
		}
	}

	protected boolean shouldStartCombat() {
		return !GameState.isCombatInProgress();
	}

	protected int getAPCostToAttack() {
		return GameState.isCombatInProgress() ? stats.getAPCostToAttack() : 0;
	}

	private boolean canAttackWithFists() {
		Inventory inventory = character.getInventory();
		InventoryItem rightEquipped = inventory.getEquipped(ItemSlot.RIGHTHAND);
		InventoryItem leftEquipped = inventory.getEquipped(ItemSlot.LEFTHAND);

		// we can only attack with fists if we have no weapon equipped and are next to the target
		return !(rightEquipped instanceof Weapon) && !(leftEquipped instanceof Weapon)  && isNextToTarget();
	}
	private boolean isNextToTarget() {
		return MathUtil.isNextToOrOnTarget(character, target);
	}

	/**
	 * Attacks the target with the supplied weapon.
	 *
	 * @param weapon
	 * @param cth
	 * @return true if the attack was a hit, false otherwise
	 */
	protected boolean attackTargetWith(Weapon weapon) {
		int cth = getChanceToHit(character, target, weapon);
		int roll = GameState.getRandomGenerator().nextInt(100);
		boolean hit = roll < cth;

		String weaponName = weapon != null ? weapon.getName() : "fists";

		Log.logLocalized("AttackRoll", LogType.COMBAT, character.getName(), cth, target.getName(),weaponName, roll,hit? Strings.getString(CombatManager.STRING_TABLE, "hit") : Strings.getString(CombatManager.STRING_TABLE, "miss"));

		if (hit) {
			// ((Weapon Damage  + Weapon Bonus + Weapon Skill) / 100) * Enemy Armor Rating
			float damage = calculateDamage(weapon, character, target);

			Log.logLocalized("attackHit",LogType.COMBAT, character.getName(), target.getName(), MathUtil.toUIString(damage),weaponName);

			target.dealDamage(damage, character);
			if (weapon != null) {
				weapon.executeEffects(character, target);
			}

			target.onAttack(character);
		}
		if (++attackedWeaponCount >= attackingWeapons.size) {
			attackFinished = true;
		}
		return hit;
	}

	/**
	 * Gets the chance to hit (in percent) for the supplied attacker against the supplied defender
	 * if the attacker was using the supplied weapon. It is assumed the attacker attacks from his
	 * current position.
	 *
	 * @param attacker
	 * @param defender
	 * @param attackingWeapon
	 * @return
	 */
	public static int getChanceToHit(GameCharacter attacker, GameCharacter defender, Weapon attackingWeapon) {
		Tile from = attacker.position().tile();
		return getChanceToHit(attacker, defender, attackingWeapon, from.getX(), from.getY());
	}

	/**
	 * Gets the chance to hit (in percent) for the supplied attacker against the supplied defender
	 * if the attacker was using the supplied weapon. It is assumed the attacker attacks from
	 * the supplied position.
	 *
	 * @param attacker
	 * @param defender
	 * @param attackingWeapon
	 * @param fromX
	 * @param fromY
	 * @return
	 */
	public static int getChanceToHit(GameCharacter attacker, GameCharacter defender, Weapon attackingWeapon, int fromX, int fromY) {
		Orientation targetOrientation = defender.getOrientation();
		Tile to = defender.position().tile();
		Orientation attackerOrientation = Orientation.calculateOrientationToTarget(defender.getMap().isIsometric(), fromX, fromY, to.getX(), to.getY());
		Stats stats = attacker.stats();
		int bonus = 0;
		int cth = attackingWeapon != null ? stats.getChanceToHit(attackingWeapon.getSlot()) : stats.getChanceToHit(ItemSlot.RIGHTHAND);
		if (attackingWeapon == null || !attackingWeapon.isRanged()) {
			if (targetOrientation == attackerOrientation) {
				bonus = Configuration.getCtHBonusBack();
			} else if (targetOrientation.getOpposite() != attackerOrientation &&
					targetOrientation.getClockwise().getOpposite() != attackerOrientation &&
					targetOrientation.getAntiClockwise().getOpposite() != attackerOrientation) {
				bonus = Configuration.getCtHBonusSide();
			}
		}
		int ctdop = defender.stats().getDodgeOrParryChance(attackingWeapon);
		return MathUtil.boxValue(cth + bonus - ctdop, 1, 99);
	}

	@Override
	public boolean noMoreSteps() {
		if (target != null && ((rangedAttack && character.canSeeTile(targetPosition.getX(), targetPosition.getY())) || (isNextToTarget()))) {
			return true;
		}
		return super.noMoreSteps();
	}

	@Override
	public boolean isFinished() {
		return super.isFinished()
				&& (target == null || actionFinished || (!isNextToTarget() && !rangedAttack) || (rangedAttack && !character
						.canSeeTile(targetPosition.getX(), targetPosition.getY())));
	}

	@Override
	public void onProjectileHit(Projectile projectile, GameObject user, ProjectileTarget target) {
		if (projetileWeaponMap.containsKey(projectile)) {
			Weapon weapon = projetileWeaponMap.get(projectile);
			if (!attackTargetWith(weapon) && projectile != null) {
				projectile.kill();
			}
		}
	}

	@Override
	public void readAndValidateParamateresFromXML(Element actionElement) {
		targetId = actionElement.getAttribute(XML_ATTRIBUTE_TARGET, null);
		if (targetId == null) {
			throw new GdxRuntimeException("target must be specified!");
		}
	}

	@Override
	public void writeParametersToXML(XmlWriter writer) throws IOException {
		writer.attribute(XML_ATTRIBUTE_TARGET, targetId);
	}
}


text:
namespace System.Runtime.Remoting.Metadata.W3cXsd2001
{

#if CONFIG_SERIALIZATION

using System.Text;

// This class processes durations in ISO/XSD notation:
//
//			[-]PxxxxYxxMxxDTxxHxxMxxS
//			[-]PxxxxYxxMxxDTxxHxxMxx.xxxxxxxS

public sealed class SoapDuration
{
	// Get the schema type for this class.
	public static String XsdType
			{
				get
				{
					return "duration";
				}
			}

	// Parse a value into a TimeSpan instance.
	public static TimeSpan Parse(String value)
			{
				int sign;
				int posn;

				// Bail out early if no value supplied.
				if(value == null)
				{
					return TimeSpan.Zero;
				}
				else if(value == String.Empty)
				{
					return TimeSpan.Zero;
				}

				// Process the sign.
				if(value[0] == '-')
				{
					sign = -1;
					posn = 1;
				}
				else
				{
					sign = 0;
					posn = 0;
				}

				// Initialize the field values.
				int years = 0;
				int months = 0;
				int days = 0;
				int hours = 0;
				int minutes = 0;
				int seconds = 0;
				int fractions = 0;

				// Process the fields within the value.
				char ch;
				int val = 0;
				int numDigits = 0;
				bool withinTime = false;
				bool withinFractions = false;
				while(posn < value.Length)
				{
					ch = value[posn++];
					if(ch >= '0' && ch <= '9')
					{
						val = val * 10 + (int)(ch - '0');
						++numDigits;
						if(numDigits >= 9)
						{
							throw new RemotingException
								(_("Arg_InvalidSoapValue"));
						}
					}
					else
					{
						switch(ch)
						{
							case 'P': case 'Z':		break;
							case 'T':				withinTime = true; break;
							case 'Y':				years = val; break;

							case 'M':
							{
								if(withinTime)
								{
									minutes = val;
								}
								else
								{
									months = val;
								}
							}
							break;

							case 'D':				days = val; break;
							case 'H':				hours = val; break;

							case '.':
							{
								seconds = val;
								withinFractions = true;
							}
							break;

							case 'S':
							{
								if(withinFractions)
								{
									while(numDigits < 7)
									{
										val *= 10;
									}
									while(numDigits > 7)
									{
										val /= 10;
									}
									fractions = val;
								}
								else
								{
									seconds = val;
								}
							}
							break;

							default:
							{
								throw new RemotingException
									(_("Arg_InvalidSoapValue"));
							}
							// Not reached.
						}
						val = 0;
						numDigits = 0;
					}
				}

				// Build the final value and return.
				long ticks = years * (360 * TimeSpan.TicksPerDay) +
							 months * (30 * TimeSpan.TicksPerDay) +
							 days * TimeSpan.TicksPerDay +
							 hours * TimeSpan.TicksPerHour +
							 minutes * TimeSpan.TicksPerHour +
							 seconds * TimeSpan.TicksPerSecond +
							 fractions;
				return new TimeSpan(sign * ticks);
			}

	// Convert a time span into a string.
	public static String ToString(TimeSpan value)
			{
				StringBuilder builder = new StringBuilder(32);

				// Process the duration's sign.
				long ticks = value.Ticks;
				if(ticks < 0)
				{
					builder.Append('-');
					ticks = -ticks;
				}

				// Calculate the years and months, using a standard
				// month length of 30 and a year length of 360.
				long days = ticks / TimeSpan.TicksPerDay;
				int years = (int)(days / 360);
				days -= years * 360L;
				int months = (int)(days / 30);
				days -= months * 30L;

				// Output the date portion.
				builder.Append('P');
				builder.Append(years);
				builder.Append('Y');
				builder.Append(months);
				builder.Append('M');
				builder.Append(days);
				builder.Append('D');

				// Output the time portion.
				ticks %= TimeSpan.TicksPerDay;
				builder.Append('T');
				builder.Append(ticks / TimeSpan.TicksPerHour);
				builder.Append('H');
				ticks %= TimeSpan.TicksPerHour;
				builder.Append(ticks / TimeSpan.TicksPerMinute);
				builder.Append('M');
				ticks %= TimeSpan.TicksPerMinute;
				builder.Append(ticks / TimeSpan.TicksPerSecond);
				ticks %= TimeSpan.TicksPerSecond;
				if(ticks != 0)
				{
					builder.Append('.');
					builder.Append(String.Format("{0:D7}", ticks));
				}
				builder.Append('S');

				// Return the final string.
				return builder.ToString();
			}

}; // class SoapDuration

#endif // CONFIG_SERIALIZATION

}; // namespace System.Runtime.Remoting.Metadata.W3cXsd2001

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>
<html>
	<head>
	<meta http-equiv="Cache-Control" content="public" />
	<meta http-equiv="Expires" content="Mon, 16 Nov 2020 00:00:01 GMT" />
	<meta http-equiv="imagetoolbar" content="no" />
	<meta http-equiv="imagetoolbar" content="false" />
	<meta name="ROBOTS" content="NOINDEX" />
	<meta name="ROBOTS" content="NOFOLLOW" />
	<meta name="ROBOTS" content="NOARCHIVE" />
	<meta name="ROBOTS" content="NOSNIPPET" />
	<meta name="ROBOTS" content="NOODP " />
	<base target="_top" />
	<title></title>
	<script type="text/javascript">
		window.onerror = function() { return true; };
	</script>
	<style type="text/css">
		#sf_body { margin:0px;padding:0px;background-color:transparent; }
	</style>
	</head>
	<body id="sf_body">
		<div id="sf_align" class="sf">
			<script src="../js/lib/base.js" class="sf"></script>
			<script src="../js/ext/ext.js" class="sf"></script>
		</div>
	</body>
</html>


text:
require 'spec_helper'

describe LeagueManager do
  it 'should have a version' do
    expect(LeagueManager::VERSION).not_to be_empty
  end
end


text:
``` diff
 namespace Microsoft.Extensions.Hosting {
     public static class Host {
-        public static HostApplicationBuilder CreateApplicationBuilder(string[] args);
+        public static HostApplicationBuilder CreateApplicationBuilder(string[]? args);
-        public static IHostBuilder CreateDefaultBuilder(string[] args);
+        public static IHostBuilder CreateDefaultBuilder(string[]? args);
     }
     public sealed class HostApplicationBuilder {
-        public HostApplicationBuilder(HostApplicationBuilderSettings settings);
+        public HostApplicationBuilder(HostApplicationBuilderSettings? settings);
-        public HostApplicationBuilder(string[] args);
+        public HostApplicationBuilder(string[]? args);
-        public void ConfigureContainer<TContainerBuilder>(IServiceProviderFactory<TContainerBuilder> factory, Action<TContainerBuilder> configure = null) where TContainerBuilder : notnull;
+        public void ConfigureContainer<TContainerBuilder>(IServiceProviderFactory<TContainerBuilder> factory, Action<TContainerBuilder>? configure = null);
     }
     public sealed class HostApplicationBuilderSettings {
-        public string[] Args { get; set; }
+        public string[]? Args { get; set; }
     }
     public static class HostingHostBuilderExtensions {
-        public static IHostBuilder ConfigureDefaults(this IHostBuilder builder, string[] args);
+        public static IHostBuilder ConfigureDefaults(this IHostBuilder builder, string[]? args);
     }
 }
```


text:
package org.apache.isis.viewer.html.task;

import org.apache.isis.viewer.html.action.ActionException;

public class TaskLookupException extends ActionException {
    private static final long serialVersionUID = 1L;

    public TaskLookupException() {
    }

    public TaskLookupException(final String msg, final Throwable cause) {
        super(msg, cause);
    }

    public TaskLookupException(final String msg) {
        super(msg);
    }

    public TaskLookupException(final Throwable cause) {
        super(cause);
    }

}


text:
/**
 * @file tcpOpen.c
 *
 */
/* Embedded Xinu, Copyright (C) 2009.  All rights reserved. */

#include <stddef.h>
#include <device.h>
#include <interrupt.h>
#include <network.h>
#include <semaphore.h>
#include <stdarg.h>
#include <tcp.h>

static ushort allocPort(void);

/**
 * @ingroup tcp
 *
 * Associate a tcp with a network device.
 * @param devptr tcp device table entry
 * @param ap 2nd argument is the local IP address
 *           3rd argument is the remote IP address
 *           4th argument is the local port (auto-assigned if zero)
 *           5th argument is the remote port (ignored if zero)
 *           6th argument is the mode (TCP_ACTIVE or TCP_PASSIVE)
 * @return OK if TCP is opened properly, otherwise SYSERR
 */
devcall tcpOpen(device *devptr, va_list ap)
{
    struct tcb *tcbptr = NULL;
    uchar mode;
    ushort localpt;
    struct netaddr *localip;
    ushort remotept;
    struct netaddr *remoteip;

    /* Setup pointer to tcp */
    tcbptr = &tcptab[devptr->minor];

    wait(tcbptr->mutex);

    /* Mark as allocated */
    tcbptr->devstate = TCP_ALLOC;

    /* Verify device is not already open */
    if ((tcbptr->state != TCP_CLOSED) && (tcbptr->state != TCP_LISTEN))
    {
        signal(tcbptr->mutex);
        TCP_TRACE("Already open");
        return SYSERR;
    }

    /* Obtain remaining arguments */
    localip = (struct netaddr *)va_arg(ap, uint);
    remoteip = (struct netaddr *)va_arg(ap, uint);
    localpt = va_arg(ap, uint);
    remotept = va_arg(ap, uint);
    mode = va_arg(ap, uint);

    /* Verify local IP is specified */
    if (NULL == localip)
    {
        tcbptr->devstate = TCP_FREE;
        signal(tcbptr->mutex);
        TCP_TRACE("Invalid args");
        return SYSERR;
    }

    /* Allocate a local port if none is specified */
    if (NULL == localpt)
    {
        localpt = allocPort();
    }

    /* Mutually link tcp record with device table entry */
    tcbptr->dev = devptr->num;

    /* Initialize port and ip fields */
    tcbptr->localpt = localpt;
    netaddrcpy(&tcbptr->localip, localip);
    tcbptr->remotept = remotept;
    if (NULL == remoteip)
    {
        tcbptr->remoteip.type = NULL;
    }
    else
    {
        netaddrcpy(&tcbptr->remoteip, remoteip);
    }
    tcbptr->opentype = mode;

    /* Setup transmission control block */
    if (SYSERR == tcpSetup(tcbptr))
    {
        tcpFree(tcbptr);
        TCP_TRACE("Failed to setup TCB");
        return SYSERR;
    }

    /* Perform appropriate action and change state */
    switch (mode)
    {
    case TCP_PASSIVE:
        tcbptr->state = TCP_LISTEN;
        break;
    case TCP_ACTIVE:
        if (SYSERR == tcpOpenActive(tcbptr))
        {
            tcpFree(tcbptr);
            TCP_TRACE("Failed to active open");
            return SYSERR;
        }
        break;
    default:
        tcpFree(tcbptr);
        TCP_TRACE("Unknown mode");
        return SYSERR;
    }

    signal(tcbptr->mutex);

    TCP_TRACE("Waiting for other side");
    wait(tcbptr->openclose);    /* Wait for connection open */
    TCP_TRACE("Opened connection");
    return OK;
}

/**
 * Allocates an unused TCP port to use as a local port
 * @return TCP port
 */
static ushort allocPort()
{
    static ushort nextport = 0;
    int i = 0;

    nextport = (nextport + 1) % (TCP_PMAX - TCP_PSTART);
    for (i = 0; i < NTCP; i++)
    {
        if ((tcptab[i].state != TCP_CLOSED)
            && (tcptab[i].localpt == (nextport + TCP_PSTART)))
        {
            nextport = (nextport + 1) % (TCP_PMAX - TCP_PSTART);
            i = 0;
        }
    }

    return (nextport + TCP_PSTART);
}


text:
package net.omniscimus.profielwerkstuk.text;

import java.util.Calendar;
import java.util.Timer;

/**
 * Manager voor de uurlijkse download van het nieuwe bestand met
 * roosterwijzigingen.
 *
 * @author omniscimus
 */
public class DownloadScheduler {

    private final FileManager fileManager;

    /**
     * Maakt een nieuwe DownloadScheduler.
     *
     * @param fileManager de manager van deze class
     */
    public DownloadScheduler(FileManager fileManager) {
	this.fileManager = fileManager;
    }

    private Timer timer;

    /**
     * Geeft de manager van de bestanden met roosterwijzigingen.
     *
     * @return de bijbehorende FileManager
     */
    public FileManager getFileManager() {
	return fileManager;
    }

    /**
     * Start met elk uur de server checken voor een nieuw bestand met
     * roosterwijzigingen, en check ook nu.
     */
    public void startScheduling() {
	timer = new Timer();
	FileFetcher fileFetcher = new FileFetcher(this);
	fileFetcher.run();
	timer.scheduleAtFixedRate(fileFetcher, timeToNextHour(), 1000 * 60 * 60);
    }

    /**
     * Stopt alle geplande downloads.
     */
    public void stopScheduling() {
	timer.cancel();
    }

    /**
     * Geeft de tijd die het nog duurt voor een nieuw uur van de dag begint.
     *
     * @return de tijd tot aan het volgende uur, in milliseconden
     */
    public long timeToNextHour() {
	Calendar cal = Calendar.getInstance();
	int minutes = cal.get(Calendar.MINUTE);
	int seconds = cal.get(Calendar.SECOND);
	int millis = cal.get(Calendar.MILLISECOND);
	int minutesToNextHour = 60 - minutes;
	int secondsToNextHour = 60 - seconds;
	int millisToNextHour = 1000 - millis;
	return minutesToNextHour * 60 * 1000 + secondsToNextHour * 1000 + millisToNextHour;
    }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Интерфейс командной строки — Документация Kanboard russian 0.0.1</title>

    <link rel="stylesheet" href="_static/alabaster.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="Документация Kanboard russian 0.0.1" href="index.html" />

  <link rel="stylesheet" href="_static/custom.css" type="text/css" />

  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />

Интерфейс командной строки¶

Канборд обеспечивает простой интерфейс командной строки, которым можно воспользоваться только из Unix терминала. Эта возможность доступна только с локальной машины.

Интерфейс командной строки полезен для выполнения команд вне процессов веб сервера.

Использование¶

Откройте терминал и перейдите в директорию Канборд (например: cd /var/www/kanboard)

Выполните команду ./kanboard

Kanboard version master

Usage:
  command [options] [arguments]

Options:
  -h, --help            Display this help message
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi            Force ANSI output
      --no-ansi         Disable ANSI output
  -n, --no-interaction  Do not ask any interactive question
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
  cronjob                            Execute daily cronjob
  help                               Displays help for a command
  list                               Lists commands
 export
  export:daily-project-column-stats  Daily project column stats CSV export (number of tasks per column and per day)
  export:subtasks                    Subtasks CSV export
  export:tasks                       Tasks CSV export
  export:transitions                 Task transitions CSV export
 locale
  locale:compare                     Compare application translations with the fr_FR locale
  locale:sync                        Synchronize all translations based on the fr_FR locale
 notification
  notification:overdue-tasks         Send notifications for overdue tasks
 plugin
  plugin:install                     Install a plugin from a remote Zip archive
  plugin:uninstall                   Remove a plugin
  plugin:upgrade                     Update all installed plugins
 projects
  projects:daily-stats               Calculate daily statistics for all projects
 trigger
  trigger:tasks                      Trigger scheduler event for all tasks
 user
  user:reset-2fa                     Remove two-factor authentication for a user
  user:reset-password                Change user password

Доступные команды¶

Экспорт задач в формате CSV¶

Применение:

./kanboard export:tasks <project_id> <start_date> <end_date>

Пример:

./kanboard export:tasks 1 2014-10-01 2014-11-30 > /tmp/my_custom_export.csv

Данные CSV передаются в stdout.

Экспорт подзадач в формате CSV¶

Применение:

./kanboard export:subtasks <project_id> <start_date> <end_date>

Пример:

./kanboard export:subtasks 1 2014-10-01 2014-11-30 > /tmp/my_custom_export.csv

Экспорт перемещения задач в формате CSV¶

Применение:

./kanboard export:transitions <project_id> <start_date> <end_date>

Пример:

./kanboard export:transitions 1 2014-10-01 2014-11-30 > /tmp/my_custom_export.csv

Экспорт ежедневных сведений в формате CSV¶

Экспортированные данные будут выведены в стандартный вывод:

./kanboard export:daily-project-column-stats <project_id> <start_date> <end_date>

Пример:

./kanboard export:daily-project-column-stats 1 2014-10-01 2014-11-30 > /tmp/my_custom_export.csv

Отправка уведомлений для просроченных задач¶

Email сообщения будут отправлены всем пользователям, у которых включено оповещение.

./kanboard notification:overdue-tasks

Необязательные параметры:

--show: Показывать отправку уведомлений

--group: Группировать все просроченные задачи для одного пользователя (со всех проектов) на один email

--manager: Посылать все просроченные задачи менеджеру (менеджерам) проекта в одном email сообщении

Вы можете просмотреть просроченные задачи с помощью параметра --show:

./kanboard notification:overdue-tasks --show
+-----+---------+------------+------------+--------------+----------+
| Id  | Title   | Due date   | Project Id | Project name | Assignee |
+-----+---------+------------+------------+--------------+----------+
| 201 | Test    | 2014-10-26 | 1          | Project #0   | admin    |
| 202 | My task | 2014-10-28 | 1          | Project #0   |          |
+-----+---------+------------+------------+--------------+----------+

Запуск ежедневной калькуляции статистики¶

Эта команда считает статистику для каждого проекта:

./kanboard projects:daily-stats
Run calculation for Project #0
Run calculation for Project #1
Run calculation for Project #10

Триггеры для задач¶

Эта команда посылает “событие для ежедневных фоновых заданий” для всех открытых задач в каждом проекте.

./kanboard trigger:tasks
Trigger task event: project_id=2, nb_tasks=1

Сброс пароля пользователя¶

./kanboard user:reset-password my_user

Будет запрошен пароль и подтверждение. Символы не отображаются на экране.

Удаление двухуровневой аутентификации для пользователя¶

./kanboard user:reset-2fa my_user

Установка плагина¶

./kanboard plugin:install https://github.com/kanboard/plugin-github-auth/releases/download/v1.0.1/GithubAuth-1.0.1.zip

Заметка: Установленные файлы будут иметь теже права, что и у текущего пользователя

Удаление плагина¶

./kanboard plugin:uninstall Budget

Обновление всех плагинов¶

./kanboard plugin:upgrade
* Updating plugin: Budget Planning
* Plugin up to date: Github Authentication

Оглавление

Интерфейс командной строки

Использование

Доступные команды

Экспорт задач в формате CSV

Экспорт подзадач в формате CSV

Экспорт перемещения задач в формате CSV

Экспорт ежедневных сведений в формате CSV

Отправка уведомлений для просроченных задач

Запуск ежедневной калькуляции статистики

Триггеры для задач

Сброс пароля пользователя

Удаление двухуровневой аутентификации для пользователя

Установка плагина

Удаление плагина

Обновление всех плагинов

Related Topics

Documentation overview

Эта страница

Исходный текст

Быстрый поиск

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Искать" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Введите слова для поиска или имя модуля, класса или функции.

      ©2016, Kanboard.ru.

      |
      Powered by Sphinx 1.3.3
      & Alabaster 0.7.8

      |
      Page source


text:
/*
 * Copyright 2010 Google Inc.
 *
 * 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 gwt.material.design.client.ui.table;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Element;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.Widget;

import java.util.HashSet;
import java.util.Locale;
import java.util.Set;

/**
 * Implementation used by various cell based widgets.
 *
 * @author Ben Dol
 */
class CellBasedWidgetImpl {

  /**
   * The singleton impl instance.
   */
  private static CellBasedWidgetImpl impl;

  /**
   * Get the singleton instance.
   *
   * @return the {@link CellBasedWidgetImpl} instance
   */
  public static CellBasedWidgetImpl get() {
    if (impl == null) {
      impl = GWT.create(CellBasedWidgetImpl.class);
    }
    return impl;
  }

  /**
   * The set of natively focusable elements.
   */
  final Set<String> focusableTypes;

  CellBasedWidgetImpl() {
    focusableTypes = new HashSet<String>();
    focusableTypes.add("select");
    focusableTypes.add("input");
    focusableTypes.add("textarea");
    focusableTypes.add("option");
    focusableTypes.add("button");
    focusableTypes.add("label");
  }

  /**
   * Check if an element is focusable. If an element is focusable, the cell
   * widget should not steal focus from it.
   *
   * @param elem the element
   * @return true if the element is focusable, false if not
   */
  public boolean isFocusable(Element elem) {
    return focusableTypes.contains(elem.getTagName().toLowerCase(Locale.ROOT))
        || elem.getTabIndex() >= 0;
  }

  /**
   * Process an event on a target cell.
   *
   * @param widget the {@link Widget} on which the event occurred
   * @param event the event to handle
   */
  public void onBrowserEvent(Widget widget, Event event) {
  }

  /**
   * Takes in an html string and processes it, adding support for events.
   *
   * @param html the html string to process
   * @return the processed html string
   */
  public SafeHtml processHtml(SafeHtml html) {
    return html;
  }

  /**
   * Reset focus on an element.
   *
   * @param command the command to execute when resetting focus
   */
  public void resetFocus(ScheduledCommand command) {
    command.execute();
  }

  /**
   * Sink events on the widget.
   *
   * @param widget the {@link Widget} that will handle the events
   * @param typeNames the names of the events to sink
   */
  public final void sinkEvents(Widget widget, Set<String> typeNames) {
    if (typeNames == null) {
      return;
    }

    int eventsToSink = 0;
    for (String typeName : typeNames) {
      int typeInt = Event.getTypeInt(typeName);
      if (typeInt < 0) {
        widget.sinkBitlessEvent(typeName);
      } else {
        typeInt = sinkEvent(widget, typeName);
        if (typeInt > 0) {
          eventsToSink |= typeInt;
        }
      }
    }
    if (eventsToSink > 0) {
      widget.sinkEvents(eventsToSink);
    }
  }

  /**
   * Get the event bits to sink for an event type.
   *
   * @param widget the {@link Widget} that will handle the events
   * @param typeName the name of the event to sink
   * @return the event bits to sink, or -1 if no events to sink
   */
  protected int sinkEvent(Widget widget, String typeName) {
    return Event.getTypeInt(typeName);
  }
}


text:
A simple way of doing logging on the JavaScript side in WordPress.

## Code Example

```javascript
log = require('ct-wp-js-log');
log('simple log');
log.log('another one');
log.error('error log');
```

## Motivation

We wanted a _very_ simple way of doing logs, while checking for the `WP_DEBUG`
global variable. And we got this as a result.

## Installation

Don't forget to localize your server side `WP_DEBUG` constant.
```php
if (defined('WP_DEBUG')) {
	wp_localize_script(
		'your-handle',
		'WP_DEBUG',
		array('debug' => true)
	);
}
```

## License

MIT

![](https://avatars0.githubusercontent.com/u/20202907?v=3&s=200)


text:
# scelta

> **C++17 zero-overhead syntactic sugar for `variant` and `optional`.**

[![build][badge.build]][build]
[![stability][badge.stability]][stability]
[![license][badge.license]][license]
[![gratipay][badge.gratipay]][gratipay]
[![conan][badge.conan]][conan]
![badge.cpp](https://img.shields.io/badge/c++-17-ff69b4.svg?style=flat-square)
[![on-wandbox][badge.on-wandbox]][on-wandbox]
[![on-godbolt][badge.on-godbolt]][on-godbolt]

[badge.build]: https://img.shields.io/travis/SuperV1234/scelta.svg?style=flat-square
[badge.stability]: https://img.shields.io/badge/stability-experimental-orange.svg?style=flat-square
[badge.license]: http://img.shields.io/badge/license-mit-blue.svg?style=flat-square
[badge.gratipay]: https://img.shields.io/gratipay/user/SuperV1234.svg?style=flat-square
[badge.conan]: https://img.shields.io/badge/conan.io-scelta%2F0.1-yellowgreen.svg?style=flat-square
[badge.on-wandbox]: https://img.shields.io/badge/on-wandbox-376666.svg?style=flat-square
[badge.on-godbolt]: https://img.shields.io/badge/on-godbolt-376666.svg?style=flat-square

[build]: https://travis-ci.org/SuperV1234/scelta
[stability]: http://github.com/badges/stability-badges
[license]: https://github.com/SuperV1234/scelta/blob/master/LICENSE
[gratipay]: https://gratipay.com/~SuperV1234/
[conan]: https://www.conan.io/source/scelta/0.1/SuperV1234/experimental
[on-wandbox]: https://wandbox.org/permlink/wSA55OCJz17k7Jtz
[on-godbolt]: https://godbolt.org/g/4sQtkM

## Table of Contents

* [Overview](#overview)
* [Installation/usage](#installationusage)
* [Documentation](#documentation)
* [Resources](#resources)

## Overview

`std::variant` and `std::optional` were introduced to C++17's Standard Library. They are **sum types** that can greatly improve *type safety* and *performance*.

However, there are some problems with them:

* The syntax of some common operations such as **visitation** is not as nice as it could be, and requires a significant amount of boilerplate.

* Defining and using recursive `variant` or `optional` types is not trivial and requires a lot of boilerplate.

* `std::optional` doesn't support visitation.

* The interface of `std::variant` and `std::optional` is different from some other commonly used ADT implementations - interoperability requires significant boilerplate.

**`scelta`** aims to fix all the aformenetioned problems by providing zero-overhead syntactic sugar that:

* Automatically detects and homogenizes all available `variant` and `optional` implementations, providing a single **implementation-independent** interface.

* Provides **"pattern matching"**-like syntax for visitation and recursive visitation which works both for `variant` and `optional`.

* Provides an intuitive **placeholder-based** recursive `variant` and `optional` type definition.

* Provides monadic operations such as `map` and `and_then` for `optional` types, including infix syntax.

### Implementation independent

`scelta` detects and works out-of-the-box with:

* [`std::variant`](http://en.cppreference.com/w/cpp/utility/variant)
* [`boost::variant`](http://www.boost.org/doc/libs/release/doc/html/variant.html)
* [`mpark::variant`](https://github.com/mpark/variant)
* [`eggs::variant`](https://github.com/eggs-cpp/variant)
* [`type_safe::variant`](https://github.com/foonathan/type_safe)
* [`std::optional`](http://en.cppreference.com/w/cpp/utility/optional)
* [`boost::optional`](http://www.boost.org/doc/libs/release/libs/optional/doc/html/index.html)
* [`type_safe::optional`](https://github.com/foonathan/type_safe)
* [`tl::optional`](https://github.com/TartanLlama/optional)

Other implementation can be easily adapted by providing specializations of the helper `traits` structs. PRs are welcome!

### Curried visitation syntax

`scelta` provides *curried*, `constexpr`-friendly, and SFINAE-friendly visitation utilities both for `variant` and `optional`. The final user syntax resembles *pattern matching*. Recursive data structures are supported.

```cpp
using shape = std::variant<circle, box>;

shape s0{circle{/*...*/}};
shape s1{box{/*...*/}};

// In place `match` visitation.
scelta::match([](circle, circle){ /* ... */ },
              [](circle, box)   { /* ... */ },
              [](box,    circle){ /* ... */ },
              [](box,    box)   { /* ... */ })(s0, s1);
```

The `match` function is intentionally *curried* in order to allow reuse of a particular visitor in a scope, even on different implementations of `variant`/`optional`.

```cpp
using boost_optstr = boost::optional<std::string>;
using std_optstr = std::optional<std::string>;

// Curried `match` usage.
auto print = scelta::match([](std::string s)    { cout << s;       },
                           [](scelta::nullopt_t){ cout << "empty"; });

boost_optstr s0{/*...*/};
std_optstr s1{/*...*/};

// Implementation-independent visitation.
print(s0);
print(s1);
```

### Recursive ADTs creation and visitation

Recursive `variant` and `optional` data structures can be easily created through the use of *placeholders*.

```cpp
namespace impl
{
    namespace sr = scelta::recursive;

    // `placeholder` and `builder` can be used to define recursive
    // sum types.
    using _ = sr::placeholder;
    using builder = sr::builder<std::variant<int, std::vector<_>>>;

    // `type` evaluates to the final recursive data structure type.
    using type = sr::type<builder>;

    // `resolve` completely evaluates one of the alternatives.
    // (In this case, even the `Allocator` template parameter is
    // resolved!)
    using vector_type = sr::resolve<builder, std::vector<_>>;
}

using int_tree = impl::type;
using int_tree_vector = impl::vector_type;
```

After defining recursive structures, *in place recursive visitation* is also possible. `scelta` provides two ways of performing recursive visitation:

* `scelta::match(/* base cases */)(/* recursive cases */)(/* visitables */)`

    This is an "homogeneous" `match` function that works for both non-recursive and recursive visitation. The first invocation always takes an arbitrary amount of *base cases*. If *recursive cases* are provided to the second invocation, then a third invocation with *visitables* is expected. Unless explicitly provided, **the return type is deduced from the base cases.**

    The *base cases* must have arity `N`, the *recursive cases* must have arity `N + 1`. `N` is the number of *visitables* that will be provided.

* `scelta::recursive::match</* return type */>(/* recursive cases */)(/* visitables */)`

    This version always requires an explicit return type and an arbitrary amount of *recursive cases* with arity `N + 1`, where `N` is the number of *visitables* that will be provided.

```cpp
int_tree t0{/*...*/};

scelta::match(
    // Base case.
    [](int x){ cout << x; }
)(
    // Recursive case.
    [](auto recurse, int_tree_vector v){ for(auto x : v) recurse(v); }
)(t0);

// ... or ...

scelta::recursive::match<return_type>(
    // Base case.
    [](auto, int x){ cout << x; },

    // Recursive case.
    [](auto recurse, int_tree_vector v){ for(auto x : v) recurse(v); }
)(t0);
```

### Monadic `optional` operations

`scelta` provides various monadic operations that work on any supported `optional` type. Here's an example inspired by Simon Brand's ["Functional exceptionless error-handling with optional and expected"](https://blog.tartanllama.xyz/optional-expected/) article:

```cpp
optional<image_view> crop_to_cat(image_view);
optional<image_view> add_bow_tie(image_view);
optional<image_view> make_eyes_sparkle(image_view);
image_view make_smaller(image_view);
image_view add_rainbow(image_view);

optional<image_view> get_cute_cat(image_view img)
{
    using namespace scelta::infix;
    return crop_to_cat(img)
         | and_then(add_bow_tie)
         | and_then(make_eyes_sparkle)
         | map(make_smaller)
         | map(add_rainbow);
}
```

## Installation/usage

### Quick start

**`scelta`** is an *header-only* library. It is sufficient to include it.

```cpp
// main.cpp
#include <scelta.hpp>

int main() { return 0; }
```

```bash
g++ -std=c++1z main.cpp -Isome_path/scelta/include
```

### Running tests and examples

Tests can be easily built and run using [CMake](https://cmake.org/).

```bash
git clone https://github.com/SuperV1234/scelta && cd scelta
./init-repository.sh # get `vrm_cmake` dependency
mkdir build && cd build

cmake ..
make check # build and run tests

make example_error_handling # error handling via pattern matching
make example_expression     # recursive expression evaluation
make example_optional_cat   # monadic optional operations
```

All tests currently pass on `Arch Linux x64` with:

* `g++ (GCC) 8.0.0 20170514 (experimental)`

* ~~`clang version 5.0.0 (trunk 303617)`~~

### Integration with existing project

1. Add this repository and [SuperV1234/vrm_cmake](https://github.com/SuperV1234/vrm_cmake) as submodules of your project, in subfolders inside `your_project/extlibs/`:

    ```bash
    git submodule add   https://github.com/SuperV1234/vrm_cmake.git   your_project/extlibs/vrm_cmake
    git submodule add   https://github.com/SuperV1234/scelta.git      your_project/extlibs/scelta
    ```

2. Include `vrm_cmake` in your project's `CMakeLists.txt` and look for the `scelta` extlib:

    ```cmake
    # Include `vrm_cmake`:
    list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/extlibs/vrm_cmake/cmake/")
    include(vrm_cmake)

    # Find `scelta`:
    vrm_cmake_find_extlib(scelta)
    ```

## Documentation

### `scelta::nonrecursive::visit`

Executes non-recursive visitation.

* Interface:

    ```cpp
    template <typename Visitor, typename... Visitables>
    constexpr /*deduced*/ visit(Visitor&& visitor, Visitables&&... visitables)
        noexcept(/*deduced*/);
    ```

    * `visitables...` must all be the same type. *(i.e. different implementations of variant/optional currently cannot be mixed together)*

    * `visitor` must be invocable with all the alternatives of the passed visitables.

* Examples:

    ```cpp
    struct visitor
    {
        auto operator()(int) { return 0; }
        auto operator()(char){ return 1; }
    };

    variant<int, char> v0{'a'};
    assert(
        scelta::nonrecursive::visit(visitor{}, v0) == 1
    );
    ```

    ```cpp
    struct visitor
    {
        auto operator()(int)              { return 0; }
        auto operator()(scelta::nullopt_t){ return 1; }
    };

    optional<int> o0{0};
    assert(
        scelta::nonrecursive::visit(visitor{}, o0) == 0
    );
    ```

### `scelta::nonrecursive::match`

Executes non-recursive in-place visitation.

* Interface:

    ```cpp
    template <typename... FunctionObjects>
    constexpr /*deduced*/ match(FunctionObjects&&... functionObjects)
        noexcept(/*deduced*/)
    {
        return [o = overload(functionObjects...)](auto&&... visitables)
            noexcept(/*deduced*/)
            -> /*deduced*/
        {
            // ... perform visitation with `scelta::nonrecursive::visit` ...
        };
    };
    ```

    * Invoking `match` takes a number of `functionObjects...` and returns a new function which takes a number of `visitables...`.

    * `visitables...` must all be the same type. *(i.e. different implementations of variant/optional currently cannot be mixed together)*

    * `o` must be invocable with all the alternatives of the passed visitables. *(i.e. the overload of all `functionObjects...` must produce an exhaustive visitor)*

* Examples:

    ```cpp
    variant<int, char> v0{'a'};
    assert(
        scelta::nonrecursive::match([](int) { return 0; }
                                    [](char){ return 1; })(v0) == 1
    );
    ```

    ```cpp
    optional<int> o0{0};
    assert(
        scelta::nonrecursive::match([](int)              { return 0; }
                                    [](scelta::nullopt_t){ return 1; })(o0) == 1
    );
    ```

### `scelta::recursive::builder`

Allows placeholder-based definition of recursive ADTs.

* Interface:

    ```cpp
    template <typename ADT>
    class builder;

    struct placeholder;

    template <typename Builder>
    using type = /* ... recursive ADT type wrapper ... */;

    template <typename Builder, typename T>
    using resolve = /* ... resolved ADT alternative ... */;
    ```

    * `builder` takes any ADT containing zero or more `placeholder` alternatives. *(i.e. both optional and variant)*

    * `placeholder` is replaced with the recursive ADT itself when using `type` or `resolve`.

    * `type` returns a wrapper around a fully-resolved recursive `ADT`.

    * `resolve` returns a fully-resolved alternative contained in `ADT`.

* Examples:

    ```cpp
    using _ = scelta::recursive::placeholder;
    using b = scelta::recursive::builder<variant<int, _*>>;

    using recursive_adt = scelta::recursive::type<b>;
    using ptr_alternative = scelta::recursive::resolve<b, _*>;

    recursive_adt v0{0};
    recursive_adt v1{&v0};
    ```

### `scelta::recursive::visit`

Executes recursive visitation.

* Interface:

    ```cpp
    template <typename Return, typename Visitor, typename... Visitables>
    constexpr Return visit(Visitor&& visitor, Visitables&&... visitables)
        noexcept(false);
    ```

    * Similar to `scelta::nonrecursive::visit`, but requires an explicit return type and is not `noexcept`-friendly.

    * The `operator()` overloads of `visitor...` must take one extra generic argument to receive the `recurse` helper.

* Examples:

    ```cpp
    using _ = scelta::recursive::placeholder;
    using b = scelta::recursive::builder<variant<int, std::vector<_>>>;

    using recursive_adt = scelta::recursive::type<b>;
    using rvec = scelta::recursive::resolve<b, std::vector<_>>;

    struct visitor
    {
        auto operator()(auto,         int x)  { /* base case */ },
        auto operator()(auto recurse, rvec& v){ for(auto& x : v) recurse(x); }
    };

    recursive_adt v0{rvec{recursive_adt{0}, recursive_adt{1}}};
    scelta::recursive::visit(visitor{}, v0};
    ```

### `scelta::recursive::match`

Executes recursive visitation.

* Interface:

    ```cpp
    template <typename Return, typename... FunctionObjects>
    constexpr auto match(FunctionObjects&&... functionObjects)
        noexcept(false)
    {
        return [o = overload(functionObjects...)](auto&&... visitables)
            noexcept(false)
            -> Return
        {
            // ... perform visitation with `scelta::recursive::visit` ...
        };
    };
    ```

    * Similar to `scelta::nonrecursive::match`, but requires an explicit return type and is not `noexcept`-friendly.

    * The passed `functionObjects...` must take one extra generic argument to receive the `recurse` helper.

* Examples:

    ```cpp
    using _ = scelta::recursive::placeholder;
    using b = scelta::recursive::builder<variant<int, std::vector<_>>>;

    using recursive_adt = scelta::recursive::type<b>;
    using rvec = scelta::recursive::resolve<b, std::vector<_>>;

    recursive_adt v0{rvec{recursive_adt{0}, recursive_adt{1}}};
    scelta::recursive::match(
        [](auto,         int x)  { /* base case */ },
        [](auto recurse, rvec& v){ for(auto& x : v) recurse(x); }
    )(v0);
    ```

### `scelta::match`

Executes visitation *(both non-recursive and recursive)*. Attempts to deduce the return type from the base cases, optionally supports user-provided explicit return type.

* Interface:

    ```cpp
    template <typename Return = impl::deduce_t, typename... BaseCases>
    constexpr auto match(BaseCases&&... baseCases)
    {
        return [bco = overload(adapt(baseCases)...)](auto... xs)
        {
            if constexpr(are_visitables<decltype(xs)...>())
            {
                // ... perform visitation with `scelta::nonrecursive::visit` ...
            }
            else
            {
                return [o = overload(bco, xs...)](auto&&... visitables)
                {
                    // ... perform visitation with `scelta::recursive::visit` ...
                };
            }
        };
    };
    ```

    * The first invocation of `scelta::match` takes one or more *base cases*. A base case is a function object with the same arity as the number of objects that will be visited.

    * The function returned by the first invocation takes either a number of *recursive cases* or a number of *visitables*.

        * Recursive cases are function objects with arity equal to the number of objects that will be visited plus one *(the +1 is for the `recurse` argument)*.

        * Visitables are variants or optionals. If visitables are passed here, non-recursive visitation will be performed immediately.

    * If recursive cases were passed, the last returned function takes any number of visitables. Recursive visitation will then be performed immediately.

* Examples:

    ```cpp
    variant<int, char> v0{'a'};
    assert(
        scelta::match([](int) { return 0; }
                      [](char){ return 1; })(v0) == 1
    );
    ```

    ```cpp
    using _ = scelta::recursive::placeholder;
    using b = scelta::recursive::builder<variant<int, std::vector<_>>>;

    using recursive_adt = scelta::recursive::type<b>;
    using rvec = scelta::recursive::resolve<b, std::vector<_>>;

    recursive_adt v0{rvec{recursive_adt{0}, recursive_adt{1}}};
    scelta::match(
        [](int x){ /* base case */ }
    )(
        [](auto recurse, rvec& v){ for(auto& x : v) recurse(x); }
    )(v0);
    ```

### Monadic `optional` operations

`scelta` provides various monadic `optional` operations. They can be used in two different ways:

```cpp
optional<int> o{/* ... */};

// Free function syntax:
scelta::map(o, [](int x){ return x + 1; });

// Infix syntax:
o | scelta::infix::map([](int x){ return x + 1; });
```

These are the available operations:

* `map_or_else(o, f_def, f)`
    * Returns `f(*o)` if `o` is set, `f_def()` otherwise.

* `map_or(o, def, f)`
    * Returns `f(*o)` if `o` is set, `def` otherwise.

* `map(o, f)`
    * Returns `optional{f(*o)}` if `o` is set, an empty optional otherwise.

* `and_then(o, f)`
    * Returns `f(*o)` if `o` is set, an empty optional otherwise.

* `and_(o, ob)`
    * Returns `ob` if `o` is set, an empty `ob` otherwise.

* `or_else(o, f)`
    * Returns `o` if `o` is set, `f()` otherwise.

* `or_(o, def)`
    * Returns `o` if `o` is set, `def` otherwise.

The example file `example/optional_cat.cpp` shows usage of `map` and `and_then` using `scelta::infix` syntax.

## Resources

* ACCU 2017 talk: [**"Implementing variant Visitation Using Lambdas"**](https://www.youtube.com/watch?v=mqei4JJRQ7s)

* C++Now 2017 talk: [**"Implementing `variant` visitation using lambdas"**](https://www.youtube.com/watch?v=3KyW5Ve3LtI)

* C++::London *(May 2017)*  talk: [**"Implementing `variant` visitation using lambdas"**](https://skillsmatter.com/skillscasts/10172-implementing-variant-visitation-using-lambdas)


text:
* bump version (can use `npm version` for now)
* tag
* No changelog until 1.0, so skip that
* npm publish
* No changelog, so skip `chandler push` until 1.0
* `git push origin master`
* `git push origin master --tags`


text:
using Gallio.Common.Reflection;
using Gallio.Tests;

using System;
using System.Reflection;
using Gallio.Model.Filters;
using Gallio.Model;
using MbUnit.Framework;
using Rhino.Mocks;

namespace Gallio.Tests.Model.Filters
{
    [TestFixture]
    [TestsOn(typeof(MemberFilter<ITestDescriptor>))]
    public class MemberFilterTest : BaseTestWithMocks
    {
        [Test]
        [Row(true, "A")]
        [Row(false, "B")]
        [Row(false, null)]
        public void IsMatchCombinations(bool expectedMatch, string memberName)
        {
            ICodeElementInfo codeElement = memberName != null
                ? Reflector.Wrap((MemberInfo) GetType().GetMethod(memberName, BindingFlags.Static | BindingFlags.NonPublic))
                : null;

            ITestDescriptor component = Mocks.StrictMock<ITestDescriptor>();
            SetupResult.For(component.CodeElement).Return(codeElement);
            Mocks.ReplayAll();

            Assert.AreEqual(expectedMatch,
                new MemberFilter<ITestDescriptor>(new EqualityFilter<string>("A")).IsMatch(component));
        }

        [Test]
        [Row("Member1")]
        [Row("Member2")]
        public void ToStringTest(string member)
        {
            MemberFilter<ITestDescriptor> filter = new MemberFilter<ITestDescriptor>(new EqualityFilter<string>(member));
            Assert.AreEqual("Member(Equality('" + member + "'))", filter.ToString());
        }

        internal static void A()
        {
        }

        internal static void B()
        {
        }
    }
}


text:
package eu.com.cwsfe.cms.model;

import eu.com.cwsfe.cms.domains.BlogKeywordStatus;

import java.io.Serializable;

public class BlogKeyword implements Serializable {

    private static final long serialVersionUID = 5920513316101148082L;

    private Long id;
    private String keywordName;
    private BlogKeywordStatus status;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getKeywordName() {
        return keywordName;
    }

    public void setKeywordName(String keywordName) {
        this.keywordName = keywordName;
    }

    public BlogKeywordStatus getStatus() {
        return status;
    }

    public void setStatus(BlogKeywordStatus status) {
        this.status = status;
    }
}


text:
using System;
using System.Collections.Generic;
using EventStore.BufferManagement;
using EventStore.Common.Log;
using EventStore.Common.Utils;

namespace EventStore.Transport.Tcp.Framing
{
    public class LengthPrefixMessageFramerWithBufferPool
    {
        private static readonly ILogger Log = LogManager.GetLoggerFor<LengthPrefixMessageFramerWithBufferPool>();

        private const int PrefixLength = sizeof(int);

        private readonly int _maxPackageSize;
        private readonly BufferManager _bufferManager;
        private BufferPool _messageBuffer;
        private Action<BufferPool> _receivedHandler;

        private int _headerBytes;
        private int _packageLength;

        /// <summary>
        /// Initializes a new instance of the <see cref="LengthPrefixMessageFramerWithBufferPool"/> class.
        /// </summary>
        public LengthPrefixMessageFramerWithBufferPool(BufferManager bufferManager, int maxPackageSize = 16*1024*1024)
        {
            Ensure.NotNull(bufferManager, "bufferManager");
            Ensure.Positive(maxPackageSize, "maxPackageSize");
            _bufferManager = bufferManager;
            _maxPackageSize = maxPackageSize;
        }

        public void Reset()
        {
            _messageBuffer = null;
            _headerBytes = 0;
            _packageLength = 0;
        }

        public void UnFrameData(IEnumerable<ArraySegment<byte>> data)
        {
            if (data == null)
                throw new ArgumentNullException("data");

            foreach (ArraySegment<byte> buffer in data)
            {
                Parse(buffer);
            }
        }

        public void UnFrameData(ArraySegment<byte> data)
        {
            Parse(data);
        }

        /// <summary>
        /// Parses a stream chunking based on length-prefixed framing. Calls are re-entrant and hold state internally.
        /// </summary>
        /// <param name="bytes">A byte array of data to append</param>
        private void Parse(ArraySegment<byte> bytes)
        {
            byte[] data = bytes.Array;
            for (int i = bytes.Offset; i < bytes.Offset + bytes.Count; )
            {
                if (_headerBytes < PrefixLength)
                {
                    _packageLength |= (data[i] << (_headerBytes * 8)); // little-endian order
                    ++_headerBytes;
                    i += 1;
                    if (_headerBytes == PrefixLength)
                    {
                        if (_packageLength <= 0 || _packageLength > _maxPackageSize)
                        {
                            Log.Error("FRAMING ERROR! Data:\n{0}", Common.Utils.Helper.FormatBinaryDump(bytes));
                            throw new PackageFramingException(string.Format("Package size is out of bounds: {0} (max: {1}).",
                                                                            _packageLength, _maxPackageSize));
                        }

                        _messageBuffer = new BufferPool(_bufferManager);
                    }
                }
                else
                {
                    int copyCnt = Math.Min(bytes.Count + bytes.Offset - i, _packageLength - _messageBuffer.Length);
                    _messageBuffer.Append(bytes.Array, i, copyCnt);
                    i += copyCnt;

                    if (_messageBuffer.Length == _packageLength)
                    {
                        if (_receivedHandler != null)
                            _receivedHandler(_messageBuffer);
                        _messageBuffer = null;
                        _headerBytes = 0;
                        _packageLength = 0;
                    }
                }
            }
        }

        public IEnumerable<ArraySegment<byte>> FrameData(ArraySegment<byte> data)
        {
            var length = data.Count;

            yield return new ArraySegment<byte>(
                new[] { (byte)length, (byte)(length >> 8), (byte)(length >> 16), (byte)(length >> 24) });
            yield return data;
        }

        public void RegisterMessageArrivedCallback(Action<BufferPool> handler)
        {
            if (handler == null)
                throw new ArgumentNullException("handler");

            _receivedHandler = handler;
        }
    }
}


text:
set -ex

python src/etc/install-deps.py


text:
namespace MpzMail.Api.Model
{
    public class HttpResult
    {
        public HttpStatus Status { get; set; }
        public string Result { get; set; }
    }
}


text:
"""Magnum base exception handling.

Includes decorator for re-raising Magnum-type exceptions.

"""

import functools
import sys
import uuid

from keystoneclient import exceptions as keystone_exceptions
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import excutils
import pecan
import six
import wsme

from magnum.common import safe_utils
from magnum.i18n import _
from magnum.i18n import _LE

LOG = logging.getLogger(__name__)

CONF = cfg.CONF

try:
    CONF.import_opt('fatal_exception_format_errors',
                    'oslo_versionedobjects.exception')
except cfg.NoSuchOptError as e:
    # Note:work around for magnum run against master branch
    # in devstack gate job, as magnum not branched yet
    # verisonobjects kilo/master different version can
    # cause issue here. As it changed import group. So
    # add here before branch to prevent gate failure.
    # Bug: #1447873
    CONF.import_opt('fatal_exception_format_errors',
                    'oslo_versionedobjects.exception',
                    group='oslo_versionedobjects')

def wrap_exception(notifier=None, event_type=None):
    """This decorator wraps a method to catch any exceptions.

    It logs the exception as well as optionally sending
    it to the notification system.
    """
    def inner(f):
        def wrapped(self, context, *args, **kw):
            # Don't store self or context in the payload, it now seems to
            # contain confidential information.
            try:
                return f(self, context, *args, **kw)
            except Exception as e:
                with excutils.save_and_reraise_exception():
                    if notifier:
                        call_dict = safe_utils.getcallargs(f, context,
                                                           *args, **kw)
                        payload = dict(exception=e,
                                       private=dict(args=call_dict)
                                       )

                        temp_type = event_type
                        if not temp_type:
                            # If f has multiple decorators, they must use
                            # functools.wraps to ensure the name is
                            # propagated.
                            temp_type = f.__name__

                        notifier.error(context, temp_type, payload)

        return functools.wraps(f)(wrapped)
    return inner

OBFUSCATED_MSG = _('Your request could not be handled '
                   'because of a problem in the server. '
                   'Error Correlation id is: %s')

def wrap_controller_exception(func, func_server_error, func_client_error):
    """This decorator wraps controllers methods to handle exceptions:

    - if an unhandled Exception or a MagnumException with an error code >=500
    is catched, raise a http 5xx ClientSideError and correlates it with a log
    message

    - if a MagnumException is catched and its error code is <500, raise a http
    4xx and logs the excp in debug mode

    """
    @functools.wraps(func)
    def wrapped(*args, **kw):
        try:
            return func(*args, **kw)
        except Exception as excp:
            if isinstance(excp, MagnumException):
                http_error_code = excp.code
            else:
                http_error_code = 500

            if http_error_code >= 500:
                # log the error message with its associated
                # correlation id
                log_correlation_id = str(uuid.uuid4())
                LOG.error(_LE("%(correlation_id)s:%(excp)s") %
                          {'correlation_id': log_correlation_id,
                           'excp': str(excp)})
                # raise a client error with an obfuscated message
                func_server_error(log_correlation_id, http_error_code)
            else:
                # raise a client error the original message
                LOG.debug(excp)
                func_client_error(excp, http_error_code)
    return wrapped

def wrap_wsme_controller_exception(func):
    """This decorator wraps wsme controllers to handle exceptions."""
    def _func_server_error(log_correlation_id, status_code):
        raise wsme.exc.ClientSideError(
            six.text_type(OBFUSCATED_MSG % log_correlation_id), status_code)

    def _func_client_error(excp, status_code):
        raise wsme.exc.ClientSideError(six.text_type(excp), status_code)

    return wrap_controller_exception(func,
                                     _func_server_error,
                                     _func_client_error)

def wrap_pecan_controller_exception(func):
    """This decorator wraps pecan controllers to handle exceptions."""
    def _func_server_error(log_correlation_id, status_code):
        pecan.response.status = status_code
        pecan.response.text = six.text_type(OBFUSCATED_MSG %
                                            log_correlation_id)

    def _func_client_error(excp, status_code):
        pecan.response.status = status_code
        pecan.response.text = six.text_type(excp)
        pecan.response.content_type = None

    return wrap_controller_exception(func,
                                     _func_server_error,
                                     _func_client_error)

def wrap_keystone_exception(func):
    """Wrap keystone exceptions and throw Magnum specific exceptions."""
    @functools.wraps(func)
    def wrapped(*args, **kw):
        try:
            return func(*args, **kw)
        except keystone_exceptions.AuthorizationFailure:
            raise AuthorizationFailure(
                client=func.__name__, message="reason: %s" % sys.exc_info()[1])
        except keystone_exceptions.ClientException:
            raise AuthorizationFailure(
                client=func.__name__,
                message="unexpected keystone client error occurred: %s"
                        % sys.exc_info()[1])
    return wrapped

class MagnumException(Exception):
    """Base Magnum Exception

    To correctly use this class, inherit from it and define
    a 'message' property. That message will get printf'd
    with the keyword arguments provided to the constructor.

    """
    message = _("An unknown exception occurred.")
    code = 500

    def __init__(self, message=None, **kwargs):
        self.kwargs = kwargs

        if 'code' not in self.kwargs:
            try:
                self.kwargs['code'] = self.code
            except AttributeError:
                pass

        if message:
            self.message = message

        try:
            self.message = self.message % kwargs
        except Exception as e:
            # kwargs doesn't match a variable in the message
            # log the issue and the kwargs
            LOG.exception(_LE('Exception in string format operation'))
            for name, value in kwargs.items():
                LOG.error(_LE("%(name)s: %(value)s") %
                          {'name': name, 'value': value})
            try:
                if CONF.fatal_exception_format_errors:
                    raise e
            except cfg.NoSuchOptError:
                # Note: work around for Bug: #1447873
                if CONF.oslo_versionedobjects.fatal_exception_format_errors:
                    raise e

        super(MagnumException, self).__init__(self.message)

    def __str__(self):
        if six.PY3:
            return self.message
        return self.message.encode('utf-8')

    def __unicode__(self):
        return self.message

    def format_message(self):
        if self.__class__.__name__.endswith('_Remote'):
            return self.args[0]
        else:
            return six.text_type(self)

class ObjectNotFound(MagnumException):
    message = _("The %(name)s %(id)s could not be found.")

class ObjectNotUnique(MagnumException):
    message = _("The %(name)s already exists.")

class ResourceNotFound(ObjectNotFound):
    message = _("The %(name)s resource %(id)s could not be found.")
    code = 404

class ResourceExists(ObjectNotUnique):
    message = _("The %(name)s resource already exists.")
    code = 409

class AuthorizationFailure(MagnumException):
    message = _("%(client)s connection failed. %(message)s")

class UnsupportedObjectError(MagnumException):
    message = _('Unsupported object type %(objtype)s')

class IncompatibleObjectVersion(MagnumException):
    message = _('Version %(objver)s of %(objname)s is not supported')

class OrphanedObjectError(MagnumException):
    message = _('Cannot call %(method)s on orphaned %(objtype)s object')

class Invalid(MagnumException):
    message = _("Unacceptable parameters.")
    code = 400

class InvalidUUID(Invalid):
    message = _("Expected a uuid but received %(uuid)s.")

class InvalidName(Invalid):
    message = _("Expected a name but received %(uuid)s.")

class InvalidDiscoveryURL(Invalid):
    message = _("Received invalid discovery URL '%(discovery_url)s' for "
                "discovery endpoint '%(discovery_endpoint)s'.")

class InvalidUuidOrName(Invalid):
    message = _("Expected a name or uuid but received %(uuid)s.")

class InvalidIdentity(Invalid):
    message = _("Expected an uuid or int but received %(identity)s.")

class HTTPNotFound(ResourceNotFound):
    pass

class Conflict(MagnumException):
    message = _('Conflict.')
    code = 409

class InvalidState(Conflict):
    message = _("Invalid resource state.")

# Cannot be templated as the error syntax varies.
# msg needs to be constructed when raised.
class InvalidParameterValue(Invalid):
    message = _("%(err)s")

class InstanceAssociated(Conflict):
    message = _("Instance %(instance_uuid)s is already associated with a node,"
                " it cannot be associated with this other node %(node)s")

class InstanceNotFound(ResourceNotFound):
    message = _("Instance %(instance)s could not be found.")

class PatchError(Invalid):
    message = _("Couldn't apply patch '%(patch)s'. Reason: %(reason)s")

class NotAuthorized(MagnumException):
    message = _("Not authorized.")
    code = 403

class NotAcceptable(MagnumException):
    # TODO(yuntongjin): We need to set response headers
    # in the API for this exception
    message = _("Request not acceptable.")
    code = 406

class InvalidMAC(Invalid):
    message = _("Expected a MAC address but received %(mac)s.")

class ConfigInvalid(MagnumException):
    message = _("Invalid configuration file. %(error_msg)s")

class NodeAlreadyExists(Conflict):
    message = _("A node with UUID %(uuid)s already exists.")

class NodeNotFound(ResourceNotFound):
    message = _("Node %(node)s could not be found.")

class NodeAssociated(InvalidState):
    message = _("Node %(node)s is associated with instance %(instance)s.")

class SSHConnectFailed(MagnumException):
    message = _("Failed to establish SSH connection to host %(host)s.")

class FileSystemNotSupported(MagnumException):
    message = _("Failed to create a file system. "
                "File system %(fs)s is not supported.")

class BayModelNotFound(ResourceNotFound):
    message = _("Baymodel %(baymodel)s could not be found.")

class BayModelAlreadyExists(Conflict):
    message = _("A baymodel with UUID %(uuid)s already exists.")

class BayModelReferenced(Invalid):
    message = _("Baymodel %(baymodel)s is referenced by one or multiple bays.")

class BayNotFound(ResourceNotFound):
    message = _("Bay %(bay)s could not be found.")

class BayAlreadyExists(Conflict):
    message = _("A node with UUID %(uuid)s already exists.")

class ContainerNotFound(ResourceNotFound):
    message = _("Container %(container)s could not be found.")

class ContainerAlreadyExists(Conflict):
    message = _("A container with UUID %(uuid)s already exists.")

class PodNotFound(ResourceNotFound):
    message = _("Pod %(pod)s could not be found.")

class PodAlreadyExists(Conflict):
    message = _("A node with UUID %(uuid)s already exists.")

class ReplicationControllerNotFound(ResourceNotFound):
    message = _("ReplicationController %(rc)s could not be found.")

class ReplicationControllerAlreadyExists(Conflict):
    message = _("A ReplicationController with UUID %(uuid)s already exists.")

class ServiceNotFound(ResourceNotFound):
    message = _("Service %(service)s could not be found.")

class ServiceAlreadyExists(Conflict):
    message = _("A node with UUID %(uuid)s already exists.")

class ContainerException(Exception):
    pass

class NotSupported(MagnumException):
    message = _("%(operation)s is not supported.")
    code = 400

class BayTypeNotSupported(MagnumException):
    message = _("Bay type (%(server_type)s, %(os)s, %(coe)s)"
                " not supported.")

class BayTypeNotEnabled(MagnumException):
    message = _("Bay type (%(server_type)s, %(os)s, %(coe)s)"
                " not enabled.")

class RequiredParameterNotProvided(MagnumException):
    message = _("Required parameter %(heat_param)s not provided.")

class Urllib2InvalidScheme(MagnumException):
    message = _("The urllib2 URL %(url) has an invalid scheme.")

class OperationInProgress(Invalid):
    message = _("Bay %(bay_name)s already has an operation in progress.")

class ImageNotFound(ResourceNotFound):
    message = _("Image %(image_id)s could not be found.")

class ImageNotAuthorized(MagnumException):
    message = _("Not authorized for image %(image_id)s.")

class OSDistroFieldNotFound(ResourceNotFound):
    message = _("Image %(image_id)s doesn't contain os_distro field.")

class KubernetesAPIFailed(MagnumException):
    def __init__(self, message=None, **kwargs):
        self.__class__.code = kwargs.get('code')
        super(KubernetesAPIFailed, self).__init__(message, **kwargs)

class X509KeyPairNotFound(ResourceNotFound):
    message = _("A key pair %(keypair)s could not be found.")

class X509KeyPairAlreadyExists(Conflict):
    message = _("A key pair with UUID %(uuid)s already exists.")

class CertificateStorageException(MagnumException):
    message = _("Could not store certificate: %(msg)s")

class CertificateValidationError(Invalid):
    message = _("Extension '%(extension)s' not allowed")


text:
""" Import cache.

This is not about caching the search of modules in the file system, but about
maintaining a cache of module trees built.

It can happen that modules become unused, and then dropped from active modules,
and then later active again, via another import, and in this case, we should
not start anew, but reuse what we already found out about it.
"""

import os

from nuitka.plugins.Plugins import Plugins
from nuitka.utils.FileOperations import relpath

imported_modules = {}
imported_by_name = {}

def addImportedModule(imported_module):
    module_filename = relpath(imported_module.getFilename())

    if os.path.basename(module_filename) == "__init__.py":
        module_filename = os.path.dirname(module_filename)

    key = (module_filename, imported_module.getFullName())

    if key in imported_modules:
        assert imported_module is imported_modules[key], key
    else:
        Plugins.onModuleDiscovered(imported_module)

    imported_modules[key] = imported_module
    imported_by_name[imported_module.getFullName()] = imported_module

    # We don't expect that to happen.
    assert not imported_module.isMainModule()

def isImportedModuleByPath(module_relpath):
    for key in imported_modules:
        if key[0] == module_relpath:
            return True

    return False

def isImportedModuleByName(full_name):
    return full_name in imported_by_name

def getImportedModuleByName(full_name):
    return imported_by_name[full_name]

def getImportedModuleByNameAndPath(full_name, module_relpath):
    if module_relpath is None:
        # pyi deps only
        return getImportedModuleByName(full_name)

    if os.path.basename(module_relpath) == "__init__.py":
        module_relpath = os.path.dirname(module_relpath)

    return imported_modules[module_relpath, full_name]

def getImportedModuleByPath(module_relpath, module_package):
    for key in imported_modules:
        if key[0] == module_relpath:
            module = imported_modules[key]

            if (
                module.getCompileTimeFilename().endswith("__init__.py")
                and module.getFullName().getPackageName() != module_package
            ):
                continue

            return imported_modules[key]

    raise KeyError(module_relpath)

def replaceImportedModule(old, new):
    for key, value in imported_by_name.items():
        if value == old:
            imported_by_name[key] = new
            break
    else:
        assert False

    for key, value in imported_modules.items():
        if value == old:
            imported_modules[key] = new
            break
    else:
        assert False


text:
from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid

class HUnitR01_CompleteLHS(HimesisPreConditionPatternLHS):
	def __init__(self):
		"""
		Creates the himesis graph representing the AToM3 model HUnitR01_CompleteLHS
		"""
		# Flag this instance as compiled now
		self.is_compiled = True

		super(HUnitR01_CompleteLHS, self).__init__(name='HUnitR01_CompleteLHS', num_nodes=0, edges=[])

		# Add the edges
		self.add_edges([])

		# Set the graph attributes
		self["mm__"] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule']
		self["MT_constraint__"] = """return True"""
		self["name"] = """"""
		self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'HUnitR01_CompleteLHS')
		self["equations"] = []
		# Set the node attributes

		# match class State(State) node
		self.add_node()
		self.vs[0]["MT_pre__attr1"] = """return True"""
		self.vs[0]["MT_label__"] = """1"""
		self.vs[0]["mm__"] = """MT_pre__State"""
		self.vs[0]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'State')

		# apply class ProcDef(ProcDef) node
		self.add_node()
		self.vs[1]["MT_pre__attr1"] = """return True"""
		self.vs[1]["MT_label__"] = """2"""
		self.vs[1]["mm__"] = """MT_pre__ProcDef"""
		self.vs[1]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'ProcDef')

		# apply class Name(Name1) node
		self.add_node()
		self.vs[2]["MT_pre__attr1"] = """return True"""
		self.vs[2]["MT_label__"] = """3"""
		self.vs[2]["mm__"] = """MT_pre__Name"""
		self.vs[2]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Name1')

		# apply class Name(Name2) node
		self.add_node()
		self.vs[3]["MT_pre__attr1"] = """return True"""
		self.vs[3]["MT_label__"] = """4"""
		self.vs[3]["mm__"] = """MT_pre__Name"""
		self.vs[3]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Name2')

		# apply class Name(Name3) node
		self.add_node()
		self.vs[4]["MT_pre__attr1"] = """return True"""
		self.vs[4]["MT_label__"] = """5"""
		self.vs[4]["mm__"] = """MT_pre__Name"""
		self.vs[4]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Name3')

		# apply association null--channelNames-->nullnode
		self.add_node()
		self.vs[5]["MT_pre__attr1"] = """return attr_value == "channelNames" """
		self.vs[5]["MT_label__"] = """6"""
		self.vs[5]["mm__"] = """MT_pre__directLink_T"""
		self.vs[5]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'ProcDefassoc5Name1')

		# apply association null--channelNames-->nullnode
		self.add_node()
		self.vs[6]["MT_pre__attr1"] = """return attr_value == "channelNames" """
		self.vs[6]["MT_label__"] = """7"""
		self.vs[6]["mm__"] = """MT_pre__directLink_T"""
		self.vs[6]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'ProcDefassoc6Name2')

		# apply association null--channelNames-->nullnode
		self.add_node()
		self.vs[7]["MT_pre__attr1"] = """return attr_value == "channelNames" """
		self.vs[7]["MT_label__"] = """8"""
		self.vs[7]["mm__"] = """MT_pre__directLink_T"""
		self.vs[7]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'ProcDefassoc7Name3')

		self['equations'].append(((1,'name'),('concat',(('constant','S'),(0,'name')))))
		self['equations'].append(((2,'literal'),('constant','exit')))
		self['equations'].append(((3,'literal'),('constant','exack')))
		self['equations'].append(((4,'literal'),('constant','enp')))

		# Add the edges
		self.add_edges([
			(1,5), # apply class null(ProcDef) -> association channelNames
			(5,2), # association null -> apply class null(Name1)
			(1,6), # apply class null(ProcDef) -> association channelNames
			(6,3), # association null -> apply class null(Name2)
			(1,7), # apply class null(ProcDef) -> association channelNames
			(7,4), # association null -> apply class null(Name3)
		])

	# define evaluation methods for each match class.

	def eval_attr11(self, attr_value, this):
		return True

	# define evaluation methods for each apply class.

	def eval_attr12(self, attr_value, this):
		return True

	def eval_attr13(self, attr_value, this):
		return True

	def eval_attr14(self, attr_value, this):
		return True

	def eval_attr15(self, attr_value, this):
		return True

		# define evaluation methods for each match association.

		# define evaluation methods for each apply association.

	def eval_attr16(self, attr_value, this):
		return attr_value == "channelNames"
	def eval_attr17(self, attr_value, this):
		return attr_value == "channelNames"
	def eval_attr18(self, attr_value, this):
		return attr_value == "channelNames"

	def constraint(self, PreNode, graph):
		return True


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

namespace _12.N_th_bit
{
    class Program
    {
        static void Main(string[] args)
        {

            int number = int.Parse(Console.ReadLine());
            int position = int.Parse(Console.ReadLine());
            int mask = 1 << position;
           // Console.WriteLine(mask);
            int bit = number & mask;
          //  Console.WriteLine(bit);
            bit = bit >> position;
            Console.WriteLine(bit);
        }
    }
}


text:
/*
 * Schematica (http://www.schematica.org)
 *
 * 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.schematica.db.task;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import org.schematica.db.Store;

/**
 * An executable task for processing documents within a {@link Store}. Tasks are potentially very long-running activities that may
 * require significant processing (e.g., running map-reduce over millions of documents) and resources that must be
 * {@link Results#close() released}. But sometimes tasks are also small enough that your application may want to simply run the
 * task and wait for its completion.
 *

 * Tasks are designed to be executed directly (synchronously) within the same thread, or asynchronously via
 * {@link ExecutorService#submit(Callable) submission} to an {@link ExecutorService}.
 *

 *
Synchronous (direct) execution

 *

 * To inoke immediately and synchronously from the calling thread:
 *
 *

 *   Task<T> task = ...
 *   Results<T> results = null;
 *   try {
 *       results = task.call();  // runs the task in this thread
 *       T output = result.getOutput();
 *   } catch ( SchematicaException e ) {
 *       // deal with any problems ...
 *   } finally {
 *       if ( result != null ) result.close();
 *   }
 *

 *
 * Now, this example shows how the {@link Results} object must always be closed to release any resources that it might be using.
 * (For example, the results may have been so large that they were buffered on the file system, and when you are finished these
 * temporary files must be cleaned up.)
 *

 *

 * Java 7 introduces the try-with-resources statement
 * that will ensure that any resources created at the beginning of the {@code try} block will definitely be closed properly even
 * when exceptions occur. Because Schematica's {@link Results} interface implements {@link AutoCloseable}, we can write the code
 * in a slightly more compact fashion that is even more robust:
 *
 *

 *   Task<T> task = ...
 *   try ( Results<T> results = task.call() ) {  // runs the task, closes the results in a finally
 *       T output = results.getOutput();
 *       // do something with the output
 *   } catch ( SchematicaException e ) {
 *       // deal with any problems ...
 *   }
 *

 *
 *

 *
Asynchronous execution

 *

 * Some tasks may take a long time to execute, so Schematica's Tasks are designed to be asynchronously executed using Java's
 * standard {@link ExecutorService}. After creating a Task, simply submit the task to your ExecutorService and obtain the
 * {@link Future}:
 *
 *

 *   Task<T> task = ...
 *   ExecutorService executor = ...
 *   Future<Results<T>> future = executor.submit(task);     // submit for aynchronous execution
 *

 *
 * Here the {@code submit} call does not block and immediately returns a {@link Future} that can be used to
 * {@link Future#cancel(boolean) cancel} the task, determine if the task has been {@link Future#isCancelled() cancelled}, and to
 * {@link Future#get() wait indefinitely} or for a {@link Future#get(long, java.util.concurrent.TimeUnit) maximum amount of time}
 * for the task to be completed.
 *

 *

 * For example, a different part of the code can obtain the {@link Future} instance and periodically check whether the work has
 * been completed:
 *
 *

 * if (future.isDone()) {
 *     try (Results<T> results = future.get()) {
 *         T output = results.getOutput();
 *         // do something with the output
 *     } catch (ExecutionException e) {
 *         // The task completed but there was a probelm during task execution ...
 *     }
 * }
 *

 *
 *

 *

 * Alternatively, another thread might want to wait a certain amount of time for the task to complete:
 *
 *

 * try (Results<T> results = future.get(10, TimeUnit.MINUTES)) {
 *     T output = results.getOutput();
 *     // do something with the output
 * } catch (TimeoutException e) {
 *     // The work wasn't done within our limit ...
 * } catch (InterruptedException e) {
 *     // The task was probably cancelled or stopped ...
 * } catch (ExecutionException e) {
 *     // The task completed but there was a probelm during task execution ...
 * }
 *

 *
 *

 *

 * Again, because {@link Results} is {@link AutoCloseable auto-closeable}, Java will guarantee that it is {@link Results#close()
 * closed} in the {@code finally} portion of the {@code try} blocks.
 *

 *
 * @author Randall Hauch (rhauch@redhat.com)
 * @param <T> the type of result that should be returned when this task is completed.
 */
public interface Task<T> extends Callable<Results<T>> {

}


text:
package com.amazonaws.services.elasticmapreduce.model;

import java.io.Serializable;

import com.amazonaws.AmazonWebServiceRequest;

/**
 * Container for the parameters to the {@link com.amazonaws.services.elasticmapreduce.AmazonElasticMapReduce#listInstanceGroups(ListInstanceGroupsRequest) ListInstanceGroups operation}.
 *

 * Provides all available details about the instance groups in a cluster.
 *

 *
 * @see com.amazonaws.services.elasticmapreduce.AmazonElasticMapReduce#listInstanceGroups(ListInstanceGroupsRequest)
 */
public class ListInstanceGroupsRequest extends AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     * The identifier of the cluster for which to list the instance groups.
     */
    private String clusterId;

    /**
     * The pagination token that indicates the next set of results to
     * retrieve.
     */
    private String marker;

    /**
     * The identifier of the cluster for which to list the instance groups.
     *
     * @return The identifier of the cluster for which to list the instance groups.
     */
    public String getClusterId() {
        return clusterId;
    }

    /**
     * The identifier of the cluster for which to list the instance groups.
     *
     * @param clusterId The identifier of the cluster for which to list the instance groups.
     */
    public void setClusterId(String clusterId) {
        this.clusterId = clusterId;
    }

    /**
     * The identifier of the cluster for which to list the instance groups.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param clusterId The identifier of the cluster for which to list the instance groups.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public ListInstanceGroupsRequest withClusterId(String clusterId) {
        this.clusterId = clusterId;
        return this;
    }

    /**
     * The pagination token that indicates the next set of results to
     * retrieve.
     *
     * @return The pagination token that indicates the next set of results to
     *         retrieve.
     */
    public String getMarker() {
        return marker;
    }

    /**
     * The pagination token that indicates the next set of results to
     * retrieve.
     *
     * @param marker The pagination token that indicates the next set of results to
     *         retrieve.
     */
    public void setMarker(String marker) {
        this.marker = marker;
    }

    /**
     * The pagination token that indicates the next set of results to
     * retrieve.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param marker The pagination token that indicates the next set of results to
     *         retrieve.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public ListInstanceGroupsRequest withMarker(String marker) {
        this.marker = marker;
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getClusterId() != null) sb.append("ClusterId: " + getClusterId() + ",");
        if (getMarker() != null) sb.append("Marker: " + getMarker() );
        sb.append("}");
        return sb.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getClusterId() == null) ? 0 : getClusterId().hashCode());
        hashCode = prime * hashCode + ((getMarker() == null) ? 0 : getMarker().hashCode());
        return hashCode;
    }

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

        if (obj instanceof ListInstanceGroupsRequest == false) return false;
        ListInstanceGroupsRequest other = (ListInstanceGroupsRequest)obj;

        if (other.getClusterId() == null ^ this.getClusterId() == null) return false;
        if (other.getClusterId() != null && other.getClusterId().equals(this.getClusterId()) == false) return false;
        if (other.getMarker() == null ^ this.getMarker() == null) return false;
        if (other.getMarker() != null && other.getMarker().equals(this.getMarker()) == false) return false;
        return true;
    }

    @Override
    public ListInstanceGroupsRequest clone() {

            return (ListInstanceGroupsRequest) super.clone();
    }

}


text:
class SettingModel:
	def __init__(self, dbRow):
		self.Key = dbRow["Key"]
		self.Value = dbRow["Value"]