text:
"use strict";
/* jshint undef: true, unused: true */
/* global Turu, describe, it, expect, beforeEach */

describe('Turu: .middle', function () {

  beforeEach(Turu.reset);

  it('runs the code', function () {
    var v = 0;
    Turu.middle(function (data) {
      if (_.isMatch(data, {action: 'family'}))
        v = data.value;
    });
    Turu.run({action: 'family', value: 'Simpsons'});
    expect(v).toEqual('Simpsons');
  });

}); // === describe Turu: .middle

describe('Turu: .bottom:', function () {

  beforeEach(Turu.reset);

  it('runs the code after middle functions', function () {
    var v = [];

    Turu.bottom(function (data) {
      if (_.isMatch(data, {action: 'movie'}))
        v.push(data.value + ' last');
    });

    Turu.middle(function (data) {
      if (_.isMatch(data, {action: 'movie'}))
        v.push(data.value + ' middle');
    });

    Turu.run({action: 'movie', value: 'Simpsons'});
    expect(v).toEqual(['Simpsons middle', 'Simpsons last']);
  });

}); // === describe Turu: .bottom =================


text:
usage(){
echo "
BBWrap v34.x
Last modified April 21, 2015

Description:  Wrapper for BBMap to allow multiple input and output files for the same reference.

To index:                 bbwrap.sh ref=<reference fasta>
To map:                   bbwrap.sh in=<file,file,...> out=<file,file,...>
To map without an index:  bbwrap.sh ref=<reference fasta> in=<file,file,...> out=<file,file,...> nodisk
To map pairs and singletons and output them into the same file:
bbwrap.sh in1=read1.fq,singleton.fq in2=read2.fq,null out=mapped.sam append

BBWrap will not work with stdin and stdout, or histogram output.

Other Parameters:

in=<file,file>    Input sequences to map.
mapper=bbmap      Select mapper.  May be BBMap, BBMapPacBio,
                  or BBMapPacBioSkimmer.
append=f          Append to files rather than overwriting them.
                  If append is enabled, and there is exactly one output file,
                  all output will be written to that file.

***** All BBMap parameters can be used; see bbmap.sh for more details. *****
"
}

pushd . > /dev/null
DIR="${BASH_SOURCE[0]}"
while [ -h "$DIR" ]; do
  cd "$(dirname "$DIR")"
  DIR="$(readlink "$(basename "$DIR")")"
done
cd "$(dirname "$DIR")"
DIR="$(pwd)/"
popd > /dev/null

#DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/"
CP="$DIR""current/"
NATIVELIBDIR="$DIR""jni/"

z="-Xmx1g"
z2="-Xms1g"
EA="-ea"
set=0

if [ -z "$1" ] || [[ $1 == -h ]] || [[ $1 == --help ]]; then
	usage
	exit
fi

calcXmx () {
	source "$DIR""/calcmem.sh"
	parseXmx "$@"
	if [[ $set == 1 ]]; then
		return
	fi
	freeRam 3200m 84
	z="-Xmx${RAM}m"
	z2="-Xms${RAM}m"
}
calcXmx "$@"

bbwrap() {
	#module unload oracle-jdk
	#module unload samtools
	#module load oracle-jdk/1.7_64bit
	#module load pigz
	#module load samtools
	local CMD="java -Djava.library.path=$NATIVELIBDIR $EA $z -cp $CP align2.BBWrap build=1 overwrite=true fastareadlen=500 $@"
	echo $CMD >&2
	eval $CMD
}

bbwrap "$@"

redpajama_set_name: RedPajamaGithub


text:
using BenchmarkDotNet.Attributes;
using BepuPhysics;
using BepuPhysics.Collidables;
using BepuPhysics.CollisionDetection;
using BepuPhysics.Constraints;
using BepuUtilities;
using BepuUtilities.Memory;
using System.Diagnostics;
using System.Numerics;
using System.Runtime.CompilerServices;

namespace DemoBenchmarks;

/// <summary>
/// Evaluates performance of a simulation similar to the first timesteps of the RagdollTubeDemo.
/// </summary>
public class RagdollTubeBenchmark
{
    public struct SubgroupCollisionFilter
    {
        public ushort SubgroupMembership;
        public ushort CollidableSubgroups;
        public int GroupId;
        public SubgroupCollisionFilter(int groupId)
        {
            GroupId = groupId;
            SubgroupMembership = ushort.MaxValue;
            CollidableSubgroups = ushort.MaxValue;
        }
        public SubgroupCollisionFilter(int groupId, int subgroupId)
        {
            GroupId = groupId;
            Debug.Assert(subgroupId >= 0 && subgroupId < 16, "The subgroup field is a ushort; it can only hold 16 distinct subgroups.");
            SubgroupMembership = (ushort)(1 << subgroupId);
            CollidableSubgroups = ushort.MaxValue;
        }
        public void DisableCollision(int subgroupId)
        {
            Debug.Assert(subgroupId >= 0 && subgroupId < 16, "The subgroup field is a ushort; it can only hold 16 distinct subgroups.");
            CollidableSubgroups ^= (ushort)(1 << subgroupId);
        }
        public static void DisableCollision(ref SubgroupCollisionFilter filterA, ref SubgroupCollisionFilter filterB)
        {
            filterA.CollidableSubgroups &= (ushort)~filterB.SubgroupMembership;
            filterB.CollidableSubgroups &= (ushort)~filterA.SubgroupMembership;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool AllowCollision(in SubgroupCollisionFilter a, in SubgroupCollisionFilter b)
        {
            return a.GroupId != b.GroupId || (a.CollidableSubgroups & b.SubgroupMembership) > 0;
        }

    }

    struct SubgroupFilteredCallbacks : INarrowPhaseCallbacks
    {
        public CollidableProperty<SubgroupCollisionFilter> CollisionFilters;
        public PairMaterialProperties Material;
        public SubgroupFilteredCallbacks(CollidableProperty<SubgroupCollisionFilter> filters)
        {
            CollisionFilters = filters;
            Material = new PairMaterialProperties(1, 2, new SpringSettings(30, 1));
        }
        public SubgroupFilteredCallbacks(CollidableProperty<SubgroupCollisionFilter> filters, PairMaterialProperties material)
        {
            CollisionFilters = filters;
            Material = material;
        }
        public void Initialize(Simulation simulation)
        {
            CollisionFilters.Initialize(simulation);
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool AllowContactGeneration(int workerIndex, CollidableReference a, CollidableReference b, ref float speculativeMargin)
        {
            if (b.Mobility != CollidableMobility.Static)
            {
                return SubgroupCollisionFilter.AllowCollision(CollisionFilters[a.BodyHandle], CollisionFilters[b.BodyHandle]);
            }
            return a.Mobility == CollidableMobility.Dynamic || b.Mobility == CollidableMobility.Dynamic;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool AllowContactGeneration(int workerIndex, CollidablePair pair, int childIndexA, int childIndexB)
        {
            return true;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public unsafe bool ConfigureContactManifold<TManifold>(int workerIndex, CollidablePair pair, ref TManifold manifold, out PairMaterialProperties pairMaterial) where TManifold : unmanaged, IContactManifold<TManifold>
        {
            pairMaterial = Material;
            return true;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public unsafe bool ConfigureContactManifold(int workerIndex, CollidablePair pair, int childIndexA, int childIndexB, ref ConvexContactManifold manifold)
        {
            return true;
        }
        public void Dispose()
        {
            CollisionFilters.Dispose();
        }
    }

    public struct DemoPoseIntegratorCallbacks : IPoseIntegratorCallbacks
    {
        public Vector3 Gravity;
        public float LinearDamping;
        public float AngularDamping;
        public readonly AngularIntegrationMode AngularIntegrationMode => AngularIntegrationMode.Nonconserving;
        public readonly bool AllowSubstepsForUnconstrainedBodies => false;
        public readonly bool IntegrateVelocityForKinematics => false;
        public void Initialize(Simulation simulation) { }
        public DemoPoseIntegratorCallbacks(Vector3 gravity, float linearDamping = .03f, float angularDamping = .03f) : this()
        {
            Gravity = gravity;
            LinearDamping = linearDamping;
            AngularDamping = angularDamping;
        }

        Vector3Wide gravityWideDt;
        Vector<float> linearDampingDt;
        Vector<float> angularDampingDt;

        public void PrepareForIntegration(float dt)
        {
            linearDampingDt = new Vector<float>(MathF.Pow(MathHelper.Clamp(1 - LinearDamping, 0, 1), dt));
            angularDampingDt = new Vector<float>(MathF.Pow(MathHelper.Clamp(1 - AngularDamping, 0, 1), dt));
            gravityWideDt = Vector3Wide.Broadcast(Gravity * dt);
        }
        public void IntegrateVelocity(Vector<int> bodyIndices, Vector3Wide position, QuaternionWide orientation, BodyInertiaWide localInertia, Vector<int> integrationMask, int workerIndex, Vector<float> dt, ref BodyVelocityWide velocity)
        {
            velocity.Linear = (velocity.Linear + gravityWideDt) * linearDampingDt;
            velocity.Angular = velocity.Angular * angularDampingDt;
        }
    }
    static BodyHandle AddBody<TShape>(TShape shape, float mass, in RigidPose pose, Simulation simulation) where TShape : unmanaged, IConvexShape
    {
        //Note that this always registers a new shape instance. You could be more clever/efficient and share shapes, but the goal here is to show the most basic option.
        //Also, the cost of registering different shapes isn't that high for tiny implicit shapes.
        var shapeIndex = simulation.Shapes.Add(shape);
        var description = BodyDescription.CreateDynamic(pose, shape.ComputeInertia(mass), shapeIndex, 0.01f);
        return simulation.Bodies.Add(description);
    }

    static RigidPose GetWorldPose(Vector3 localPosition, Quaternion localOrientation, RigidPose ragdollPose)
    {
        RigidPose worldPose;
        RigidPose.Transform(localPosition, ragdollPose, out worldPose.Position);
        QuaternionEx.ConcatenateWithoutOverlap(localOrientation, ragdollPose.Orientation, out worldPose.Orientation);
        return worldPose;
    }
    public static void GetCapsuleForLineSegment(Vector3 start, Vector3 end, float radius, out Capsule capsule, out Vector3 position, out Quaternion orientation)
    {
        position = 0.5f * (start + end);

        var offset = end - start;
        capsule.HalfLength = 0.5f * offset.Length();
        capsule.Radius = radius;
        //The capsule shape's length is along its local Y axis, so get the shortest rotation from Y to the current orientation.
        var cross = Vector3.Cross(offset / capsule.Length, new Vector3(0, 1, 0));
        var crossLength = cross.Length();
        orientation = crossLength > 1e-8f ? QuaternionEx.CreateFromAxisAngle(cross / crossLength, (float)Math.Asin(crossLength)) : Quaternion.Identity;
    }

    public static Quaternion CreateBasis(Vector3 z, Vector3 x)
    {
        //For ease of use, don't assume that x is perpendicular to z, nor that either input is normalized.
        Matrix3x3 basis;
        basis.Z = Vector3.Normalize(z);
        basis.Y = Vector3.Normalize(Vector3.Cross(basis.Z, x));
        basis.X = Vector3.Cross(basis.Y, basis.Z);
        QuaternionEx.CreateFromRotationMatrix(basis, out var toReturn);
        return toReturn;
    }

    static AngularMotor BuildAngularMotor()
    {
        //By default, these motors use nonzero softness (inverse damping) to damp the relative motion between ragdoll pieces.
        //If you set the damping to 0 and then set the maximum force to some finite value (75 works reasonably well), the ragdolls act more like action figures.
        //You could also replace the AngularMotors with AngularServos and provide actual relative orientation goals for physics-driven animation.
        return new AngularMotor { TargetVelocityLocalA = new Vector3(), Settings = new MotorSettings(float.MaxValue, 0.01f) };
    }

    static RagdollArmHandles AddArm(float sign, Vector3 localShoulder, RigidPose localChestPose, BodyHandle chestHandle, ref SubgroupCollisionFilter chestMask,
        int limbBaseBitIndex, int ragdollIndex, RigidPose ragdollPose, CollidableProperty<SubgroupCollisionFilter> filters, SpringSettings constraintSpringSettings, Simulation simulation)
    {
        RagdollArmHandles handles;
        var localElbow = localShoulder + new Vector3(sign * 0.45f, 0, 0);
        var localWrist = localElbow + new Vector3(sign * 0.45f, 0, 0);
        var handPosition = localWrist + new Vector3(sign * 0.1f, 0, 0);
        GetCapsuleForLineSegment(localShoulder, localElbow, 0.1f, out var upperArmShape, out var upperArmPosition, out var upperArmOrientation);
        handles.UpperArm = AddBody(upperArmShape, 5, GetWorldPose(upperArmPosition, upperArmOrientation, ragdollPose), simulation);
        GetCapsuleForLineSegment(localElbow, localWrist, 0.09f, out var lowerArmShape, out var lowerArmPosition, out var lowerArmOrientation);
        handles.LowerArm = AddBody(lowerArmShape, 5, GetWorldPose(lowerArmPosition, lowerArmOrientation, ragdollPose), simulation);
        handles.Hand = AddBody(new Box(0.2f, 0.1f, 0.2f), 2, GetWorldPose(handPosition, Quaternion.Identity, ragdollPose), simulation);

        //Create joints between limb pieces.
        //Chest-Upper Arm
        simulation.Solver.Add(chestHandle, handles.UpperArm, new BallSocket
        {
            LocalOffsetA = QuaternionEx.Transform(localShoulder - localChestPose.Position, QuaternionEx.Conjugate(localChestPose.Orientation)),
            LocalOffsetB = QuaternionEx.Transform(localShoulder - upperArmPosition, QuaternionEx.Conjugate(upperArmOrientation)),
            SpringSettings = constraintSpringSettings
        });
        simulation.Solver.Add(chestHandle, handles.UpperArm, new SwingLimit
        {
            AxisLocalA = QuaternionEx.Transform(Vector3.Normalize(new Vector3(sign, 0, 1)), QuaternionEx.Conjugate(localChestPose.Orientation)),
            AxisLocalB = QuaternionEx.Transform(new Vector3(sign, 0, 0), QuaternionEx.Conjugate(upperArmOrientation)),
            MaximumSwingAngle = MathHelper.Pi * 0.56f,
            SpringSettings = constraintSpringSettings
        });
        simulation.Solver.Add(chestHandle, handles.UpperArm, new TwistLimit
        {
            LocalBasisA = QuaternionEx.Concatenate(CreateBasis(new Vector3(1, 0, 0), new Vector3(0, 0, -1)), QuaternionEx.Conjugate(localChestPose.Orientation)),
            LocalBasisB = QuaternionEx.Concatenate(CreateBasis(new Vector3(1, 0, 0), new Vector3(0, 0, -1)), QuaternionEx.Conjugate(upperArmOrientation)),
            MinimumAngle = MathHelper.Pi * -0.55f,
            MaximumAngle = MathHelper.Pi * 0.55f,
            SpringSettings = constraintSpringSettings
        });
        simulation.Solver.Add(chestHandle, handles.UpperArm, BuildAngularMotor());

        //Upper Arm-Lower Arm
        simulation.Solver.Add(handles.UpperArm, handles.LowerArm, new SwivelHinge
        {
            LocalOffsetA = QuaternionEx.Transform(localElbow - upperArmPosition, QuaternionEx.Conjugate(upperArmOrientation)),
            LocalSwivelAxisA = new Vector3(1, 0, 0),
            LocalOffsetB = QuaternionEx.Transform(localElbow - lowerArmPosition, QuaternionEx.Conjugate(lowerArmOrientation)),
            LocalHingeAxisB = new Vector3(0, 1, 0),
            SpringSettings = constraintSpringSettings
        });
        simulation.Solver.Add(handles.UpperArm, handles.LowerArm, new SwingLimit
        {
            AxisLocalA = new Vector3(0, 1, 0),
            AxisLocalB = new Vector3(sign, 0, 0),
            MaximumSwingAngle = MathHelper.PiOver2,
            SpringSettings = constraintSpringSettings
        });
        simulation.Solver.Add(handles.UpperArm, handles.LowerArm, new TwistLimit
        {
            LocalBasisA = QuaternionEx.Concatenate(CreateBasis(new Vector3(1, 0, 0), new Vector3(0, 0, -1)), QuaternionEx.Conjugate(upperArmOrientation)),
            LocalBasisB = QuaternionEx.Concatenate(CreateBasis(new Vector3(1, 0, 0), new Vector3(0, 0, -1)), QuaternionEx.Conjugate(lowerArmOrientation)),
            MinimumAngle = MathHelper.Pi * -0.55f,
            MaximumAngle = MathHelper.Pi * 0.55f,
            SpringSettings = constraintSpringSettings
        });
        simulation.Solver.Add(handles.UpperArm, handles.LowerArm, BuildAngularMotor());

        //Lower Arm-Hand
        simulation.Solver.Add(handles.LowerArm, handles.Hand, new BallSocket
        {
            LocalOffsetA = QuaternionEx.Transform(localWrist - lowerArmPosition, QuaternionEx.Conjugate(lowerArmOrientation)),
            LocalOffsetB = localWrist - handPosition,
            SpringSettings = constraintSpringSettings
        });
        simulation.Solver.Add(handles.LowerArm, handles.Hand, new SwingLimit
        {
            AxisLocalA = QuaternionEx.Transform(new Vector3(sign, 0, 0), QuaternionEx.Conjugate(lowerArmOrientation)),
            AxisLocalB = new Vector3(sign, 0, 0),
            MaximumSwingAngle = MathHelper.PiOver2,
            SpringSettings = constraintSpringSettings
        });
        simulation.Solver.Add(handles.LowerArm, handles.Hand, new TwistServo
        {
            LocalBasisA = QuaternionEx.Concatenate(CreateBasis(new Vector3(1, 0, 0), new Vector3(0, 0, 1)), QuaternionEx.Conjugate(lowerArmOrientation)),
            LocalBasisB = CreateBasis(new Vector3(1, 0, 0), new Vector3(0, 0, 1)),
            TargetAngle = 0,
            SpringSettings = constraintSpringSettings,
            ServoSettings = new ServoSettings(float.MaxValue, 0, float.MaxValue)
        });
        simulation.Solver.Add(handles.LowerArm, handles.Hand, BuildAngularMotor());

        //Disable collisions between connected ragdoll pieces.
        var upperArmLocalIndex = limbBaseBitIndex;
        var lowerArmLocalIndex = limbBaseBitIndex + 1;
        var handLocalIndex = limbBaseBitIndex + 2;
        ref var upperArmFilter = ref filters.Allocate(handles.UpperArm);
        ref var lowerArmFilter = ref filters.Allocate(handles.LowerArm);
        ref var handFilter = ref filters.Allocate(handles.Hand);
        upperArmFilter = new SubgroupCollisionFilter(ragdollIndex, upperArmLocalIndex);
        lowerArmFilter = new SubgroupCollisionFilter(ragdollIndex, lowerArmLocalIndex);
        handFilter = new SubgroupCollisionFilter(ragdollIndex, handLocalIndex);
        SubgroupCollisionFilter.DisableCollision(ref chestMask, ref upperArmFilter);
        SubgroupCollisionFilter.DisableCollision(ref upperArmFilter, ref lowerArmFilter);
        SubgroupCollisionFilter.DisableCollision(ref lowerArmFilter, ref handFilter);

        return handles;
    }

    static RagdollLegHandles AddLeg(Vector3 localHip, RigidPose localHipsPose, BodyHandle hipsHandle, ref SubgroupCollisionFilter hipsFilter,
        int limbBaseBitIndex, int ragdollIndex, RigidPose ragdollPose, CollidableProperty<SubgroupCollisionFilter> filters, SpringSettings constraintSpringSettings, Simulation simulation)
    {
        RagdollLegHandles handles;
        var localKnee = localHip - new Vector3(0, 0.5f, 0);
        var localAnkle = localKnee - new Vector3(0, 0.5f, 0);
        var localFoot = localAnkle + new Vector3(0, -0.075f, 0.05f);
        GetCapsuleForLineSegment(localHip, localKnee, 0.12f, out var upperLegShape, out var upperLegPosition, out var upperLegOrientation);
        handles.UpperLeg = AddBody(upperLegShape, 5, GetWorldPose(upperLegPosition, upperLegOrientation, ragdollPose), simulation);
        GetCapsuleForLineSegment(localKnee, localAnkle, 0.11f, out var lowerLegShape, out var lowerLegPosition, out var lowerLegOrientation);
        handles.LowerLeg = AddBody(lowerLegShape, 5, GetWorldPose(lowerLegPosition, lowerLegOrientation, ragdollPose), simulation);
        handles.Foot = AddBody(new Box(0.2f, 0.15f, 0.3f), 2, GetWorldPose(localFoot, Quaternion.Identity, ragdollPose), simulation);

        //Create joints between limb pieces.
        //Hips-Upper Leg
        simulation.Solver.Add(hipsHandle, handles.UpperLeg, new BallSocket
        {
            LocalOffsetA = QuaternionEx.Transform(localHip - localHipsPose.Position, QuaternionEx.Conjugate(localHipsPose.Orientation)),
            LocalOffsetB = QuaternionEx.Transform(localHip - upperLegPosition, QuaternionEx.Conjugate(upperLegOrientation)),
            SpringSettings = constraintSpringSettings
        });
        simulation.Solver.Add(hipsHandle, handles.UpperLeg, new SwingLimit
        {
            AxisLocalA = QuaternionEx.Transform(Vector3.Normalize(new Vector3(Math.Sign(localHip.X), -1, 0)), QuaternionEx.Conjugate(localHipsPose.Orientation)),
            AxisLocalB = QuaternionEx.Transform(new Vector3(0, -1, 0), QuaternionEx.Conjugate(upperLegOrientation)),
            MaximumSwingAngle = MathHelper.PiOver2,
            SpringSettings = constraintSpringSettings
        });
        simulation.Solver.Add(hipsHandle, handles.UpperLeg, new TwistLimit
        {
            LocalBasisA = QuaternionEx.Concatenate(CreateBasis(new Vector3(0, -1, 0), new Vector3(0, 0, 1)), QuaternionEx.Conjugate(localHipsPose.Orientation)),
            LocalBasisB = QuaternionEx.Concatenate(CreateBasis(new Vector3(0, -1, 0), new Vector3(0, 0, 1)), QuaternionEx.Conjugate(upperLegOrientation)),
            MinimumAngle = localHip.X < 0 ? MathHelper.Pi * -0.05f : MathHelper.Pi * -0.55f,
            MaximumAngle = localHip.X < 0 ? MathHelper.Pi * 0.55f : MathHelper.Pi * 0.05f,
            SpringSettings = constraintSpringSettings
        });
        simulation.Solver.Add(hipsHandle, handles.UpperLeg, BuildAngularMotor());

        //Upper Leg-Lower Leg
        simulation.Solver.Add(handles.UpperLeg, handles.LowerLeg, new Hinge
        {
            LocalHingeAxisA = QuaternionEx.Transform(new Vector3(1, 0, 0), QuaternionEx.Conjugate(upperLegOrientation)),
            LocalOffsetA = QuaternionEx.Transform(localKnee - upperLegPosition, QuaternionEx.Conjugate(upperLegOrientation)),
            LocalHingeAxisB = QuaternionEx.Transform(new Vector3(1, 0, 0), QuaternionEx.Conjugate(lowerLegOrientation)),
            LocalOffsetB = QuaternionEx.Transform(localKnee - lowerLegPosition, QuaternionEx.Conjugate(lowerLegOrientation)),
            SpringSettings = constraintSpringSettings
        });
        simulation.Solver.Add(handles.UpperLeg, handles.LowerLeg, new SwingLimit
        {
            AxisLocalA = QuaternionEx.Transform(new Vector3(0, 0, 1), QuaternionEx.Conjugate(upperLegOrientation)),
            AxisLocalB = QuaternionEx.Transform(new Vector3(0, 1, 0), QuaternionEx.Conjugate(lowerLegOrientation)),
            MaximumSwingAngle = MathHelper.PiOver2,
            SpringSettings = constraintSpringSettings
        });
        simulation.Solver.Add(handles.UpperLeg, handles.LowerLeg, BuildAngularMotor());

        //Lower Leg-Foot
        simulation.Solver.Add(handles.LowerLeg, handles.Foot, new BallSocket
        {
            LocalOffsetA = QuaternionEx.Transform(localAnkle - lowerLegPosition, QuaternionEx.Conjugate(lowerLegOrientation)),
            LocalOffsetB = localAnkle - localFoot,
            SpringSettings = constraintSpringSettings
        });
        simulation.Solver.Add(handles.LowerLeg, handles.Foot, new SwingLimit
        {
            AxisLocalA = QuaternionEx.Transform(new Vector3(0, 1, 0), QuaternionEx.Conjugate(lowerLegOrientation)),
            AxisLocalB = new Vector3(0, 1, 0),
            MaximumSwingAngle = 1,
            SpringSettings = constraintSpringSettings
        });
        simulation.Solver.Add(handles.LowerLeg, handles.Foot, new TwistServo
        {
            LocalBasisA = QuaternionEx.Concatenate(CreateBasis(new Vector3(0, 1, 0), new Vector3(0, 0, 1)), QuaternionEx.Conjugate(lowerLegOrientation)),
            LocalBasisB = CreateBasis(new Vector3(0, 1, 0), new Vector3(0, 0, 1)),
            TargetAngle = 0,
            SpringSettings = constraintSpringSettings,
            ServoSettings = new ServoSettings(float.MaxValue, 0, float.MaxValue)
        });
        simulation.Solver.Add(handles.LowerLeg, handles.Foot, BuildAngularMotor());

        //Disable collisions between connected ragdoll pieces.
        var upperLegLocalIndex = limbBaseBitIndex;
        var lowerLegLocalIndex = limbBaseBitIndex + 1;
        var footLocalIndex = limbBaseBitIndex + 2;
        ref var upperLegFilter = ref filters.Allocate(handles.UpperLeg);
        ref var lowerLegFilter = ref filters.Allocate(handles.LowerLeg);
        ref var footFilter = ref filters.Allocate(handles.Foot);
        upperLegFilter = new SubgroupCollisionFilter(ragdollIndex, upperLegLocalIndex);
        lowerLegFilter = new SubgroupCollisionFilter(ragdollIndex, lowerLegLocalIndex);
        footFilter = new SubgroupCollisionFilter(ragdollIndex, footLocalIndex);
        SubgroupCollisionFilter.DisableCollision(ref hipsFilter, ref upperLegFilter);
        SubgroupCollisionFilter.DisableCollision(ref upperLegFilter, ref lowerLegFilter);
        SubgroupCollisionFilter.DisableCollision(ref lowerLegFilter, ref footFilter);
        return handles;
    }

    public struct RagdollArmHandles
    {
        public BodyHandle UpperArm;
        public BodyHandle LowerArm;
        public BodyHandle Hand;
    }
    public struct RagdollLegHandles
    {
        public BodyHandle UpperLeg;
        public BodyHandle LowerLeg;
        public BodyHandle Foot;
    }
    public struct RagdollHandles
    {
        public BodyHandle Head;
        public BodyHandle Chest;
        public BodyHandle Abdomen;
        public BodyHandle Hips;
        public RagdollArmHandles LeftArm;
        public RagdollArmHandles RightArm;
        public RagdollLegHandles LeftLeg;
        public RagdollLegHandles RightLeg;
    }

    public static RagdollHandles AddRagdoll(Vector3 position, Quaternion orientation, int ragdollIndex, CollidableProperty<SubgroupCollisionFilter> collisionFilters, Simulation simulation)
    {
        var ragdollPose = new RigidPose { Position = position, Orientation = orientation };
        var horizontalOrientation = QuaternionEx.CreateFromAxisAngle(new Vector3(0, 0, 1), MathHelper.PiOver2);
        RagdollHandles handles;
        var hipsPose = new RigidPose { Position = new Vector3(0, 1.1f, 0), Orientation = horizontalOrientation };
        handles.Hips = AddBody(new Capsule(0.17f, 0.25f), 8, GetWorldPose(hipsPose.Position, hipsPose.Orientation, ragdollPose), simulation);
        var abdomenPose = new RigidPose { Position = new Vector3(0, 1.3f, 0), Orientation = horizontalOrientation };
        handles.Abdomen = AddBody(new Capsule(0.17f, 0.22f), 7, GetWorldPose(abdomenPose.Position, abdomenPose.Orientation, ragdollPose), simulation);
        var chestPose = new RigidPose { Position = new Vector3(0, 1.6f, 0), Orientation = horizontalOrientation };
        handles.Chest = AddBody(new Capsule(0.21f, 0.3f), 10, GetWorldPose(chestPose.Position, chestPose.Orientation, ragdollPose), simulation);
        var headPose = new RigidPose { Position = new Vector3(0, 2.05f, 0), Orientation = Quaternion.Identity };
        handles.Head = AddBody(new Sphere(0.2f), 5, GetWorldPose(headPose.Position, headPose.Orientation, ragdollPose), simulation);

        //Attach constraints between torso pieces.
        var springSettings = new SpringSettings(15f, 1f);
        var lowerSpine = (hipsPose.Position + abdomenPose.Position) * 0.5f;
        //Hips-Abdomen
        simulation.Solver.Add(handles.Hips, handles.Abdomen, new BallSocket
        {
            LocalOffsetA = QuaternionEx.Transform(lowerSpine - hipsPose.Position, QuaternionEx.Conjugate(hipsPose.Orientation)),
            LocalOffsetB = QuaternionEx.Transform(lowerSpine - abdomenPose.Position, QuaternionEx.Conjugate(abdomenPose.Orientation)),
            SpringSettings = springSettings
        });
        simulation.Solver.Add(handles.Hips, handles.Abdomen, new SwingLimit
        {
            AxisLocalA = QuaternionEx.Transform(new Vector3(0, 1, 0), QuaternionEx.Conjugate(hipsPose.Orientation)),
            AxisLocalB = QuaternionEx.Transform(new Vector3(0, 1, 0), QuaternionEx.Conjugate(abdomenPose.Orientation)),
            MaximumSwingAngle = MathHelper.Pi * 0.27f,
            SpringSettings = springSettings
        });
        simulation.Solver.Add(handles.Hips, handles.Abdomen, new TwistLimit
        {
            LocalBasisA = QuaternionEx.Concatenate(CreateBasis(new Vector3(0, 1, 0), new Vector3(1, 0, 0)), QuaternionEx.Conjugate(hipsPose.Orientation)),
            LocalBasisB = QuaternionEx.Concatenate(CreateBasis(new Vector3(0, 1, 0), new Vector3(1, 0, 0)), QuaternionEx.Conjugate(abdomenPose.Orientation)),
            MinimumAngle = MathHelper.Pi * -0.2f,
            MaximumAngle = MathHelper.Pi * 0.2f,
            SpringSettings = springSettings
        });
        simulation.Solver.Add(handles.Hips, handles.Abdomen, BuildAngularMotor());

        //Abdomen-Chest
        var upperSpine = (abdomenPose.Position + chestPose.Position) * 0.5f;
        simulation.Solver.Add(handles.Abdomen, handles.Chest, new BallSocket
        {
            LocalOffsetA = QuaternionEx.Transform(upperSpine - abdomenPose.Position, QuaternionEx.Conjugate(abdomenPose.Orientation)),
            LocalOffsetB = QuaternionEx.Transform(upperSpine - chestPose.Position, QuaternionEx.Conjugate(chestPose.Orientation)),
            SpringSettings = springSettings
        });
        simulation.Solver.Add(handles.Abdomen, handles.Chest, new SwingLimit
        {
            AxisLocalA = QuaternionEx.Transform(new Vector3(0, 1, 0), QuaternionEx.Conjugate(abdomenPose.Orientation)),
            AxisLocalB = QuaternionEx.Transform(new Vector3(0, 1, 0), QuaternionEx.Conjugate(chestPose.Orientation)),
            MaximumSwingAngle = MathHelper.Pi * 0.27f,
            SpringSettings = springSettings
        });
        simulation.Solver.Add(handles.Abdomen, handles.Chest, new TwistLimit
        {
            LocalBasisA = QuaternionEx.Concatenate(CreateBasis(new Vector3(0, 1, 0), new Vector3(1, 0, 0)), QuaternionEx.Conjugate(abdomenPose.Orientation)),
            LocalBasisB = QuaternionEx.Concatenate(CreateBasis(new Vector3(0, 1, 0), new Vector3(1, 0, 0)), QuaternionEx.Conjugate(chestPose.Orientation)),
            MinimumAngle = MathHelper.Pi * -0.2f,
            MaximumAngle = MathHelper.Pi * 0.2f,
            SpringSettings = springSettings
        });
        simulation.Solver.Add(handles.Abdomen, handles.Chest, BuildAngularMotor());

        //Chest-Head
        var neck = (headPose.Position + chestPose.Position) * 0.5f;
        simulation.Solver.Add(handles.Chest, handles.Head, new BallSocket
        {
            LocalOffsetA = QuaternionEx.Transform(neck - chestPose.Position, QuaternionEx.Conjugate(chestPose.Orientation)),
            LocalOffsetB = neck - headPose.Position,
            SpringSettings = springSettings
        });
        simulation.Solver.Add(handles.Chest, handles.Head, new SwingLimit
        {
            AxisLocalA = QuaternionEx.Transform(new Vector3(0, 1, 0), QuaternionEx.Conjugate(chestPose.Orientation)),
            AxisLocalB = new Vector3(0, 1, 0),
            MaximumSwingAngle = MathHelper.PiOver2 * 0.9f,
            SpringSettings = springSettings
        });
        simulation.Solver.Add(handles.Chest, handles.Head, new TwistLimit
        {
            LocalBasisA = QuaternionEx.Concatenate(CreateBasis(new Vector3(0, 1, 0), new Vector3(1, 0, 0)), QuaternionEx.Conjugate(chestPose.Orientation)),
            LocalBasisB = QuaternionEx.Concatenate(CreateBasis(new Vector3(0, 1, 0), new Vector3(1, 0, 0)), QuaternionEx.Conjugate(headPose.Orientation)),
            MinimumAngle = MathHelper.Pi * -0.5f,
            MaximumAngle = MathHelper.Pi * 0.5f,
            SpringSettings = springSettings
        });
        simulation.Solver.Add(handles.Chest, handles.Head, BuildAngularMotor());

        var hipsLocalIndex = 0;
        var abdomenLocalIndex = 1;
        var chestLocalIndex = 2;
        var headLocalIndex = 3;
        ref var hipsFilter = ref collisionFilters.Allocate(handles.Hips);
        ref var abdomenFilter = ref collisionFilters.Allocate(handles.Abdomen);
        ref var chestFilter = ref collisionFilters.Allocate(handles.Chest);
        ref var headFilter = ref collisionFilters.Allocate(handles.Head);
        hipsFilter = new SubgroupCollisionFilter(ragdollIndex, hipsLocalIndex);
        abdomenFilter = new SubgroupCollisionFilter(ragdollIndex, abdomenLocalIndex);
        chestFilter = new SubgroupCollisionFilter(ragdollIndex, chestLocalIndex);
        headFilter = new SubgroupCollisionFilter(ragdollIndex, headLocalIndex);
        //Disable collisions in the torso and head.
        SubgroupCollisionFilter.DisableCollision(ref hipsFilter, ref abdomenFilter);
        SubgroupCollisionFilter.DisableCollision(ref abdomenFilter, ref chestFilter);
        SubgroupCollisionFilter.DisableCollision(ref chestFilter, ref headFilter);

        //Build all the limbs. Setting the masks is delayed until after the limbs have been created and have disabled collisions with the chest/hips.
        handles.RightArm = AddArm(1, chestPose.Position + new Vector3(0.4f, 0.1f, 0), chestPose, handles.Chest, ref chestFilter, 4, ragdollIndex, ragdollPose, collisionFilters, springSettings, simulation);
        handles.LeftArm = AddArm(-1, chestPose.Position + new Vector3(-0.4f, 0.1f, 0), chestPose, handles.Chest, ref chestFilter, 7, ragdollIndex, ragdollPose, collisionFilters, springSettings, simulation);
        handles.RightLeg = AddLeg(hipsPose.Position + new Vector3(-0.17f, -0.2f, 0), hipsPose, handles.Hips, ref hipsFilter, 10, ragdollIndex, ragdollPose, collisionFilters, springSettings, simulation);
        handles.LeftLeg = AddLeg(hipsPose.Position + new Vector3(0.17f, -0.2f, 0), hipsPose, handles.Hips, ref hipsFilter, 13, ragdollIndex, ragdollPose, collisionFilters, springSettings, simulation);
        return handles;
    }

    const int timestepCount = 384;
    BufferPool BufferPool;
    Simulation Simulation;

    [IterationSetup]
    public unsafe void Initialize()
    {
        var filters = new CollidableProperty<SubgroupCollisionFilter>();
        BufferPool = new BufferPool();
        Simulation = Simulation.Create(BufferPool, new SubgroupFilteredCallbacks(filters, new PairMaterialProperties(2, float.MaxValue, new SpringSettings(10, 1))), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)), new SolveDescription(4, 1));

        int ragdollIndex = 0;
        var spacing = new Vector3(1.7f, 1.8f, 0.5f);
        int width = 4;
        int height = 4;
        int length = 2;
        var origin = -0.5f * spacing * new Vector3(width - 1, 0, length - 1) + new Vector3(0, 5f, 0);
        for (int i = 0; i < width; ++i)
        {
            for (int j = 0; j < height; ++j)
            {
                for (int k = 0; k < length; ++k)
                {
                    AddRagdoll(origin + spacing * new Vector3(i, j, k), QuaternionEx.CreateFromAxisAngle(new Vector3(0, 1, 0), MathHelper.Pi * 0.05f), ragdollIndex++, filters, Simulation);
                }
            }
        }

        var tubeCenter = new Vector3(0, 8, 0);
        const int panelCount = 20;
        const float tubeRadius = 6;
        var panelShape = new Box(MathF.PI * 2 * tubeRadius / panelCount, 1, 80);
        var panelShapeIndex = Simulation.Shapes.Add(panelShape);
        var builder = new CompoundBuilder(BufferPool, Simulation.Shapes, panelCount + 1);
        for (int i = 0; i < panelCount; ++i)
        {
            var rotation = QuaternionEx.CreateFromAxisAngle(Vector3.UnitZ, i * MathHelper.TwoPi / panelCount);
            QuaternionEx.TransformUnitY(rotation, out var localUp);
            var position = localUp * tubeRadius;
            builder.AddForKinematic(panelShapeIndex, (position, rotation), 1);
        }
        builder.AddForKinematic(Simulation.Shapes.Add(new Box(1, 2, panelShape.Length)), new Vector3(0, tubeRadius - 1, 0), 0);
        builder.BuildKinematicCompound(out var children);
        var compound = new BigCompound(children, Simulation.Shapes, BufferPool);
        var tubeHandle = Simulation.Bodies.Add(BodyDescription.CreateKinematic(tubeCenter, (default, new Vector3(0, 0, .25f)), Simulation.Shapes.Add(compound), 0f));
        filters[tubeHandle] = new SubgroupCollisionFilter(int.MaxValue);
        builder.Dispose();

        var staticShape = new Box(300, 1, 300);
        var staticShapeIndex = Simulation.Shapes.Add(staticShape);
        var staticDescription = new StaticDescription(new Vector3(0, -0.5f, 0), staticShapeIndex);
        Simulation.Statics.Add(staticDescription);
    }

    [IterationCleanup]
    public void CleanUp()
    {
        BufferPool.Clear();
        BufferPool = null;
    }

    [Benchmark]
    public unsafe void RagdollTubeBenchmarks()
    {
        for (int i = 0; i < timestepCount; ++i)
        {
            Simulation.Timestep(1 / 60f);
        }
    }
}


text:
using System;

namespace UnityEngine.Rendering.PostProcessing
{
    // Multi-scale volumetric obscurance
    // TODO: Fix VR support

#if UNITY_2017_1_OR_NEWER
    [Serializable]
    public sealed class MultiScaleVO : IAmbientOcclusionMethod
    {
        internal enum MipLevel { Original, L1, L2, L3, L4, L5, L6 }

        enum Pass
        {
            DepthCopy,
            CompositionDeferred,
            CompositionForward,
            DebugOverlay
        }

        // The arrays below are reused between frames to reduce GC allocation.
        readonly float[] m_SampleThickness =
        {
            Mathf.Sqrt(1f - 0.2f * 0.2f),
            Mathf.Sqrt(1f - 0.4f * 0.4f),
            Mathf.Sqrt(1f - 0.6f * 0.6f),
            Mathf.Sqrt(1f - 0.8f * 0.8f),
            Mathf.Sqrt(1f - 0.2f * 0.2f - 0.2f * 0.2f),
            Mathf.Sqrt(1f - 0.2f * 0.2f - 0.4f * 0.4f),
            Mathf.Sqrt(1f - 0.2f * 0.2f - 0.6f * 0.6f),
            Mathf.Sqrt(1f - 0.2f * 0.2f - 0.8f * 0.8f),
            Mathf.Sqrt(1f - 0.4f * 0.4f - 0.4f * 0.4f),
            Mathf.Sqrt(1f - 0.4f * 0.4f - 0.6f * 0.6f),
            Mathf.Sqrt(1f - 0.4f * 0.4f - 0.8f * 0.8f),
            Mathf.Sqrt(1f - 0.6f * 0.6f - 0.6f * 0.6f)
        };

        readonly float[] m_InvThicknessTable = new float[12];
        readonly float[] m_SampleWeightTable = new float[12];

        readonly int[] m_Widths = new int[7];
        readonly int[] m_Heights = new int[7];

        AmbientOcclusion m_Settings;
        PropertySheet m_PropertySheet;
        PostProcessResources m_Resources;

        // Can't use a temporary because we need to share it between cmdbuffers - also fixes a weird
        // command buffer warning
        RenderTexture m_AmbientOnlyAO;

        readonly RenderTargetIdentifier[] m_MRT =
        {
            BuiltinRenderTextureType.GBuffer0,    // Albedo, Occ
            BuiltinRenderTextureType.CameraTarget // Ambient
        };

        public MultiScaleVO(AmbientOcclusion settings)
        {
            m_Settings = settings;
        }

        public DepthTextureMode GetCameraFlags()
        {
            return DepthTextureMode.Depth;
        }

        // Special case for AO [because SRPs], please don't do this in other effects, it's bad
        // practice in this framework
        public void SetResources(PostProcessResources resources)
        {
            m_Resources = resources;
        }

        void Alloc(CommandBuffer cmd, int id, MipLevel size, RenderTextureFormat format, bool uav)
        {
            int sizeId = (int)size;
            cmd.GetTemporaryRT(id, new RenderTextureDescriptor
            {
                width = m_Widths[sizeId],
                height = m_Heights[sizeId],
                colorFormat = format,
                depthBufferBits = 0,
                autoGenerateMips = false,
                msaaSamples = 1,
                enableRandomWrite = uav,
                dimension = TextureDimension.Tex2D,
                sRGB = false
            }, FilterMode.Point);
        }

        void AllocArray(CommandBuffer cmd, int id, MipLevel size, RenderTextureFormat format, bool uav)
        {
            int sizeId = (int)size;
            cmd.GetTemporaryRT(id, new RenderTextureDescriptor
            {
                width = m_Widths[sizeId],
                height = m_Heights[sizeId],
                colorFormat = format,
                depthBufferBits = 0,
                volumeDepth = 16,
                autoGenerateMips = false,
                msaaSamples = 1,
                enableRandomWrite = uav,
                dimension = TextureDimension.Tex2DArray,
                sRGB = false
            }, FilterMode.Point);
        }

        void Release(CommandBuffer cmd, int id)
        {
            cmd.ReleaseTemporaryRT(id);
        }

        // Calculate values in _ZBuferParams (built-in shader variable)
        // We can't use _ZBufferParams in compute shaders, so this function is
        // used to give the values in it to compute shaders.
        Vector4 CalculateZBufferParams(Camera camera)
        {
            float fpn = camera.farClipPlane / camera.nearClipPlane;

            if (SystemInfo.usesReversedZBuffer)
                return new Vector4(fpn - 1f, 1f, 0f, 0f);

            return new Vector4(1f - fpn, fpn, 0f, 0f);
        }

        float CalculateTanHalfFovHeight(Camera camera)
        {
            return 1f / camera.projectionMatrix[0, 0];
        }

        Vector2 GetSize(MipLevel mip)
        {
            return new Vector2(m_Widths[(int)mip], m_Heights[(int)mip]);
        }

        Vector3 GetSizeArray(MipLevel mip)
        {
            return new Vector3(m_Widths[(int)mip], m_Heights[(int)mip], 16);
        }

        public void GenerateAOMap(CommandBuffer cmd, Camera camera, RenderTargetIdentifier destination, RenderTargetIdentifier? depthMap, bool invert)
        {
            // Base size
            m_Widths[0] = camera.pixelWidth * (RuntimeUtilities.isSinglePassStereoEnabled ? 2 : 1);
            m_Heights[0] = camera.pixelHeight;

            // L1 -> L6 sizes
            for (int i = 1; i < 7; i++)
            {
                int div = 1 << i;
                m_Widths[i]  = (m_Widths[0]  + (div - 1)) / div;
                m_Heights[i] = (m_Heights[0] + (div - 1)) / div;
            }

            // Allocate temporary textures
            PushAllocCommands(cmd);

            // Render logic
            PushDownsampleCommands(cmd, camera, depthMap);

            float tanHalfFovH = CalculateTanHalfFovHeight(camera);
            PushRenderCommands(cmd, ShaderIDs.TiledDepth1, ShaderIDs.Occlusion1, GetSizeArray(MipLevel.L3), tanHalfFovH);
            PushRenderCommands(cmd, ShaderIDs.TiledDepth2, ShaderIDs.Occlusion2, GetSizeArray(MipLevel.L4), tanHalfFovH);
            PushRenderCommands(cmd, ShaderIDs.TiledDepth3, ShaderIDs.Occlusion3, GetSizeArray(MipLevel.L5), tanHalfFovH);
            PushRenderCommands(cmd, ShaderIDs.TiledDepth4, ShaderIDs.Occlusion4, GetSizeArray(MipLevel.L6), tanHalfFovH);

            PushUpsampleCommands(cmd, ShaderIDs.LowDepth4, ShaderIDs.Occlusion4, ShaderIDs.LowDepth3,   ShaderIDs.Occlusion3, ShaderIDs.Combined3, GetSize(MipLevel.L4), GetSize(MipLevel.L3));
            PushUpsampleCommands(cmd, ShaderIDs.LowDepth3, ShaderIDs.Combined3,  ShaderIDs.LowDepth2,   ShaderIDs.Occlusion2, ShaderIDs.Combined2, GetSize(MipLevel.L3), GetSize(MipLevel.L2));
            PushUpsampleCommands(cmd, ShaderIDs.LowDepth2, ShaderIDs.Combined2,  ShaderIDs.LowDepth1,   ShaderIDs.Occlusion1, ShaderIDs.Combined1, GetSize(MipLevel.L2), GetSize(MipLevel.L1));
            PushUpsampleCommands(cmd, ShaderIDs.LowDepth1, ShaderIDs.Combined1,  ShaderIDs.LinearDepth, null,                 destination,         GetSize(MipLevel.L1), GetSize(MipLevel.Original), invert);

            // Cleanup
            PushReleaseCommands(cmd);
        }

        void PushAllocCommands(CommandBuffer cmd)
        {
            Alloc(cmd, ShaderIDs.LinearDepth, MipLevel.Original, RenderTextureFormat.RHalf, true);

            Alloc(cmd, ShaderIDs.LowDepth1, MipLevel.L1, RenderTextureFormat.RFloat, true);
            Alloc(cmd, ShaderIDs.LowDepth2, MipLevel.L2, RenderTextureFormat.RFloat, true);
            Alloc(cmd, ShaderIDs.LowDepth3, MipLevel.L3, RenderTextureFormat.RFloat, true);
            Alloc(cmd, ShaderIDs.LowDepth4, MipLevel.L4, RenderTextureFormat.RFloat, true);

            AllocArray(cmd, ShaderIDs.TiledDepth1, MipLevel.L3, RenderTextureFormat.RHalf, true);
            AllocArray(cmd, ShaderIDs.TiledDepth2, MipLevel.L4, RenderTextureFormat.RHalf, true);
            AllocArray(cmd, ShaderIDs.TiledDepth3, MipLevel.L5, RenderTextureFormat.RHalf, true);
            AllocArray(cmd, ShaderIDs.TiledDepth4, MipLevel.L6, RenderTextureFormat.RHalf, true);

            Alloc(cmd, ShaderIDs.Occlusion1, MipLevel.L1, RenderTextureFormat.R8, true);
            Alloc(cmd, ShaderIDs.Occlusion2, MipLevel.L2, RenderTextureFormat.R8, true);
            Alloc(cmd, ShaderIDs.Occlusion3, MipLevel.L3, RenderTextureFormat.R8, true);
            Alloc(cmd, ShaderIDs.Occlusion4, MipLevel.L4, RenderTextureFormat.R8, true);

            Alloc(cmd, ShaderIDs.Combined1, MipLevel.L1, RenderTextureFormat.R8, true);
            Alloc(cmd, ShaderIDs.Combined2, MipLevel.L2, RenderTextureFormat.R8, true);
            Alloc(cmd, ShaderIDs.Combined3, MipLevel.L3, RenderTextureFormat.R8, true);
        }

        void PushDownsampleCommands(CommandBuffer cmd, Camera camera, RenderTargetIdentifier? depthMap)
        {
            RenderTargetIdentifier depthMapId;
            bool needDepthMapRelease = false;

            if (depthMap != null)
            {
                depthMapId = depthMap.Value;
            }
            else
            {
                // Make a copy of the depth texture, or reuse the resolved depth
                // buffer (it's only available in some specific situations).
                if (!RuntimeUtilities.IsResolvedDepthAvailable(camera))
                {
                    Alloc(cmd, ShaderIDs.DepthCopy, MipLevel.Original, RenderTextureFormat.RFloat, false);
                    depthMapId = new RenderTargetIdentifier(ShaderIDs.DepthCopy);
                    cmd.BlitFullscreenTriangle(BuiltinRenderTextureType.None, depthMapId, m_PropertySheet, (int)Pass.DepthCopy);
                    needDepthMapRelease = true;
                }
                else
                {
                    depthMapId = BuiltinRenderTextureType.ResolvedDepth;
                }
            }

            // 1st downsampling pass.
            var cs = m_Resources.computeShaders.multiScaleAODownsample1;
            int kernel = cs.FindKernel("main");

            cmd.SetComputeTextureParam(cs, kernel, "LinearZ", ShaderIDs.LinearDepth);
            cmd.SetComputeTextureParam(cs, kernel, "DS2x", ShaderIDs.LowDepth1);
            cmd.SetComputeTextureParam(cs, kernel, "DS4x", ShaderIDs.LowDepth2);
            cmd.SetComputeTextureParam(cs, kernel, "DS2xAtlas", ShaderIDs.TiledDepth1);
            cmd.SetComputeTextureParam(cs, kernel, "DS4xAtlas", ShaderIDs.TiledDepth2);
            cmd.SetComputeVectorParam(cs, "ZBufferParams", CalculateZBufferParams(camera));
            cmd.SetComputeTextureParam(cs, kernel, "Depth", depthMapId);

            cmd.DispatchCompute(cs, kernel, m_Widths[(int)MipLevel.L4], m_Heights[(int)MipLevel.L4], 1);

            if (needDepthMapRelease)
                Release(cmd, ShaderIDs.DepthCopy);

            // 2nd downsampling pass.
            cs = m_Resources.computeShaders.multiScaleAODownsample2;
            kernel = cs.FindKernel("main");

            cmd.SetComputeTextureParam(cs, kernel, "DS4x", ShaderIDs.LowDepth2);
            cmd.SetComputeTextureParam(cs, kernel, "DS8x", ShaderIDs.LowDepth3);
            cmd.SetComputeTextureParam(cs, kernel, "DS16x", ShaderIDs.LowDepth4);
            cmd.SetComputeTextureParam(cs, kernel, "DS8xAtlas", ShaderIDs.TiledDepth3);
            cmd.SetComputeTextureParam(cs, kernel, "DS16xAtlas", ShaderIDs.TiledDepth4);

            cmd.DispatchCompute(cs, kernel, m_Widths[(int)MipLevel.L6], m_Heights[(int)MipLevel.L6], 1);
        }

        void PushRenderCommands(CommandBuffer cmd, int source, int destination, Vector3 sourceSize, float tanHalfFovH)
        {
            // Here we compute multipliers that convert the center depth value into (the reciprocal
            // of) sphere thicknesses at each sample location. This assumes a maximum sample radius
            // of 5 units, but since a sphere has no thickness at its extent, we don't need to
            // sample that far out. Only samples whole integer offsets with distance less than 25
            // are used. This means that there is no sample at (3, 4) because its distance is
            // exactly 25 (and has a thickness of 0.)

            // The shaders are set up to sample a circular region within a 5-pixel radius.
            const float kScreenspaceDiameter = 10f;

            // SphereDiameter = CenterDepth * ThicknessMultiplier. This will compute the thickness
            // of a sphere centered at a specific depth. The ellipsoid scale can stretch a sphere
            // into an ellipsoid, which changes the characteristics of the AO.
            // TanHalfFovH: Radius of sphere in depth units if its center lies at Z = 1
            // ScreenspaceDiameter: Diameter of sample sphere in pixel units
            // ScreenspaceDiameter / BufferWidth: Ratio of the screen width that the sphere actually covers
            float thicknessMultiplier = 2f * tanHalfFovH * kScreenspaceDiameter / sourceSize.x;
            if (RuntimeUtilities.isSinglePassStereoEnabled)
                thicknessMultiplier *= 2f;

            // This will transform a depth value from [0, thickness] to [0, 1].
            float inverseRangeFactor = 1f / thicknessMultiplier;

            // The thicknesses are smaller for all off-center samples of the sphere. Compute
            // thicknesses relative to the center sample.
            for (int i = 0; i < 12; i++)
                m_InvThicknessTable[i] = inverseRangeFactor / m_SampleThickness[i];

            // These are the weights that are multiplied against the samples because not all samples
            // are equally important. The farther the sample is from the center location, the less
            // they matter. We use the thickness of the sphere to determine the weight.  The scalars
            // in front are the number of samples with this weight because we sum the samples
            // together before multiplying by the weight, so as an aggregate all of those samples
            // matter more. After generating this table, the weights are normalized.
            m_SampleWeightTable[ 0] = 4 * m_SampleThickness[ 0];    // Axial
            m_SampleWeightTable[ 1] = 4 * m_SampleThickness[ 1];    // Axial
            m_SampleWeightTable[ 2] = 4 * m_SampleThickness[ 2];    // Axial
            m_SampleWeightTable[ 3] = 4 * m_SampleThickness[ 3];    // Axial
            m_SampleWeightTable[ 4] = 4 * m_SampleThickness[ 4];    // Diagonal
            m_SampleWeightTable[ 5] = 8 * m_SampleThickness[ 5];    // L-shaped
            m_SampleWeightTable[ 6] = 8 * m_SampleThickness[ 6];    // L-shaped
            m_SampleWeightTable[ 7] = 8 * m_SampleThickness[ 7];    // L-shaped
            m_SampleWeightTable[ 8] = 4 * m_SampleThickness[ 8];    // Diagonal
            m_SampleWeightTable[ 9] = 8 * m_SampleThickness[ 9];    // L-shaped
            m_SampleWeightTable[10] = 8 * m_SampleThickness[10];    // L-shaped
            m_SampleWeightTable[11] = 4 * m_SampleThickness[11];    // Diagonal

            // Zero out the unused samples.
            // FIXME: should we support SAMPLE_EXHAUSTIVELY mode?
            m_SampleWeightTable[0] = 0;
            m_SampleWeightTable[2] = 0;
            m_SampleWeightTable[5] = 0;
            m_SampleWeightTable[7] = 0;
            m_SampleWeightTable[9] = 0;

            // Normalize the weights by dividing by the sum of all weights
            var totalWeight = 0f;

            foreach (float w in m_SampleWeightTable)
                totalWeight += w;

            for (int i = 0; i < m_SampleWeightTable.Length; i++)
                m_SampleWeightTable[i] /= totalWeight;

            // Set the arguments for the render kernel.
            var cs = m_Resources.computeShaders.multiScaleAORender;
            int kernel = cs.FindKernel("main_interleaved");

            cmd.SetComputeFloatParams(cs, "gInvThicknessTable", m_InvThicknessTable);
            cmd.SetComputeFloatParams(cs, "gSampleWeightTable", m_SampleWeightTable);
            cmd.SetComputeVectorParam(cs, "gInvSliceDimension", new Vector2(1f / sourceSize.x, 1f / sourceSize.y));
            cmd.SetComputeVectorParam(cs, "AdditionalParams", new Vector2(-1f / m_Settings.thicknessModifier.value, m_Settings.intensity.value));
            cmd.SetComputeTextureParam(cs, kernel, "DepthTex", source);
            cmd.SetComputeTextureParam(cs, kernel, "Occlusion", destination);

            // Calculate the thread group count and add a dispatch command with them.
            uint xsize, ysize, zsize;
            cs.GetKernelThreadGroupSizes(kernel, out xsize, out ysize, out zsize);

            cmd.DispatchCompute(
                cs, kernel,
                ((int)sourceSize.x + (int)xsize - 1) / (int)xsize,
                ((int)sourceSize.y + (int)ysize - 1) / (int)ysize,
                ((int)sourceSize.z + (int)zsize - 1) / (int)zsize
            );
        }

        void PushUpsampleCommands(CommandBuffer cmd, int lowResDepth, int interleavedAO, int highResDepth, int? highResAO, RenderTargetIdentifier dest, Vector3 lowResDepthSize, Vector2 highResDepthSize, bool invert = false)
        {
            var cs = m_Resources.computeShaders.multiScaleAOUpsample;
            int kernel = cs.FindKernel(highResAO == null
                ? invert
                    ? "main_invert"
                    : "main"
                : "main_blendout");

            float stepSize = 1920f / lowResDepthSize.x;
            float bTolerance = 1f - Mathf.Pow(10f, m_Settings.blurTolerance.value) * stepSize;
            bTolerance *= bTolerance;
            float uTolerance = Mathf.Pow(10f, m_Settings.upsampleTolerance.value);
            float noiseFilterWeight = 1f / (Mathf.Pow(10f, m_Settings.noiseFilterTolerance.value) + uTolerance);

            cmd.SetComputeVectorParam(cs, "InvLowResolution", new Vector2(1f / lowResDepthSize.x, 1f / lowResDepthSize.y));
            cmd.SetComputeVectorParam(cs, "InvHighResolution", new Vector2(1f / highResDepthSize.x, 1f / highResDepthSize.y));
            cmd.SetComputeVectorParam(cs, "AdditionalParams", new Vector4(noiseFilterWeight, stepSize, bTolerance, uTolerance));

            cmd.SetComputeTextureParam(cs, kernel, "LoResDB", lowResDepth);
            cmd.SetComputeTextureParam(cs, kernel, "HiResDB", highResDepth);
            cmd.SetComputeTextureParam(cs, kernel, "LoResAO1", interleavedAO);

            if (highResAO != null)
                cmd.SetComputeTextureParam(cs, kernel, "HiResAO", highResAO.Value);

            cmd.SetComputeTextureParam(cs, kernel, "AoResult", dest);

            int xcount = ((int)highResDepthSize.x + 17) / 16;
            int ycount = ((int)highResDepthSize.y + 17) / 16;
            cmd.DispatchCompute(cs, kernel, xcount, ycount, 1);
        }

        void PushReleaseCommands(CommandBuffer cmd)
        {
            Release(cmd, ShaderIDs.LinearDepth);

            Release(cmd, ShaderIDs.LowDepth1);
            Release(cmd, ShaderIDs.LowDepth1);
            Release(cmd, ShaderIDs.LowDepth1);
            Release(cmd, ShaderIDs.LowDepth1);

            Release(cmd, ShaderIDs.TiledDepth1);
            Release(cmd, ShaderIDs.TiledDepth2);
            Release(cmd, ShaderIDs.TiledDepth3);
            Release(cmd, ShaderIDs.TiledDepth4);

            Release(cmd, ShaderIDs.Occlusion1);
            Release(cmd, ShaderIDs.Occlusion2);
            Release(cmd, ShaderIDs.Occlusion3);
            Release(cmd, ShaderIDs.Occlusion4);

            Release(cmd, ShaderIDs.Combined1);
            Release(cmd, ShaderIDs.Combined2);
            Release(cmd, ShaderIDs.Combined3);
        }

        void PreparePropertySheet(PostProcessRenderContext context)
        {
            var sheet = context.propertySheets.Get(m_Resources.shaders.multiScaleAO);
            sheet.ClearKeywords();
            sheet.properties.SetVector(ShaderIDs.AOColor, Color.white - m_Settings.color.value);
            m_PropertySheet = sheet;
        }

        void CheckAOTexture(PostProcessRenderContext context)
        {
            if (m_AmbientOnlyAO == null || !m_AmbientOnlyAO.IsCreated() || m_AmbientOnlyAO.width != context.width || m_AmbientOnlyAO.height != context.height)
            {
                RuntimeUtilities.Destroy(m_AmbientOnlyAO);

                m_AmbientOnlyAO = new RenderTexture(context.width, context.height, 0, RenderTextureFormat.R8, RenderTextureReadWrite.Linear)
                {
                    hideFlags = HideFlags.DontSave,
                    filterMode = FilterMode.Point,
                    enableRandomWrite = true
                };
                m_AmbientOnlyAO.Create();
            }
        }

        void PushDebug(PostProcessRenderContext context)
        {
            if (context.IsDebugOverlayEnabled(DebugOverlay.AmbientOcclusion))
                context.PushDebugOverlay(context.command, m_AmbientOnlyAO, m_PropertySheet, (int)Pass.DebugOverlay);
        }

        public void RenderAfterOpaque(PostProcessRenderContext context)
        {
            var cmd = context.command;
            cmd.BeginSample("Ambient Occlusion");
            SetResources(context.resources);
            PreparePropertySheet(context);
            CheckAOTexture(context);

            // In Forward mode, fog is applied at the object level in the grometry pass so we need
            // to apply it to AO as well or it'll drawn on top of the fog effect.
            if (context.camera.actualRenderingPath == RenderingPath.Forward && RenderSettings.fog)
            {
                m_PropertySheet.EnableKeyword("APPLY_FORWARD_FOG");
                m_PropertySheet.properties.SetVector(
                    ShaderIDs.FogParams,
                    new Vector3(RenderSettings.fogDensity, RenderSettings.fogStartDistance, RenderSettings.fogEndDistance)
                );
            }

            GenerateAOMap(cmd, context.camera, m_AmbientOnlyAO, null, false);
            PushDebug(context);
            cmd.SetGlobalTexture(ShaderIDs.MSVOcclusionTexture, m_AmbientOnlyAO);
            cmd.BlitFullscreenTriangle(BuiltinRenderTextureType.None, BuiltinRenderTextureType.CameraTarget, m_PropertySheet, (int)Pass.CompositionForward);
            cmd.EndSample("Ambient Occlusion");
        }

        public void RenderAmbientOnly(PostProcessRenderContext context)
        {
            var cmd = context.command;
            cmd.BeginSample("Ambient Occlusion Render");
            SetResources(context.resources);
            PreparePropertySheet(context);
            CheckAOTexture(context);
            GenerateAOMap(cmd, context.camera, m_AmbientOnlyAO, null, false);
            PushDebug(context);
            cmd.EndSample("Ambient Occlusion Render");
        }

        public void CompositeAmbientOnly(PostProcessRenderContext context)
        {
            var cmd = context.command;
            cmd.BeginSample("Ambient Occlusion Composite");
            cmd.SetGlobalTexture(ShaderIDs.MSVOcclusionTexture, m_AmbientOnlyAO);
            cmd.BlitFullscreenTriangle(BuiltinRenderTextureType.None, m_MRT, BuiltinRenderTextureType.CameraTarget, m_PropertySheet, (int)Pass.CompositionDeferred);
            cmd.EndSample("Ambient Occlusion Composite");
        }

        public void Release()
        {
            RuntimeUtilities.Destroy(m_AmbientOnlyAO);
            m_AmbientOnlyAO = null;
        }
    }
#else
    [Serializable]
    public sealed class MultiScaleVO : IAmbientOcclusionMethod
    {
        public MultiScaleVO(AmbientOcclusion settings)
        {
        }

        public void SetResources(PostProcessResources resources)
        {
        }

        public DepthTextureMode GetCameraFlags()
        {
            return DepthTextureMode.None;
        }

        public void GenerateAOMap(CommandBuffer cmd, Camera camera, RenderTargetIdentifier destination, RenderTargetIdentifier? depthMap, bool invert)
        {
        }

        public void RenderAfterOpaque(PostProcessRenderContext context)
        {
        }

        public void RenderAmbientOnly(PostProcessRenderContext context)
        {
        }

        public void CompositeAmbientOnly(PostProcessRenderContext context)
        {
        }

        public void Release()
        {
        }
    }
#endif
}


text:
from django import forms
from django.forms.widgets import media_property

__all__ = ['Select',
           'Textarea',
           'TextInput',
           'CheckboxInput',
           'HiddenInput',
           'PasswordInput',
           'media_property']

Select    = forms.Select
Textarea  = forms.Textarea
TextInput = forms.TextInput
CheckboxInput = forms.CheckboxInput
HiddenInput = forms.HiddenInput
PasswordInput = forms.PasswordInput


text:
var matchHTML = require('../debug');

it("doesn't care for line breaks", function() {
  const expected = "<!DOCTYPE html>\n";
  const given = '<!DOCTYPE html>';

  expect(matchHTML(expected, given)).toEqual(true);
});

it("knows how to handle comments", function() {
  const expected = "<!DOCTYPE html>\n<!-- Isso é um comentário -->";
  const given = "<!DOCTYPE html>\n<!-- Isso é um comentário -->";

  expect(matchHTML(expected, given)).toEqual(true);
});

it("knows how to handle empty inputs", function() {
  const expected = "<!DOCTYPE html>\n";

  expect(matchHTML(expected, undefined)).toEqual(false);
  expect(matchHTML(expected, null)).toEqual(false);
  expect(matchHTML(expected, '')).toEqual(false);
});


text:
Game Editor for [Mario Revolution](https://github.com/JKord/MarioRevolution/releases/tag/v1.0)

### About
[Instruction](https://github.com/JKord/MarioRevolution/blob/master/Instruction.pdf)

### Version
1.0

### Installation
[Designer-Level.zip](https://github.com/JKord/DesignerLevelForMarioRevolution/releases/tag/v1.0) -> Designer Level.exe

License
----
[MIT](../master/LICENSE)

**Copyright (c) 2011 Jura**


text:
require 'spec_helper'

describe Gitlab::GithubImport::Importer::DiffNoteImporter do
  let(:project) { create(:project) }
  let(:client) { double(:client) }
  let(:user) { create(:user) }
  let(:created_at) { Time.new(2017, 1, 1, 12, 00) }
  let(:updated_at) { Time.new(2017, 1, 1, 12, 15) }

  let(:hunk) do
    '@@ -1 +1 @@
    -Hello
    +Hello world'
  end

  let(:note) do
    Gitlab::GithubImport::Representation::DiffNote.new(
      noteable_type: 'MergeRequest',
      noteable_id: 1,
      commit_id: '123abc',
      file_path: 'README.md',
      diff_hunk: hunk,
      author: Gitlab::GithubImport::Representation::User
        .new(id: user.id, login: user.username),
      note: 'Hello',
      created_at: created_at,
      updated_at: updated_at,
      github_id: 1
    )
  end

  let(:importer) { described_class.new(note, project, client) }

  describe '#execute' do
    context 'when the merge request no longer exists' do
      it 'does not import anything' do
        expect(Gitlab::Database).not_to receive(:bulk_insert)

        importer.execute
      end
    end

    context 'when the merge request exists' do
      let!(:merge_request) do
        create(:merge_request, source_project: project, target_project: project)
      end

      before do
        allow(importer)
          .to receive(:find_merge_request_id)
          .and_return(merge_request.id)
      end

      it 'imports the note' do
        allow(importer.user_finder)
          .to receive(:author_id_for)
          .and_return([user.id, true])

        expect(Gitlab::Database)
          .to receive(:bulk_insert)
          .with(
            LegacyDiffNote.table_name,
            [
              {
                noteable_type: 'MergeRequest',
                noteable_id: merge_request.id,
                project_id: project.id,
                author_id: user.id,
                note: 'Hello',
                system: false,
                commit_id: '123abc',
                line_code: note.line_code,
                type: 'LegacyDiffNote',
                created_at: created_at,
                updated_at: updated_at,
                st_diff: note.diff_hash.to_yaml
              }
            ]
          )
          .and_call_original

        importer.execute
      end

      it 'imports the note when the author could not be found' do
        allow(importer.user_finder)
          .to receive(:author_id_for)
          .and_return([project.creator_id, false])

        expect(Gitlab::Database)
          .to receive(:bulk_insert)
          .with(
            LegacyDiffNote.table_name,
            [
              {
                noteable_type: 'MergeRequest',
                noteable_id: merge_request.id,
                project_id: project.id,
                author_id: project.creator_id,
                note: "*Created by: #{user.username}*\n\nHello",
                system: false,
                commit_id: '123abc',
                line_code: note.line_code,
                type: 'LegacyDiffNote',
                created_at: created_at,
                updated_at: updated_at,
                st_diff: note.diff_hash.to_yaml
              }
            ]
          )
          .and_call_original

        importer.execute
      end

      it 'produces a valid LegacyDiffNote' do
        allow(importer.user_finder)
          .to receive(:author_id_for)
          .and_return([user.id, true])

        importer.execute

        note = project.notes.diff_notes.take

        expect(note).to be_valid
        expect(note.diff).to be_an_instance_of(Gitlab::Git::Diff)
      end

      it 'does not import the note when a foreign key error is raised' do
        allow(importer.user_finder)
          .to receive(:author_id_for)
          .and_return([project.creator_id, false])

        expect(Gitlab::Database)
          .to receive(:bulk_insert)
          .and_raise(ActiveRecord::InvalidForeignKey, 'invalid foreign key')

        expect { importer.execute }.not_to raise_error
      end
    end
  end

  describe '#find_merge_request_id' do
    it 'returns a merge request ID' do
      expect_any_instance_of(Gitlab::GithubImport::IssuableFinder)
        .to receive(:database_id)
        .and_return(10)

      expect(importer.find_merge_request_id).to eq(10)
    end
  end
end


text:
module Rack
  class Request
    def subdomains(tld_len=1) # we set tld_len to 1, use 2 for co.uk or similar
      # cache the result so we only compute it once.
      @env['rack.env.subdomains'] ||= lambda {
        # check if the current host is an IP address, if so return an empty array
        return [] if (host.nil? ||
                      /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.match(host))
        host.split('.')[0...(1 - tld_len - 2)] # pull everything except the TLD
      }.call
    end
  end
end

module Magis
  include Mongo
  @@home_folder = ""
  def self.framework_path
    @@local_path ||= File.expand_path("../../", File.dirname(__FILE__))
  end
  def self.file(filename)
    local_path = self.framework_path
    project_path = File.expand_path(self.home_folder)

    file_contents = nil
    full_file_name = project_path + filename

    if File.file?(full_file_name)
      file_contents = File.new(full_file_name).readlines
    elsif File.file?(local_path + filename)
      full_file_name = local_path + filename
      file_contents = File.new(full_file_name).readlines
    end

    file_contents
  end

  def self.application
    Api
  end

  def self.env
    @@environment ||= ENV['RACK_ENV']
    setup ||= @@environment == "setup"
    production ||= @@environment == "production"
    development ||= @@environment == "development"
    test ||= @@environment == "test"
    @environments ||= OpenStruct.new({
      setup?: setup,
      production?: production,
      development?: development,
      test?: test
    })
    @environments
  end

  def self.home_folder
    Dir.pwd
  end

  def self.set_db
    uri = ENV["DB_URI"] || Magis.load_configuration("database")["uri"]

    if uri
      client = MongoClient.from_uri(uri)
    else
      client = MongoClient.new
    end

    db_name = ENV["DB_NAME"] || Magis.load_configuration("database")["name"]

    @@db = client[db_name]
  end

  def self.db
    @@db
  end

  def self.load_collection(file)
    if File.exist?(home_folder + "/collections/" + file + ".yml")
      YAML.load_file(home_folder + "/collections/" + file + ".yml")
    else
      Hash.new
    end
  end

  def self.load_configuration(file)
    @@files ||= Hash.new
    if File.exist?(home_folder + "/config/" + file + ".yml")
      @@files[file] ||= YAML.load_file(home_folder + "/config/" + file + ".yml")
    else
      Hash.new
    end
  end

  def self.omni_auth_config(type)
    configuration = self.load_configuration(type)
    configuration[:id] ||= nil
    configuration[:secret] ||= nil

    configuration
  end

  def self.start
    Dir["/api/*.rb"].each {|file| require file }
    self.set_db
  end
end


text:
#ifndef IVW_RAWVOLUMERAMLOADER_H
#define IVW_RAWVOLUMERAMLOADER_H

#include <inviwo/core/common/inviwocoredefine.h>
#include <inviwo/core/common/inviwo.h>
#include <inviwo/core/io/bytereaderutil.h>
#include <inviwo/core/io/datareaderexception.h>
#include <inviwo/core/datastructures/diskrepresentation.h>
#include <inviwo/core/datastructures/volume/volumeramprecision.h>

namespace inviwo {

/**
 * \class RawVolumeRAMLoader
 *
 * \brief A loader of raw files. Used to create VolumeRAM representations.
 *
 * This class us used by the DatVolumeReader, IvfVolumeReader and RawVolumeReader.
 */

class IVW_CORE_API RawVolumeRAMLoader : public DiskRepresentationLoader {
public:
    RawVolumeRAMLoader(const std::string& rawFile, size_t offset, size3_t dimensions,
                       bool littleEndian, const DataFormatBase* format);
    virtual RawVolumeRAMLoader* clone() const override;
    virtual std::shared_ptr<DataRepresentation> createRepresentation() const override;
    virtual void updateRepresentation(std::shared_ptr<DataRepresentation> dest) const override;

    using type = std::shared_ptr<VolumeRAM>;

    template <class T>
    std::shared_ptr<VolumeRAM> dispatch() const {
        typedef typename T::type F;

        std::size_t size = dimensions_.x * dimensions_.y * dimensions_.z;
        auto data = util::make_unique<F[]>(size);

        if (!data) {
            throw DataReaderException(
                "Error: Could not allocate memory for loading raw file: " + rawFile_, IvwContext);
        }

        util::readBytesIntoBuffer(rawFile_, offset_, size * format_->getSize(), littleEndian_,
                                  format_->getSize(), data.get());

        auto repr = std::make_shared<VolumeRAMPrecision<F>>(data.get(), dimensions_);
        data.release();
        return repr;
    }

private:
    std::string rawFile_;
    size_t offset_;
    size3_t dimensions_;
    bool littleEndian_;
    const DataFormatBase* format_;
};

}  // namespace

#endif  // IVW_RAWVOLUMERAMLOADER_H


text:
package brooklyn.networking.sdn;

import java.net.InetAddress;
import java.util.Collections;
import java.util.concurrent.Callable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Optional;
import com.google.common.collect.Iterables;

import org.apache.brooklyn.api.entity.Entity;
import org.apache.brooklyn.api.entity.EntityLocal;
import org.apache.brooklyn.api.entity.EntitySpec;
import org.apache.brooklyn.api.mgmt.Task;
import org.apache.brooklyn.core.config.render.RendererHints;
import org.apache.brooklyn.core.entity.Entities;
import org.apache.brooklyn.core.entity.EntityPredicates;
import org.apache.brooklyn.core.feed.ConfigToAttributes;
import org.apache.brooklyn.entity.group.DynamicGroup;
import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
import org.apache.brooklyn.entity.stock.DelegateEntity;
import org.apache.brooklyn.util.core.task.DynamicTasks;
import org.apache.brooklyn.util.core.task.TaskBuilder;
import org.apache.brooklyn.util.net.Cidr;
import org.apache.brooklyn.util.repeat.Repeater;
import org.apache.brooklyn.util.time.Duration;

import brooklyn.entity.container.docker.DockerHost;
import brooklyn.entity.container.docker.DockerInfrastructure;
import brooklyn.networking.VirtualNetwork;

/**
 * An SDN agent process on a Docker host.
 */
public abstract class SdnAgentImpl extends SoftwareProcessImpl implements SdnAgent {

    private static final Logger LOG = LoggerFactory.getLogger(SdnAgent.class);

    @Override
    public void init() {
        super.init();

        ConfigToAttributes.apply(this, DOCKER_HOST);
        ConfigToAttributes.apply(this, SDN_PROVIDER);
    }

    @Override
    public SdnAgentDriver getDriver() {
        return (SdnAgentDriver) super.getDriver();
    }

    @Override
    protected void connectSensors() {
        super.connectSensors();
        super.connectServiceUpIsRunning();
    }

    @Override
    public void disconnectSensors() {
        super.disconnectServiceUpIsRunning();
        super.disconnectSensors();
    }

    @Override
    public DockerHost getDockerHost() {
        return sensors().get(DOCKER_HOST);
    }

    @Override
    public void preStart() {
        InetAddress address = sensors().get(SDN_PROVIDER).getNextAgentAddress(getId());
        sensors().set(SDN_AGENT_ADDRESS, address);
    }

    @Override
    public void postStart() {
        ((EntityLocal) getDockerHost()).sensors().set(SDN_AGENT, this);
    }

    @Override
    public void rebind() {
        super.rebind();
        // TODO implement custom SDN agent rebind logic
    }

    @Override
    public InetAddress attachNetwork(String containerId, final String networkId) {
        final SdnProvider provider = sensors().get(SDN_PROVIDER);
        boolean createNetwork = false;
        Cidr subnetCidr = null;
        synchronized (provider.getNetworkMutex()) {
            subnetCidr = provider.getSubnetCidr(networkId);
            if (subnetCidr == null) {
                subnetCidr = provider.getNextSubnetCidr(networkId);
                createNetwork = true;
            }
        }
        if (createNetwork) {
            // Get a CIDR for the subnet from the availabkle pool and create a virtual network
            EntitySpec<VirtualNetwork> networkSpec = EntitySpec.create(VirtualNetwork.class)
                    .configure(VirtualNetwork.NETWORK_ID, networkId)
                    .configure(VirtualNetwork.NETWORK_CIDR, subnetCidr);

            // Start and then add this virtual network as a child of SDN_NETWORKS
            VirtualNetwork network = provider.sensors().get(SdnProvider.SDN_NETWORKS).addChild(networkSpec);
            Entities.manage(network);
            Entities.start(network, Collections.singleton(((DockerInfrastructure) provider.sensors().get(SdnProvider.DOCKER_INFRASTRUCTURE)).getDynamicLocation()));
            Entities.waitForServiceUp(network);
        } else {
            Task<Boolean> lookup = TaskBuilder.<Boolean> builder()
                    .name("Waiting until virtual network is available")
                    .body(new Callable<Boolean>() {
                        @Override
                        public Boolean call() throws Exception {
                            return Repeater.create()
                                    .every(Duration.TEN_SECONDS)
                                    .until(new Callable<Boolean>() {
                                        public Boolean call() {
                                            Optional<Entity> found = Iterables.tryFind(provider.sensors().get(SdnProvider.SDN_NETWORKS).getMembers(),
                                                    EntityPredicates.attributeEqualTo(VirtualNetwork.NETWORK_ID, networkId));
                                            return found.isPresent();
                                        }
                                    })
                                    .limitTimeTo(Duration.ONE_MINUTE)
                                    .run();
                        }
                    })
                    .build();
            Boolean result = DynamicTasks.queueIfPossible(lookup)
                    .orSubmitAndBlock()
                    .andWaitForSuccess();
            if (!result) {
                throw new IllegalStateException(String.format("Cannot find virtual network entity for %s", networkId));
            }
        }

        InetAddress address = getDriver().attachNetwork(containerId, networkId);
        LOG.info("Attached container ID {} to {}: {}", new Object[] { containerId, networkId,  address.getHostAddress() });

        // Rescan SDN network groups for containers
        DynamicGroup network = (DynamicGroup) Iterables.find(provider.sensors().get(SdnProvider.SDN_APPLICATIONS).getMembers(),
                EntityPredicates.attributeEqualTo(VirtualNetwork.NETWORK_ID, networkId));
        network.rescanEntities();

        return address;
    }

    @Override
    public String provisionNetwork(VirtualNetwork network) {
        String networkId = network.sensors().get(VirtualNetwork.NETWORK_ID);

        // Record the network CIDR being provisioned, allocating if required
        Cidr subnetCidr = network.config().get(VirtualNetwork.NETWORK_CIDR);
        if (subnetCidr == null) {
            subnetCidr = sensors().get(SDN_PROVIDER).getNextSubnetCidr(networkId);
        } else {
            sensors().get(SDN_PROVIDER).recordSubnetCidr(networkId, subnetCidr);
        }
        ((EntityLocal) network).sensors().set(VirtualNetwork.NETWORK_CIDR, subnetCidr);

        // Create the netwoek using the SDN driver
        getDriver().createSubnet(network.getId(), networkId, subnetCidr);

        return networkId;
    }

    static {
        RendererHints.register(DOCKER_HOST, new RendererHints.NamedActionWithUrl("Open", DelegateEntity.EntityUrl.entityUrl()));
        RendererHints.register(SDN_PROVIDER, new RendererHints.NamedActionWithUrl("Open", DelegateEntity.EntityUrl.entityUrl()));
        RendererHints.register(SDN_AGENT, new RendererHints.NamedActionWithUrl("Open", DelegateEntity.EntityUrl.entityUrl()));
    }

}


text:
package com.netflix.genie.common.exceptions;

import java.net.HttpURLConnection;

/**
 * Extension of a GenieException for all internal server failures.
 *
 * @author tgianos
 */
public class GenieServerException extends GenieException {

    /**
     * Constructor.
     *
     * @param msg   human readable message
     * @param cause reason for this exception
     */
    public GenieServerException(final String msg, final Throwable cause) {
        super(HttpURLConnection.HTTP_INTERNAL_ERROR, msg, cause);
    }

    /**
     * Constructor.
     *
     * @param msg human readable message
     */
    public GenieServerException(final String msg) {
        super(HttpURLConnection.HTTP_INTERNAL_ERROR, msg);
    }
}


text:
package br.usp.ime.academicdevoir.infra;

public class Constantes {
    public static final int MAX_TAM_CAMPO = 1000000000;
    public static final int NUM_REGISTROS_PAGINA = 200;
}


text: <title>can/map/app</title>


text:
package machinelearningservices

import (
	"context"

	original "github.com/Azure/azure-sdk-for-go/services/machinelearningservices/mgmt/2019-05-01/machinelearningservices"
)

const (
	DefaultBaseURI = original.DefaultBaseURI
)

type AllocationState = original.AllocationState

const (
	Resizing AllocationState = original.Resizing
	Steady   AllocationState = original.Steady
)

type ComputeType = original.ComputeType

const (
	ComputeTypeAKS               ComputeType = original.ComputeTypeAKS
	ComputeTypeAmlCompute        ComputeType = original.ComputeTypeAmlCompute
	ComputeTypeDatabricks        ComputeType = original.ComputeTypeDatabricks
	ComputeTypeDataFactory       ComputeType = original.ComputeTypeDataFactory
	ComputeTypeDataLakeAnalytics ComputeType = original.ComputeTypeDataLakeAnalytics
	ComputeTypeHDInsight         ComputeType = original.ComputeTypeHDInsight
	ComputeTypeVirtualMachine    ComputeType = original.ComputeTypeVirtualMachine
)

type ComputeTypeBasicCompute = original.ComputeTypeBasicCompute

const (
	ComputeTypeAKS1               ComputeTypeBasicCompute = original.ComputeTypeAKS1
	ComputeTypeAmlCompute1        ComputeTypeBasicCompute = original.ComputeTypeAmlCompute1
	ComputeTypeCompute            ComputeTypeBasicCompute = original.ComputeTypeCompute
	ComputeTypeDatabricks1        ComputeTypeBasicCompute = original.ComputeTypeDatabricks1
	ComputeTypeDataFactory1       ComputeTypeBasicCompute = original.ComputeTypeDataFactory1
	ComputeTypeDataLakeAnalytics1 ComputeTypeBasicCompute = original.ComputeTypeDataLakeAnalytics1
	ComputeTypeHDInsight1         ComputeTypeBasicCompute = original.ComputeTypeHDInsight1
	ComputeTypeVirtualMachine1    ComputeTypeBasicCompute = original.ComputeTypeVirtualMachine1
)

type ComputeTypeBasicComputeNodesInformation = original.ComputeTypeBasicComputeNodesInformation

const (
	ComputeTypeBasicComputeNodesInformationComputeTypeAmlCompute              ComputeTypeBasicComputeNodesInformation = original.ComputeTypeBasicComputeNodesInformationComputeTypeAmlCompute
	ComputeTypeBasicComputeNodesInformationComputeTypeComputeNodesInformation ComputeTypeBasicComputeNodesInformation = original.ComputeTypeBasicComputeNodesInformationComputeTypeComputeNodesInformation
)

type ComputeTypeBasicComputeSecrets = original.ComputeTypeBasicComputeSecrets

const (
	ComputeTypeBasicComputeSecretsComputeTypeAKS            ComputeTypeBasicComputeSecrets = original.ComputeTypeBasicComputeSecretsComputeTypeAKS
	ComputeTypeBasicComputeSecretsComputeTypeComputeSecrets ComputeTypeBasicComputeSecrets = original.ComputeTypeBasicComputeSecretsComputeTypeComputeSecrets
	ComputeTypeBasicComputeSecretsComputeTypeDatabricks     ComputeTypeBasicComputeSecrets = original.ComputeTypeBasicComputeSecretsComputeTypeDatabricks
	ComputeTypeBasicComputeSecretsComputeTypeVirtualMachine ComputeTypeBasicComputeSecrets = original.ComputeTypeBasicComputeSecretsComputeTypeVirtualMachine
)

type ProvisioningState = original.ProvisioningState

const (
	Canceled  ProvisioningState = original.Canceled
	Creating  ProvisioningState = original.Creating
	Deleting  ProvisioningState = original.Deleting
	Failed    ProvisioningState = original.Failed
	Succeeded ProvisioningState = original.Succeeded
	Unknown   ProvisioningState = original.Unknown
	Updating  ProvisioningState = original.Updating
)

type ResourceIdentityType = original.ResourceIdentityType

const (
	SystemAssigned ResourceIdentityType = original.SystemAssigned
)

type Status = original.Status

const (
	Disabled Status = original.Disabled
	Enabled  Status = original.Enabled
)

type UnderlyingResourceAction = original.UnderlyingResourceAction

const (
	Delete UnderlyingResourceAction = original.Delete
	Detach UnderlyingResourceAction = original.Detach
)

type UsageUnit = original.UsageUnit

const (
	Count UsageUnit = original.Count
)

type VMPriority = original.VMPriority

const (
	Dedicated   VMPriority = original.Dedicated
	LowPriority VMPriority = original.LowPriority
)

type AKS = original.AKS
type AKSProperties = original.AKSProperties
type AksComputeSecrets = original.AksComputeSecrets
type AksNetworkingConfiguration = original.AksNetworkingConfiguration
type AmlCompute = original.AmlCompute
type AmlComputeNodeInformation = original.AmlComputeNodeInformation
type AmlComputeNodesInformation = original.AmlComputeNodesInformation
type AmlComputeProperties = original.AmlComputeProperties
type BaseClient = original.BaseClient
type BasicCompute = original.BasicCompute
type BasicComputeNodesInformation = original.BasicComputeNodesInformation
type BasicComputeSecrets = original.BasicComputeSecrets
type ClusterUpdateParameters = original.ClusterUpdateParameters
type ClusterUpdateProperties = original.ClusterUpdateProperties
type Compute = original.Compute
type ComputeNodesInformation = original.ComputeNodesInformation
type ComputeResource = original.ComputeResource
type ComputeSecrets = original.ComputeSecrets
type ComputeSecretsModel = original.ComputeSecretsModel
type DataFactory = original.DataFactory
type DataLakeAnalytics = original.DataLakeAnalytics
type DataLakeAnalyticsProperties = original.DataLakeAnalyticsProperties
type Databricks = original.Databricks
type DatabricksComputeSecrets = original.DatabricksComputeSecrets
type DatabricksProperties = original.DatabricksProperties
type Error = original.Error
type ErrorDetail = original.ErrorDetail
type ErrorResponse = original.ErrorResponse
type HDInsight = original.HDInsight
type HDInsightProperties = original.HDInsightProperties
type Identity = original.Identity
type ListUsagesResult = original.ListUsagesResult
type ListUsagesResultIterator = original.ListUsagesResultIterator
type ListUsagesResultPage = original.ListUsagesResultPage
type ListWorkspaceKeysResult = original.ListWorkspaceKeysResult
type MachineLearningComputeClient = original.MachineLearningComputeClient
type MachineLearningComputeCreateOrUpdateFuture = original.MachineLearningComputeCreateOrUpdateFuture
type MachineLearningComputeDeleteFuture = original.MachineLearningComputeDeleteFuture
type MachineLearningComputeUpdateFuture = original.MachineLearningComputeUpdateFuture
type NodeStateCounts = original.NodeStateCounts
type Operation = original.Operation
type OperationDisplay = original.OperationDisplay
type OperationListResult = original.OperationListResult
type OperationsClient = original.OperationsClient
type PaginatedComputeResourcesList = original.PaginatedComputeResourcesList
type PaginatedComputeResourcesListIterator = original.PaginatedComputeResourcesListIterator
type PaginatedComputeResourcesListPage = original.PaginatedComputeResourcesListPage
type Password = original.Password
type RegistryListCredentialsResult = original.RegistryListCredentialsResult
type Resource = original.Resource
type ResourceID = original.ResourceID
type ScaleSettings = original.ScaleSettings
type ServicePrincipalCredentials = original.ServicePrincipalCredentials
type SslConfiguration = original.SslConfiguration
type SystemService = original.SystemService
type Usage = original.Usage
type UsageName = original.UsageName
type UsagesClient = original.UsagesClient
type UserAccountCredentials = original.UserAccountCredentials
type VirtualMachine = original.VirtualMachine
type VirtualMachineProperties = original.VirtualMachineProperties
type VirtualMachineSSHCredentials = original.VirtualMachineSSHCredentials
type VirtualMachineSecrets = original.VirtualMachineSecrets
type VirtualMachineSize = original.VirtualMachineSize
type VirtualMachineSizeListResult = original.VirtualMachineSizeListResult
type VirtualMachineSizesClient = original.VirtualMachineSizesClient
type Workspace = original.Workspace
type WorkspaceListResult = original.WorkspaceListResult
type WorkspaceListResultIterator = original.WorkspaceListResultIterator
type WorkspaceListResultPage = original.WorkspaceListResultPage
type WorkspaceProperties = original.WorkspaceProperties
type WorkspacePropertiesUpdateParameters = original.WorkspacePropertiesUpdateParameters
type WorkspaceUpdateParameters = original.WorkspaceUpdateParameters
type WorkspacesClient = original.WorkspacesClient

func New(subscriptionID string) BaseClient {
	return original.New(subscriptionID)
}
func NewListUsagesResultIterator(page ListUsagesResultPage) ListUsagesResultIterator {
	return original.NewListUsagesResultIterator(page)
}
func NewListUsagesResultPage(getNextPage func(context.Context, ListUsagesResult) (ListUsagesResult, error)) ListUsagesResultPage {
	return original.NewListUsagesResultPage(getNextPage)
}
func NewMachineLearningComputeClient(subscriptionID string) MachineLearningComputeClient {
	return original.NewMachineLearningComputeClient(subscriptionID)
}
func NewMachineLearningComputeClientWithBaseURI(baseURI string, subscriptionID string) MachineLearningComputeClient {
	return original.NewMachineLearningComputeClientWithBaseURI(baseURI, subscriptionID)
}
func NewOperationsClient(subscriptionID string) OperationsClient {
	return original.NewOperationsClient(subscriptionID)
}
func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient {
	return original.NewOperationsClientWithBaseURI(baseURI, subscriptionID)
}
func NewPaginatedComputeResourcesListIterator(page PaginatedComputeResourcesListPage) PaginatedComputeResourcesListIterator {
	return original.NewPaginatedComputeResourcesListIterator(page)
}
func NewPaginatedComputeResourcesListPage(getNextPage func(context.Context, PaginatedComputeResourcesList) (PaginatedComputeResourcesList, error)) PaginatedComputeResourcesListPage {
	return original.NewPaginatedComputeResourcesListPage(getNextPage)
}
func NewUsagesClient(subscriptionID string) UsagesClient {
	return original.NewUsagesClient(subscriptionID)
}
func NewUsagesClientWithBaseURI(baseURI string, subscriptionID string) UsagesClient {
	return original.NewUsagesClientWithBaseURI(baseURI, subscriptionID)
}
func NewVirtualMachineSizesClient(subscriptionID string) VirtualMachineSizesClient {
	return original.NewVirtualMachineSizesClient(subscriptionID)
}
func NewVirtualMachineSizesClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineSizesClient {
	return original.NewVirtualMachineSizesClientWithBaseURI(baseURI, subscriptionID)
}
func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {
	return original.NewWithBaseURI(baseURI, subscriptionID)
}
func NewWorkspaceListResultIterator(page WorkspaceListResultPage) WorkspaceListResultIterator {
	return original.NewWorkspaceListResultIterator(page)
}
func NewWorkspaceListResultPage(getNextPage func(context.Context, WorkspaceListResult) (WorkspaceListResult, error)) WorkspaceListResultPage {
	return original.NewWorkspaceListResultPage(getNextPage)
}
func NewWorkspacesClient(subscriptionID string) WorkspacesClient {
	return original.NewWorkspacesClient(subscriptionID)
}
func NewWorkspacesClientWithBaseURI(baseURI string, subscriptionID string) WorkspacesClient {
	return original.NewWorkspacesClientWithBaseURI(baseURI, subscriptionID)
}
func PossibleAllocationStateValues() []AllocationState {
	return original.PossibleAllocationStateValues()
}
func PossibleComputeTypeBasicComputeNodesInformationValues() []ComputeTypeBasicComputeNodesInformation {
	return original.PossibleComputeTypeBasicComputeNodesInformationValues()
}
func PossibleComputeTypeBasicComputeSecretsValues() []ComputeTypeBasicComputeSecrets {
	return original.PossibleComputeTypeBasicComputeSecretsValues()
}
func PossibleComputeTypeBasicComputeValues() []ComputeTypeBasicCompute {
	return original.PossibleComputeTypeBasicComputeValues()
}
func PossibleComputeTypeValues() []ComputeType {
	return original.PossibleComputeTypeValues()
}
func PossibleProvisioningStateValues() []ProvisioningState {
	return original.PossibleProvisioningStateValues()
}
func PossibleResourceIdentityTypeValues() []ResourceIdentityType {
	return original.PossibleResourceIdentityTypeValues()
}
func PossibleStatusValues() []Status {
	return original.PossibleStatusValues()
}
func PossibleUnderlyingResourceActionValues() []UnderlyingResourceAction {
	return original.PossibleUnderlyingResourceActionValues()
}
func PossibleUsageUnitValues() []UsageUnit {
	return original.PossibleUsageUnitValues()
}
func PossibleVMPriorityValues() []VMPriority {
	return original.PossibleVMPriorityValues()
}
func UserAgent() string {
	return original.UserAgent() + " profiles/preview"
}
func Version() string {
	return original.Version()
}


text: R CMD REMOVE --library=$PREFIX/lib/R/library/ RNAmodR.Data


text:
module Populator
  module Adapters
    module Abstract
      # Executes multiple SQL statements in one query when joined with ";"
      def execute_batch(sql, name = nil)
        raise NotImplementedError, "execute_batch is an abstract method"
      end

      def populate(table, columns, rows, name = nil)
        execute("INSERT INTO #{table} #{columns} VALUES #{rows.join(', ')}", name)
      end
    end
  end
end

ActiveRecord::ConnectionAdapters::AbstractAdapter.class_eval do
  include Populator::Adapters::Abstract
end


text:
'use strict';

// Instructors controller
angular.module('instructors').controller('InstructorsController', ['$scope', 'Assessment', 'Camp', '$upload', '$stateParams', '$location', 'Authentication', '$http',
    function($scope, Assessment, Camp, $upload, $stateParams, $location, Authentication, $http) {
        $scope.user = Authentication.user;

        // instructor signin
        $scope.instructor_signin = function() {
            $http.post('/auth/signin', $scope.credentials).success(function(response) {

                // If successful we assign the response to the global user model
                $scope.user = response;

                // And redirect to the right page
                if ($scope.user.role === 'instructor') {
                    $location.path('/instructors/home');
                } else {
                    $location.path('/');
                }
            }).error(function(response) {
                $scope.error = response.message;
                $location.path('/');
            });
        };

        // instructor's home page
        $scope.instructorHome = function() {
            if (!$scope.user) {
                $location.path('/');
            }
        };

        // list all bootcamps
        $scope.listBootcamps = function() {
            Camp.query(function success(response) {
                    $scope.success = true;
                    $scope.bootcamps = response;
                    $scope.traineeCountArr = [];

                    for (var i in $scope.bootcamps) {
                        var traineeCount = 0;

                        for (var j in $scope.bootcamps[i].applicants) {
                            if ($scope.bootcamps[i].applicants[j].role === 'trainee') {
                                traineeCount += 1;
                            }
                        }
                        $scope.traineeCountArr.push(traineeCount);
                    }
                },
                function(error) {
                    $scope.error = error.message;
                });
        };

        // viewing only a particular bootcamp
        $scope.viewBootcamp = function() {
            $scope.error = false;
            if ($stateParams.bootcampId.length === 0) {
                $scope.error = true;
            } else {
                Camp.get({
                        campId: $stateParams.bootcampId
                    },
                    function success(response) {
                        $scope.bootcamp = response;
                        $scope.applicants = $scope.bootcamp.applicants;
                    },
                    function(error) {
                        $scope.error = true;
                    }
                );
            }
        };

        // filter to get only trainees
        $scope.onlyTrainees = function(applicant) {
            return applicant.role === 'trainee';
        };

        // list all trainees
        $scope.listTrainees = function() {
            $http.get('/instructor/trainees').success(function(response) {
                $scope.success = true;
                $scope.trainees = response;
            }).error(function(response) {
                $scope.error = response.message;
            });
        };

        // view a particular trainee
        $scope.viewTrainee = function() {
            if ($stateParams.applicantId === "") {
                $scope.error = true;
            } else {
                Assessment.get({
                        traineeId: $stateParams.applicantId
                    },
                    function success(response) {
                        $scope.success = true;
                        $scope.error = false;
                        $scope.trainee = response;
                        $scope.assessments = $scope.trainee.assessments;
                    },
                    function(error) {
                        $scope.error = true;
                    }
                );
            }
        };

        // list all fellows
        $scope.listFellows = function() {
            $http.get('/instructor/fellows').success(function(response) {
                $scope.success = true;
                $scope.fellows = response;
            }).error(function(response) {
                $scope.error = response.message;
            });
        };

        // view a particular fellow
        $scope.viewFellow = function() {
            if ($stateParams.fellowId.length < 20) {
                $location.path('/');
            } else {
                $http.get('/instructor/trainee/' + $stateParams.fellowId).success(function(response) {
                    $scope.success = true;
                    $scope.fellow = response;
                }).error(function(response) {
                    $scope.error = response.message;
                });
            }
        };

        // show instructor profile picture
        $scope.showImage = function(img) {
            if (img) {
                img = img.substring(6);
                return img;
            } else {
                return 'http://www.localcrimenews.com/wp-content/uploads/2013/07/default-user-icon-profile.png';
            }
        };

        // get assessment
        $scope.getAssessment = function() {
            $scope.error = false;
            Assessment.get({
                    traineeId: $stateParams.applicantId,
                    assmtId: $stateParams.assessmentId
                },
                function success(response) {
                    if (response._id) {
                        $scope.assessment = response;
                        var date = new Date($scope.assessment.assessment_date),
                            year = date.getFullYear(),
                            month = date.getMonth(),
                            day = date.getDate();

                        //month 2 digits
                        month = ("0" + (month + 1)).slice(-2);

                        //year 2 digits
                        year = year.toString().substr(2, 2);

                        $scope.assessment.assessment_date = month + '/' + day + "/" + year;
                    } else {
                        $scope.error = true;
                    }
                },
                function(error) {
                    $scope.error = true;
                }
            );
        };
    }
]);