text:
///btSoftBody implementation by Nathanael Presson

#ifndef _BT_SOFT_BODY_H
#define _BT_SOFT_BODY_H

#include "LinearMath/btAlignedObjectArray.h"
#include "LinearMath/btTransform.h"
#include "LinearMath/btIDebugDraw.h"
#include "LinearMath/btVector3.h"
#include "BulletDynamics/Dynamics/btRigidBody.h"

#include "BulletCollision/CollisionShapes/btConcaveShape.h"
#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h"
#include "btSparseSDF.h"
#include "BulletCollision/BroadphaseCollision/btDbvt.h"
#include "BulletDynamics/Featherstone/btMultiBodyLinkCollider.h"
#include "BulletDynamics/Featherstone/btMultiBodyConstraint.h"
//#ifdef BT_USE_DOUBLE_PRECISION
//#define btRigidBodyData	btRigidBodyDoubleData
//#define btRigidBodyDataName	"btRigidBodyDoubleData"
//#else
#define btSoftBodyData btSoftBodyFloatData
#define btSoftBodyDataName "btSoftBodyFloatData"
static const btScalar OVERLAP_REDUCTION_FACTOR = 0.1;
static unsigned long seed = 243703;
//#endif //BT_USE_DOUBLE_PRECISION

class btBroadphaseInterface;
class btDispatcher;
class btSoftBodySolver;

/* btSoftBodyWorldInfo	*/
struct btSoftBodyWorldInfo
{
	btScalar air_density;
	btScalar water_density;
	btScalar water_offset;
	btScalar m_maxDisplacement;
	btVector3 water_normal;
	btBroadphaseInterface* m_broadphase;
	btDispatcher* m_dispatcher;
	btVector3 m_gravity;
	btSparseSdf<3> m_sparsesdf;

	btSoftBodyWorldInfo()
		: air_density((btScalar)1.2),
		  water_density(0),
		  water_offset(0),
		  m_maxDisplacement(1000.f),  //avoid soft body from 'exploding' so use some upper threshold of maximum motion that a node can travel per frame
		  water_normal(0, 0, 0),
		  m_broadphase(0),
		  m_dispatcher(0),
		  m_gravity(0, -10, 0)
	{
	}
};

///The btSoftBody is an class to simulate cloth and volumetric soft bodies.
///There is two-way interaction between btSoftBody and btRigidBody/btCollisionObject.
class btSoftBody : public btCollisionObject
{
public:
	btAlignedObjectArray<const class btCollisionObject*> m_collisionDisabledObjects;

	// The solver object that handles this soft body
	btSoftBodySolver* m_softBodySolver;

	//
	// Enumerations
	//

	///eAeroModel
	struct eAeroModel
	{
		enum _
		{
			V_Point,             ///Vertex normals are oriented toward velocity
			V_TwoSided,          ///Vertex normals are flipped to match velocity
			V_TwoSidedLiftDrag,  ///Vertex normals are flipped to match velocity and lift and drag forces are applied
			V_OneSided,          ///Vertex normals are taken as it is
			F_TwoSided,          ///Face normals are flipped to match velocity
			F_TwoSidedLiftDrag,  ///Face normals are flipped to match velocity and lift and drag forces are applied
			F_OneSided,          ///Face normals are taken as it is
			END
		};
	};

	///eVSolver : velocities solvers
	struct eVSolver
	{
		enum _
		{
			Linear,  ///Linear solver
			END
		};
	};

	///ePSolver : positions solvers
	struct ePSolver
	{
		enum _
		{
			Linear,     ///Linear solver
			Anchors,    ///Anchor solver
			RContacts,  ///Rigid contacts solver
			SContacts,  ///Soft contacts solver
			END
		};
	};

	///eSolverPresets
	struct eSolverPresets
	{
		enum _
		{
			Positions,
			Velocities,
			Default = Positions,
			END
		};
	};

	///eFeature
	struct eFeature
	{
		enum _
		{
			None,
			Node,
			Link,
			Face,
			Tetra,
			END
		};
	};

	typedef btAlignedObjectArray<eVSolver::_> tVSolverArray;
	typedef btAlignedObjectArray<ePSolver::_> tPSolverArray;

	//
	// Flags
	//

	///fCollision
	struct fCollision
	{
		enum _
		{
			RVSmask = 0x000f,  ///Rigid versus soft mask
			SDF_RS = 0x0001,   ///SDF based rigid vs soft
			CL_RS = 0x0002,    ///Cluster vs convex rigid vs soft
			SDF_RD = 0x0004,   ///rigid vs deformable

			SVSmask = 0x00f0,  ///Rigid versus soft mask
			VF_SS = 0x0010,    ///Vertex vs face soft vs soft handling
			CL_SS = 0x0020,    ///Cluster vs cluster soft vs soft handling
			CL_SELF = 0x0040,  ///Cluster soft body self collision
			VF_DD = 0x0080,    ///Vertex vs face soft vs soft handling

			RVDFmask = 0x0f00,  /// Rigid versus deformable face mask
			SDF_RDF = 0x0100,   /// GJK based Rigid vs. deformable face
			SDF_MDF = 0x0200,   /// GJK based Multibody vs. deformable face
			SDF_RDN = 0x0400,   /// SDF based Rigid vs. deformable node
			/* presets	*/
			Default = SDF_RS,
			END
		};
	};

	///fMaterial
	struct fMaterial
	{
		enum _
		{
			DebugDraw = 0x0001,  /// Enable debug draw
			/* presets	*/
			Default = DebugDraw,
			END
		};
	};

	//
	// API Types
	//

	/* sRayCast		*/
	struct sRayCast
	{
		btSoftBody* body;     /// soft body
		eFeature::_ feature;  /// feature type
		int index;            /// feature index
		btScalar fraction;    /// time of impact fraction (rayorg+(rayto-rayfrom)*fraction)
	};

	/* ImplicitFn	*/
	struct ImplicitFn
	{
		virtual ~ImplicitFn() {}
		virtual btScalar Eval(const btVector3& x) = 0;
	};

	//
	// Internal types
	//

	typedef btAlignedObjectArray<btScalar> tScalarArray;
	typedef btAlignedObjectArray<btVector3> tVector3Array;

	/* sCti is Softbody contact info	*/
	struct sCti
	{
		const btCollisionObject* m_colObj; /* Rigid body			*/
		btVector3 m_normal;                /* Outward normal		*/
		btScalar m_offset;                 /* Offset from origin	*/
		btVector3 m_bary;                  /* Barycentric weights for faces */
	};

	/* sMedium		*/
	struct sMedium
	{
		btVector3 m_velocity; /* Velocity				*/
		btScalar m_pressure;  /* Pressure				*/
		btScalar m_density;   /* Density				*/
	};

	/* Base type	*/
	struct Element
	{
		void* m_tag;  // User data
		Element() : m_tag(0) {}
	};
	/* Material		*/
	struct Material : Element
	{
		btScalar m_kLST;  // Linear stiffness coefficient [0,1]
		btScalar m_kAST;  // Area/Angular stiffness coefficient [0,1]
		btScalar m_kVST;  // Volume stiffness coefficient [0,1]
		int m_flags;      // Flags
	};

	/* Feature		*/
	struct Feature : Element
	{
		Material* m_material;  // Material
	};
	/* Node			*/
	struct RenderNode
	{
		btVector3 m_x;
		btVector3 m_uv1;
		btVector3 m_normal;
	};
	struct Node : Feature
	{
		btVector3 m_x;       // Position
		btVector3 m_q;       // Previous step position/Test position
		btVector3 m_v;       // Velocity
		btVector3 m_vn;      // Previous step velocity
		btVector3 m_f;       // Force accumulator
		btVector3 m_n;       // Normal
		btScalar m_im;       // 1/mass
		btScalar m_area;     // Area
		btDbvtNode* m_leaf;  // Leaf data
		int m_constrained;   // depth of penetration
		int m_battach : 1;   // Attached
		int index;
		btVector3 m_splitv;               // velocity associated with split impulse
		btMatrix3x3 m_effectiveMass;      // effective mass in contact
		btMatrix3x3 m_effectiveMass_inv;  // inverse of effective mass
	};
	/* Link			*/
	ATTRIBUTE_ALIGNED16(struct)
	Link : Feature
	{
		btVector3 m_c3;      // gradient
		Node* m_n[2];        // Node pointers
		btScalar m_rl;       // Rest length
		int m_bbending : 1;  // Bending link
		btScalar m_c0;       // (ima+imb)*kLST
		btScalar m_c1;       // rl^2
		btScalar m_c2;       // |gradient|^2/c0

		BT_DECLARE_ALIGNED_ALLOCATOR();
	};
	struct RenderFace
	{
		RenderNode* m_n[3];          // Node pointers
	};

	/* Face			*/
	struct Face : Feature
	{
		Node* m_n[3];          // Node pointers
		btVector3 m_normal;    // Normal
		btScalar m_ra;         // Rest area
		btDbvtNode* m_leaf;    // Leaf data
		btVector4 m_pcontact;  // barycentric weights of the persistent contact
		btVector3 m_n0, m_n1, m_vn;
		int m_index;
	};
	/* Tetra		*/
	struct Tetra : Feature
	{
		Node* m_n[4];              // Node pointers
		btScalar m_rv;             // Rest volume
		btDbvtNode* m_leaf;        // Leaf data
		btVector3 m_c0[4];         // gradients
		btScalar m_c1;             // (4*kVST)/(im0+im1+im2+im3)
		btScalar m_c2;             // m_c1/sum(|g0..3|^2)
		btMatrix3x3 m_Dm_inverse;  // rest Dm^-1
		btMatrix3x3 m_F;
		btScalar m_element_measure;
		btVector4 m_P_inv[3];  // first three columns of P_inv matrix
	};

	/*  TetraScratch  */
	struct TetraScratch
	{
		btMatrix3x3 m_F;           // deformation gradient F
		btScalar m_trace;          // trace of F^T * F
		btScalar m_J;              // det(F)
		btMatrix3x3 m_cofF;        // cofactor of F
		btMatrix3x3 m_corotation;  // corotatio of the tetra
	};

	/* RContact		*/
	struct RContact
	{
		sCti m_cti;        // Contact infos
		Node* m_node;      // Owner node
		btMatrix3x3 m_c0;  // Impulse matrix
		btVector3 m_c1;    // Relative anchor
		btScalar m_c2;     // ima*dt
		btScalar m_c3;     // Friction
		btScalar m_c4;     // Hardness

		// jacobians and unit impulse responses for multibody
		btMultiBodyJacobianData jacobianData_normal;
		btMultiBodyJacobianData jacobianData_t1;
		btMultiBodyJacobianData jacobianData_t2;
		btVector3 t1;
		btVector3 t2;
	};

	class DeformableRigidContact
	{
	public:
		sCti m_cti;        // Contact infos
		btMatrix3x3 m_c0;  // Impulse matrix
		btVector3 m_c1;    // Relative anchor
		btScalar m_c2;     // inverse mass of node/face
		btScalar m_c3;     // Friction
		btScalar m_c4;     // Hardness
		btMatrix3x3 m_c5;  // inverse effective mass

		// jacobians and unit impulse responses for multibody
		btMultiBodyJacobianData jacobianData_normal;
		btMultiBodyJacobianData jacobianData_t1;
		btMultiBodyJacobianData jacobianData_t2;
		btVector3 t1;
		btVector3 t2;
	};

	class DeformableNodeRigidContact : public DeformableRigidContact
	{
	public:
		Node* m_node;  // Owner node
	};

	class DeformableNodeRigidAnchor : public DeformableNodeRigidContact
	{
	public:
		btVector3 m_local;  // Anchor position in body space
	};

	class DeformableFaceRigidContact : public DeformableRigidContact
	{
	public:
		Face* m_face;              // Owner face
		btVector3 m_contactPoint;  // Contact point
		btVector3 m_bary;          // Barycentric weights
		btVector3 m_weights;       // v_contactPoint * m_weights[i] = m_face->m_node[i]->m_v;
	};

	struct DeformableFaceNodeContact
	{
		Node* m_node;         // Node
		Face* m_face;         // Face
		btVector3 m_bary;     // Barycentric weights
		btVector3 m_weights;  // v_contactPoint * m_weights[i] = m_face->m_node[i]->m_v;
		btVector3 m_normal;   // Normal
		btScalar m_margin;    // Margin
		btScalar m_friction;  // Friction
		btScalar m_imf;       // inverse mass of the face at contact point
		btScalar m_c0;        // scale of the impulse matrix;
	};

	/* SContact		*/
	struct SContact
	{
		Node* m_node;         // Node
		Face* m_face;         // Face
		btVector3 m_weights;  // Weigths
		btVector3 m_normal;   // Normal
		btScalar m_margin;    // Margin
		btScalar m_friction;  // Friction
		btScalar m_cfm[2];    // Constraint force mixing
	};
	/* Anchor		*/
	struct Anchor
	{
		Node* m_node;         // Node pointer
		btVector3 m_local;    // Anchor position in body space
		btRigidBody* m_body;  // Body
		btScalar m_influence;
		btMatrix3x3 m_c0;  // Impulse matrix
		btVector3 m_c1;    // Relative anchor
		btScalar m_c2;     // ima*dt
	};
	/* Note			*/
	struct Note : Element
	{
		const char* m_text;    // Text
		btVector3 m_offset;    // Offset
		int m_rank;            // Rank
		Node* m_nodes[4];      // Nodes
		btScalar m_coords[4];  // Coordinates
	};
	/* Pose			*/
	struct Pose
	{
		bool m_bvolume;       // Is valid
		bool m_bframe;        // Is frame
		btScalar m_volume;    // Rest volume
		tVector3Array m_pos;  // Reference positions
		tScalarArray m_wgh;   // Weights
		btVector3 m_com;      // COM
		btMatrix3x3 m_rot;    // Rotation
		btMatrix3x3 m_scl;    // Scale
		btMatrix3x3 m_aqq;    // Base scaling
	};
	/* Cluster		*/
	struct Cluster
	{
		tScalarArray m_masses;
		btAlignedObjectArray<Node*> m_nodes;
		tVector3Array m_framerefs;
		btTransform m_framexform;
		btScalar m_idmass;
		btScalar m_imass;
		btMatrix3x3 m_locii;
		btMatrix3x3 m_invwi;
		btVector3 m_com;
		btVector3 m_vimpulses[2];
		btVector3 m_dimpulses[2];
		int m_nvimpulses;
		int m_ndimpulses;
		btVector3 m_lv;
		btVector3 m_av;
		btDbvtNode* m_leaf;
		btScalar m_ndamping; /* Node damping		*/
		btScalar m_ldamping; /* Linear damping	*/
		btScalar m_adamping; /* Angular damping	*/
		btScalar m_matching;
		btScalar m_maxSelfCollisionImpulse;
		btScalar m_selfCollisionImpulseFactor;
		bool m_containsAnchor;
		bool m_collide;
		int m_clusterIndex;
		Cluster() : m_leaf(0), m_ndamping(0), m_ldamping(0), m_adamping(0), m_matching(0), m_maxSelfCollisionImpulse(100.f), m_selfCollisionImpulseFactor(0.01f), m_containsAnchor(false)
		{
		}
	};
	/* Impulse		*/
	struct Impulse
	{
		btVector3 m_velocity;
		btVector3 m_drift;
		int m_asVelocity : 1;
		int m_asDrift : 1;
		Impulse() : m_velocity(0, 0, 0), m_drift(0, 0, 0), m_asVelocity(0), m_asDrift(0) {}
		Impulse operator-() const
		{
			Impulse i = *this;
			i.m_velocity = -i.m_velocity;
			i.m_drift = -i.m_drift;
			return (i);
		}
		Impulse operator*(btScalar x) const
		{
			Impulse i = *this;
			i.m_velocity *= x;
			i.m_drift *= x;
			return (i);
		}
	};
	/* Body			*/
	struct Body
	{
		Cluster* m_soft;
		btRigidBody* m_rigid;
		const btCollisionObject* m_collisionObject;

		Body() : m_soft(0), m_rigid(0), m_collisionObject(0) {}
		Body(Cluster* p) : m_soft(p), m_rigid(0), m_collisionObject(0) {}
		Body(const btCollisionObject* colObj) : m_soft(0), m_collisionObject(colObj)
		{
			m_rigid = (btRigidBody*)btRigidBody::upcast(m_collisionObject);
		}

		void activate() const
		{
			if (m_rigid)
				m_rigid->activate();
			if (m_collisionObject)
				m_collisionObject->activate();
		}
		const btMatrix3x3& invWorldInertia() const
		{
			static const btMatrix3x3 iwi(0, 0, 0, 0, 0, 0, 0, 0, 0);
			if (m_rigid) return (m_rigid->getInvInertiaTensorWorld());
			if (m_soft) return (m_soft->m_invwi);
			return (iwi);
		}
		btScalar invMass() const
		{
			if (m_rigid) return (m_rigid->getInvMass());
			if (m_soft) return (m_soft->m_imass);
			return (0);
		}
		const btTransform& xform() const
		{
			static const btTransform identity = btTransform::getIdentity();
			if (m_collisionObject) return (m_collisionObject->getWorldTransform());
			if (m_soft) return (m_soft->m_framexform);
			return (identity);
		}
		btVector3 linearVelocity() const
		{
			if (m_rigid) return (m_rigid->getLinearVelocity());
			if (m_soft) return (m_soft->m_lv);
			return (btVector3(0, 0, 0));
		}
		btVector3 angularVelocity(const btVector3& rpos) const
		{
			if (m_rigid) return (btCross(m_rigid->getAngularVelocity(), rpos));
			if (m_soft) return (btCross(m_soft->m_av, rpos));
			return (btVector3(0, 0, 0));
		}
		btVector3 angularVelocity() const
		{
			if (m_rigid) return (m_rigid->getAngularVelocity());
			if (m_soft) return (m_soft->m_av);
			return (btVector3(0, 0, 0));
		}
		btVector3 velocity(const btVector3& rpos) const
		{
			return (linearVelocity() + angularVelocity(rpos));
		}
		void applyVImpulse(const btVector3& impulse, const btVector3& rpos) const
		{
			if (m_rigid) m_rigid->applyImpulse(impulse, rpos);
			if (m_soft) btSoftBody::clusterVImpulse(m_soft, rpos, impulse);
		}
		void applyDImpulse(const btVector3& impulse, const btVector3& rpos) const
		{
			if (m_rigid) m_rigid->applyImpulse(impulse, rpos);
			if (m_soft) btSoftBody::clusterDImpulse(m_soft, rpos, impulse);
		}
		void applyImpulse(const Impulse& impulse, const btVector3& rpos) const
		{
			if (impulse.m_asVelocity)
			{
				//				printf("impulse.m_velocity = %f,%f,%f\n",impulse.m_velocity.getX(),impulse.m_velocity.getY(),impulse.m_velocity.getZ());
				applyVImpulse(impulse.m_velocity, rpos);
			}
			if (impulse.m_asDrift)
			{
				//				printf("impulse.m_drift = %f,%f,%f\n",impulse.m_drift.getX(),impulse.m_drift.getY(),impulse.m_drift.getZ());
				applyDImpulse(impulse.m_drift, rpos);
			}
		}
		void applyVAImpulse(const btVector3& impulse) const
		{
			if (m_rigid) m_rigid->applyTorqueImpulse(impulse);
			if (m_soft) btSoftBody::clusterVAImpulse(m_soft, impulse);
		}
		void applyDAImpulse(const btVector3& impulse) const
		{
			if (m_rigid) m_rigid->applyTorqueImpulse(impulse);
			if (m_soft) btSoftBody::clusterDAImpulse(m_soft, impulse);
		}
		void applyAImpulse(const Impulse& impulse) const
		{
			if (impulse.m_asVelocity) applyVAImpulse(impulse.m_velocity);
			if (impulse.m_asDrift) applyDAImpulse(impulse.m_drift);
		}
		void applyDCImpulse(const btVector3& impulse) const
		{
			if (m_rigid) m_rigid->applyCentralImpulse(impulse);
			if (m_soft) btSoftBody::clusterDCImpulse(m_soft, impulse);
		}
	};
	/* Joint		*/
	struct Joint
	{
		struct eType
		{
			enum _
			{
				Linear = 0,
				Angular,
				Contact
			};
		};
		struct Specs
		{
			Specs() : erp(1), cfm(1), split(1) {}
			btScalar erp;
			btScalar cfm;
			btScalar split;
		};
		Body m_bodies[2];
		btVector3 m_refs[2];
		btScalar m_cfm;
		btScalar m_erp;
		btScalar m_split;
		btVector3 m_drift;
		btVector3 m_sdrift;
		btMatrix3x3 m_massmatrix;
		bool m_delete;
		virtual ~Joint() {}
		Joint() : m_delete(false) {}
		virtual void Prepare(btScalar dt, int iterations);
		virtual void Solve(btScalar dt, btScalar sor) = 0;
		virtual void Terminate(btScalar dt) = 0;
		virtual eType::_ Type() const = 0;
	};
	/* LJoint		*/
	struct LJoint : Joint
	{
		struct Specs : Joint::Specs
		{
			btVector3 position;
		};
		btVector3 m_rpos[2];
		void Prepare(btScalar dt, int iterations);
		void Solve(btScalar dt, btScalar sor);
		void Terminate(btScalar dt);
		eType::_ Type() const { return (eType::Linear); }
	};
	/* AJoint		*/
	struct AJoint : Joint
	{
		struct IControl
		{
			virtual ~IControl() {}
			virtual void Prepare(AJoint*) {}
			virtual btScalar Speed(AJoint*, btScalar current) { return (current); }
			static IControl* Default()
			{
				static IControl def;
				return (&def);
			}
		};
		struct Specs : Joint::Specs
		{
			Specs() : icontrol(IControl::Default()) {}
			btVector3 axis;
			IControl* icontrol;
		};
		btVector3 m_axis[2];
		IControl* m_icontrol;
		void Prepare(btScalar dt, int iterations);
		void Solve(btScalar dt, btScalar sor);
		void Terminate(btScalar dt);
		eType::_ Type() const { return (eType::Angular); }
	};
	/* CJoint		*/
	struct CJoint : Joint
	{
		int m_life;
		int m_maxlife;
		btVector3 m_rpos[2];
		btVector3 m_normal;
		btScalar m_friction;
		void Prepare(btScalar dt, int iterations);
		void Solve(btScalar dt, btScalar sor);
		void Terminate(btScalar dt);
		eType::_ Type() const { return (eType::Contact); }
	};
	/* Config		*/
	struct Config
	{
		eAeroModel::_ aeromodel;    // Aerodynamic model (default: V_Point)
		btScalar kVCF;              // Velocities correction factor (Baumgarte)
		btScalar kDP;               // Damping coefficient [0,1]
		btScalar kDG;               // Drag coefficient [0,+inf]
		btScalar kLF;               // Lift coefficient [0,+inf]
		btScalar kPR;               // Pressure coefficient [-inf,+inf]
		btScalar kVC;               // Volume conversation coefficient [0,+inf]
		btScalar kDF;               // Dynamic friction coefficient [0,1]
		btScalar kMT;               // Pose matching coefficient [0,1]
		btScalar kCHR;              // Rigid contacts hardness [0,1]
		btScalar kKHR;              // Kinetic contacts hardness [0,1]
		btScalar kSHR;              // Soft contacts hardness [0,1]
		btScalar kAHR;              // Anchors hardness [0,1]
		btScalar kSRHR_CL;          // Soft vs rigid hardness [0,1] (cluster only)
		btScalar kSKHR_CL;          // Soft vs kinetic hardness [0,1] (cluster only)
		btScalar kSSHR_CL;          // Soft vs soft hardness [0,1] (cluster only)
		btScalar kSR_SPLT_CL;       // Soft vs rigid impulse split [0,1] (cluster only)
		btScalar kSK_SPLT_CL;       // Soft vs rigid impulse split [0,1] (cluster only)
		btScalar kSS_SPLT_CL;       // Soft vs rigid impulse split [0,1] (cluster only)
		btScalar maxvolume;         // Maximum volume ratio for pose
		btScalar timescale;         // Time scale
		int viterations;            // Velocities solver iterations
		int piterations;            // Positions solver iterations
		int diterations;            // Drift solver iterations
		int citerations;            // Cluster solver iterations
		int collisions;             // Collisions flags
		tVSolverArray m_vsequence;  // Velocity solvers sequence
		tPSolverArray m_psequence;  // Position solvers sequence
		tPSolverArray m_dsequence;  // Drift solvers sequence
		btScalar drag;              // deformable air drag
		btScalar m_maxStress;       // Maximum principle first Piola stress
	};
	/* SolverState	*/
	struct SolverState
	{
		//if you add new variables, always initialize them!
		SolverState()
			: sdt(0),
			  isdt(0),
			  velmrg(0),
			  radmrg(0),
			  updmrg(0)
		{
		}
		btScalar sdt;     // dt*timescale
		btScalar isdt;    // 1/sdt
		btScalar velmrg;  // velocity margin
		btScalar radmrg;  // radial margin
		btScalar updmrg;  // Update margin
	};
	/// RayFromToCaster takes a ray from, ray to (instead of direction!)
	struct RayFromToCaster : btDbvt::ICollide
	{
		btVector3 m_rayFrom;
		btVector3 m_rayTo;
		btVector3 m_rayNormalizedDirection;
		btScalar m_mint;
		Face* m_face;
		int m_tests;
		RayFromToCaster(const btVector3& rayFrom, const btVector3& rayTo, btScalar mxt);
		void Process(const btDbvtNode* leaf);

		static /*inline*/ btScalar rayFromToTriangle(const btVector3& rayFrom,
													 const btVector3& rayTo,
													 const btVector3& rayNormalizedDirection,
													 const btVector3& a,
													 const btVector3& b,
													 const btVector3& c,
													 btScalar maxt = SIMD_INFINITY);
	};

	//
	// Typedefs
	//

	typedef void (*psolver_t)(btSoftBody*, btScalar, btScalar);
	typedef void (*vsolver_t)(btSoftBody*, btScalar);
	typedef btAlignedObjectArray<Cluster*> tClusterArray;
	typedef btAlignedObjectArray<Note> tNoteArray;
	typedef btAlignedObjectArray<Node> tNodeArray;
	typedef btAlignedObjectArray< RenderNode> tRenderNodeArray;
	typedef btAlignedObjectArray<btDbvtNode*> tLeafArray;
	typedef btAlignedObjectArray<Link> tLinkArray;
	typedef btAlignedObjectArray<Face> tFaceArray;
	typedef btAlignedObjectArray<RenderFace> tRenderFaceArray;
	typedef btAlignedObjectArray<Tetra> tTetraArray;
	typedef btAlignedObjectArray<Anchor> tAnchorArray;
	typedef btAlignedObjectArray<RContact> tRContactArray;
	typedef btAlignedObjectArray<SContact> tSContactArray;
	typedef btAlignedObjectArray<Material*> tMaterialArray;
	typedef btAlignedObjectArray<Joint*> tJointArray;
	typedef btAlignedObjectArray<btSoftBody*> tSoftBodyArray;

	//
	// Fields
	//

	Config m_cfg;                      // Configuration
	SolverState m_sst;                 // Solver state
	Pose m_pose;                       // Pose
	void* m_tag;                       // User data
	btSoftBodyWorldInfo* m_worldInfo;  // World info
	tNoteArray m_notes;                // Notes
	tNodeArray m_nodes;                // Nodes
	tRenderNodeArray m_renderNodes;    // Render Nodes
	tLinkArray m_links;                // Links
	tFaceArray m_faces;                // Faces
	tRenderFaceArray m_renderFaces;          // Faces
	tTetraArray m_tetras;              // Tetras
	btAlignedObjectArray<TetraScratch> m_tetraScratches;
	btAlignedObjectArray<TetraScratch> m_tetraScratchesTn;
	tAnchorArray m_anchors;  // Anchors
	btAlignedObjectArray<DeformableNodeRigidAnchor> m_deformableAnchors;
	tRContactArray m_rcontacts;  // Rigid contacts
	btAlignedObjectArray<DeformableNodeRigidContact> m_nodeRigidContacts;
	btAlignedObjectArray<DeformableFaceNodeContact> m_faceNodeContacts;
	btAlignedObjectArray<DeformableFaceRigidContact> m_faceRigidContacts;
	tSContactArray m_scontacts;     // Soft contacts
	tJointArray m_joints;           // Joints
	tMaterialArray m_materials;     // Materials
	btScalar m_timeacc;             // Time accumulator
	btVector3 m_bounds[2];          // Spatial bounds
	bool m_bUpdateRtCst;            // Update runtime constants
	btDbvt m_ndbvt;                 // Nodes tree
	btDbvt m_fdbvt;                 // Faces tree
	btDbvntNode* m_fdbvnt;          // Faces tree with normals
	btDbvt m_cdbvt;                 // Clusters tree
	tClusterArray m_clusters;       // Clusters
	btScalar m_dampingCoefficient;  // Damping Coefficient
	btScalar m_sleepingThreshold;
	btScalar m_maxSpeedSquared;
	btAlignedObjectArray<btVector3> m_quads;  // quadrature points for collision detection
	btScalar m_repulsionStiffness;
	btScalar m_gravityFactor;
	bool m_cacheBarycenter;
	btAlignedObjectArray<btVector3> m_X;  // initial positions

	btAlignedObjectArray<btVector4> m_renderNodesInterpolationWeights;
	btAlignedObjectArray<btAlignedObjectArray<const btSoftBody::Node*> > m_renderNodesParents;
	btAlignedObjectArray<btScalar> m_z;  // vertical distance used in extrapolation
	bool m_useSelfCollision;
	bool m_softSoftCollision;

	btAlignedObjectArray<bool> m_clusterConnectivity;  //cluster connectivity, for self-collision

	btVector3 m_windVelocity;

	btScalar m_restLengthScale;

	//
	// Api
	//

	/* ctor																	*/
	btSoftBody(btSoftBodyWorldInfo* worldInfo, int node_count, const btVector3* x, const btScalar* m);

	/* ctor																	*/
	btSoftBody(btSoftBodyWorldInfo* worldInfo);

	void initDefaults();

	/* dtor																	*/
	virtual ~btSoftBody();
	/* Check for existing link												*/

	btAlignedObjectArray<int> m_userIndexMapping;

	btSoftBodyWorldInfo* getWorldInfo()
	{
		return m_worldInfo;
	}

	void setDampingCoefficient(btScalar damping_coeff)
	{
		m_dampingCoefficient = damping_coeff;
	}

	///@todo: avoid internal softbody shape hack and move collision code to collision library
	virtual void setCollisionShape(btCollisionShape* collisionShape)
	{
	}

	bool checkLink(int node0,
				   int node1) const;
	bool checkLink(const Node* node0,
				   const Node* node1) const;
	/* Check for existring face												*/
	bool checkFace(int node0,
				   int node1,
				   int node2) const;
	/* Append material														*/
	Material* appendMaterial();
	/* Append note															*/
	void appendNote(const char* text,
					const btVector3& o,
					const btVector4& c = btVector4(1, 0, 0, 0),
					Node* n0 = 0,
					Node* n1 = 0,
					Node* n2 = 0,
					Node* n3 = 0);
	void appendNote(const char* text,
					const btVector3& o,
					Node* feature);
	void appendNote(const char* text,
					const btVector3& o,
					Link* feature);
	void appendNote(const char* text,
					const btVector3& o,
					Face* feature);
	/* Append node															*/
	void appendNode(const btVector3& x, btScalar m);
	/* Append link															*/
	void appendLink(int model = -1, Material* mat = 0);
	void appendLink(int node0,
					int node1,
					Material* mat = 0,
					bool bcheckexist = false);
	void appendLink(Node* node0,
					Node* node1,
					Material* mat = 0,
					bool bcheckexist = false);
	/* Append face															*/
	void appendFace(int model = -1, Material* mat = 0);
	void appendFace(int node0,
					int node1,
					int node2,
					Material* mat = 0);
	void appendTetra(int model, Material* mat);
	//
	void appendTetra(int node0,
					 int node1,
					 int node2,
					 int node3,
					 Material* mat = 0);

	/* Append anchor														*/
	void appendDeformableAnchor(int node, btRigidBody* body);
	void appendDeformableAnchor(int node, btMultiBodyLinkCollider* link);
	void appendAnchor(int node,
					  btRigidBody* body, bool disableCollisionBetweenLinkedBodies = false, btScalar influence = 1);
	void appendAnchor(int node, btRigidBody* body, const btVector3& localPivot, bool disableCollisionBetweenLinkedBodies = false, btScalar influence = 1);
	void removeAnchor(int node);
	/* Append linear joint													*/
	void appendLinearJoint(const LJoint::Specs& specs, Cluster* body0, Body body1);
	void appendLinearJoint(const LJoint::Specs& specs, Body body = Body());
	void appendLinearJoint(const LJoint::Specs& specs, btSoftBody* body);
	/* Append linear joint													*/
	void appendAngularJoint(const AJoint::Specs& specs, Cluster* body0, Body body1);
	void appendAngularJoint(const AJoint::Specs& specs, Body body = Body());
	void appendAngularJoint(const AJoint::Specs& specs, btSoftBody* body);
	/* Add force (or gravity) to the entire body							*/
	void addForce(const btVector3& force);
	/* Add force (or gravity) to a node of the body							*/
	void addForce(const btVector3& force,
				  int node);
	/* Add aero force to a node of the body */
	void addAeroForceToNode(const btVector3& windVelocity, int nodeIndex);

	/* Add aero force to a face of the body */
	void addAeroForceToFace(const btVector3& windVelocity, int faceIndex);

	/* Add velocity to the entire body										*/
	void addVelocity(const btVector3& velocity);

	/* Set velocity for the entire body										*/
	void setVelocity(const btVector3& velocity);

	/* Add velocity to a node of the body									*/
	void addVelocity(const btVector3& velocity,
					 int node);
	/* Set mass																*/
	void setMass(int node,
				 btScalar mass);
	/* Get mass																*/
	btScalar getMass(int node) const;
	/* Get total mass														*/
	btScalar getTotalMass() const;
	/* Set total mass (weighted by previous masses)							*/
	void setTotalMass(btScalar mass,
					  bool fromfaces = false);
	/* Set total density													*/
	void setTotalDensity(btScalar density);
	/* Set volume mass (using tetrahedrons)									*/
	void setVolumeMass(btScalar mass);
	/* Set volume density (using tetrahedrons)								*/
	void setVolumeDensity(btScalar density);
	/* Get the linear velocity of the center of mass                        */
	btVector3 getLinearVelocity();
	/* Set the linear velocity of the center of mass                        */
	void setLinearVelocity(const btVector3& linVel);
	/* Set the angular velocity of the center of mass                       */
	void setAngularVelocity(const btVector3& angVel);
	/* Get best fit rigid transform                                         */
	btTransform getRigidTransform();
	/* Transform to given pose                                              */
	void transformTo(const btTransform& trs);
	/* Transform															*/
	void transform(const btTransform& trs);
	/* Translate															*/
	void translate(const btVector3& trs);
	/* Rotate															*/
	void rotate(const btQuaternion& rot);
	/* Scale																*/
	void scale(const btVector3& scl);
	/* Get link resting lengths scale										*/
	btScalar getRestLengthScale();
	/* Scale resting length of all springs									*/
	void setRestLengthScale(btScalar restLength);
	/* Set current state as pose											*/
	void setPose(bool bvolume,
				 bool bframe);
	/* Set current link lengths as resting lengths							*/
	void resetLinkRestLengths();
	/* Return the volume													*/
	btScalar getVolume() const;
	/* Cluster count														*/
	btVector3 getCenterOfMass() const
	{
		btVector3 com(0, 0, 0);
		for (int i = 0; i < m_nodes.size(); i++)
		{
			com += (m_nodes[i].m_x * this->getMass(i));
		}
		com /= this->getTotalMass();
		return com;
	}
	int clusterCount() const;
	/* Cluster center of mass												*/
	static btVector3 clusterCom(const Cluster* cluster);
	btVector3 clusterCom(int cluster) const;
	/* Cluster velocity at rpos												*/
	static btVector3 clusterVelocity(const Cluster* cluster, const btVector3& rpos);
	/* Cluster impulse														*/
	static void clusterVImpulse(Cluster* cluster, const btVector3& rpos, const btVector3& impulse);
	static void clusterDImpulse(Cluster* cluster, const btVector3& rpos, const btVector3& impulse);
	static void clusterImpulse(Cluster* cluster, const btVector3& rpos, const Impulse& impulse);
	static void clusterVAImpulse(Cluster* cluster, const btVector3& impulse);
	static void clusterDAImpulse(Cluster* cluster, const btVector3& impulse);
	static void clusterAImpulse(Cluster* cluster, const Impulse& impulse);
	static void clusterDCImpulse(Cluster* cluster, const btVector3& impulse);
	/* Generate bending constraints based on distance in the adjency graph	*/
	int generateBendingConstraints(int distance,
								   Material* mat = 0);
	/* Randomize constraints to reduce solver bias							*/
	void randomizeConstraints();
	/* Release clusters														*/
	void releaseCluster(int index);
	void releaseClusters();
	/* Generate clusters (K-mean)											*/
	///generateClusters with k=0 will create a convex cluster for each tetrahedron or triangle
	///otherwise an approximation will be used (better performance)
	int generateClusters(int k, int maxiterations = 8192);
	/* Refine																*/
	void refine(ImplicitFn* ifn, btScalar accurary, bool cut);
	/* CutLink																*/
	bool cutLink(int node0, int node1, btScalar position);
	bool cutLink(const Node* node0, const Node* node1, btScalar position);

	///Ray casting using rayFrom and rayTo in worldspace, (not direction!)
	bool rayTest(const btVector3& rayFrom,
				 const btVector3& rayTo,
				 sRayCast& results);
	bool rayFaceTest(const btVector3& rayFrom,
					 const btVector3& rayTo,
					 sRayCast& results);
	int rayFaceTest(const btVector3& rayFrom, const btVector3& rayTo,
					btScalar& mint, int& index) const;
	/* Solver presets														*/
	void setSolver(eSolverPresets::_ preset);
	/* predictMotion														*/
	void predictMotion(btScalar dt);
	/* solveConstraints														*/
	void solveConstraints();
	/* staticSolve															*/
	void staticSolve(int iterations);
	/* solveCommonConstraints												*/
	static void solveCommonConstraints(btSoftBody** bodies, int count, int iterations);
	/* solveClusters														*/
	static void solveClusters(const btAlignedObjectArray<btSoftBody*>& bodies);
	/* integrateMotion														*/
	void integrateMotion();
	/* defaultCollisionHandlers												*/
	void defaultCollisionHandler(const btCollisionObjectWrapper* pcoWrap);
	void defaultCollisionHandler(btSoftBody* psb);
	void setSelfCollision(bool useSelfCollision);
	bool useSelfCollision();
	void updateDeactivation(btScalar timeStep);
	void setZeroVelocity();
	bool wantsSleeping();

	//
	// Functionality to deal with new accelerated solvers.
	//

	/**
	 * Set a wind velocity for interaction with the air.
	 */
	void setWindVelocity(const btVector3& velocity);

	/**
	 * Return the wind velocity for interaction with the air.
	 */
	const btVector3& getWindVelocity();

	//
	// Set the solver that handles this soft body
	// Should not be allowed to get out of sync with reality
	// Currently called internally on addition to the world
	void setSoftBodySolver(btSoftBodySolver* softBodySolver)
	{
		m_softBodySolver = softBodySolver;
	}

	//
	// Return the solver that handles this soft body
	//
	btSoftBodySolver* getSoftBodySolver()
	{
		return m_softBodySolver;
	}

	//
	// Return the solver that handles this soft body
	//
	btSoftBodySolver* getSoftBodySolver() const
	{
		return m_softBodySolver;
	}

	//
	// Cast
	//

	static const btSoftBody* upcast(const btCollisionObject* colObj)
	{
		if (colObj->getInternalType() == CO_SOFT_BODY)
			return (const btSoftBody*)colObj;
		return 0;
	}
	static btSoftBody* upcast(btCollisionObject* colObj)
	{
		if (colObj->getInternalType() == CO_SOFT_BODY)
			return (btSoftBody*)colObj;
		return 0;
	}

	//
	// ::btCollisionObject
	//

	virtual void getAabb(btVector3& aabbMin, btVector3& aabbMax) const
	{
		aabbMin = m_bounds[0];
		aabbMax = m_bounds[1];
	}
	//
	// Private
	//
	void pointersToIndices();
	void indicesToPointers(const int* map = 0);

	int rayTest(const btVector3& rayFrom, const btVector3& rayTo,
				btScalar& mint, eFeature::_& feature, int& index, bool bcountonly) const;
	void initializeFaceTree();
	void rebuildNodeTree();
	btVector3 evaluateCom() const;
	bool checkDeformableContact(const btCollisionObjectWrapper* colObjWrap, const btVector3& x, btScalar margin, btSoftBody::sCti& cti, bool predict = false) const;
	bool checkDeformableFaceContact(const btCollisionObjectWrapper* colObjWrap, Face& f, btVector3& contact_point, btVector3& bary, btScalar margin, btSoftBody::sCti& cti, bool predict = false) const;
	bool checkContact(const btCollisionObjectWrapper* colObjWrap, const btVector3& x, btScalar margin, btSoftBody::sCti& cti) const;
	void updateNormals();
	void updateBounds();
	void updatePose();
	void updateConstants();
	void updateLinkConstants();
	void updateArea(bool averageArea = true);
	void initializeClusters();
	void updateClusters();
	void cleanupClusters();
	void prepareClusters(int iterations);
	void solveClusters(btScalar sor);
	void applyClusters(bool drift);
	void dampClusters();
	void setSpringStiffness(btScalar k);
	void setGravityFactor(btScalar gravFactor);
	void setCacheBarycenter(bool cacheBarycenter);
	void initializeDmInverse();
	void updateDeformation();
	void advanceDeformation();
	void applyForces();
	void setMaxStress(btScalar maxStress);
	void interpolateRenderMesh();
	void setCollisionQuadrature(int N);
	static void PSolve_Anchors(btSoftBody* psb, btScalar kst, btScalar ti);
	static void PSolve_RContacts(btSoftBody* psb, btScalar kst, btScalar ti);
	static void PSolve_SContacts(btSoftBody* psb, btScalar, btScalar ti);
	static void PSolve_Links(btSoftBody* psb, btScalar kst, btScalar ti);
	static void VSolve_Links(btSoftBody* psb, btScalar kst);
	static psolver_t getSolver(ePSolver::_ solver);
	static vsolver_t getSolver(eVSolver::_ solver);
	void geometricCollisionHandler(btSoftBody* psb);
#define SAFE_EPSILON SIMD_EPSILON * 100.0
	void updateNode(btDbvtNode* node, bool use_velocity, bool margin)
	{
		if (node->isleaf())
		{
			btSoftBody::Node* n = (btSoftBody::Node*)(node->data);
			ATTRIBUTE_ALIGNED16(btDbvtVolume)
			vol;
			btScalar pad = margin ? m_sst.radmrg : SAFE_EPSILON;  // use user defined margin or margin for floating point precision
			if (use_velocity)
			{
				btVector3 points[2] = {n->m_x, n->m_x + m_sst.sdt * n->m_v};
				vol = btDbvtVolume::FromPoints(points, 2);
				vol.Expand(btVector3(pad, pad, pad));
			}
			else
			{
				vol = btDbvtVolume::FromCR(n->m_x, pad);
			}
			node->volume = vol;
			return;
		}
		else
		{
			updateNode(node->childs[0], use_velocity, margin);
			updateNode(node->childs[1], use_velocity, margin);
			ATTRIBUTE_ALIGNED16(btDbvtVolume)
			vol;
			Merge(node->childs[0]->volume, node->childs[1]->volume, vol);
			node->volume = vol;
		}
	}

	void updateNodeTree(bool use_velocity, bool margin)
	{
		if (m_ndbvt.m_root)
			updateNode(m_ndbvt.m_root, use_velocity, margin);
	}

	template <class DBVTNODE>  // btDbvtNode or btDbvntNode
	void updateFace(DBVTNODE* node, bool use_velocity, bool margin)
	{
		if (node->isleaf())
		{
			btSoftBody::Face* f = (btSoftBody::Face*)(node->data);
			btScalar pad = margin ? m_sst.radmrg : SAFE_EPSILON;  // use user defined margin or margin for floating point precision
			ATTRIBUTE_ALIGNED16(btDbvtVolume)
			vol;
			if (use_velocity)
			{
				btVector3 points[6] = {f->m_n[0]->m_x, f->m_n[0]->m_x + m_sst.sdt * f->m_n[0]->m_v,
									   f->m_n[1]->m_x, f->m_n[1]->m_x + m_sst.sdt * f->m_n[1]->m_v,
									   f->m_n[2]->m_x, f->m_n[2]->m_x + m_sst.sdt * f->m_n[2]->m_v};
				vol = btDbvtVolume::FromPoints(points, 6);
			}
			else
			{
				btVector3 points[3] = {f->m_n[0]->m_x,
									   f->m_n[1]->m_x,
									   f->m_n[2]->m_x};
				vol = btDbvtVolume::FromPoints(points, 3);
			}
			vol.Expand(btVector3(pad, pad, pad));
			node->volume = vol;
			return;
		}
		else
		{
			updateFace(node->childs[0], use_velocity, margin);
			updateFace(node->childs[1], use_velocity, margin);
			ATTRIBUTE_ALIGNED16(btDbvtVolume)
			vol;
			Merge(node->childs[0]->volume, node->childs[1]->volume, vol);
			node->volume = vol;
		}
	}
	void updateFaceTree(bool use_velocity, bool margin)
	{
		if (m_fdbvt.m_root)
			updateFace(m_fdbvt.m_root, use_velocity, margin);
		if (m_fdbvnt)
			updateFace(m_fdbvnt, use_velocity, margin);
	}

	template <typename T>
	static inline T BaryEval(const T& a,
							 const T& b,
							 const T& c,
							 const btVector3& coord)
	{
		return (a * coord.x() + b * coord.y() + c * coord.z());
	}

	void applyRepulsionForce(btScalar timeStep, bool applySpringForce)
	{
		btAlignedObjectArray<int> indices;
		{
			// randomize the order of repulsive force
			indices.resize(m_faceNodeContacts.size());
			for (int i = 0; i < m_faceNodeContacts.size(); ++i)
				indices[i] = i;
#define NEXTRAND (seed = (1664525L * seed + 1013904223L) & 0xffffffff)
			int i, ni;

			for (i = 0, ni = indices.size(); i < ni; ++i)
			{
				btSwap(indices[i], indices[NEXTRAND % ni]);
			}
		}
		for (int k = 0; k < m_faceNodeContacts.size(); ++k)
		{
			int i = indices[k];
			btSoftBody::DeformableFaceNodeContact& c = m_faceNodeContacts[i];
			btSoftBody::Node* node = c.m_node;
			btSoftBody::Face* face = c.m_face;
			const btVector3& w = c.m_bary;
			const btVector3& n = c.m_normal;
			btVector3 l = node->m_x - BaryEval(face->m_n[0]->m_x, face->m_n[1]->m_x, face->m_n[2]->m_x, w);
			btScalar d = c.m_margin - n.dot(l);
			d = btMax(btScalar(0), d);

			const btVector3& va = node->m_v;
			btVector3 vb = BaryEval(face->m_n[0]->m_v, face->m_n[1]->m_v, face->m_n[2]->m_v, w);
			btVector3 vr = va - vb;
			const btScalar vn = btDot(vr, n);  // dn < 0 <==> opposing
			if (vn > OVERLAP_REDUCTION_FACTOR * d / timeStep)
				continue;
			btVector3 vt = vr - vn * n;
			btScalar I = 0;
			btScalar mass = node->m_im == 0 ? 0 : btScalar(1) / node->m_im;
			if (applySpringForce)
				I = -btMin(m_repulsionStiffness * timeStep * d, mass * (OVERLAP_REDUCTION_FACTOR * d / timeStep - vn));
			if (vn < 0)
				I += 0.5 * mass * vn;
			int face_penetration = 0, node_penetration = node->m_constrained;
			for (int i = 0; i < 3; ++i)
				face_penetration |= face->m_n[i]->m_constrained;
			btScalar I_tilde = 2.0 * I / (1.0 + w.length2());

			//             double the impulse if node or face is constrained.
			if (face_penetration > 0 || node_penetration > 0)
			{
				I_tilde *= 2.0;
			}
			if (face_penetration <= 0)
			{
				for (int j = 0; j < 3; ++j)
					face->m_n[j]->m_v += w[j] * n * I_tilde * node->m_im;
			}
			if (node_penetration <= 0)
			{
				node->m_v -= I_tilde * node->m_im * n;
			}

			// apply frictional impulse
			btScalar vt_norm = vt.safeNorm();
			if (vt_norm > SIMD_EPSILON)
			{
				btScalar delta_vn = -2 * I * node->m_im;
				btScalar mu = c.m_friction;
				btScalar vt_new = btMax(btScalar(1) - mu * delta_vn / (vt_norm + SIMD_EPSILON), btScalar(0)) * vt_norm;
				I = 0.5 * mass * (vt_norm - vt_new);
				vt.safeNormalize();
				I_tilde = 2.0 * I / (1.0 + w.length2());
				//                 double the impulse if node or face is constrained.
				if (face_penetration > 0 || node_penetration > 0)
					I_tilde *= 2.0;
				if (face_penetration <= 0)
				{
					for (int j = 0; j < 3; ++j)
						face->m_n[j]->m_v += w[j] * vt * I_tilde * (face->m_n[j])->m_im;
				}
				if (node_penetration <= 0)
				{
					node->m_v -= I_tilde * node->m_im * vt;
				}
			}
		}
	}
	virtual int calculateSerializeBufferSize() const;

	///fills the dataBuffer and returns the struct name (and 0 on failure)
	virtual const char* serialize(void* dataBuffer, class btSerializer* serializer) const;
};

#endif  //_BT_SOFT_BODY_H


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.container.model;

/**
 * SetMonitoringServiceRequest sets the monitoring service of a cluster.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Kubernetes Engine API. For a detailed explanation
 * see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class SetMonitoringServiceRequest extends com.google.api.client.json.GenericJson {

  /**
   * Deprecated. The name of the cluster to upgrade. This field has been deprecated and replaced by
   * the name field.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String clusterId;

  /**
   * Required. The monitoring service the cluster should use to write metrics. Currently available
   * options: * "monitoring.googleapis.com/kubernetes" - The Cloud Monitoring service with a
   * Kubernetes-native resource model * `monitoring.googleapis.com` - The legacy Cloud Monitoring
   * service (no longer available as of GKE 1.15). * `none` - No metrics will be exported from the
   * cluster. If left as an empty string,`monitoring.googleapis.com/kubernetes` will be used for GKE
   * 1.14+ or `monitoring.googleapis.com` for earlier versions.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String monitoringService;

  /**
   * The name (project, location, cluster) of the cluster to set monitoring. Specified in the format
   * `projects/locations/clusters`.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String name;

  /**
   * Deprecated. The Google Developers Console [project ID or project
   * number](https://cloud.google.com/resource-manager/docs/creating-managing-projects). This field
   * has been deprecated and replaced by the name field.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String projectId;

  /**
   * Deprecated. The name of the Google Compute Engine
   * [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides.
   * This field has been deprecated and replaced by the name field.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String zone;

  /**
   * Deprecated. The name of the cluster to upgrade. This field has been deprecated and replaced by
   * the name field.
   * @return value or {@code null} for none
   */
  public java.lang.String getClusterId() {
    return clusterId;
  }

  /**
   * Deprecated. The name of the cluster to upgrade. This field has been deprecated and replaced by
   * the name field.
   * @param clusterId clusterId or {@code null} for none
   */
  public SetMonitoringServiceRequest setClusterId(java.lang.String clusterId) {
    this.clusterId = clusterId;
    return this;
  }

  /**
   * Required. The monitoring service the cluster should use to write metrics. Currently available
   * options: * "monitoring.googleapis.com/kubernetes" - The Cloud Monitoring service with a
   * Kubernetes-native resource model * `monitoring.googleapis.com` - The legacy Cloud Monitoring
   * service (no longer available as of GKE 1.15). * `none` - No metrics will be exported from the
   * cluster. If left as an empty string,`monitoring.googleapis.com/kubernetes` will be used for GKE
   * 1.14+ or `monitoring.googleapis.com` for earlier versions.
   * @return value or {@code null} for none
   */
  public java.lang.String getMonitoringService() {
    return monitoringService;
  }

  /**
   * Required. The monitoring service the cluster should use to write metrics. Currently available
   * options: * "monitoring.googleapis.com/kubernetes" - The Cloud Monitoring service with a
   * Kubernetes-native resource model * `monitoring.googleapis.com` - The legacy Cloud Monitoring
   * service (no longer available as of GKE 1.15). * `none` - No metrics will be exported from the
   * cluster. If left as an empty string,`monitoring.googleapis.com/kubernetes` will be used for GKE
   * 1.14+ or `monitoring.googleapis.com` for earlier versions.
   * @param monitoringService monitoringService or {@code null} for none
   */
  public SetMonitoringServiceRequest setMonitoringService(java.lang.String monitoringService) {
    this.monitoringService = monitoringService;
    return this;
  }

  /**
   * The name (project, location, cluster) of the cluster to set monitoring. Specified in the format
   * `projects/locations/clusters`.
   * @return value or {@code null} for none
   */
  public java.lang.String getName() {
    return name;
  }

  /**
   * The name (project, location, cluster) of the cluster to set monitoring. Specified in the format
   * `projects/locations/clusters`.
   * @param name name or {@code null} for none
   */
  public SetMonitoringServiceRequest setName(java.lang.String name) {
    this.name = name;
    return this;
  }

  /**
   * Deprecated. The Google Developers Console [project ID or project
   * number](https://cloud.google.com/resource-manager/docs/creating-managing-projects). This field
   * has been deprecated and replaced by the name field.
   * @return value or {@code null} for none
   */
  public java.lang.String getProjectId() {
    return projectId;
  }

  /**
   * Deprecated. The Google Developers Console [project ID or project
   * number](https://cloud.google.com/resource-manager/docs/creating-managing-projects). This field
   * has been deprecated and replaced by the name field.
   * @param projectId projectId or {@code null} for none
   */
  public SetMonitoringServiceRequest setProjectId(java.lang.String projectId) {
    this.projectId = projectId;
    return this;
  }

  /**
   * Deprecated. The name of the Google Compute Engine
   * [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides.
   * This field has been deprecated and replaced by the name field.
   * @return value or {@code null} for none
   */
  public java.lang.String getZone() {
    return zone;
  }

  /**
   * Deprecated. The name of the Google Compute Engine
   * [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides.
   * This field has been deprecated and replaced by the name field.
   * @param zone zone or {@code null} for none
   */
  public SetMonitoringServiceRequest setZone(java.lang.String zone) {
    this.zone = zone;
    return this;
  }

  @Override
  public SetMonitoringServiceRequest set(String fieldName, Object value) {
    return (SetMonitoringServiceRequest) super.set(fieldName, value);
  }

  @Override
  public SetMonitoringServiceRequest clone() {
    return (SetMonitoringServiceRequest) super.clone();
  }

}

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>
<title>Selection test iframe</title>
<link rel=author title="Aryeh Gregor" href=ayg@aryeh.name>
<body>
<script src=common.js></script>
<script>
"use strict";

// This script only exists because we want to evaluate the range endpoints
// in each iframe using that iframe's local variables set up by common.js.  It
// just creates a range with the endpoints given by
// eval(window.testRangeInput), and assigns the result to window.testRange.  If
// there's an exception, it's assigned to window.unexpectedException.
// Everything else is to be done by the script that created the iframe.
window.unexpectedException = null;

function run() {
    window.unexpectedException = null;
    try {
        window.testRange = rangeFromEndpoints(eval(window.testRangeInput));
    } catch(e) {
        window.unexpectedException = e;
    }
}

// Remove the scripts so they don't run repeatedly when the iframe is
// reinitialized
[].forEach.call(document.querySelectorAll("script"), function(script) {
    script.parentNode.removeChild(script);
});

testDiv.style.display = "none";
</script>


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

<title>Rept (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

FIELD |

CONSTR |

METHOD

DETAIL:

FIELD |

CONSTR |

METHOD

org.apache.poi.ss.formula.functions

Class Rept

java.lang.Object

org.apache.poi.ss.formula.functions.Fixed2ArgFunction

org.apache.poi.ss.formula.functions.Rept

All Implemented Interfaces:

Function, Function2Arg

public class Rept
extends Fixed2ArgFunction

Implementation for Excel REPT () function.

 Syntax:
 REPT  (text,number_times )

 Repeats text a given number of times. Use REPT to fill a cell with a number of instances of a text string.

 text : text The text that you want to repeat.
 number_times:  A positive number specifying the number of times to repeat text.

 If number_times is 0 (zero), REPT returns "" (empty text).
 If this argument contains a decimal value, this function ignores the numbers to the right side of the decimal point.

 The result of the REPT function cannot be longer than 32,767 characters, or REPT returns #VALUE!.

Author:

cedric dot walter @ gmail dot com

Constructor Summary

Constructors

Constructor and Description

Rept()

Method Summary

Methods

Modifier and Type
Method and Description

ValueEval
evaluate(int srcRowIndex,
        int srcColumnIndex,
        ValueEval text,
        ValueEval number_times)

see Function.evaluate(ValueEval[], int, int)

Methods inherited from class org.apache.poi.ss.formula.functions.Fixed2ArgFunction

evaluate

Methods inherited from class java.lang.Object

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

Constructor Detail

Rept

public Rept()

Method Detail

evaluate

public ValueEval evaluate(int srcRowIndex,
                 int srcColumnIndex,
                 ValueEval text,
                 ValueEval number_times)

Description copied from interface: Function2Arg

see Function.evaluate(ValueEval[], int, int)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

FIELD |

CONSTR |

METHOD

DETAIL:

FIELD |

CONSTR |

METHOD

                Copyright 2016 The Apache Software Foundation or
        its licensors, as applicable.


text:
FROM ruby:2.6.3-slim
ENV PORT 3000

WORKDIR /app

RUN apt-get update && \
  DEBIAN_FRONTEND=noninteractive apt-get install -qq -y --fix-missing --no-install-recommends \
    build-essential \
    curl \
    git && \
    apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

COPY Gemfile Gemfile.lock ./
RUN bundle install

COPY . .

ENTRYPOINT bundle exec unicorn -p $PORT -c ./config/unicorn.rb


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var router_1 = require('@angular/router');
var user_service_1 = require('../../services/user.service');
var IntroductionComponent = (function () {
    function IntroductionComponent(element, userService) {
        this.element = element;
        this.userService = userService;
        this.user = {
            Name: '',
            Email: ''
        };
    }
    IntroductionComponent.prototype.ngAfterViewInit = function () {
        var self = this;
        componentHandler
            .upgradeElements(self.element.nativeElement.querySelectorAll('.mdl-textfield'));
    };
    IntroductionComponent.prototype.signup = function () {
        this.userService.signup(this.user)
            .subscribe(function (res) { return console.log(res); }, function (err) { return console.error(err); });
    };
    IntroductionComponent = __decorate([
        core_1.Component({
            selector: 'introduction',
            templateUrl: 'app/components/introduction/introduction.html',
            providers: [user_service_1.UserService],
            directives: [router_1.ROUTER_DIRECTIVES]
        }),
        __metadata('design:paramtypes', [core_1.ElementRef, user_service_1.UserService])
    ], IntroductionComponent);
    return IntroductionComponent;
}());
exports.IntroductionComponent = IntroductionComponent;
//# sourceMappingURL=introduction.component.js.map


text:
.icon-arrow-in {
  background-image: url(../images/arrow_in.png);
}

.icon-arrow-out {
  background-image: url(../images/arrow_out.png);
}

.simplify-on, .simplify-off {
  float: right;
}

.simple-box textarea {
  width: 99%;
  min-width: 99%;
  max-width: 99%;
}

p.no-label {
  padding: 3px 0 3px 8px;
}

.simple-box {
  padding:6px;
  margin-bottom: 10px;
  background-color:#f6f6f6;
  color:#505050;
  line-height:1.5em;
  border: 1px solid #e4e4e4;
}

.simple-buttons {
}

input#issue_assigned_to_id_ac {
  width: 60%;
}

#new-member-candidate {
  font-weight: bold;
}

#ruler {
  position: absolute;
  top: 115px;
  left: 0;
  width: 1000px;
  background-color: gray;
  height: 1px;
}

.simple-box.tabular label {
  margin-top: 2px;
}

.simple-hidden {
  display: none;
}

.select2-field input {
  padding: 0;
}

ul.select2-results {
  max-height: 400px;
}

select:not([multiple='multiple']) {
  -webkit-padding-end: 22px;
  -webkit-padding-start: 8px;
}

select:not([multiple='multiple']) {
  -webkit-appearance: button;
  -webkit-border-radius: 4px;
  -webkit-user-select: none;

  background-color: #fff;
  background-image: url(/plugin_assets/redmine__select2/images/select2-arrow.png), -webkit-gradient(linear, left bottom, left top, color-stop(0, #eeeeee), color-stop(0.5, white));
  background-image: url(/plugin_assets/redmine__select2/images/select2-arrow.png), -o-linear-gradient(bottom, #eeeeee 0%, #ffffff 50%);
  background-image: url(/plugin_assets/redmine__select2/images/select2-arrow.png), -ms-linear-gradient(top, #ffffff 0%, #eeeeee 50%);
  background-position: center right;
  background-repeat: no-repeat;
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr = '#ffffff', endColorstr = '#eeeeee', GradientType = 0);

  background-image: url(/plugin_assets/redmine__select2/images/select2-arrow.png), linear-gradient(top, #ffffff 0%, #eeeeee 50%);

  border: 1px solid #aaa;
  border-radius: 4px 4px 4px 4px;
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  height: 22px;
  padding: 0 13px 0 3px;

  font: inherit;
}

@-moz-document url-prefix() {
  select:not([multiple='multiple']) {
    -webkit-appearance: none;
    -moz-appearance: none;
    text-indent: 1px;
    text-overflow: '';

    background-image: url("/plugin_assets/redmine__select2/images/select2-arrow.png"), -moz-linear-gradient(center bottom , #EEEEEE 0%, white 50%);

    padding: 1px 3px 0 2px;
  }
}

@media \0screen {
  select { padding-right: 0; }
}

.simple-box select, .simple-box select#issue_done_ratio {
  width: 20%;
}

.simple-box input, .simple-box textarea {
  font: inherit;
}


text:
// Copyright 2008 Google Inc. All Rights Reserved

package org.waveprotocol.wave.model.operation;

/**
 * An operation sink is an opaque operation applier.  It has a single method through which
 * operations are passed, and must obey the contract that the intent of that operation gets
 * executed.  Note this is a weaker contract than actually executing the {@link
 * Operation#apply(Object)} method on that operation (for example, the operation may be transformed
 * into another operation instance, so that the new operation's {@code apply} method would be called
 * instead).
 *
 * A sink also abstracts away the locating of the appropriate object to which the operation is
 * applied.   Usually, a sink will either pass the operation to another sink, or be a manager for
 * instances of the target type to which the operation applies, and will identify the appropriate
 * instance and then execute the operation's {@code apply} method on that instance.
 *
*
 *
 * @param <T>
 */
public interface OperationSink<T extends Operation<?>> {
  /**
   * An operation sink which does nothing with consumed operations.
   */
  static final OperationSink<Operation<?>> VOID =
    new OperationSink<Operation<?>>() {
      @Override
      public void consume(Operation<?> op) {
      }
    };

  /** Builds operation sinks which simply apply sunk operations to a target. */
  final class Executor {
    /**
     * Creates a new operation sink which applies all received ops to a target.
     *
     * @param target target to which to apply ops.
     * @param <O> type of operations sunk
     * @param <T> type of the operation target
     */
    public static <O extends Operation<? super T>, T> OperationSink<O> build(final T target) {
      return new OperationSink<O>() {
        public void consume(O op) throws OperationException {
          op.apply(target);
        }
      };
    }
  }

  /**
   * Consumes an operation.  Usually, this will involve finding an appropriate target for the
   * operation, then calling {@link Operation#apply(Object)} on that target.  However, this is not
   * a strong guarantee.  The only contract for a sink is to ensure that the intent of the given
   * operation is effected.
   *
   * @param op  operation to apply
   */
  public void consume(T op) throws OperationException;
}


text:
<?php

/**
 * Standard event handler for context cursor manipulation.
 *
 * @access public
 * @module record
 * @package User interface
 */

# Copyright (c) 2000-2002 dev/consulting GmbH
# Copyright (c) 2011 Sven Michael Klose <pixel@copei.de>
#
# Licensed under the MIT, BSD and GPL licenses.

/**
 * Initialise this module.
 *
 * @param object application $app
 */
function _records_init (&$app)
{
    $h = array ('record_create', 'record_update', 'record_delete', 'record_delete_force');
    util_add_raw_functions ($app, $h);

    $app->record_messages = array (
        'record_saved' => 'Record saved.',
        'delete_ask' => 'Delete this record?',
        'delete_nothing' => 'Nothing delted.',
        'delete_done' => 'Record removed.',
        'create_done' => 'Record created.',
        'yes' => 'Yes.',
        'no' => 'No.'
    );
}

/**
 * Create record listed in $sources with optional field values or aliases.
 *
 * @access public
 * @param object application $app
 * @param array $set Source set which describes the records to be created.
 */
function record_create_set (&$app, &$set)
{
    $ui =& $app->ui;

    $keyset = array ();
    foreach ($set as $cursortype => $sources) {
        $tmp = "cursor_$cursortype";
        $cursor = new $tmp;

        foreach ($sources as $source => $v) {
            list ($values, $pre) = $v;
            if (!is_array ($pre))
                die_traced ("Can't create record. Preset values are not in an array for source $source.");

            # Replace aliases by key to inserted record in specified source in
            # this function. An alias is placed in preset_values' field data in
            # the form @<source name>.
            foreach ($pre as $field => $data) {
                if (substr ($data, 0, 1) == '@') {
                    $s = substr ($data, 1);
                    if (!isset ($aliases[$s]))
                        die_traced ("No record in source $source created source $s could point to.");

                    # Replace alias by id of inserted record.
                    $pre[$field] = $aliases[$s];
                }
            }

            # Create record.
            $cursor->set_source ($source);
            $cursor->set_preset_values ($pre);
            $key = $cursor->create ($values);
            $keyset[$cursor->type ()][$source] = $key;

            # Remeber key for alias.
            $aliases[$source] = $key;

            # Highlight new record.
            $cursor->set_key ($key);
            $ui->highlight[$cursor->id ()] = '#00FF00';
        }
    }

    if (!$keyset)
        die_traced ('Couldn\'t create record.');
    if ($keyset && isset ($app->record_messages['create_done']))
        $ui->msgbox ($app->record_messages['create_done']);

    return $keyset;
}

/**
 * Event handler: Create a new row in table.
 *
 * Optional event argument 'sources' takes a source set, otherwise the
 * context cursor is used and field values can be specified in
 * array 'preset_values. 'msg' takes a message to print if the record
 * was created.
 *
 * @access public
 * @param object application $app
 * @see record_create_set()
 */
function record_create (&$app)
{
    $sources = $app->arg ('sources', ARG_OPTIONAL);
    $msg = $app->arg ('msg', ARG_OPTIONAL);
    $pre = $app->arg ('preset_values', ARG_OPTIONAL);

    # If link was created without arguments, create a source set with a
    # single element from the argument's cursor.
    if (!$sources) {
        $cursor = $app->arg ('_cursor');
        $sources[$cursor->type ()][$cursor->source ()] = array (null, $pre ? $pre : array ());
    } else
        if ($app->arg ('preset_values', ARG_OPTIONAL))
            die_traced ("Arguments 'preset_values' and 'sources' can't be used together.");

    return record_create_set ($app, $sources);
}

/**
 * Calls form_update() and outputs a success or error message.
 *
 * Non-existing primary keys will be ignored. The event context is
 * highlighted.
 *
 * @access public
 * @param object application $app
 * @see cmd_update (), form_update()
 */
function record_update (&$app)
{
    $cursor = $app->arg ('_cursor');
    $ui =& $app->ui;

    $err = form_update ($app);
    if ($err)
        $ui->panic ($err);

    $ui->highlight[$cursor->id ()] = '#00FF00';
    $ui->msgbox ($app->record_messages['record_saved']);
}

/**
 * Event handler: Ask to delete records.
 *
 * This handler asks to kill records and then triggers record_delete_force().
 * Event argument '_cursor' can contain the context cursor, an array of
 * cursors can be passed in 'cursor_list' instead. 'yes_view' can contain
 * an event that is triggered if record were deleted, 'no_view' can contain
 * one for the opposite case (the deletion failed).
 *
 * @access public
 * @param object application $app
 * @see record_delete_force()
 */
function record_delete (&$app)
{
    $cursor = $app->arg ('_cursor', ARG_OPTIONAL);
    $cursor_list = $app->arg ('cursor_list', ARG_OPTIONAL);
    $yes_view = $app->arg ('yes_view', ARG_OPTIONAL);
    $no_view = $app->arg ('no_view', ARG_OPTIONAL);
    $ui =& $app->ui;
    $m = $app->record_messages;
    $tv = $app->event ();

    # Highlight records, check available cursors.
    if (!$cursor_list && !is_array ($cursor_list)) {
        if (!$cursor)
            die_traced ('No cursor.');
        if (!$cursor->key ())
            die_traced ("No key of any record in source '{${$cursor->source ()}}'.");

        # Highlight record.
        $ui->highlight[$cursor->id ()] = '#FFAAAA';
    } else {
        # Cancel deletion if cursor list is empty.
        if (!sizeof ($cursor_list))
            return;

        # Highlight records.
        foreach ($cursor_list as $cursor) {
            $cursor->set_field ('');
            $ui->highlight[$cursor->id ()] = '#FFAAAA';
        }
    }

    if (!$yes_view) {
        if (!$tv->next)
            die_traced ('No argument \'yes_view\' nor next view.');
        $yes_view = $tv->next;
    }
    if (!$no_view) {
        if (!$tv->next)
            die_traced ('No argument \'no_view\' nor next view.');
        $no_view = $tv->next;
    }

    # Create link to real kill.
    $yes = new event ('record_delete_force');
    $yes->set_next ($yes_view);
    $yes->set_arg ('_cursor', $app->arg ('_cursor', ARG_OPTIONAL));
    $yes->set_arg ('cursor_list', $cursor_list);

    $ui->confirm ($m['delete_ask'], $m['yes'], $yes, $m['no'], $no_view);
}

/**
 * Event handler: Delete records.
 *
 * Event argument '_cursor' can contain the context cursor, an array of
 * cursors can be passed in 'cursor_list' instead.
 *
 * @access public
 * @param object application $app
 */
function record_delete_force (&$app)
{
    $cursor = $app->arg ('_cursor', ARG_OPTIONAL);
    $cursor_list = $app->arg ('cursor_list', ARG_OPTIONAL);
    $ui =& $app->ui;

    if (!$cursor_list) {
        if (!$cursor)
            die_traced ('No context cursor or cursor_list.');

        $err = $cursor->delete ();
        if (!$err)
            return;
    } else
        foreach ($cursor_list as $cursor)
            if ($err = $cursor->delete ())
                break;

    if (isset ($err))
        $ui->panic ($err);

    $ui->msgbox ($app->record_messages['delete_done']);
}

?>


text:
set -e

RUT_VERSION=1.0.4-SNAPSHOT
NEXUS_BASE=/home/edalquist/Downloads/nexus

# Download and install rut plugin
RUT_PLUGIN_BASEDIR=${NEXUS_BASE}/sonatype-work/nexus/plugin-repository/nexus-rut-auth-plugin-
RUT_PLUGIN_DIR=${RUT_PLUGIN_BASEDIR}${RUT_VERSION}
rm -Rf ${RUT_PLUGIN_BASEDIR}*
mkdir -p ${RUT_PLUGIN_DIR}
cp ./nexus-rut-auth-plugin/target/nexus-rut-auth-plugin-${RUT_VERSION}.jar ${RUT_PLUGIN_DIR}/nexus-rut-auth-plugin-${RUT_VERSION}.jar

# Download and install rut filter
RUT_FILTER_BASE=${NEXUS_BASE}/nexus-oss-webapp/nexus/WEB-INF/lib/nexus-rut-auth-filter-
RUT_FILTER=${RUT_FILTER_BASE}${RUT_VERSION}.jar
rm -f ${RUT_FILTER_BASE}*
cp ./nexus-rut-auth-filter/target/nexus-rut-auth-filter-${RUT_VERSION}.jar ${RUT_FILTER}

# Update the web.xml to enable the remote-user filter
sed -ie 's/org.sonatype.nexus.security.filter.authc.NexusSecureHttpAuthenticationFilter/edu.wisc.nexus.auth.rut.RemoteUserNexusSecureHttpAuthenticationFilter/g' ${NEXUS_BASE}/nexus-oss-webapp/nexus/WEB-INF/web.xml


text:
int createTorrent(Torrent t){
	FILE *file = fopen("newTorrent.torrent", "wb");
	int i;

	fprintf(file, "d8:announce%d:%s13:announce-listll", strlen(t.announce), t.announce);
	for(i=0; i<sizeof(t.announceList)/sizeof(t.announceList[0])-1; i++)
		fprintf(file, "%d:%sel", strlen(t.announceList[i]), t.announceList[i]);
	fprintf(file, "%d:%see4:infod5:filesld", strlen(t.announceList[i]), t.announceList[i]);

	for(i=0; i<sizeof(t.files)/sizeof(t.files[0]); i++)
		fprintf(file, "6:lengthi%de4:name%d:%s", t.files[i].length, strlen(t.files[i].name), t.files[i].name);

	fprintf(file, "12:piece lengthi%de6:pieces%d:", t.pieceLength, sizeof(t.pieces)/t.pieceLength);
	for(i=0; i<sizeof(t.pieces)/sizeof(t.pieces[0]); i++)
		fprintf(file, "%x", t.pieces[i]);

	fclose(file);
	return 1;
}

int saveToFile(char *filePath, char *torrentPath, char *data,  unsigned char *hash, int pieceLength){
	int index = findHash(hash, torrentPath);
	FILE *file;
	fopen(filePath, "wb");
	fseek(file, index*pieceLength, SEEK_SET);
	fprintf(file, "%s", data);
	fclose(file);
	return 0;
}

char *readFromFile(char *filePath, char *torrentPath, unsigned char *hash, int pieceLength){
	int index = findHash(hash, torrentPath);
	char *piece;

	FILE *file;
	fopen(filePath, "rb");
	fseek(file, index*pieceLength, SEEK_SET);
	fread(piece, pieceLength, 1, file);
	fclose(file);
	return piece;
}


text:
/////////////////////////////////////////////////////////////////////////////
// Name:        wx/gtk1/toplevel.h
// Purpose:
// Author:      Robert Roebling
// Id:          $Id$
// Copyright:   (c) 1998 Robert Roebling, Julian Smart
// Licence:     wxWindows licence
/////////////////////////////////////////////////////////////////////////////

#ifndef __GTKTOPLEVELH__
#define __GTKTOPLEVELH__

//-----------------------------------------------------------------------------
// wxTopLevelWindowGTK
//-----------------------------------------------------------------------------

class WXDLLIMPEXP_CORE wxTopLevelWindowGTK : public wxTopLevelWindowBase
{
public:
    // construction
    wxTopLevelWindowGTK() { Init(); }
    wxTopLevelWindowGTK(wxWindow *parent,
                        wxWindowID id,
                        const wxString& title,
                        const wxPoint& pos = wxDefaultPosition,
                        const wxSize& size = wxDefaultSize,
                        long style = wxDEFAULT_FRAME_STYLE,
                        const wxString& name = wxFrameNameStr)
    {
        Init();

        Create(parent, id, title, pos, size, style, name);
    }

    bool Create(wxWindow *parent,
                wxWindowID id,
                const wxString& title,
                const wxPoint& pos = wxDefaultPosition,
                const wxSize& size = wxDefaultSize,
                long style = wxDEFAULT_FRAME_STYLE,
                const wxString& name = wxFrameNameStr);

    virtual ~wxTopLevelWindowGTK();

    // implement base class pure virtuals
    virtual void Maximize(bool maximize = true);
    virtual bool IsMaximized() const;
    virtual void Iconize(bool iconize = true);
    virtual bool IsIconized() const;
    virtual void SetIcons(const wxIconBundle& icons);
    virtual void Restore();

    virtual bool ShowFullScreen(bool show, long style = wxFULLSCREEN_ALL);
    virtual bool IsFullScreen() const { return m_fsIsShowing; }

    virtual bool SetShape(const wxRegion& region);

    virtual void RequestUserAttention(int flags = wxUSER_ATTENTION_INFO);

    virtual void SetWindowStyleFlag( long style );

    virtual bool Show(bool show = true);

    virtual void Raise();

    virtual bool IsActive();

    virtual void SetTitle( const wxString &title );
    virtual wxString GetTitle() const { return m_title; }

    // Experimental, to allow help windows to be
    // viewable from within modal dialogs
    virtual void AddGrab();
    virtual void RemoveGrab();
    virtual bool IsGrabbed() const { return m_grabbed; }

    // implementation from now on
    // --------------------------

    // move the window to the specified location and resize it: this is called
    // from both DoSetSize() and DoSetClientSize()
    virtual void DoMoveWindow(int x, int y, int width, int height);

    // GTK callbacks
    virtual void GtkOnSize( int x, int y, int width, int height );
    virtual void OnInternalIdle();

    // do *not* call this to iconize the frame, this is a private function!
    void SetIconizeState(bool iconic);

    int           m_miniEdge,
                  m_miniTitle;
    GtkWidget    *m_mainWidget;
    bool          m_insertInClientArea;  /* not from within OnCreateXXX */

    bool          m_fsIsShowing;         /* full screen */
    long          m_fsSaveGdkFunc, m_fsSaveGdkDecor;
    long          m_fsSaveFlag;
    wxRect        m_fsSaveFrame;

    // m_windowStyle translated to GDK's terms
    long          m_gdkFunc,
                  m_gdkDecor;

    // private gtk_timeout_add result for mimicing wxUSER_ATTENTION_INFO and
    // wxUSER_ATTENTION_ERROR difference, -2 for no hint, -1 for ERROR hint, rest for GtkTimeout handle.
    int m_urgency_hint;

protected:
    // common part of all ctors
    void Init();

    // override wxWindow methods to take into account tool/menu/statusbars
    virtual void DoSetSize(int x, int y,
                           int width, int height,
                           int sizeFlags = wxSIZE_AUTO);

    virtual void DoSetClientSize(int width, int height);
    virtual void DoGetClientSize( int *width, int *height ) const;

    wxString      m_title;

    // is the frame currently iconized?
    bool m_isIconized;
    // is the frame currently grabbed explicitly
    // by the application?
    bool m_grabbed;
};

#endif // __GTKTOPLEVELH__


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

namespace ZencoderWrapper
{
    public class CreateAccountRequest
    {
        /// <summary>
        /// Set to "1" if you agree to the Terms of Service.
        /// </summary>
        public string terms_of_service { get; set; }
        public string email { get; set; }
        public string password { get; set; }
        public string affiliate_code { get; set; }
        public bool? newsletter { get; set; }

        public CreateAccountRequest()
        {

        }

        public CreateAccountRequest(string email, string password)
            : this()
        {
            this.terms_of_service = "1";
            this.email = email;
            this.password = password;
        }

        public CreateAccountRequest(string email, string password, string affiliate_code)
            :this(email, password)
        {
            this.affiliate_code = affiliate_code;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <TextView
        android:layout_centerInParent="true"
        android:id="@+id/tv_item"
        android:textSize="16sp"
        android:gravity="center_vertical"
        android:layout_width="wrap_content"
        android:layout_height="50dp"/>

</RelativeLayout>


text:
<!doctype html>

    <title>Code coverage report for express-stormpath/lib/helpers/prep-account-data.js</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../../../prettify.css" />
    <link rel="stylesheet" href="../../../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      all files / express-stormpath/lib/helpers/ prep-account-data.js

        96.3%
        Statements
        26/27

        91.3%
        Branches
        21/23

        100%
        Functions
        3/3

        96.3%
        Lines
        26/27

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79

1×
25×

25×
1×

24×
1×

23×
1×

22×
2×

22×

22×

22×
100×
100×
88×
12×
3×
3×
3×
3×

9×
7×
7×

7×

22×

'use strict';

/**
 * @private
 * @callback prepAccountDataCallback
 * @param {Object} accountData - The prepared Stormpath Account data that is now
 *  ready to be created.
 */

/**
 * Takes in form data from a registration request, and converts it into a
 * valid Stormpath account object.
 *
 * This consists of extracting all non-core fields into customData to ensure
 * arbitrary data gets copied over to custom data upon account creation.
 *
 * @param {Object} formData - The user supplied form data.
 * @param {Object} stormpathConfig - The Stormpath configuration object.
 * @param {prepAccountDataCallback} callback - The callback to run.
 */
module.exports = function (formData, stormpathConfig, callback) {
  var passwordConfirmFieldName = 'passwordConfirm';

  if (!formData) {
    throw new Error('prepAccountData must be provided with a formData argument.');
  }

  if (!stormpathConfig) {
    throw new Error('prepAccountData must be provided with a stormpathConfig argument.');
  }

  if (!callback) {
    throw new Error('prepAccountData must be provided with a callback argument.');
  }

  if (stormpathConfig.web && stormpathConfig.web.register && stormpathConfig.web.register.fields && stormpathConfig.web.register.fields.passwordConfirm && stormpathConfig.web.register.fields.passwordConfirm.name) {
    passwordConfirmFieldName = stormpathConfig.web.register.fields.passwordConfirm.name;
  }

  var coreFields = [
    'username',
    'email',
    'password',
    'givenName',
    'middleName',
    'surname',
    'status',
    'password'
  ];

  var accountObject = { };

  Object.keys(formData).forEach(function (key) {
    var value = formData[key];
    if (coreFields.indexOf(key) > -1) {
      accountObject[key] = value;
    } else if (key === 'customData') {
      Eif (accountObject.customData) {
        Object.keys(value).reduce(function (customData, field) {
          customData[field] = value[field];
          return customData;
        }, accountObject.customData);

      } else {
        accountObject.customData = value;
      }

    } else if (key !== passwordConfirmFieldName) {
      Eif (!accountObject.customData) {
        accountObject.customData = {};
      }
      accountObject.customData[key] = value;
    }

  });

  callback(accountObject);
};

  Code coverage
  generated by istanbul at Fri Nov 20 2015 09:41:24 GMT-0800 (PST)


text:
namespace _03.Mankind
{
    using System;
    using System.Text;

    public class Worker : Human
    {
       // private const int workerLastNameMinLength = 3;
        private const int workerWeekMinSalary = 10;
        private const int workerMinWorkingHours = 1;
        private const int workerMaxWorkingHours = 12;

        private decimal weekSalary;
        private decimal workingHours;

        public Worker(string firstName, string lastName, decimal salary, decimal workingHours)
            : base(firstName, lastName)
        {
            this.WeekSalary = salary;
            this.WorkingHours = workingHours;
        }

        public decimal WeekSalary
        {
            get
            {
                return this.weekSalary;
            }
            set
            {
                if (value <= workerWeekMinSalary)
                {
                    throw new ArgumentException("Expected value mismatch! Argument: weekSalary");
                }
                this.weekSalary = value;
            }
        }

        public decimal WorkingHours
        {
            get
            {
                return this.workingHours;
            }
            set
            {
                if (value < workerMinWorkingHours || value > workerMaxWorkingHours)
                {
                    throw new ArgumentException("Expected value mismatch! Argument: workHoursPerDay");
                }
                this.workingHours = value;
            }
        }

        public string SalaryperHour()
        {
            var paymentPerDay = this.WeekSalary / 5;
            return $"{paymentPerDay / this.WorkingHours:F2}";
        }

        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.Append("First Name: ").AppendLine(this.FirstName)
                .Append("Last Name: ").AppendLine(this.LastName)
                .Append("Week Salary: ").AppendLine($"{this.WeekSalary:F2}")
                .Append("Hours per day: ").AppendLine($"{this.WorkingHours:F2}")
                .Append("Salary per hour: ").AppendLine(SalaryperHour())
                .AppendLine();

            return sb.ToString();
        }
    }
}


text:
<!DOCTYPE html>

<meta charset="UTF-8">
	<title>Hotel Panoramic</title>

	<meta name="apple-mobile-web-app-capable" content="yes">

	<meta name="apple-mobile-web-app-status-bar-style" content="black">

	<meta name="apple-mobile-web-app-title" content="Lemonado Web App">

	<meta name="viewport" content="width=device-width, initial-scale=1">

	<link href="assets/img/apple/apple-touch-icon-152x152.png"
		  sizes="152x152"
		  rel="apple-touch-icon">

	<link href="assets/img/apple/apple-touch-icon-144x144.png"
		  sizes="144x144"
		  rel="apple-touch-icon">

	<link href="assets/img/apple/apple-touch-icon-120x120.png"
		  sizes="120x120"
		  rel="apple-touch-icon">

	<link href="assets/img/apple/apple-touch-icon-114x114.png"
		  sizes="114x114"
		  rel="apple-touch-icon">

	<link href="assets/img/apple/apple-touch-icon-76x76.png"
		  sizes="76x76"
		  rel="apple-touch-icon">

	<link href="assets/img/apple/apple-touch-icon-72x72.png"
		  sizes="72x72"
		  rel="apple-touch-icon">

	<link href="assets/img/apple/apple-touch-icon-57x57.png"
		  sizes="57x57"
		  rel="apple-touch-icon">

	<link href="assets/img/apple/apple-touch-startup-image-1536x2008.png"
		  media="(device-width: 768px) and (device-height: 1024px)
			 and (orientation: portrait)
			 and (-webkit-device-pixel-ratio: 2)"
		  rel="apple-touch-startup-image">

	<link href="assets/img/apple/apple-touch-startup-image-1496x2048.png"
		  media="(device-width: 768px) and (device-height: 1024px)
			 and (orientation: landscape)
			 and (-webkit-device-pixel-ratio: 2)"
		  rel="apple-touch-startup-image">

	<link href="assets/img/apple/apple-touch-startup-image-768x1004.png"
		  media="(device-width: 768px) and (device-height: 1024px)
			 and (orientation: portrait)
			 and (-webkit-device-pixel-ratio: 1)"
		  rel="apple-touch-startup-image">

	<link href="assets/img/apple/apple-touch-startup-image-748x1024.png"
		  media="(device-width: 768px) and (device-height: 1024px)
			 and (orientation: landscape)
			 and (-webkit-device-pixel-ratio: 1)"
		  rel="apple-touch-startup-image">

	<link href="assets/img/apple/apple-touch-startup-image-640x1096.png"
		  media="(device-width: 320px) and (device-height: 568px)
			 and (-webkit-device-pixel-ratio: 2)"
		  rel="apple-touch-startup-image">

	<link href="assets/img/apple/apple-touch-startup-image-640x920.png"
		  media="(device-width: 320px) and (device-height: 480px)
			 and (-webkit-device-pixel-ratio: 2)"
		  rel="apple-touch-startup-image">

	<link href="assets/img/apple/apple-touch-startup-image-320x460.png"
		  media="(device-width: 320px) and (device-height: 480px)
			 and (-webkit-device-pixel-ratio: 1)"
		  rel="apple-touch-startup-image">
<link rel="stylesheet" href="assets/css/jquery.mobile-1.4.5.min.css">
	<link rel="stylesheet" href="assets/css/style.css" />
	<link rel="stylesheet" href="assets/css/owl.carousel.css">
	<link rel="stylesheet" href="assets/css/owl.theme.css">
	<link rel="stylesheet" href="assets/css/photoswipe.css">

Home

Hotels

Gallery

Music

Information

Social

Share this page on:

			Gallery

Hotel Panoramic

Hotel with swimming pool in the Tuscan countryside. Our fees include overnight stay and a buffet breakfast with fresh cakes, a wide variety of cheeses, cold cuts, yogurt, fruit juices, jams, honey, and coffee bar.
All the rooms have been recently renovated and have toilet facilities with 90×120 cm shower, king-size bed, TV sat LCD, SKY free,telephone, parquet floor, living room, free WI FI also in pool, minibar, air-conditioning, independent heating system, safe, fire resistant tissues, sound-proof walls, lift, left-luggage room and balcony (on request).
The hotel is surrounded by a large garden which offers a breath-taking view over the Tuscan countryside.
Hydro-massage swimming pool and solarium, sunbeds and umbrellas at no extra charge. Free parking lot. W provide transport service from/to Montepulciano at request. Bedroom service 24 hours a day. English-speaking personnel. All credit cards accepted. The hotel's energy consumption is fully covered by renewable sources.
Pet-friendly hotel. Internet point. Tennis court. Ping Pong.
Our qualified personnel will welcome you at the reception and answer any question you have to make your stay in Montepulciano as comfortable as possible.

Contacts

Via di Villa Bianca, 8 53045 Montepulciano (SI)

Coordinate Satellitari: 43.076325,11.791854 (on Google Maps and OpenStreetMap)

 Tel. 0578 798398-798394 | Fax 0578 799205

 www.hotelpanoramic.com

 info@hotelpanoramic.com

          <input type="button" value="Book Now">

Copyright 2015 - 2020. All rights reserved


text:
System timestamp denotes the time of backend cluster system. Application timestamp denotes the time at which message is generated. For example, for IoT edge device, the timestamp at which field sensor device creates a message is type of application timestamp, while the timestamp at which that message get received by the backend is type of system time.

### Master, and Worker

Gearpump follow master slave architecture. Every cluster contains one or more Master node, and several worker nodes. Worker node is responsible to manage local resources on single machine, and Master node is responsible to manage global resources of the whole cluster.

![Actor Hierarchy](../img/actor_hierarchy.png)

### Application

Application is what we want to parallel and run on the cluster. There are different application types, for example MapReduce application and streaming application are different application types. Gearpump natively supports Streaming Application types, it also contains several templates to help user to create custom application types, like distributedShell.

### AppMaster and Executor

In runtime, every application instance is represented by a single AppMaster and a list of Executors. AppMaster represents the command and controls center of the Application instance. It communicates with user, master, worker, and executor to get the job done. Each executor is a parallel unit for distributed application. Typically AppMaster and Executor will be started as JVM processes on worker nodes.

### Application Submission Flow

When user submits an application to Master, Master will first find an available worker to start the AppMaster. After AppMaster is started, AppMaster will request Master for more resources (worker) to start executors. The Executor now is only an empty container. After the executors are started, the AppMaster will then distribute real computation tasks to the executor and run them in parallel way.

To submit an application, a Gearpump client specifies a computation defined within a DAG and submits this to an active master. The SubmitApplication message is sent to the Master who then forwards this to an AppManager.

![Submit App](../img/submit.png)
Figure: User Submit Application

The AppManager locates an available worker and launches an AppMaster in a sub-process JVM of the worker. The AppMaster will then negotiate with the Master for Resource allocation in order to distribute the DAG as defined within the Application. The allocated workers will then launch Executors (new JVMs).

![Launch Executors and Tasks](../img/submit2.png)
Figure: Launch Executors and Tasks

### Streaming Topology, Processor, and Task

For streaming application type, each application contains a topology, which is a DAG (directed acyclic graph) to describe the data flow. Each node in the DAG is a processor. For example, for word count it contains two processors, Split and Sum. The Split processor splits a line to a list of words, and then the Sum processor summarize the frequency of each word.
An application is a DAG of processors. Each processor handles messages.

![DAG](../img/dag.png)
Figure: Processor DAG

### Streaming Task and Partitioner

For streaming application type, Task is the minimum unit of parallelism. In runtime, each Processor is paralleled to a list of tasks, with different tasks running in different executor. You can define Partitioner to denote the data shuffling rule between upstream processor tasks and downstream processor tasks.

![Data Shuffle](../img/shuffle.png)
Figure: Task Data Shuffling