text:
package gcewing.architecture;

import java.util.*;
import static java.lang.Math.*;

import net.minecraft.block.*;
import net.minecraft.block.state.*;
import net.minecraft.entity.*;
import net.minecraft.entity.player.*;
import net.minecraft.init.*;
import net.minecraft.item.*;
import net.minecraft.nbt.*;
import net.minecraft.world.*;
import net.minecraft.tileentity.*;
import net.minecraft.util.*;

import static net.minecraft.util.EnumFacing.*;

import gcewing.architecture.BaseModClient.*;

//------------------------------------------------------------------------------

public abstract class ShapeKind {

	public Object[] profiles; // indexed by local face

	public Object profileForLocalFace(Shape shape, EnumFacing face) {
		if (profiles != null)
			return profiles[face.ordinal()];
		else
			return null;
	}

	public double placementOffsetX() {
		return 0;
	}

	public abstract void renderShape(ShapeTE te,
		ITexture[] textures, IRenderTarget target, Trans3 t,
		boolean renderBase, boolean renderSecondary);

	public ItemStack newStack(Shape shape, IBlockState materialState, int stackSize) {
		ShapeTE te = new ShapeTE(shape, materialState);
		int light = te.baseBlockState.getBlock().getLightValue();
		return BaseTileEntity.blockStackWithTileEntity(ArchitectureCraft.blockShape, stackSize, light, te);
	}

	public ItemStack newStack(Shape shape, Block materialBlock, int materialMeta, int stackSize) {
		return newStack(shape, materialBlock.getStateFromMeta(materialMeta), stackSize);
	}

	public boolean orientOnPlacement(EntityPlayer player, ShapeTE te,
		BlockPos npos, IBlockState nstate, TileEntity nte, EnumFacing otherFace, Vector3 hit)
	{
		if (nte instanceof ShapeTE)
			return orientOnPlacement(player, te, (ShapeTE)nte, otherFace, hit);
		else
			return orientOnPlacement(player, te, null, otherFace, hit);
	}

	public boolean orientOnPlacement(EntityPlayer player, ShapeTE te, ShapeTE nte, EnumFacing otherFace,
		Vector3 hit)
	{
		//boolean debug = !te.getWorld().isRemote;
		if (nte != null && !player.isSneaking()) {
			Object otherProfile = Profile.getProfileGlobal(nte.shape, nte.side, nte.turn, otherFace);
			if (otherProfile != null) {
				EnumFacing thisFace = otherFace.getOpposite();
				for (int i = 0; i < 4; i++) {
					int turn = (nte.turn + i) & 3;
					Object thisProfile = Profile.getProfileGlobal(te.shape, nte.side, turn, thisFace);
					if (Profile.matches(thisProfile, otherProfile)) {
						//if (debug)
						//	System.out.printf("ShapeKind.orientOnPlacement: side %s turn %s\n", nte.side, turn);
						te.setSide(nte.side);
						te.setTurn(turn);
						te.setOffsetX(nte.getOffsetX());
						return true;
					}
				}
			}
		}
		return false;
	}

	public boolean canPlaceUpsideDown() {
		return true;
	}

	public double sideZoneSize() {
		return 1/4d;
	}

	public boolean highlightZones() {
		return false;
	}

	public void onChiselUse(ShapeTE te, EntityPlayer player, EnumFacing face, Vector3 hit) {
		EnumFacing side = zoneHit(face, hit);
		//System.out.printf("ShapeKind.onChiselUse: face = %s, hit = %s, side = %s\n", face, hit, side);
		if (side != null)
			chiselUsedOnSide(te, player, side);
		else
			chiselUsedOnCentre(te, player);
	}

	public void chiselUsedOnSide(ShapeTE te, EntityPlayer player, EnumFacing side) {
		te.toggleConnectionGlobal(side);
	}

	public void chiselUsedOnCentre(ShapeTE te, EntityPlayer player) {
		if (te.secondaryBlockState != null) {
			ItemStack stack = newSecondaryMaterialStack(te.secondaryBlockState);
			if (stack != null) {
				if (!Utils.playerIsInCreativeMode(player))
					Block.spawnAsEntity(te.getWorld(), te.getPos(), stack);
				te.setSecondaryMaterial(null);
			}
		}
	}

	protected ItemStack newSecondaryMaterialStack(IBlockState state) {
		if (acceptsCladding())
			return ArchitectureCraft.itemCladding.newStack(state, 1);
		else
			return null;
	}

	public void onHammerUse(ShapeTE te, EntityPlayer player, EnumFacing face, Vector3 hit) {
		//System.out.printf("ShapeKind.onHammerUse\n");
		if (player.isSneaking())
			te.setSide((te.side + 1) % 6);
		else {
			double dx = te.getOffsetX();
			if (dx != 0) {
				dx = - dx;
				te.setOffsetX(dx);
			}
			if (dx >= 0)
				te.setTurn((te.turn + 1) % 4);
		}
		te.markChanged();
	}

	public EnumFacing zoneHit(EnumFacing face, Vector3 hit) {
		double r = 0.5 - sideZoneSize();
		//System.out.printf("ShapeKind.zoneHit: hit = (%.3f,%.3f,%.3f) r = %.3f\n",
		//	hit.x, hit.y, hit.z, r);
		if (hit.x <= -r && face != WEST) return WEST;
		if (hit.x >=  r && face != EAST) return EAST;
		if (hit.y <= -r && face != DOWN) return DOWN;
		if (hit.y >=  r && face != UP) return UP;
		if (hit.z <= -r && face != NORTH) return NORTH;
		if (hit.z >=  r && face != SOUTH) return SOUTH;
		return null;
	}

	public boolean acceptsCladding() {
		return false;
	}

	public boolean isValidSecondaryMaterial(IBlockState state) {
		return false;
	}

	public boolean secondaryDefaultsToBase() {
		return false;
	}

	public AxisAlignedBB getBounds(ShapeTE te, IBlockAccess world, BlockPos pos, IBlockState state,
		Entity entity, Trans3 t)
	{
		List<AxisAlignedBB> list = new ArrayList<AxisAlignedBB>();
		addCollisionBoxesToList(te, world, pos, state, entity, t, list);
		return Utils.unionOfBoxes(list);
	}

	public void addCollisionBoxesToList(ShapeTE te, IBlockAccess world, BlockPos pos, IBlockState state,
		Entity entity, Trans3 t, List list)
	{
		int mask = te.shape.occlusionMask;
		int param = mask & 0xff;
		double r, h;
		switch (mask & 0xff00) {
			case 0x000: // 2x2x2 cubelet bitmap
				for (int i = 0; i < 8; i++)
					if ((mask & (1 << i)) != 0) {
						Vector3 p = new Vector3(
							(i & 1) != 0 ? 0.5 : -0.5,
							(i & 4) != 0 ? 0.5 : -0.5,
							(i & 2) != 0 ? 0.5 : -0.5);
						addBox(Vector3.zero, p, t, list);
					}
					break;
			case 0x100: // Square, full size in Y
				r = param / 16.0;
				addBox(new Vector3(-r, -0.5, -r), new Vector3(r, 0.5, r), t, list);
				break;
			case 0x200: // Slab, full size in X and Y
				r = param / 32.0;
				addBox(new Vector3(-0.5, -0.5, -r), new Vector3(0.5, 0.5, r), t, list);
				break;
			case 0x300: // Slab in back corner
				r = ((param & 0xf) + 1) / 16.0; // width and length of slab
				h = ((param >> 4) + 1) / 16.0; // height of slab from bottom
				addBox(new Vector3(-0.5, -0.5, 0.5 - r), new Vector3(-0.5 + r, -0.5 + h, 0.5), t, list);
				break;
			case 0x400: // Slab at back
			case 0x500: // Slabs at back and right
				r = ((param & 0xf) + 1) / 16.0; // thickness of slab
				h = ((param >> 4) + 1) / 16.0; // height of slab from bottom
				addBox(new Vector3(-0.5, -0.5, 0.5 - r), new Vector3(0.5, -0.5 + h, 0.5), t, list);
				if ((mask & 0x100) != 0)
					addBox(new Vector3(-0.5, -0.5, -0.5), new Vector3(-0.5 + r, -0.5 + h, 0.5), t, list);
				break;
			default: // Full cube
				addBox(new Vector3(-0.5, -0.5, -0.5), new Vector3(0.5, 0.5, 0.5), t, list);
		}
	}

	protected void addBox(Vector3 p0, Vector3 p1, Trans3 t, List list) {
		//addBox(t.p(p0), t.p(p1), list);
		t.addBox(p0, p1, list);
	}

	//------------------------------------------------------------------------------

	public static Roof Roof = new Roof();

	public static class Roof extends ShapeKind {

//		static boolean debugPlacement = true;

		@Override
		public boolean acceptsCladding() {
			return true;
		}

		@Override
		public boolean secondaryDefaultsToBase() {
			return true;
		}

		public void renderShape(ShapeTE te,
			ITexture[] textures, IRenderTarget target, Trans3 t,
			boolean renderBase, boolean renderSecondary)
		{
			new RenderRoof(te, textures, t, target, renderBase, renderSecondary).render();
		}

//		@Override
//		public boolean orientOnPlacement(EntityPlayer player, ShapeTE te, ShapeTE nte, EnumFacing face,
//			Vector3 hit)
//		{
////			if (!te.getWorld().isRemote)
////				System.out.printf("Roof.orientOnPlacement\n");
//			if (!player.isSneaking() && nte != null && nte.shape.kind instanceof Roof) {
//				EnumFacing nlf = nte.localFace(face);
//				Profile np = profileForLocalFace(nte.shape, nlf);
//				Profile p = opposite(np);
//				EnumFacing lf = localFaceForProfile(te.shape, p);
//				if (lf != null) {
//					int turn = BaseUtils.turnToFace(lf, face.getOpposite());
//					if (debugPlacement && !te.getWorld().isRemote) {
//						System.out.printf(
//							"Roof.orientOnPlacement: Aligning profile %s on local side %s of neighbour " +
//							"with profile %s on local side %s\n", np, nlf, p, lf);
//						System.out.printf("Roof.orientOnPlacement: Turning local side %s to face global direction %s\n",
//							lf, face.getOpposite());
//						System.out.printf("Roof.orientOnPlacement: side %s turn %s\n", nte.side, turn);
//					}
//					te.setSide(nte.side);
//					te.setTurn(turn);
//					return true;
//				}
//			}
//			return false;
//		}

		protected enum RoofProfile {None, Left, Right, Ridge, Valley};

		static {
			Profile.declareOpposite(RoofProfile.Left, RoofProfile.Right);
		}

//		protected RoofProfile opposite(RoofProfile p) {
//			switch (p) {
//				case Left: return RoofProfile.Right;
//				case Right: return RoofProfile.Left;
//			}
//			return p;
//		}

		@Override
		public Object profileForLocalFace(Shape shape, EnumFacing face) {
			switch (shape) {
				case RoofTile:
				case RoofOverhang:
					switch (face) {
						case EAST: return RoofProfile.Left;
						case WEST: return RoofProfile.Right;
					}
					break;
				case RoofOuterCorner:
				case RoofOverhangOuterCorner:
					switch (face) {
						case SOUTH: return RoofProfile.Left;
						case WEST: return RoofProfile.Right;
					}
					break;
				case RoofInnerCorner:
				case RoofOverhangInnerCorner:
					switch (face) {
						case EAST: return RoofProfile.Left;
						case NORTH: return RoofProfile.Right;
					}
					break;
				case RoofRidge:
				case RoofSmartRidge:
				case RoofOverhangRidge:
					return RoofProfile.Ridge;
				case RoofValley:
				case RoofSmartValley:
				case RoofOverhangValley:
					return RoofProfile.Valley;
			}
			return RoofProfile.None;
		}

//		protected EnumFacing localFaceForProfile(Shape shape, Profile p) {
//			switch (shape) {
//				case RoofTile:
//				case RoofOverhang:
//					switch (p) {
//						case Left: return EAST;
//						case Right: return WEST;
//					}
//					break;
//				case RoofOuterCorner:
//				case RoofOverhangOuterCorner:
//					switch (p) {
//						case Left: return SOUTH;
//						case Right: return WEST;
//					}
//					break;
//				case RoofInnerCorner:
//				case RoofOverhangInnerCorner:
//					switch (p) {
//						case Left: return EAST;
//						case Right: return NORTH;
//					}
//					break;
//				case RoofRidge:
//				case RoofOverhangRidge:
//					switch (p) {
//						case Ridge:
//							return EAST;
//					}
//					break;
//				case RoofValley:
//				case RoofOverhangValley:
//					switch (p) {
//						case Valley:
//							return EAST;
//					}
//					break;
//			}
//			return null;
//		}

	}

	//------------------------------------------------------------------------------

	public static Model Model(String name) {
		return new Model(name, null);
	}

	public static Model Model(String name, Object[] profiles) {
		return new Model(name, profiles);
	}

	public static class Model extends ShapeKind {

		protected String modelName;
		private IModel model;

		public Model(String name, Object[] profiles) {
			this.modelName = "shape/" + name + ".smeg";
			this.profiles = profiles;
		}

		@Override
		public boolean secondaryDefaultsToBase() {
			return true;
		}

		@Override
		public AxisAlignedBB getBounds(ShapeTE te, IBlockAccess world, BlockPos pos, IBlockState state,
			Entity entity, Trans3 t)
		{
			return t.t(getModel().getBounds());
		}

		public void renderShape(ShapeTE te,
			ITexture[] textures, IRenderTarget target, Trans3 t,
			boolean renderBase, boolean renderSecondary)
		{
            IModel model = getModel();
            model.render(t, target, textures);
		}

		protected IModel getModel() {
			if (model == null)
				model = ArchitectureCraft.mod.getModel(modelName);
			return model;
		}

		@Override
		public boolean acceptsCladding() {
			BaseModel model = (BaseModel)getModel();
			for (BaseModel.Face face : model.faces)
				if (face.texture >= 2)
					return true;
			return false;
		}

		@Override
		public void addCollisionBoxesToList(ShapeTE te, IBlockAccess world, BlockPos pos, IBlockState state,
			Entity entity, Trans3 t, List list)
		{
			if (te.shape.occlusionMask == 0)
				getModel().addBoxesToList(t, list);
			else
				super.addCollisionBoxesToList(te, world, pos, state, entity, t, list);
		}

		@Override
		public double placementOffsetX() {
			List<AxisAlignedBB> list = new ArrayList<AxisAlignedBB>();
			getModel().addBoxesToList(Trans3.ident, list);
			AxisAlignedBB bounds = Utils.unionOfBoxes(list);
			if (Shape.debugPlacement) {
				for (AxisAlignedBB box : list)
					System.out.printf("ShapeKind.Model.placementOffsetX: %s\n", box);
				System.out.printf("ShapeKind.Model.placementOffsetX: bounds = %s\n", bounds);
			}
			return 0.5 * (1 - (bounds.maxX - bounds.minX));
		}

	}

	//------------------------------------------------------------------------------

	public static abstract class Window extends ShapeKind {

		public enum FrameKind {None, Plain, Corner};

		public EnumFacing[] frameSides;
		public boolean[] frameAlways;
		public FrameKind[] frameKinds;
		public EnumFacing[] frameOrientations;
		public Trans3[] frameTrans;

		@Override
		public boolean orientOnPlacement(EntityPlayer player, ShapeTE te, ShapeTE nte, EnumFacing otherFace,
			Vector3 hit)
		{
			int turn = -1;
			// If click is on side of a non-window block, orient perpendicular to it
			if (!player.isSneaking() && (nte == null || !(nte.shape.kind instanceof ShapeKind.Window))) {
				switch (otherFace) {
					case EAST:
					case WEST:
						turn = 0;
						break;
					case NORTH:
					case SOUTH:
						turn = 1;
						break;
				}
			}
			if (turn >= 0) {
				te.setSide(0);
				te.setTurn(turn);
				return true;
			}
			else
				return false;
		}

		public FrameKind frameKindForLocalSide(EnumFacing side) {
			return frameKinds[side.ordinal()];
		}

		public EnumFacing frameOrientationForLocalSide(EnumFacing side) {
			return frameOrientations[side.ordinal()];
		}

		@Override
		public boolean canPlaceUpsideDown() {
			return false;
		}

		@Override
		public double sideZoneSize() {
			return 1/8d; // 3/32d;
		}

		@Override
		public boolean highlightZones() {
			return true;
		}

		public void renderShape(ShapeTE te,
			ITexture[] textures, IRenderTarget target, Trans3 t,
			boolean renderBase, boolean renderSecondary)
		{
			new RenderWindow(te, textures, t, target, renderBase, renderSecondary).render();
		}

//		@Override
//		public void chiselUsedOnCentre(ShapeTE te, EntityPlayer player) {
//			if (te.secondaryBlockState != null) {
//				ItemStack stack = BaseUtils.blockStackWithState(te.secondaryBlockState, 1);
//				dropSecondaryMaterial(te, player, stack);
//			}
//		}

		@Override
		protected ItemStack newSecondaryMaterialStack(IBlockState state) {
			return BaseUtils.blockStackWithState(state, 1);
		}

		@Override
		public boolean isValidSecondaryMaterial(IBlockState state) {
			Block block = state.getBlock();
			return block == Blocks.glass_pane || block == Blocks.stained_glass_pane;
		}

		@Override
		public void addCollisionBoxesToList(ShapeTE te, IBlockAccess world, BlockPos pos, IBlockState state,
			Entity entity, Trans3 t, List list)
		{
			final double r = 1/8d, s = 3/32d;
			double[] e = new double[4];
			addCentreBoxesToList(r, s, t, list);
			for (int i = 0; i <= 3; i++) {
				boolean frame = frameAlways[i] || !isConnectedGlobal(te, t.t(frameSides[i]));
				if (entity == null || frame) {
					Trans3 ts = t.t(frameTrans[i]);
					addFrameBoxesToList(i, r, s, ts, list);
				}
				e[i] = frame ? 0.5 - r : 0.5;
			}
			if (te.secondaryBlockState != null)
				addGlassBoxesToList(r, s, 1/32d, e, t, list);
		}

		protected void addCentreBoxesToList(double r, double s, Trans3 t, List list) {
		}

		protected void addFrameBoxesToList(int i, double r, double s, Trans3 ts, List list) {
			ts.addBox(-0.5, -0.5, -s, 0.5, -0.5 + r, s, list);
		}

		protected void addGlassBoxesToList(double r, double s, double w, double e[], Trans3 t, List list) {
			t.addBox(-e[3], -e[0], -w, e[1], e[2], w, list);
		}

		protected boolean isConnectedGlobal(ShapeTE te, EnumFacing globalDir) {
			return getConnectedWindowGlobal(te, globalDir) != null;
		}

		public ShapeTE getConnectedWindowGlobal(ShapeTE te, EnumFacing globalDir) {
			EnumFacing thisLocalDir = te.localFace(globalDir);
			FrameKind thisFrameKind = frameKindForLocalSide(thisLocalDir);
			if (thisFrameKind != FrameKind.None) {
				EnumFacing thisOrient = frameOrientationForLocalSide(thisLocalDir);
				ShapeTE nte = te.getConnectedNeighbourGlobal(globalDir);
				if (nte != null && nte.shape.kind instanceof Window) {
					Window otherKind = (Window)nte.shape.kind;
					EnumFacing otherLocalDir = nte.localFace(globalDir.getOpposite());
					FrameKind otherFrameKind = otherKind.frameKindForLocalSide(otherLocalDir);
					if (otherFrameKind != FrameKind.None) {
						EnumFacing otherOrient = otherKind.frameOrientationForLocalSide(otherLocalDir);
						if (framesMatch(thisFrameKind, otherFrameKind,
							te.globalFace(thisOrient), nte.globalFace(otherOrient)))
								return nte;
					}
				}
			}
			return null;
		}

		protected boolean framesMatch(FrameKind kind1, FrameKind kind2,
			EnumFacing orient1, EnumFacing orient2)
		{
			if (kind1 == kind2) {
				switch (kind1) {
					case Plain:
						return orient1.getAxis() == orient2.getAxis();
					default:
						return orient1 == orient2;
				}
			}
			return false;
		}

//		protected EnumFacing getFrameOrientationGlobal(ShapeTE te, EnumFacing globalDir) {
//			Trans3 t = te.localToGlobalRotation();
//			EnumFacing localDir = t.it(globalDir);
//			return frameOrientations[localDir.ordinal()];
//		}

	}

	//------------------------------------------------------------------------------

	public static Cladding Cladding = new Cladding();

	public static class Cladding extends ShapeKind {

		public void renderShape(ShapeTE te,
			ITexture[] textures, IRenderTarget target, Trans3 t,
			boolean renderBase, boolean renderSecondary)
		{}

		public ItemStack newStack(Shape shape, Block materialBlock, int materialMeta, int stackSize) {
			return ArchitectureCraft.itemCladding.newStack(materialBlock, materialMeta, stackSize);
		}

	}

	//------------------------------------------------------------------------------

	public static Model Banister(String name) {
		return new Banister(name);
	}

	public static class Banister extends Model {

		public Banister(String modelName) {
			super(modelName, Profile.Generic.tbOffset);
		}

		public boolean orientOnPlacement(EntityPlayer player, ShapeTE te,
			BlockPos npos, IBlockState nstate, TileEntity nte, EnumFacing otherFace, Vector3 hit)
		{
			//System.out.printf("Banister.orientOnPlacement: nstate = %s\n", nstate);
			if (!player.isSneaking()) {
			    Block nblock = nstate.getBlock();
			    boolean placedOnStair = false;
			    int nside = -1; // Side that the neighbouring block is placed on
			    int nturn = -1; // Turn of the neighbouring block
				if (BlockStairs.isBlockStairs(nblock) && (otherFace == UP || otherFace == DOWN)) {
				    placedOnStair = true;
				    nside = stairsSide(nstate);
				    nturn = BaseUtils.turnToFace(SOUTH, stairsFacing(nstate));
				    if (nside == 1 && (nturn & 1) == 0)
				        nturn ^= 2;
				}
				else if (nblock instanceof ShapeBlock) {
				    if (nte instanceof ShapeTE) {
				        placedOnStair = true;
				        nside = ((ShapeTE)nte).side;
				        nturn = ((ShapeTE)nte).turn;
				    }
				}
				if (placedOnStair) {
					int side = otherFace.getOpposite().ordinal();
					if (side == nside) {
						Vector3 h = Trans3.sideTurn(side, 0).ip(hit);
						double offx = te.shape.offsetXForPlacementHit(side, nturn, hit);
						te.setSide(side);
						te.setTurn(nturn & 3);
						te.setOffsetX(offx);
						return true;
					}
				}
			}
			return super.orientOnPlacement(player, te, npos, nstate, nte, otherFace, hit);
		}

		private static EnumFacing stairsFacing(IBlockState state) {
			return (EnumFacing)state.getValue(BlockStairs.FACING);
		}

		private static int stairsSide(IBlockState state) {
			if (state.getValue(BlockStairs.HALF) == BlockStairs.EnumHalf.TOP)
				return 1;
			else
				return 0;
		}

		@Override
		public double placementOffsetX() {
			return 6/16d;
		}

	}

	//------------------------------------------------------------------------------

}


text:
package VMOMI::TaskReasonAlarm;
use parent 'VMOMI::TaskReason';

use strict;
use warnings;

our @class_ancestors = (
    'TaskReason',
    'DynamicData',
);

our @class_members = (
    ['alarmName', undef, 0, ],
    ['alarm', 'ManagedObjectReference', 0, ],
    ['entityName', undef, 0, ],
    ['entity', 'ManagedObjectReference', 0, ],
);

sub get_class_ancestors {
    return @class_ancestors;
}

sub get_class_members {
    my $class = shift;
    my @super_members = $class->SUPER::get_class_members();
    return (@super_members, @class_members);
}

1;

redpajama_set_name: RedPajamaGithub


text:
function X = slpcarecon(S, Y)
%SLPCARECON Reconstructs the samples in original space
%
% $ Syntax $
%   - Xr = slpcarecon(S, Y)
%
% $ Arguments $
%   - S:        the PCA model struct
%   - Y:        the principal component features
%   - Xr:       the reconstructed samples
%
% $ Description $
%   - Xr = slpcarecon(S, Y) reconstructs the original samples approximately
%     using the principal components Y. If the dimension of Y is less than
%     the subspace dimension, the leading space dimensions will be used.
%
% $ History $
%   - Created by Dahua Lin, on Aug 17, 2006
%   - Modified by Dahua Lin, on Sep 10, 2006
%       - replace sladd by sladdvec to increase efficiency
%

%% parse and verify input

if ~isstruct(S)
    error('sltoolbox:invalidarg', ...
        'S should be a PCA model struct');
end

if ~isnumeric(Y) || ndims(Y) ~= 2
    error('sltoolbox:invalidarg', ...
        'The features Y should be a 2D numeric matrix');
end

dy = size(Y, 1);
if dy > S.feadim
    error('sltoolbox:sizmismatch', ...
        'The feature dimension of Y exceeds the subspace dimension preserved in model');
end

%% reconstruct

if dy == S.feadim
    X = S.P * Y;
else
    X = S.P(:, 1:dy) * Y;
end

X = sladdvec(X, S.vmean, 1);


text:
<?php

namespace Symfony\Component\RateLimiter\Policy;

use Symfony\Component\Lock\LockInterface;
use Symfony\Component\Lock\NoLock;
use Symfony\Component\RateLimiter\Exception\MaxWaitDurationExceededException;
use Symfony\Component\RateLimiter\LimiterInterface;
use Symfony\Component\RateLimiter\RateLimit;
use Symfony\Component\RateLimiter\Reservation;
use Symfony\Component\RateLimiter\Storage\StorageInterface;

/**
 * @author Wouter de Jong <wouter@wouterj.nl>
 *
 * @experimental in 5.3
 */
final class TokenBucketLimiter implements LimiterInterface
{
    use ResetLimiterTrait;

    private $maxBurst;
    private $rate;

    public function __construct(string $id, int $maxBurst, Rate $rate, StorageInterface $storage, LockInterface $lock = null)
    {
        $this->id = $id;
        $this->maxBurst = $maxBurst;
        $this->rate = $rate;
        $this->storage = $storage;
        $this->lock = $lock ?? new NoLock();
    }

    /**
     * Waits until the required number of tokens is available.
     *
     * The reserved tokens will be taken into account when calculating
     * future token consumptions. Do not use this method if you intend
     * to skip this process.
     *
     * @param int   $tokens  the number of tokens required
     * @param float $maxTime maximum accepted waiting time in seconds
     *
     * @throws MaxWaitDurationExceededException if $maxTime is set and the process needs to wait longer than its value (in seconds)
     * @throws \InvalidArgumentException        if $tokens is larger than the maximum burst size
     */
    public function reserve(int $tokens = 1, float $maxTime = null): Reservation
    {
        if ($tokens > $this->maxBurst) {
            throw new \InvalidArgumentException(sprintf('Cannot reserve more tokens (%d) than the burst size of the rate limiter (%d).', $tokens, $this->maxBurst));
        }

        $this->lock->acquire(true);

        try {
            $bucket = $this->storage->fetch($this->id);
            if (!$bucket instanceof TokenBucket) {
                $bucket = new TokenBucket($this->id, $this->maxBurst, $this->rate);
            }

            $now = microtime(true);
            $availableTokens = $bucket->getAvailableTokens($now);
            if ($availableTokens >= $tokens) {
                // tokens are now available, update bucket
                $bucket->setTokens($availableTokens - $tokens);
                $bucket->setTimer($now);

                $reservation = new Reservation($now, new RateLimit($bucket->getAvailableTokens($now), \DateTimeImmutable::createFromFormat('U', floor($now)), true, $this->maxBurst));
            } else {
                $remainingTokens = $tokens - $availableTokens;
                $waitDuration = $this->rate->calculateTimeForTokens($remainingTokens);

                if (null !== $maxTime && $waitDuration > $maxTime) {
                    // process needs to wait longer than set interval
                    $rateLimit = new RateLimit($availableTokens, \DateTimeImmutable::createFromFormat('U', floor($now + $waitDuration)), false, $this->maxBurst);

                    throw new MaxWaitDurationExceededException(sprintf('The rate limiter wait time ("%d" seconds) is longer than the provided maximum time ("%d" seconds).', $waitDuration, $maxTime), $rateLimit);
                }

                // at $now + $waitDuration all tokens will be reserved for this process,
                // so no tokens are left for other processes.
                $bucket->setTokens(0);
                $bucket->setTimer($now + $waitDuration);

                $reservation = new Reservation($bucket->getTimer(), new RateLimit(0, \DateTimeImmutable::createFromFormat('U', floor($now + $waitDuration)), false, $this->maxBurst));
            }

            $this->storage->save($bucket);
        } finally {
            $this->lock->release();
        }

        return $reservation;
    }

    /**
     * {@inheritdoc}
     */
    public function consume(int $tokens = 1): RateLimit
    {
        try {
            return $this->reserve($tokens, 0)->getRateLimit();
        } catch (MaxWaitDurationExceededException $e) {
            return $e->getRateLimit();
        }
    }
}


text:
FROM kalabox/pantheon-appserver:v0.10.0

# Remove once terminus 0.9.4 is out
COPY install-terminus.sh /usr/local/bin/install-terminus.sh

# Install all the CLI magic
RUN \
  git clone --depth 1 --branch 5.11.0 https://github.com/drush-ops/drush.git /usr/local/src/drush5 && \
  git clone --depth 1 --branch 6.6.0 https://github.com/drush-ops/drush.git /usr/local/src/drush6 && \
  ln -s /usr/local/src/drush5/drush /usr/bin/drush5 && \
  ln -s /usr/local/src/drush6/drush /usr/bin/drush6 && \
  curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar && \
  chmod +x wp-cli.phar && mv wp-cli.phar /usr/local/bin/wp && \
  # We are going to roll our own terminus until 0.9.4 is out.
  # curl https://github.com/pantheon-systems/cli/releases/download/0.9.3/terminus.phar -L -o /usr/local/bin/terminus && \
  # chmod +x /usr/local/bin/terminus && \
  chmod +x /usr/local/bin/install-terminus.sh && sleep 5 && \
  /usr/local/bin/install-terminus.sh && \
  apt-get -y clean && \
  apt-get -y autoclean && \
  apt-get -y autoremove && \
  rm -rf /var/lib/apt/* && rm -rf && rm -rf /var/lib/cache/* && rm -rf /var/lib/log/* && rm -rf /tmp/*

# Set up our kalabox specific stuff
COPY kdrush /usr/local/bin/kdrush
COPY kterminus /usr/local/bin/kterminus
COPY kwp /usr/local/bin/kwp
COPY ssh-config /root/.ssh/config

# Set default env
ENV PHP_VERSION 5.3.29
ENV DRUSH_VERSION drush6
ENV SSH_KEY id_rsa

# Set up and link our roots for persistence
RUN \
  chmod +x /usr/local/bin/kterminus && \
  chmod +x /usr/local/bin/kdrush && \
  chmod +x /usr/local/bin/kwp && \
  mkdir -p /root/.ssh && mkdir -p /usr/share/drush/commands && \
  ln -s /src/config/drush /root/.drush && \
  ln -s /src/config/terminus /root/.terminus

# Install some extra goodies
RUN \
  cd /usr/share/drush/commands && \
  curl -L "http://ftp.drupal.org/files/projects/registry_rebuild-7.x-2.2.tar.gz" | tar -zvx && \
  curl -O "https://raw.githubusercontent.com/drush-ops/config-extra/1.0.1/config_extra.drush.inc"

ENTRYPOINT ["/usr/local/bin/kterminus"]


text:
// Copyright (c) 2009 INRIA Sophia-Antipolis (France).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
// You can redistribute it and/or modify it under the terms of the GNU
// General Public License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL$
// $Id$
//
//
// Author(s)     : Stéphane Tayeb
//
//******************************************************************************
// File Description :
// Mesh_facet_criteria_3 class.
//******************************************************************************

#ifndef CGAL_MESH_FACET_CRITERIA_3_H
#define CGAL_MESH_FACET_CRITERIA_3_H

#include <CGAL/Mesh_3/mesh_standard_facet_criteria.h>
#include <CGAL/Mesh_facet_topology.h>

namespace CGAL {

template<typename Tr,
         typename Visitor_ = Mesh_3::Facet_criterion_visitor_with_features<Tr> >
class Mesh_facet_criteria_3
{
public:
  typedef Visitor_ Visitor;
  typedef typename Visitor::Facet_quality Facet_quality;
  typedef typename Visitor::Facet_badness Facet_badness;

private:
  typedef Mesh_3::Criteria<Tr,Visitor> Criteria;
  typedef Mesh_3::Abstract_criterion<Tr,Visitor> Abstract_criterion;

  typedef typename Tr::Facet Facet;
  typedef typename Tr::Geom_traits::FT FT;

  typedef Mesh_facet_criteria_3<Tr> Self;

public:
  typedef CGAL::Tag_true Has_manifold_criterion;

  /**
   * @brief Constructor
   */
  Mesh_facet_criteria_3(const FT& angle_bound,
                        const FT& radius_bound,
                        const FT& distance_bound,
                        const Mesh_facet_topology topology =
                          FACET_VERTICES_ON_SURFACE)
  {
    if ( FT(0) != angle_bound )
      init_aspect(angle_bound);

    if ( FT(0) != radius_bound )
      init_radius(radius_bound);

    if ( FT(0) != distance_bound )
      init_distance(distance_bound);

    init_topo(topology);
  }

  // Nb: SFINAE (dummy) to avoid wrong matches with built-in numerical types
  // as int.
  template < typename Sizing_field >
  Mesh_facet_criteria_3(const FT& angle_bound,
                        const Sizing_field& radius_bound,
                        const FT& distance_bound,
                        const Mesh_facet_topology topology =
                          FACET_VERTICES_ON_SURFACE,
                        typename Sizing_field::FT /*dummy*/ = 0)
  {
    if ( FT(0) != angle_bound )
      init_aspect(angle_bound);

    init_radius(radius_bound);

    if ( FT(0) != distance_bound )
      init_distance(distance_bound);

    init_topo(topology);
  }

  /// Destructor
  ~Mesh_facet_criteria_3() { }

   /**
   * @brief returns the badness of facet \c facet
   * @param facet the facet
   * @return the badness of \c facet
   */
  Facet_badness operator()(const Facet& facet) const
  {
    return criteria_(facet);
  }

  void add(Abstract_criterion* criterion)
  {
    criteria_.add(criterion);
  }

  Mesh_facet_topology topology() const {
    return topology_;
  }

private:
  void init_aspect(const FT& angle_bound)
  {
    typedef Mesh_3::Aspect_ratio_criterion<Tr,Visitor> Aspect_criterion;
    criteria_.add(new Aspect_criterion(angle_bound));
  }

  void init_radius(const FT& radius_bound)
  {
    typedef Mesh_3::Uniform_size_criterion<Tr,Visitor> Uniform_size_criterion;
    criteria_.add(new Uniform_size_criterion(radius_bound));
  }

  template <typename Sizing_field>
  void init_radius(const Sizing_field& radius_bound)
  {
    typedef Mesh_3::Variable_size_criterion<Tr,Visitor,Sizing_field> Variable_size_criterion;
    criteria_.add(new Variable_size_criterion(radius_bound));
  }

  void init_distance(const FT& distance_bound)
  {
    typedef Mesh_3::Curvature_size_criterion<Tr,Visitor> Curvature_criterion;
    criteria_.add(new Curvature_criterion(distance_bound));
  }

  void init_topo(const Mesh_facet_topology topology)
  {
    topology_ = topology;
    switch ( topology % MANIFOLD )
    {
      case FACET_VERTICES_ON_SURFACE:
      {
        typedef Mesh_3::Facet_on_surface_criterion<Tr,Visitor> On_surface_criterion;
        criteria_.add(new On_surface_criterion());
        break;
      }

      case FACET_VERTICES_ON_SAME_SURFACE_PATCH:
      {
        typedef Mesh_3::Facet_on_same_surface_criterion<Tr,Visitor> Same_surface_criterion;
        criteria_.add(new Same_surface_criterion());
        break;
      }

      case FACET_VERTICES_ON_SAME_SURFACE_PATCH_WITH_ADJACENCY_CHECK:
      {
        // @TODO: Implement adjacency check !
        typedef Mesh_3::Facet_on_same_surface_criterion<Tr,Visitor> Same_surface_criterion;
        criteria_.add(new Same_surface_criterion());
        break;
      }
    }
  }

private:
  Criteria criteria_;
  Mesh_facet_topology topology_;
};  // end class Mesh_facet_criteria_3

}  // end namespace CGAL

#endif // CGAL_MESH_FACET_CRITERIA_3_H


text:
Net* net;
vector<NetChange> Net::changes;
Net::Mode Net::mode;
const int CLOSE_PEER_TIMER = 1000; // ms

//=================================================================================================
Net::Net() : peer(nullptr), packet_logger(nullptr), mp_load(false), mp_use_interp(true), mp_interp(0.05f), was_client(false)
{
}

//=================================================================================================
Net::~Net()
{
	DeleteElements(players);
	DeleteElements(old_players);
	if(peer)
		RakPeerInterface::DestroyInstance(peer);
	delete api;
	delete packet_logger;
}

//=================================================================================================
void Net::Init()
{
	api = new LobbyApi;
	api->Init(game->cfg);
}

//=================================================================================================
void Net::LoadLanguage()
{
	txCreateServerFailed = Str("createServerFailed");
	txInitConnectionFailed = Str("initConnectionFailed");
	txFastTravelText = Str("fastTravelText");
	txFastTravelWaiting = Str("fastTravelWaiting");
	txFastTravelCancel = Str("fastTravelCancel");
	txFastTravelDeny = Str("fastTravelDeny");
}

//=================================================================================================
void Net::LoadData()
{
	tFastTravel = res_mgr->LoadInstant<Texture>("fast_travel.png");
	tFastTravelDeny = res_mgr->LoadInstant<Texture>("fast_travel_deny.png");
}

//=================================================================================================
bool Net::ValidateNick(cstring nick)
{
	assert(nick);

	int len = strlen(nick);
	if(len == 0)
		return false;

	for(int i = 0; i < len; ++i)
	{
		if(!(isalnum(nick[i]) || nick[i] == '_'))
			return false;
	}

	if(strcmp(nick, "all") == 0)
		return false;

	return true;
}

//=================================================================================================
PlayerInfo* Net::FindPlayer(Cstring nick)
{
	assert(nick);
	for(PlayerInfo& info : players)
	{
		if(info.left == PlayerInfo::LEFT_NO && info.name == nick)
			return &info;
	}
	return nullptr;
}

//=================================================================================================
PlayerInfo* Net::FindPlayer(const SystemAddress& adr)
{
	assert(adr != UNASSIGNED_SYSTEM_ADDRESS);
	for(PlayerInfo& info : players)
	{
		if(info.adr == adr)
			return &info;
	}
	return nullptr;
}

//=================================================================================================
PlayerInfo* Net::TryGetPlayer(int id)
{
	for(PlayerInfo& info : players)
	{
		if(info.id == id)
		{
			if(info.left == PlayerInfo::LEFT_NO)
				return &info;
			break;
		}
	}
	return nullptr;
}

//=================================================================================================
void Net::OpenPeer()
{
	if(peer)
		return;

	peer = RakPeerInterface::GetInstance();
#ifdef TEST_LAG
	peer->ApplyNetworkSimulator(0.f, TEST_LAG, 0);
#endif
	if(game->cfg.GetBool("packet_logger"))
	{
		packet_logger = new PacketLogger;
		peer->AttachPlugin(packet_logger);
	}
}

//=================================================================================================
void Net::ClosePeer(bool wait, bool check_was_client)
{
	assert(peer);

	Info("Net peer shutdown.");
	peer->Shutdown(wait ? CLOSE_PEER_TIMER : 0);
	if(IsClient() && check_was_client)
		was_client = true;
	changes.clear();
	SetMode(Mode::Singleplayer);
}

//=================================================================================================
void Net::StartFastTravel(int who)
{
	// mark players
	if(IsServer() || who == 2)
	{
		for(PlayerInfo& info : players)
			info.fast_travel = false;
		if(who == 0)
			GetMe().fast_travel = true;
		else
			team->GetLeader()->player->player_info->fast_travel = true;
		fast_travel = true;
		fast_travel_timer = 0.f;
	}

	// send to server/players
	if(who == 0 || who == 1)
	{
		NetChange& c = Add1(changes);
		c.type = NetChange::FAST_TRAVEL;
		c.id = FAST_TRAVEL_START;
		c.count = 0;
	}

	// show notification
	if((who == 0 && IsServer()) || (who == 2 && team->IsLeader()))
	{
		if(fast_travel_notif)
			fast_travel_notif->Close();
		fast_travel_notif = game_gui->notifications->Add(txFastTravelWaiting, tFastTravel, -1.f);
	}
	else if(who == 1 || (who == 2 && !team->IsLeader()))
	{
		if(fast_travel_notif)
			fast_travel_notif->Close();
		fast_travel_notif = game_gui->notifications->Add(txFastTravelText, tFastTravel, -1.f);
		fast_travel_notif->buttons = true;
		fast_travel_notif->callback = delegate<void(bool)>(this, &Net::OnFastTravel);
	}
}

//=================================================================================================
void Net::CancelFastTravel(int mode, int id)
{
	fast_travel = false;

	if(!fast_travel_notif)
		return;

	switch(mode)
	{
	case FAST_TRAVEL_CANCEL:
		if(id != team->my_id)
		{
			PlayerInfo* info = TryGetPlayer(id);
			cstring name = info ? info->name.c_str() : nullptr;
			fast_travel_notif->icon = tFastTravelDeny;
			fast_travel_notif->text = Format(txFastTravelCancel, name);
			fast_travel_notif->Close(3.f);
		}
		else
			fast_travel_notif->Close();
		break;
	case FAST_TRAVEL_DENY:
		{
			PlayerInfo* info = TryGetPlayer(id);
			cstring name = info ? info->name.c_str() : nullptr;
			fast_travel_notif->icon = tFastTravelDeny;
			fast_travel_notif->text = Format(txFastTravelDeny, name);
			fast_travel_notif->Close(3.f);
		}
		break;
	case FAST_TRAVEL_NOT_SAFE:
		fast_travel_notif->icon = tFastTravelDeny;
		fast_travel_notif->text = txFastTravelNotSafe;
		fast_travel_notif->Close(3.f);
		break;
	case FAST_TRAVEL_IN_PROGRESS:
		fast_travel_notif->Close();
		break;
	}

	fast_travel_notif->buttons = false;
	fast_travel_notif = nullptr;

	if(IsServer() || (team->IsLeader() && mode == FAST_TRAVEL_CANCEL))
	{
		NetChange& c = Add1(changes);
		c.type = NetChange::FAST_TRAVEL;
		c.id = mode;
		c.count = id;
	}
}

//=================================================================================================
void Net::ClearFastTravel()
{
	if(fast_travel_notif)
	{
		fast_travel_notif->Close();
		fast_travel_notif = nullptr;
	}
	fast_travel = false;
}

//=================================================================================================
void Net::OnFastTravel(bool accept)
{
	if(accept)
	{
		PlayerInfo& me = GetMe();
		fast_travel_notif->buttons = false;
		fast_travel_notif->text = txFastTravelWaiting;
		me.fast_travel = true;

		NetChange& c = Add1(changes);
		if(IsServer())
		{
			c.type = NetChange::FAST_TRAVEL_VOTE;
			c.id = me.id;
		}
		else
		{
			c.type = NetChange::FAST_TRAVEL;
			c.id = FAST_TRAVEL_ACCEPT;
		}
	}
	else
	{
		fast_travel = false;
		fast_travel_notif->Close();
		fast_travel_notif = nullptr;

		NetChange& c = Add1(changes);
		c.type = NetChange::FAST_TRAVEL;
		c.id = FAST_TRAVEL_DENY;
		c.count = team->my_id;
	}
}


text:
ENV['RACK_ENV'] = 'test'

require 'coveralls'
require 'simplecov'

require 'autocomplete-me'

# Configure code coverage reporting
SimpleCov.formatters = [SimpleCov::Formatter::HTMLFormatter, Coveralls::SimpleCov::Formatter]

SimpleCov.start do
  add_filter '/spec'
  coverage_dir 'docs/coverage'
  minimum_coverage(95.0)
end

AutocompleteMe.config { |c| c.redis = MockRedis.new }

# Load spec helpers and support classes
Dir['./spec/support/**/*.rb'].each { |f| require f }

RSpec.configure do |config|
  config.pattern = '**/*_spec.rb'
  config.include Rack::Test::Methods
  config.include ResponseHelper
  config.expect_with :rspec do |c|
    c.syntax = :expect
  end
  config.mock_framework = :rr

  def app
    AutocompleteMe::Service.new
  end
end


text:
class LineCorpusScanner : public CorpusScanner
{
protected:
    //struct file_buffer *infb_;
    serializer *ser;
    docid_t docnum_;
    bool init;
public:
    LineCorpusScanner(int fd);
    DocumentScanner *getScanner();
    void freeScanner(DocumentScanner *scanner);

    class LineDocumentScanner : public DocumentScanner
    {
        friend class LineCorpusScanner;
    private:
        LineCorpusScanner *parent_;
        char *linebuf_;
        char *docid_;
        char *title_;
        char *body_;
        docid_t curdoc_;
        char *saveptr_;
        stemmer *z;
        inline void clean_text(char *buffer) {
          for(char *p = buffer;*p;++p) {
            char c = *p;
            if (!isalnum(c)) *p = ' '; //TODO: decide whether to include '-'
          }
        }

        LineDocumentScanner(LineCorpusScanner* parent);
        ~LineDocumentScanner();

    public:
        bool nextDocument(uint64_t &fpos, docid_t &docid, std::string name, std::vector<std::string> &title_terms, std::vector<std::string> &body_terms);
        uint64_t get_file_pos();
    };
};

#endif


text:
import styled from 'styled-components';
import ZeroConfigExample from './ZeroConfigExample';
import DeclarativeExample from './DeclarativeExample';
import DraggableExample from './DraggableExample';
import PassiveExample from './PassiveExample';
import ReactExample from './ReactExample';
import { Strong } from '~/templates/global/styled';
import CustomExample from './CustomExample';
import ChildrenExample from './ChildrenExample';
import FlipExample from './FlipExample';
import PluginsExample from './PluginsExample';
import Link from 'next/link';
import { CTA } from '~/templates/Popmotion/Masthead/styled';
import AnimateAnythingExample from './AnimateAnything';
import { ActionLink } from '~/templates/global-new/styled';

const MoreExamples = styled.div`
  margin: 20px auto 50px;
`;

export default class Examples extends React.Component {
  state = { framework: 'react' };

  setFramework = (framework) => () => this.setState({ framework });

  setFrameworkTo = {
    vue: this.setFramework('vue'),
    react: this.setFramework('react'),
  };

  render() {
    return (
      <Container>
        <BlurbText style={{ marginBottom: 40, maxWidth: '600px' }}>
          These are legacy docs for Pose. Please upgrade to{' '}
          Framer Motion.
        </BlurbText>
        <ActionLink cta href="/pose/learn/get-started" prefetch>
          Get started
        </ActionLink>

        <MoreExamples>
          <Link href="/pose/examples">
            See all examples
          </Link>
        </MoreExamples>
      </Container>
    );
  }
}


text:
import * as React from 'react'
import { Link } from 'react-router-dom'
import { genericHashLink } from 'react-router-hash-link'

export default React.forwardRef((props, ref) => genericHashLink({ ...props, ref }, Link))


text:
import { ApplicationStateAction } from "../../../action/action"

import { ValidateBoardFieldStateHandler } from "../../action_validate_field/core/action"

import { UpdateBoardValidateStateMethod } from "../../validate_board/method"

import { ValidateBoardState } from "../../validate_board/data"
import { ConvertBoardResult } from "../../kernel/data"

export interface ValidateBoardAction<N extends string, T>
    extends ApplicationStateAction<ValidateBoardActionState> {
    updateValidateState<E>(name: N): ValidateBoardFieldStateHandler<E>
    get(): ConvertBoardResult<T>
}

export type ValidateBoardMaterial<N extends string> = Readonly<{
    updateValidateState: UpdateBoardValidateStateMethod<N>
}>

export type ValidateBoardActionState = ValidateBoardState
export const initialValidateBoardState: ValidateBoardActionState = "initial"


text:
layout: link
title: '"The lazy consultant answer."'
link: http://www.fastcompany.com/1483322/exclusive-interview-wolff-olins-and-aol-why-aols-new-brand-future
tags:
- aol
- wolff olins

---

Paul Worthington, Head of Strategy at Wilf Olins:

> A lot of people are saying why didn't you change the name. The simple answer in the world we live in today is that's the lazy consultant answer.—Paul Worthington, Head of Strategy at Wolff Olins. I think the lesson here is that as tempting as it is to type "FAIL" every time you see a a flat jpg of a new rebranding effort, sometimes a little more thought and context are needed.

[EDIT: a [follow-up](http://www.wolffolinsblog.com/post/277656003/sticking-with-it) on this quote.]


text:
<?php

/**
 *
 * @author:  Gabriel BONDAZ <gabriel.bondaz@idci-consulting.fr>
 * @licence: GPL
 *
 */

namespace IDCI\Bundle\ExporterBundle\Export;

class JsonExport extends AbstractExport
{
    protected $contentType = 'application/json';

    public function buildHeader()
    {
        $this->setContent('[');
    }

    public function buildFooter()
    {
        $this->setContent($this->getContent().']');
    }

    public function addContent($content)
    {
        $glue = $this->getCount() > 0 ? ',' : '';
        parent::addContent($glue.$content);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Strict //EN">

<title>Topic: @PrePersist, @PostPersist, @PostLoad,...</title>
<link rel="shortcut icon" href="/image/favicon.ico" >
<link rel="stylesheet" type="text/css" href="/static/v2style.css" >

<meta name="Author" content="Lyubo">
<meta name="description" content="lifesycle management via annotations would be handy ">

<form action='/topic-173.html' method="post" id="GLOBAL_ACTION">
<input type='hidden' name='_WOGA_CONTROLLER' >
<input type='hidden' name='_WOGA_METHOD' >
<input type='hidden' name='_WOGA_PARAM' >
<input type='hidden' name='_WOGA_RENDER' >

home
documentation
downloads
google group
forums
bugs
feedback

 Home » Forum » Annotations and Xml mapping

Please use the google group to ask questions - thanks.

by Lyubo
04 Mar 10:39

@PrePersist, @PostPersist, @PostLoad,...

lifesycle management via annotations would be handy

04 Mar 21:29

by Rob

Quite right. At the moment you have to use the Ebean specific BeanPersistController.

However, the BeanPersistController does do more ... takes into account partial objects (loaded properties), gives you access to the transaction and server that is processing the persist request etc, allows you to override the insert/update/delete behaviour.

Also note that often @PostPersist is NOT what you want as that fires even when a transaction rolls back - in this case you'd want to use a BeanPersistListener instead.

So yes, we need to add support for the annotations... but be careful because sometimes you might need to use a BeanPersistController or BeanPersistListener instead.

Cheers, Rob.

05 Mar 22:27

by Rob

Logged as http://www.avaje.org/bugdetail-235.html

<input type="hidden" name="f_forumid" value="4">
<input type="hidden" name="f_topicid" value="173">
<input type="hidden" name="f_postid" value="">

Add Comment

Comment:
<textarea class="wide80" id="f_body" name="f_body" rows="10" cols="30"></textarea>

Create a New Topic

Title:
<input class="txt wide90" name="nt_title" value="$paramtool.getParamIfNull('nt_title','')">

Body:
<textarea class="wide90" name="nt_body" rows="10" cols="30">$paramtool.getParamIfNull('nt_body','')</textarea>

<input type="button" class="btn" value="Save" accesskey="s" onclick="woAction('app.comp.TopicNew','doNewTopic');" >
<input type="button" class="btn" value="Cancel" accesskey="c" onclick="popdialog.hide();">

home | back to top

Introduction
User Guide (pdf)
Install/Configure
Public JavaDoc
Whitepapers

General
Database Specific
Byte Code
Deployment Annotations
Features

Top Bugs
Top Enhancements

woResponse

</form>


text:
This repo contains the source files for [http://www.techaccelerator.com/](http://www.techaccelerator.com/).

Documentation is written in Markdown (with options similar to [Github's Flavor](https://help.github.com/articles/github-flavored-markdown/)).

[Jekyll](https://http://jekyllrb.com//) is used to generate static HTML files.

## Usage

On windows:
```shell
C:\> @powershell -NoProfile -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"
C:\> choco install -y ruby vscode github
C:\> powershell
C:\> wget https://rubygems.org/downloads/rubygems-update-3.0.3.gem
C:\> gem install --local rubygems-update-3.0.3.gem
C:\> update_rubygems --no-ri --no-rdoc
C:\> gem uninstall rubygems-update -x
```

Ruby and bundler are required.

```shell
$ bundle install
$ jekyll serve
==    Server address: http://127.0.0.1:4000/
```

### Frontmatter

Each page in the documentation has a header, called frontmatter, this controls where it's displayed and it's title.

e.g.

```
---
title: "Custom Domains"
sort: 40
---
```
# Publishing

Docs are published automatically by Github Pages.


text:
package org.conqat.lib.commons.digest;

import java.security.MessageDigest;

import org.conqat.lib.commons.assertion.CCSMPre;
import org.conqat.lib.commons.collections.ByteArrayWrapper;

/**
 * An MD5 digest. This is just a thin wrapper around a byte array with some
 * convenience methods. This class is used instead of plain strings to save both
 * memory and (some) execution time.
 *
 * @author $Author: kinnen $
 * @version $Rev: 41751 $
 * @ConQAT.Rating GREEN Hash: 1D8556FFB7A1CFD64495333C61B393FB
 */
public final class MD5Digest extends ByteArrayWrapper {

	/** Version used for serialization. */
	private static final long serialVersionUID = 1;

	/** Number of bytes in an MD5 sum. */
	public static final int MD5_BYTES = 16;

	/**
	 * Constructor. This calls {@link MessageDigest#digest()}, so the digest
	 * will be reset afterwards.
	 */
	public MD5Digest(MessageDigest digest) {
		this(digest.digest());
	}

	/** Constructor. */
	public MD5Digest(byte[] digest) {
		super(digest);
		CCSMPre.isTrue(digest.length == MD5_BYTES,
				"Invalid size of MD5 digest!");
	}

	/**
	 * Inserts the digest data into the given MD. This method is used to rehash
	 * multiple hashes.
	 * <p>
	 * This method is provided instead of a getter, to keep this immutable.
	 */
	public void insertIntoDigest(MessageDigest digest) {
		digest.update(array);
	}

	/**
	 * Calculates and returns a hashcode that only depends on the first 3 bytes.
	 */
	public int partialHashCode() {
		return array[0] | (array[1] << 8) | (array[2] << 16);
	}
}


text:
'use strict';

module.exports = function(options) {
  if (!options.test) {
    var ssl = options.ssl ? '?ssl=true' : '';
    return `${options.DATABASE_URL}${ssl}`;
  }

  // This configuration works on Travis CI. It's also straightforward to setup
  // locally. Just make sure that a superuser named `postgres` exists:
  // `createuser -s postgres`
  else {
    return {
      host: 'localhost',
      user: 'postgres',
      database: 'api_pls_test_db',
      password: undefined
    };
  }
};


text:
ACCEPTED

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

#### Published in
Phytopathology 19(3): 201 (1929)

#### Original name
Pestalotia guepinii var. vaccinii Shear, 1902

### Remarks
null


text:
from flask import Flask, render_template
from flask.ext.mongoengine import MongoEngine, MongoEngineSessionInterface
import configparser
from .momentjs import momentjs

app = Flask(__name__)
# Security
WTF_CSRF_ENABLED = True
app.jinja_env.globals['momentjs'] = momentjs

# App Config
config = configparser.ConfigParser()
config.read('config/config.ini')

app.config['MONGODB_SETTINGS'] = {
  'db': config['MongoDB']['db_name'],
  'host': config['MongoDB']['host'],
  'port': int(config['MongoDB']['port']),
  'username': config['MongoDB']['username'],
  'password': config['MongoDB']['password']}

app.config['SECRET_KEY'] = config['Default']['secret_key']

db = MongoEngine(app)

def register_blueprints(app):
    # Prevents circular imports
    from weighttracker.views.measurement_views import measurements
    app.register_blueprint(measurements)
    from weighttracker.views.inspiration_views import inspirations
    app.register_blueprint(inspirations)
    from weighttracker.views.foodjournal_views import foodjournals
    app.register_blueprint(foodjournals)
    from weighttracker.views.exercisejournal_views import exercisejournals
    app.register_blueprint(exercisejournals)

register_blueprints(app)

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')

def catch_all(path):
    return render_template('index.html')

if __name__ == '__main__':
  app.run()


text:
<?php declare(strict_types=1);

namespace Darvin\Utils\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Configuration injector
 */
class ConfigInjector
{
    /**
     * @var \Symfony\Component\DependencyInjection\ContainerInterface
     */
    private $container;

    /**
     * @param \Symfony\Component\DependencyInjection\ContainerInterface $container DI container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * @param array  $config Configuration
     * @param string $prefix Parameter name prefix
     */
    public function inject(array $config, string $prefix): void
    {
        foreach ($config as $name => $value) {
            $name = implode('.', [$prefix, $name]);

            $this->container->setParameter($name, $value);

            if (is_array($value) && $this->isAssociative($value)) {
                $this->inject($value, $name);
            }
        }
    }

    /**
     * @param array $array Array
     *
     * @return bool
     */
    private function isAssociative(array $array): bool
    {
        return array_values($array) !== $array;
    }
}


text:
import os
import sys
import glob
import lcm
import time
import math
import random

messageTypes = {}
messageTypeToModule = {}

def loadMessageTypes(typesDict, typesModule, verbose=False):

    originalSize = len(typesDict)
    for name, value in typesModule.__dict__.iteritems():
        if hasattr(value, '_get_packed_fingerprint'):
            typesDict[value._get_packed_fingerprint()] = value
            messageTypeToModule[value] = typesModule

    if verbose:
        print 'loaded %d lcm message types from: %s' % (len(typesDict) - originalSize, typesModule.__name__)

def findLCMModules(searchDir):

    initFiles = glob.glob(os.path.join(searchDir, '*/__init__.py'))
    for initFile in initFiles:
        if open(initFile, 'r').readline() == '"""LCM package __init__.py file\n':
            moduleDir = os.path.dirname(initFile)
            moduleName = os.path.basename(moduleDir)
            #print 'loading module:', moduleName
            if moduleName == 'bot_procman':
                continue

            sys.path.insert(0, os.path.dirname(moduleDir))
            module = __import__(moduleName)
            sys.path.pop(0)
            loadMessageTypes(messageTypes, module)

def findLCMModulesInSysPath():
    for searchDir in sys.path:
        findLCMModules(searchDir)

def getUtime():
    return int(time.time() * 1e6)

lcmCatalog = {}

def decodeMessage(messageBytes):
    cls = getMessageClass(messageBytes)
    return cls.decode(messageBytes) if cls is not None else None

def getMessageClass(messageBytes):
    return messageTypes.get(messageBytes[:8])

def getModuleNameForMessageType(msgType):
    return messageTypeToModule[msgType].__name__

def getMessageTypeFullName(msgType):
    return '%s.%s' % (getModuleNameForMessageType(msgType), msgType.__name__)

def getMessageFullName(msg):
    if msg is None:
        return '<decode failure>'
    return getMessageTypeFullName(type(msg))

def onLCMMessage(channel, messageBytes, checkExistingChannel=False):

    if not checkExistingChannel and channel in lcmCatalog:
        return

    msg = decodeMessage(messageBytes)

    if not msg:
        if channel not in lcmCatalog:
            print 'failed to decode message on channel:', channel

    else:
        if channel not in lcmCatalog:
            print 'discovered channel/msg:', channel, getMessageFullName(msg)
        else:
            previousType = type(lcmCatalog[channel])
            if previousType != type(msg):
                print 'detected message type change: %s  %s --> %s' % (channel, getMessageTypeFullName(previousType), getMessageFullName(msg))

    lcmCatalog[channel] = msg

def getArrayFieldInfo(value):

    if not len(value):
        return 'empty', None

    value = value[0]

    if isinstance(value, float):
        return 'float', None
    elif isinstance(value, int):
        return 'integer', None
    elif isinstance(value, (str, unicode)):
        return 'string', None
    elif isinstance(value, (list, tuple)):
        arrayType, messageType = getArrayFieldInfo(value)
        return 'array[%d] of ' % len(value) + arrayType, messageType
    elif type(value) in messageTypeToModule:
        return getMessageFullName(value), value
    else:
        return 'unknown', None

def printMessageFields(msg, indent=''):

    if not msg:
        return

    for slot in msg.__slots__:
        print '%s%s' % (indent, slot),
        value = getattr(msg, slot)

        if isinstance(value, float):
            print ': float'
        elif isinstance(value, int):
            print ': integer'
        elif isinstance(value, (str, unicode)):
            print ': string'
        elif isinstance(value, (list, tuple)):

            arrayType, messageValue = getArrayFieldInfo(value)
            print ': array[%d] of ' % len(value) + arrayType
            printMessageFields(messageValue, indent + '  ')

        elif type(value) in messageTypeToModule:
            print ':', getMessageFullName(value)
            printMessageFields(value, indent + '  ')
        else:
            print ':', type(value)

def printLCMCatalog():

    channels = sorted(lcmCatalog.keys())

    for channel in channels:
        msg = lcmCatalog[channel]

        print '-----------------------'
        print 'channel:', channel
        print 'message:', getMessageFullName(msg)
        printMessageFields(lcmCatalog[channel], indent='  ')

def printLogFileDescription(filename):

    log = lcm.EventLog(filename, 'r')

    print 'reading %s' % filename
    print 'log file size: %.2f MB' % (log.size()/(1024.0**2))

    for event in log:
        onLCMMessage(event.channel, event.data)

    log.close()

    printLCMCatalog()

def spyLCMTraffic():

    lc = lcm.LCM()
    lc.subscribe('.+', onLCMMessage)

    try:
        while True:
          lc.handle()
    except KeyboardInterrupt:
        pass

    print
    print
    printLCMCatalog()

def main():

    findLCMModulesInSysPath()

    if len(sys.argv) > 1:
        filename = sys.argv[1]
        printLogFileDescription(filename)
    else:
        spyLCMTraffic()

if __name__ == '__main__':
    main()


text:
<!DOCTYPE html>
{% load i18n geotrek_tags mapentity_tags static %}

{% settings_value "PRIMARY_COLOR" as primary_color %}

    {% block style %}

    {% endblock style %}

    {% block body %}

          {% block logo %}

          {% endblock logo %}

          {% block url %}

rando.geotrek.fr

{% trans "Powered by geotrek.fr" %}

          {% endblock %}

        {% if object.approved %}
          {% block trademark %}

          {% endblock %}
        {% endif %}

{{ object.name }}

            {% block main_title_h2 %}
              {{ object.districts.0.name }}{% if object.districts and object.city_departure %} - {% endif %}{{ object.city_departure }}
            {% endblock %}

          {% if object.picture_print %}

          {% else %}

          {% endif %}

        {% if object.picture_print.legend or object.picture_print.author %}
          <legend>
            {% trans "Attribution" %} :
            {{ object.picture_print.legend }}
            {% if object.picture_print.author %}({{ object.picture_print.author }}){% endif %}
          </legend>
        {% endif %}

          {% if object.description_teaser %}

              {{ object.description_teaser|safe }}

          {% endif %}

{% trans "Useful information" %}

            {% if object.type %}

                {% trans "Type" %}
                {{ object.type }}

            {% endif %}
            {% if object.dates_display %}

                {% trans "Date" %}
                {{ object.dates_display }}

            {% endif %}
            {% if object.meeting_point %}

                {% trans "Meeting point" %}
                {{ object.meeting_point }}

            {% endif %}
            {% if object.meeting_time %}

                {% trans "Meeting time" %}
                {{ object.meeting_time|time:"H \h i" }}

            {% endif %}
            {% if object.duration %}

                {% trans "Duration" %}
                {{ object.duration }}

            {% endif %}
            {% if object.target_audience %}

                {% trans "Target audience" %}
                {{ object.target_audience }}

            {% endif %}

              {% if object.themes.all %}

                  {% trans "Themes" %}
                  {% for theme in object.themes.all %}{{ theme.label }}{% endfor %}

              {% endif %}

      {% block description %}
        {% if object.description %}

{% trans "Description" %}

{{ object.description|safe }}

        {% endif %}
      {% endblock description %}

{% trans "Geographical location" %}

{% trans "All useful information" %}

      {% if object.practical_info %}

            {% trans "Practical info" %}

{{ object.practical_info | safe }}

      {% endif %}
      {% if object.contact or object.email or object.website %}

{% trans "Contact" %}

            {% if object.contact %}
{{ object.contact|safe }}
{% endif %}
            {% if object.email %}
{{ object.email }}
{% endif %}
            {% if object.website %}
{{ object.website }}
{% endif %}

      {% endif %}
      {% if object.speaker %}

{% trans "Speaker" %}

{{ object.speaker }}

      {% endif %}
      {% if object.participant_number %}

{% trans "Number of participants" %}

{{ object.participant_number }}

      {% endif %}
      {% if object.booking %}

{% trans "Booking" %}

{{ object.booking|safe }}

      {% endif %}
      {% block accessibility %}
        {% if object.accessibility %}

              {% trans "Accessibility" %}

{{ object.accessibility | safe }}

        {% endif %}
      {% endblock accessibility %}
      {% block source %}
          {% if object.source.all %}

{% trans "Source" %}

              {% for s in object.source.all %}

                    {% if s.pictogram %}{% endif %}

                      {{ s.name }}

                      {% if s.website %}{{ s.website }}{% endif %}

              {% endfor %}

          {% endif %}
      {% endblock source %}
    {% endblock body %}
    {% block footer %}

{% now 'SHORT_DATE_FORMAT' %} • {{ object.name }} •

    {% endblock footer %}


text:
<?php

require_once('pinjector/Kernel.php');
require_once('pinjector/RegistryCallback.php');
require_once('DefaultRequestHandler.php');

/**
 *
 * @author Tobias Sarnowski
 */
class DefaultRequestCallback implements RegistryCallback {

    /**
     * @var string
     */
    private $requestUri;

    /**
     * @var Kernel
     */
    private $kernel;

    /**
     * @param string $requestUri
     * @param Kernel $kernel
     * @return void
     */
    function __construct($requestUri, Kernel $kernel) {
        $this->requestUri = $requestUri;
        $this->kernel = $kernel;
    }

    /**
     * @param DefaultRequestHandler $handler
     * @return bool
     */
    public function process($handler) {
        if (preg_match($handler->getRegexMatcher(), $this->requestUri, $matches)) {
            // get the handler instance
            $handlerInstance = $this->kernel->getInstance(
                $handler->getClassName(),
                $handler->getAnnotation()
            );

            // call it!
            $handlerInstance->handleRequest($matches);
            return false;
        }
        return true;
    }
}


text:
package core

import io.apibuilder.spec.v0.models.Service
import io.apibuilder.spec.v0.models.json._
import play.api.libs.json.Json
import java.net.URI

case class FileServiceFetcher() extends ServiceFetcher {

  override def fetch(uri: String): Service = {
    val contents = scala.io.Source.fromURI(new URI(uri)).getLines.mkString
    Json.parse(contents).as[Service]
  }

}


text:
package org.apache.commons.compress.archivers;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;

/**
 * Creates Archive {@link ArchiveInputStream}s and {@link ArchiveOutputStream}s.
 *
 * @since 1.13
 */
public interface ArchiveStreamProvider {

    /**
     * Creates an archive input stream from an archiver name and an input
     * stream.
     *
     * @param name
     *            the archive name, i.e.
     *            {@value org.apache.commons.compress.archivers.ArchiveStreamFactory#AR},
     *            {@value org.apache.commons.compress.archivers.ArchiveStreamFactory#ARJ},
     *            {@value org.apache.commons.compress.archivers.ArchiveStreamFactory#ZIP},
     *            {@value org.apache.commons.compress.archivers.ArchiveStreamFactory#TAR},
     *            {@value org.apache.commons.compress.archivers.ArchiveStreamFactory#JAR},
     *            {@value org.apache.commons.compress.archivers.ArchiveStreamFactory#CPIO},
     *            {@value org.apache.commons.compress.archivers.ArchiveStreamFactory#DUMP}
     *            or
     *            {@value org.apache.commons.compress.archivers.ArchiveStreamFactory#SEVEN_Z}
     * @param in
     *            the input stream
     * @param encoding
     *            encoding name or null for the default
     * @return the archive input stream
     * @throws ArchiveException
     *             if the archiver name is not known
     * @throws StreamingNotSupportedException
     *             if the format cannot be read from a stream
     * @throws IllegalArgumentException
     *             if the archiver name or stream is null
     */
    ArchiveInputStream createArchiveInputStream(final String name, final InputStream in, final String encoding)
            throws ArchiveException;

    /**
     * Creates an archive output stream from an archiver name and an output
     * stream.
     *
     * @param name
     *            the archive name, i.e.
     *            {@value org.apache.commons.compress.archivers.ArchiveStreamFactory#AR},
     *            {@value org.apache.commons.compress.archivers.ArchiveStreamFactory#ZIP},
     *            {@value org.apache.commons.compress.archivers.ArchiveStreamFactory#TAR},
     *            {@value org.apache.commons.compress.archivers.ArchiveStreamFactory#JAR}
     *            or
     *            {@value org.apache.commons.compress.archivers.ArchiveStreamFactory#CPIO}
     * @param out
     *            the output stream
     * @param encoding
     *            encoding name or null for the default
     * @return the archive output stream
     * @throws ArchiveException
     *             if the archiver name is not known
     * @throws StreamingNotSupportedException
     *             if the format cannot be written to a stream
     * @throws IllegalArgumentException
     *             if the archiver name or stream is null
     */
    ArchiveOutputStream createArchiveOutputStream(final String name, final OutputStream out, final String encoding)
            throws ArchiveException;

    /**
     * Gets all the input stream archive names for this provider
     *
     * @return all the input archive names for this provider
     */
    Set<String> getInputStreamArchiveNames();

    /**
     * Gets all the output stream archive names for this provider
     *
     * @return all the output archive names for this provider
     */
    Set<String> getOutputStreamArchiveNames();

}


text:
package org.ojalgo.type.function;

import java.util.concurrent.BlockingQueue;
import java.util.function.Function;
import java.util.function.Supplier;

final class SequencedSupplier<S, T> implements AutoSupplier<T> {

    private Supplier<T> myCurrent;
    private final Function<S, ? extends Supplier<T>> myFactory;
    private final BlockingQueue<S> mySources;

    SequencedSupplier(final BlockingQueue<S> sources, final Function<S, ? extends Supplier<T>> factory) {

        super();

        mySources = sources;
        myFactory = factory;
        this.nextSupplier();
    }

    @Override
    public void close() throws Exception {
        if ((myCurrent != null) && (myCurrent instanceof AutoCloseable)) {
            ((AutoCloseable) myCurrent).close();
        }
    }

    public T read() {

        if (myCurrent == null) {
            return null;
        }

        T retVal = myCurrent.get();

        if (retVal == null) {

            if (myCurrent instanceof AutoCloseable) {
                try {
                    ((AutoCloseable) myCurrent).close();
                } catch (Exception cause) {
                    throw new RuntimeException(cause);
                }
            }

            this.nextSupplier();

            if (myCurrent != null) {
                retVal = myCurrent.get();
            }
        }

        return retVal;
    }

    private void nextSupplier() {
        S next = mySources.poll();
        myCurrent = next != null ? myFactory.apply(next) : null;
    }

}


text:
<?php

// autoload_psr4.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'CodeRider\\NewSiteCms\\' => array($baseDir . '/cms/src'),
    'CodeRider\\' => array($baseDir . '/src'),
);


text:
namespace ArgentPonyWarcraftClient.Integration.Tests.GameDataApi;

public class MountApiTests
{
    [ResilientFact]
    public async Task GetMountsIndexAsync_Gets_MountsIndex()
    {
        IMountApi warcraftClient = ClientFactory.BuildClient();

        RequestResult<MountsIndex> result = await warcraftClient.GetMountsIndexAsync("static-us");

        await result.Should().BeSuccessfulRequest()
            .BeEquivalentToBlizzardResponseAsync("https://us.api.blizzard.com/data/wow/mount/index?namespace=static-us&locale=en_US");
    }

    [ResilientFact]
    public async Task GetMountAsync_Gets_Mount()
    {
        IMountApi warcraftClient = ClientFactory.BuildClient();

        RequestResult<Mount> result = await warcraftClient.GetMountAsync(6, "static-us");

        await result.Should().BeSuccessfulRequest()
            .BeEquivalentToBlizzardResponseAsync("https://us.api.blizzard.com/data/wow/mount/6?namespace=static-us&locale=en_US");
    }
}


text:
package by.hut.flat.calendar.core.DBAdapter.tasks;

import android.content.Context;
import by.hut.flat.calendar.core.DBAdapter.DBAdapter;
import by.hut.flat.calendar.core.DBAdapter.tables.Cleanings;
import by.hut.flat.calendar.core.DBAdapter.tables.Interval;
import by.hut.flat.calendar.dialog.Dialog;
import by.hut.flat.calendar.flat.FlatActivity;
import by.hut.flat.calendar.internal.BroadcastSender;
import by.hut.flat.calendar.internal.Task;
import by.hut.flat.calendar.sausage.SausageActivity;
import by.hut.flat.calendar.utils.Date;

public class Book extends Task{
	private static final int state = 3;	//book = 3

	private DBAdapter db;
	private Interval dbInterval;
	private Cleanings dbCleanings;
	private Context context;
	private int FlatID;
	private int MaidenID;
	private Date firstDate;
	private Date lastDate;

	public Book (Context context, int FlatID, Date firstDate, Date lastDate,int MaidenID) {
		super(context);
		this.context = context;
		this.FlatID = FlatID;
		this.firstDate = firstDate;
		this.lastDate = lastDate;
		this.MaidenID = MaidenID;
	}

	@Override
	protected Boolean doInBackground(Void... arg0) {
		db = new DBAdapter(context);
		db.open();
		dbInterval = new Interval(db);
		dbCleanings = new Cleanings(db);
		long IntervalID = dbInterval.addInterval(FlatID, state, firstDate, lastDate);
		if (MaidenID > 0)dbCleanings.addCleaning((int)IntervalID, FlatID, MaidenID, lastDate);

		db.close();
		BroadcastSender.send(context, FlatActivity.ACTIVITY_TAG,
				new String[]{Dialog.ACTION_DO,Dialog.PARAM_FLAT_ID,Dialog.PARAM_FIRSTDATE,Dialog.PARAM_LASTDATE},
				new String[]{"refresh_flat",""+FlatID,firstDate.toString(),lastDate.toString()});
		BroadcastSender.send(context, SausageActivity.ACTIVITY_TAG,
				new String[]{Dialog.ACTION_DO,Dialog.PARAM_FLAT_ID,Dialog.PARAM_FIRSTDATE,Dialog.PARAM_LASTDATE},
				new String[]{"refresh_flat",""+FlatID,firstDate.toString(),lastDate.toString()});

		return true;
	}
}


text:
[![Codacy Badge](https://api.codacy.com/project/badge/f9670514f9184033a3be6d39cb1457e3)](https://www.codacy.com/app/brpaz/termarks)

The bookmarks manager for your terminal.

![Screenshot](http://i.imgur.com/xmgxNxz.png)

As a Linux user / developer you probably have some commands you use everyday. some of them are easy to remember but others might very complex (like ```sudo docker run -d -P training/webapp python app.py```).

Wouldn´t be nice if you could have these commands bookmarked in your terminal so you can access them easily?.

With Termarks, you can.

Termarks, allows to save your favorite commands, and search them quickly without leaving the terminal. No more searching over and over again in documentation sites to find that special command.

## Installation

This tool is built as a rubygem, so you need to have ruby installed in your system. I recommend using ruby 2.0.0 or later but might work in earlier versions.

Then, just run:

```ruby
gem install 'termarks'
```

Termarks should now be installed on your system.

## Usage

Just run ```termarks``` in your terminal. By default, it will display all your bookmarks. If you dont have any, it will prompt you for create one.

```bash
termarks add # adds a new bookmark
```

```bash
termarks list # lists all your bookmarks
```

```bash
termarks delete # deletes an existing bookmark
```

For searching your bookmarks list you can use system commands like "grep".

```bash
termarks | grep "mycommand"
```

Termarks stores the bookmarks in .termarks.yml file, in your $HOME directory.

## License

This package is licensed with MIT License.

## Contributing

1. Fork it ( https://github.com/brpaz/termarks/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
package core.framework.mongo.impl;

import core.framework.api.validate.NotNull;
import core.framework.mongo.Collection;
import core.framework.mongo.Field;
import core.framework.mongo.Id;
import org.bson.types.ObjectId;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Map;

/**
 * @author neo
 */
@Collection(name = "test_entity")
public class TestEntity {
    public static final String INT_FIELD = "int_field";

    @Id
    public ObjectId id;

    @NotNull
    @Field(name = INT_FIELD)
    public Integer intField;

    @Field(name = "double_field")
    public Double doubleField;

    @Field(name = "big_decimal_field")
    public BigDecimal bigDecimalField;

    @Field(name = "long_field")
    public Long longField;

    @Field(name = "boolean_field")
    public Boolean booleanField;

    @Field(name = "date_time_field")
    public LocalDateTime dateTimeField;

    @Field(name = "zoned_date_time_field")
    public ZonedDateTime zonedDateTimeField;

    @Field(name = "date_field")
    public LocalDate dateField;

    @Field(name = "string_field")
    public String stringField;

    @Field(name = "list_field")
    public List<String> listField;

    @Field(name = "map_field")
    public Map<String, String> mapField;

    @Field(name = "child")
    public TestChildEntity child;

    @Field(name = "children")
    public List<TestChildEntity> children;

    @Field(name = "children_map")
    public Map<String, TestChildEntity> childrenMap;

    @Field(name = "null_child")
    public TestChildEntity nullChild;

    @Field(name = "enum_map_field")
    public Map<TestEnum, String> enumMapField;

    @Field(name = "map_list_field")
    public Map<String, List<String>> mapListField;
}


text:
import chainer
from chainer import backend
from chainer.backends import cuda
from chainer import function_node
from chainer.utils import type_check
import chainerx

class Copy(function_node.FunctionNode):

    """Copies the input variable onto the specified device."""

    def __init__(self, in_device, out_device):
        self._in_device = in_device
        self.out_device = out_device

    def check_type_forward(self, in_types):
        type_check._argname(in_types, ('x',))

    def forward(self, inputs):
        x, = inputs
        return self.out_device.send(x),

    def forward_chainerx(self, inputs):
        x, = inputs
        return x.to_device(self.out_device.device),

    def backward(self, indexes, grad_outputs):
        f = Copy(self.out_device, self._in_device)
        return f.apply(grad_outputs)

# TODO(niboshi): Link from `dst` to an appropriate device specifier docs.
def copy(x, dst):
    """Copies the input variable onto the specified device.

    If the input ``x`` already resides on the device specified by ``dst``, no
    copy will actually take place and the returned variable will hold a view
    of the input. In other cases, the input will be copied to ``dst``.
    When ``dst == -1``, the array is copied to the host memory.
    This function supports copies from host to host, from host to device,
    from device to device and from device to host.

    Args:
        x (:class:`~chainer.Variable` or :ref:`ndarray`):
            Variable to be copied.
        dst: Target device specifier.

    Returns:
        ~chainer.Variable: Output variable.

    .. admonition:: Example

        >>> import chainer.backends.cuda as cuda
        >>> x_arr = np.random.uniform(-1, 1, (5, 10))
        >>> x = chainer.Variable(x_arr)
        >>> x.device
        <CpuDevice (numpy)>
        >>> y = F.copy(x, '@cupy:0') # from CPU (NumPy) to GPU 0 (CuPy)
        >>> y.device
        <GpuDevice (cupy):0>

    .. note::
        Copies between non-ChainerX devices and ChainerX devices are not
        supported.

    """
    # For backward compatibility
    if dst is cuda.DummyDevice:
        dst = chainer.get_device('@numpy')

    in_device = backend.get_device_from_array(
        x.array if isinstance(x, chainer.Variable) else x)
    out_device = chainer.get_device(dst)

    is_chainerx = in_device.xp is chainerx
    if is_chainerx != (out_device.xp is chainerx):
        raise RuntimeError(
            'F.copy does not support copies between non-ChainerX devices and '
            'ChainerX devices.\n'
            'From: {}\n'
            'To: {}'.format(in_device, out_device))

    y, = Copy(in_device, out_device).apply((x,))
    return y


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.network;

import java.util.List;

/**
 *
 */
public interface PhysicalNetwork {

    public enum State {
        Disabled,
        Enabled;
    }

    public enum IsolationMethod {
        VLAN,
        L3,
        GRE,
        STT;
    }

    public enum BroadcastDomainRange {
        POD,
        ZONE;
    }

    long getId();

    BroadcastDomainRange getBroadcastDomainRange();

    // TrafficType getTrafficType();

    long getDataCenterId();

    State getState();

    List<String> getTags();

    List<String> getIsolationMethods();

    Long getDomainId();

    String getVnet();

    String getSpeed();

    String getUuid();

    String getName();

}


text:
#ifndef DEBUG_H_
#define DEBUG_H_
#include "states.h"
void printState(DistributorState state);
char * alias byte_to_binary(int x);

#endif /* DEBUG_H_ */


text:
import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';

import { Link } from 'react-router';

import { createPureComponent } from 'utils/createPureComponent';

export default createPureComponent({

  displayName: 'App',

  renderLink() {
    const isEditing = this.props.location.pathname === '/editor';
    const to = isEditing ? '/' : '/editor';
    const text = isEditing ? 'Play this level' : 'Edit this level';
    return (<Link to={to}>{text}</Link>);
  },

  render() {
    return (
      <div className="app">
        {this.props.children}
      </div>
    );
  }

});


text:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://pythonforengineers.com/secret")

message= driver.find_element_by_tag_name('p')

print "Before pressing the button: "
print message.text
print "\n"
button = driver.find_elements_by_xpath("//*[contains(text(), 'Super')]")

button[0].click()

print "After clicking the button: "
message= driver.find_element_by_tag_name('p')

print message.text

driver.close()


text:
/**
 * @file
 * @brief
 *  This file defines the top-level icmp6 functions for the OpenThread library.
 */

#ifndef OPENTHREAD_ICMP6_H_
#define OPENTHREAD_ICMP6_H_

#include <openthread/ip6.h>
#include <openthread/message.h>

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @addtogroup api-icmp6
 *
 * @brief
 *   This module includes functions that control ICMPv6 communication.
 *
 * @{
 *
 */

/**
 * ICMPv6 Message Types
 *
 */
typedef enum otIcmp6Type
{
    OT_ICMP6_TYPE_DST_UNREACH  = 1,   ///< Destination Unreachable
    OT_ICMP6_TYPE_ECHO_REQUEST = 128, ///< Echo Request
    OT_ICMP6_TYPE_ECHO_REPLY   = 129, ///< Echo Reply
} otIcmp6Type;

/**
 * ICMPv6 Message Codes
 *
 */
typedef enum otIcmp6Code
{
    OT_ICMP6_CODE_DST_UNREACH_NO_ROUTE = 0, ///< Destination Unreachable No Route
} otIcmp6Code;

#define OT_ICMP6_HEADER_DATA_SIZE 4 ///< Size of an message specific data of ICMPv6 Header.

/**
 * @struct otIcmp6Header
 *
 * This structure represents an ICMPv6 header.
 *
 */
OT_TOOL_PACKED_BEGIN
struct otIcmp6Header
{
    uint8_t  mType;     ///< Type
    uint8_t  mCode;     ///< Code
    uint16_t mChecksum; ///< Checksum
    union OT_TOOL_PACKED_FIELD
    {
        uint8_t  m8[OT_ICMP6_HEADER_DATA_SIZE / sizeof(uint8_t)];
        uint16_t m16[OT_ICMP6_HEADER_DATA_SIZE / sizeof(uint16_t)];
        uint32_t m32[OT_ICMP6_HEADER_DATA_SIZE / sizeof(uint32_t)];
    } mData; ///< Message-specific data
} OT_TOOL_PACKED_END;

/**
 * This type represents an ICMPv6 header.
 *
 */
typedef struct otIcmp6Header otIcmp6Header;

/**
 * This callback allows OpenThread to inform the application of a received ICMPv6 message.
 *
 * @param[in]  aContext      A pointer to arbitrary context information.
 * @param[in]  aMessage      A pointer to the received message.
 * @param[in]  aMessageInfo  A pointer to message information associated with @p aMessage.
 * @param[in]  aIcmpHeader   A pointer to the received ICMPv6 header.
 *
 */
typedef void (*otIcmp6ReceiveCallback)(void *               aContext,
                                       otMessage *          aMessage,
                                       const otMessageInfo *aMessageInfo,
                                       const otIcmp6Header *aIcmpHeader);

/**
 * This structure implements ICMPv6 message handler.
 *
 */
typedef struct otIcmp6Handler
{
    otIcmp6ReceiveCallback mReceiveCallback; ///< The ICMPv6 received callback
    void *                 mContext;         ///< A pointer to arbitrary context information.
    struct otIcmp6Handler *mNext;            ///< A pointer to the next handler in the list.
} otIcmp6Handler;

/**
 * ICMPv6 Echo Reply Modes
 *
 */
typedef enum otIcmp6EchoMode
{
    OT_ICMP6_ECHO_HANDLER_DISABLED       = 0, ///< ICMPv6 Echo processing disabled
    OT_ICMP6_ECHO_HANDLER_UNICAST_ONLY   = 1, ///< ICMPv6 Echo processing enabled only for unicast requests only
    OT_ICMP6_ECHO_HANDLER_MULTICAST_ONLY = 2, ///< ICMPv6 Echo processing enabled only for multicast requests only
    OT_ICMP6_ECHO_HANDLER_ALL            = 3, ///< ICMPv6 Echo processing enabled for unicast and multicast requests
} otIcmp6EchoMode;

/**
 * This function indicates whether or not ICMPv6 Echo processing is enabled.
 *
 * @param[in]  aInstance A pointer to an OpenThread instance.
 *
 * @retval OT_ICMP6_ECHO_HANDLER_DISABLED        ICMPv6 Echo processing is disabled.
 * @retval OT_ICMP6_ECHO_HANDLER_UNICAST_ONLY    ICMPv6 Echo processing enabled for unicast requests only
 * @retval OT_ICMP6_ECHO_HANDLER_MULTICAST_ONLY  ICMPv6 Echo processing enabled for multicast requests only
 * @retval OT_ICMP6_ECHO_HANDLER_ALL             ICMPv6 Echo processing enabled for unicast and multicast requests
 *
 */
otIcmp6EchoMode otIcmp6GetEchoMode(otInstance *aInstance);

/**
 * This function sets whether or not ICMPv6 Echo processing is enabled.
 *
 * @param[in]  aInstance A pointer to an OpenThread instance.
 * @param[in]  aMode     The ICMPv6 Echo processing mode.
 *
 */
void otIcmp6SetEchoMode(otInstance *aInstance, otIcmp6EchoMode aMode);

/**
 * This function registers a handler to provide received ICMPv6 messages.
 *
 * @note A handler structure @p aHandler has to be stored in persistent (static) memory.
 *       OpenThread does not make a copy of handler structure.
 *
 * @param[in]  aInstance A pointer to an OpenThread instance.
 * @param[in]  aHandler  A pointer to a handler containing callback that is called when
 *                       an ICMPv6 message is received.
 *
 */
otError otIcmp6RegisterHandler(otInstance *aInstance, otIcmp6Handler *aHandler);

/**
 * This function sends an ICMPv6 Echo Request via the Thread interface.
 *
 * @param[in]  aInstance     A pointer to an OpenThread instance.
 * @param[in]  aMessage      A pointer to the message buffer containing the ICMPv6 payload.
 * @param[in]  aMessageInfo  A reference to message information associated with @p aMessage.
 * @param[in]  aIdentifier   An identifier to aid in matching Echo Replies to this Echo Request.
 *                           May be zero.
 *
 */
otError otIcmp6SendEchoRequest(otInstance *         aInstance,
                               otMessage *          aMessage,
                               const otMessageInfo *aMessageInfo,
                               uint16_t             aIdentifier);

/**
 * @}
 *
 */

#ifdef __cplusplus
} // extern "C"
#endif

#endif // OPENTHREAD_ICMP6_H_


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
LexicographicTournamentSelection
</TITLE>

<META NAME="keywords" CONTENT="ec.parsimony.LexicographicTournamentSelection class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

ec.parsimony

Class LexicographicTournamentSelection

java.lang.Object
  ec.BreedingSource
      ec.SelectionMethod
          ec.parsimony.LexicographicTournamentSelection

All Implemented Interfaces:
Prototype, Setup, SteadyStateBSourceForm, RandomChoiceChooser, java.io.Serializable, java.lang.Cloneable

public class LexicographicTournamentSelection
extends SelectionMethod
implements SteadyStateBSourceForm

Does a simple tournament selection, limited to the subpopulation it's
 working in at the time.

Tournament selection works like this: first, size individuals
 are chosen at random from the population.  Then of those individuals,
 the one with the best fitness is selected.  If two individuals have the
 same fitness, the one with smaller size is prefered.

 The default tournament size is 7.

Typical Number of Individuals Produced Per <tt>produce(...)</tt> call

 Always 1.

Parameters

base.<tt>size</tt>

 int >= 1
 (the tournament size)

base.<tt>pick-worst</tt>

  bool = <tt>true</tt> or <tt>false</tt> (default)
 (should we pick the worst individual in the tournament instead of the best?)

Default Base

 select.lexicographic-tournament

See Also:
Serialized Form

Field Summary

static int
DEFAULT_SIZE

          Default size

static java.lang.String
P_PICKWORST

static java.lang.String
P_SIZE

          size parameter

static java.lang.String
P_TOURNAMENT

          default base

 boolean
pickWorst

          Do we pick the worst instead of the best?

 int
size

          Size of the tournament

Fields inherited from class ec.SelectionMethod

INDS_PRODUCED

Fields inherited from class ec.BreedingSource

CHECKBOUNDARY, DEFAULT_PRODUCED, NO_PROBABILITY, P_PROB, probability, UNUSED

Constructor Summary

LexicographicTournamentSelection()

Method Summary

 Parameter
defaultBase()

          Returns the default base for this prototype.

 void
individualReplaced(SteadyStateEvolutionState state,
                   int subpopulation,
                   int thread,
                   int individual)

          Called whenever an individual has been replaced by another
        in the population.

 int
produce(int subpopulation,
        EvolutionState state,
        int thread)

          An alternative form of "produce" special to Selection Methods;
        selects an individual from the given subpopulation and
        returns its position in that subpopulation.

 void
setup(EvolutionState state,
      Parameter base)

          Sets up the BreedingPipeline.

 void
sourcesAreProperForm(SteadyStateEvolutionState state)

          Issue an error (not a fatal -- we guarantee that callers
        of this method will also call exitIfErrors) if any
        of your sources, or their sources, etc., are not
        of SteadyStateBSourceForm.

Methods inherited from class ec.SelectionMethod

finishProducing, preparePipeline, prepareToProduce, produce, produces, typicalIndsProduced

Methods inherited from class ec.BreedingSource

clone, getProbability, pickRandom, setProbability, setupProbabilities

Methods inherited from class java.lang.Object

equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

P_TOURNAMENT

public static final java.lang.String P_TOURNAMENT

default base

See Also:
Constant Field Values

P_PICKWORST

public static final java.lang.String P_PICKWORST

See Also:
Constant Field Values

P_SIZE

public static final java.lang.String P_SIZE

size parameter

See Also:
Constant Field Values

DEFAULT_SIZE

public static final int DEFAULT_SIZE

Default size

See Also:
Constant Field Values

size

public int size

Size of the tournament

pickWorst

public boolean pickWorst

Do we pick the worst instead of the best?

Constructor Detail

LexicographicTournamentSelection

public LexicographicTournamentSelection()

Method Detail

defaultBase

public Parameter defaultBase()

Description copied from interface: Prototype

Returns the default base for this prototype.
        This should generally be implemented by building off of the static base()
        method on the DefaultsForm object for the prototype's package. This should
        be callable during setup(...).

Specified by:
defaultBase in interface Prototype

setup

public void setup(EvolutionState state,
                  Parameter base)

Description copied from class: BreedingSource

Sets up the BreedingPipeline.  You can use state.output.error here
        because the top-level caller promises to call exitIfErrors() after calling
        setup.  Note that probability might get modified again by
        an external source if it doesn't normalize right.

The most common modification is to normalize it with some other
        set of probabilities, then set all of them up in increasing summation;
        this allows the use of the fast static BreedingSource-picking utility
        method, BreedingSource.pickRandom(...).  In order to use this method,
        for example, if four
        breeding source probabilities are {0.3, 0.2, 0.1, 0.4}, then
        they should get normalized and summed by the outside owners
        as: {0.3, 0.5, 0.6, 1.0}.

Specified by:
setup in interface Prototype
Specified by:
setup in interface Setup
Overrides:
setup in class BreedingSource

See Also:
Prototype.setup(EvolutionState,Parameter)

produce

public int produce(int subpopulation,
                   EvolutionState state,
                   int thread)

Description copied from class: SelectionMethod

An alternative form of "produce" special to Selection Methods;
        selects an individual from the given subpopulation and
        returns its position in that subpopulation.

Specified by:
produce in class SelectionMethod

individualReplaced

public void individualReplaced(SteadyStateEvolutionState state,
                               int subpopulation,
                               int thread,
                               int individual)

Description copied from interface: SteadyStateBSourceForm

Called whenever an individual has been replaced by another
        in the population.

Specified by:
individualReplaced in interface SteadyStateBSourceForm

sourcesAreProperForm

public void sourcesAreProperForm(SteadyStateEvolutionState state)

Description copied from interface: SteadyStateBSourceForm

Issue an error (not a fatal -- we guarantee that callers
        of this method will also call exitIfErrors) if any
        of your sources, or their sources, etc., are not
        of SteadyStateBSourceForm.

Specified by:
sourcesAreProperForm in interface SteadyStateBSourceForm

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD