text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#pragma once

#include "Factories.h"

class ALight;
class UInterpGroupInst;
class AMatineeActor;
class AActor;
class UInterpTrackMove;

// Temporarily disable a few warnings due to virtual function abuse in FBX source files
#pragma warning( push )

#pragma warning( disable : 4263 ) // 'function' : member function does not override any base class virtual member function
#pragma warning( disable : 4264 ) // 'virtual_function' : no override available for virtual member function from base 'class'; function is hidden

// Include the fbx sdk header
// temp undef/redef of _O_RDONLY because kfbxcache.h (included by fbxsdk.h) does
// a weird use of these identifiers inside an enum.
#ifdef _O_RDONLY
#define TMP_UNFBX_BACKUP_O_RDONLY _O_RDONLY
#define TMP_UNFBX_BACKUP_O_WRONLY _O_WRONLY
#undef _O_RDONLY
#undef _O_WRONLY
#endif

//Robert G. : Packing was only set for the 64bits platform, but we also need it for 32bits.
//This was found while trying to trace a loop that iterate through all character links.
//The memory didn't match what the debugger displayed, obviously since the packing was not right.
#pragma pack(push,8)

#if PLATFORM_WINDOWS
// _CRT_SECURE_NO_DEPRECATE is defined but is not enough to suppress the deprecation
// warning for vsprintf and stricmp in VS2010.  Since FBX is able to properly handle the non-deprecated
// versions on the appropriate platforms, _CRT_SECURE_NO_DEPRECATE is temporarily undefined before
// including the FBX headers

// The following is a hack to make the FBX header files compile correctly under Visual Studio 2012 and Visual Studio 2013
#if _MSC_VER >= 1700
	#define FBX_DLL_MSC_VER 1600
#endif

#endif // PLATFORM_WINDOWS

#include <fbxsdk.h>

#include "TokenizedMessage.h"

#pragma pack(pop)

#ifdef TMP_UNFBX_BACKUP_O_RDONLY
#define _O_RDONLY TMP_FBX_BACKUP_O_RDONLY
#define _O_WRONLY TMP_FBX_BACKUP_O_WRONLY
#undef TMP_UNFBX_BACKUP_O_RDONLY
#undef TMP_UNFBX_BACKUP_O_WRONLY
#endif

#pragma warning( pop )

class FSkeletalMeshImportData;
class FSkelMeshOptionalImportData;
class ASkeletalMeshActor;
class UInterpTrackMoveAxis;
struct FbxSceneInfo;

DECLARE_LOG_CATEGORY_EXTERN(LogFbx, Log, All);

#define DEBUG_FBX_NODE( Prepend, FbxNode ) FPlatformMisc::LowLevelOutputDebugStringf( TEXT("%s %s\n"), ANSI_TO_TCHAR(Prepend), ANSI_TO_TCHAR( FbxNode->GetName() ) )

namespace UnFbx
{

struct FBXImportOptions
{
	// General options
	bool bImportMaterials;
	bool bInvertNormalMap;
	bool bImportTextures;
	bool bImportLOD;
	bool bUsedAsFullName;
	bool bConvertScene;
	bool bRemoveNameSpace;
	FVector ImportTranslation;
	FRotator ImportRotation;
	float ImportUniformScale;
	EFBXNormalImportMethod NormalImportMethod;
	EFBXNormalGenerationMethod::Type NormalGenerationMethod;
	// Static Mesh options
	bool bCombineToSingle;
	EVertexColorImportOption::Type VertexColorImportOption;
	FColor VertexOverrideColor;
	bool bRemoveDegenerates;
	bool bBuildAdjacencyBuffer;
	bool bGenerateLightmapUVs;
	bool bOneConvexHullPerUCX;
	bool bAutoGenerateCollision;

	FName StaticMeshLODGroup;
	// Skeletal Mesh options
	bool bImportMorph;
	bool bImportAnimations;
	bool bUpdateSkeletonReferencePose;
	bool bResample;
	bool bImportRigidMesh;
	bool bUseT0AsRefPose;
	bool bPreserveSmoothingGroups;
	bool bKeepOverlappingVertices;
	bool bImportMeshesInBoneHierarchy;
	bool bCreatePhysicsAsset;
	UPhysicsAsset *PhysicsAsset;
	// Animation option
	USkeleton* SkeletonForAnimation;
	EFBXAnimationLengthImportType AnimationLengthImportType;
	struct FIntPoint AnimationRange;
	FString AnimationName;
	bool	bPreserveLocalTransform;
	bool	bDeleteExistingMorphTargetCurves;
	bool	bImportCustomAttribute;

	bool ShouldImportNormals()
	{
		return NormalImportMethod == FBXNIM_ImportNormals || NormalImportMethod == FBXNIM_ImportNormalsAndTangents;
	}

	bool ShouldImportTangents()
	{
		return NormalImportMethod == FBXNIM_ImportNormalsAndTangents;
	}

	void ResetForReimportAnimation()
	{
		bImportMorph = true;
		AnimationLengthImportType = FBXALIT_ExportedTime;
	}
};

struct FbxMeshInfo
{
	char* Name;
	int32 FaceNum;
	int32 VertexNum;
	bool bTriangulated;
	int32 MaterialNum;
	bool bIsSkelMesh;
	char* SkeletonRoot;
	int32 SkeletonElemNum;
	char* LODGroup;
	int32 LODLevel;
	int32 MorphNum;
};

struct FbxSceneInfo
{
	// data for static mesh
	int32 NonSkinnedMeshNum;

	//data for skeletal mesh
	int32 SkinnedMeshNum;

	// common data
	int32 TotalGeometryNum;
	int32 TotalMaterialNum;
	int32 TotalTextureNum;

	TArray<FbxMeshInfo> MeshInfo;

	/* true if it has animation */
	bool bHasAnimation;
	double FrameRate;
	double TotalTime;

};

/**
* FBX basic data conversion class.
*/
class FFbxDataConverter
{
public:

	FFbxDataConverter()
	{}

	FVector ConvertPos(FbxVector4 Vector);
	FVector ConvertDir(FbxVector4 Vector);
	FRotator ConvertEuler( FbxDouble3 Euler );
	FVector ConvertScale(FbxDouble3 Vector);
	FVector ConvertScale(FbxVector4 Vector);
	FRotator ConvertRotation(FbxQuaternion Quaternion);
	FVector ConvertRotationToFVect(FbxQuaternion Quaternion, bool bInvertRot);
	FQuat ConvertRotToQuat(FbxQuaternion Quaternion);
	float ConvertDist(FbxDouble Distance);
	bool ConvertPropertyValue(FbxProperty& FbxProperty, UProperty& UnrealProperty, union UPropertyValue& OutUnrealPropertyValue);
	FTransform ConvertTransform(FbxAMatrix Matrix);
	FMatrix ConvertMatrix(FbxAMatrix Matrix);

	FbxVector4 ConvertToFbxPos(FVector Vector);
	FbxVector4 ConvertToFbxRot(FVector Vector);
	FbxVector4 ConvertToFbxScale(FVector Vector);
	FbxVector4 ConvertToFbxColor(FColor Color);
	FbxString	ConvertToFbxString(FName Name);
	FbxString	ConvertToFbxString(const FString& String);
};

FBXImportOptions* GetImportOptions( class FFbxImporter* FbxImporter, UFbxImportUI* ImportUI, bool bShowOptionDialog, const FString& FullPath, bool& OutOperationCanceled, bool& OutImportAll, bool bIsObjFormat, bool bForceImportType = false, EFBXImportType ImportType = FBXIT_StaticMesh );
void ApplyImportUIToImportOptions(UFbxImportUI* ImportUI, FBXImportOptions& InOutImportOptions);

struct FImportedMaterialData
{
public:
	void AddImportedMaterial( FbxSurfaceMaterial& FbxMaterial, UMaterialInterface& UnrealMaterial );
	bool IsUnique( FbxSurfaceMaterial& FbxMaterial, FName ImportedMaterialName ) const;
	UMaterialInterface* GetUnrealMaterial( const FbxSurfaceMaterial& FbxMaterial ) const;
	void Clear();
private:
	/** Mapping of FBX material to Unreal material.  Some materials in FBX have the same name so we use this map to determine if materials are unique */
	TMap<FbxSurfaceMaterial*, TWeakObjectPtr<UMaterialInterface> > FbxToUnrealMaterialMap;
	TSet<FName> ImportedMaterialNames;
};

/**
 * Main FBX Importer class.
 */
class FFbxImporter
{
public:
	~FFbxImporter();
	/**
	 * Returns the importer singleton. It will be created on the first request.
	 */
	UNREALED_API static FFbxImporter* GetInstance();
	static void DeleteInstance();

	/**
	 * Detect if the FBX file has skeletal mesh model. If there is deformer definition, then there is skeletal mesh.
	 * In this function, we don't need to import the scene. But the open process is time-consume if the file is large.
	 *
	 * @param InFilename	FBX file name.
	 * @return int32 -1 if parse failed; 0 if geometry ; 1 if there are deformers; 2 otherwise
	 */
	int32 GetImportType(const FString& InFilename);

	/**
	 * Get detail infomation in the Fbx scene
	 *
	 * @param Filename Fbx file name
	 * @param SceneInfo return the scene info
	 * @return bool true if get scene info successfully
	 */
	bool GetSceneInfo(FString Filename, FbxSceneInfo& SceneInfo);

	/**
	 * Initialize Fbx file for import.
	 *
	 * @param Filename
	 * @param bParseStatistics
	 * @return bool
	 */
	bool OpenFile( FString Filename, bool bParseStatistics, bool bForSceneInfo = false );

	/**
	 * Import Fbx file.
	 *
	 * @param Filename
	 * @return bool
	 */
	bool ImportFile(FString Filename);

	/**
	 * Attempt to load an FBX scene from a given filename.
	 *
	 * @param Filename FBX file name to import.
	 * @returns true on success.
	 */
	UNREALED_API bool ImportFromFile(const FString& Filename, const FString& Type);

	/**
	 * Retrieve the FBX loader's error message explaining its failure to read a given FBX file.
	 * Note that the message should be valid even if the parser is successful and may contain warnings.
	 *
	 * @ return TCHAR*	the error message
	 */
	const TCHAR* GetErrorMessage() const
	{
		return *ErrorMessage;
	}

	/**
	 * Retrieve the object inside the FBX scene from the name
	 *
	 * @param ObjectName	Fbx object name
	 * @param Root	Root node, retrieve from it
	 * @return FbxNode*	Fbx object node
	 */
	FbxNode* RetrieveObjectFromName(const TCHAR* ObjectName, FbxNode* Root = NULL);

	/**
	 * Creates a static mesh with the given name and flags, imported from within the FBX scene.
	 * @param InParent
	 * @param Node	Fbx Node to import
	 * @param Name	the Unreal Mesh name after import
	 * @param Flags
	 * @param InStaticMesh	if LODIndex is not 0, this is the base mesh object. otherwise is NULL
	 * @param LODIndex	 LOD level to import to
	 *
	 * @returns UObject*	the UStaticMesh object.
	 */
	UNREALED_API UStaticMesh* ImportStaticMesh(UObject* InParent, FbxNode* Node, const FName& Name, EObjectFlags Flags, UFbxStaticMeshImportData* ImportData, UStaticMesh* InStaticMesh = NULL, int LODIndex = 0);

	/**
	* Creates a static mesh from all the meshes in FBX scene with the given name and flags.
	*
	* @param InParent
	* @param MeshNodeArray	Fbx Nodes to import
	* @param Name	the Unreal Mesh name after import
	* @param Flags
	* @param InStaticMesh	if LODIndex is not 0, this is the base mesh object. otherwise is NULL
	* @param LODIndex	 LOD level to import to
	*
	* @returns UObject*	the UStaticMesh object.
	*/
	UNREALED_API UStaticMesh* ImportStaticMeshAsSingle(UObject* InParent, TArray<FbxNode*>& MeshNodeArray, const FName InName, EObjectFlags Flags, UFbxStaticMeshImportData* TemplateImportData, UStaticMesh* InStaticMesh, int LODIndex = 0);

	void ImportStaticMeshSockets( UStaticMesh* StaticMesh );

	/**
	 * re-import Unreal static mesh from updated Fbx file
	 * if the Fbx mesh is in LODGroup, the LOD of mesh will be updated
	 *
	 * @param Mesh the original Unreal static mesh object
	 * @return UObject* the new Unreal mesh object
	 */
	UStaticMesh* ReimportStaticMesh(UStaticMesh* Mesh, UFbxStaticMeshImportData* TemplateImportData);

	/**
	* re-import Unreal skeletal mesh from updated Fbx file
	* If the Fbx mesh is in LODGroup, the LOD of mesh will be updated.
	* If the FBX mesh contains morph, the morph is updated.
	* Materials, textures and animation attached in the FBX mesh will not be updated.
	*
	* @param Mesh the original Unreal skeletal mesh object
	* @return UObject* the new Unreal mesh object
	*/
	USkeletalMesh* ReimportSkeletalMesh(USkeletalMesh* Mesh, UFbxSkeletalMeshImportData* TemplateImportData);

	/**
	 * Creates a skeletal mesh from Fbx Nodes with the given name and flags, imported from within the FBX scene.
	 * These Fbx Nodes bind to same skeleton. We need to bind them to one skeletal mesh.
	 *
	 * @param InParent
	 * @param NodeArray	Fbx Nodes to import
	 * @param Name	the Unreal Mesh name after import
	 * @param Flags
	 * @param FbxShapeArray	Fbx Morph objects.
	 * @param OutData - Optional import data to populate
	 * @param bCreateRenderData - Whether or not skeletal mesh rendering data will be created.
	 *
	 * @return The USkeletalMesh object created
	 */
	USkeletalMesh* ImportSkeletalMesh(UObject* InParent, TArray<FbxNode*>& NodeArray, const FName& Name, EObjectFlags Flags, UFbxSkeletalMeshImportData* TemplateImportData, bool* bCancelOperation = nullptr, TArray<FbxShape*> *FbxShapeArray = nullptr, FSkeletalMeshImportData* OutData = nullptr, bool bCreateRenderData = true );

	/**
	 * Add to the animation set, the animations contained within the FBX scene, for the given skeletal mesh
	 *
	 * @param Skeleton	Skeleton that the animation belong to
	 * @param SortedLinks	skeleton nodes which are sorted
	 * @param Filename	Fbx file name
	 * @param NodeArray node array of FBX meshes
	 */
	UAnimSequence* ImportAnimations(USkeleton* Skeleton, UObject* Outer, TArray<FbxNode*>& SortedLinks, const FString& Name, UFbxAnimSequenceImportData* TemplateImportData, TArray<FbxNode*>& NodeArray);

	/**
	 * Get Animation Time Span - duration of the animation
	 */
	FbxTimeSpan GetAnimationTimeSpan(FbxNode* RootNode, FbxAnimStack* AnimStack);

	/**
	 * Import one animation from CurAnimStack
	 *
	 * @param Skeleton	Skeleton that the animation belong to
	 * @param DestSeq 	Sequence it's overwriting data to
	 * @param Filename	Fbx file name	(not whole path)
	 * @param SortedLinks	skeleton nodes which are sorted
	 * @param NodeArray node array of FBX meshes
	 * @param CurAnimStack 	Animation Data
	 * @param ResampleRate	Resample Rate for data
	 * @param AnimTimeSpan	AnimTimeSpan
	 */
	bool ImportAnimation(USkeleton* Skeleton, UAnimSequence* DestSeq, const FString& FileName, TArray<FbxNode*>& SortedLinks, TArray<FbxNode*>& NodeArray, FbxAnimStack* CurAnimStack, const int32 ResampleRate, const FbxTimeSpan AnimTimeSpan);
	/**
	 * Calculate Max Sample Rate - separate out of the original ImportAnimations
	 *
	 * @param SortedLinks	skeleton nodes which are sorted
	 * @param NodeArray node array of FBX meshes
	 */
	int32 GetMaxSampleRate(TArray<FbxNode*>& SortedLinks, TArray<FbxNode*>& NodeArray);
	/**
	 * Validate Anim Stack - multiple check for validating animstack
	 *
	 * @param SortedLinks	skeleton nodes which are sorted
	 * @param NodeArray node array of FBX meshes
	 * @param CurAnimStack 	Animation Data
	 * @param ResampleRate	Resample Rate for data
	 * @param AnimTimeSpan	AnimTimeSpan
	 */
	bool ValidateAnimStack(TArray<FbxNode*>& SortedLinks, TArray<FbxNode*>& NodeArray, FbxAnimStack* CurAnimStack, int32 ResampleRate, bool bImportMorph, FbxTimeSpan &AnimTimeSpan);

	/**
	 * Import Fbx Morph object for the Skeletal Mesh.
	 * In Fbx, morph object is a property of the Fbx Node.
	 *
	 * @param SkelMeshNodeArray - Fbx Nodes that the base Skeletal Mesh construct from
	 * @param BaseSkelMesh - base Skeletal Mesh
	 * @param LODIndex - LOD index
	 */
	void ImportFbxMorphTarget(TArray<FbxNode*> &SkelMeshNodeArray, USkeletalMesh* BaseSkelMesh, UObject* Parent, int32 LODIndex);

	/**
	 * Import LOD object for skeletal mesh
	 *
	 * @param InSkeletalMesh - LOD mesh object
	 * @param BaseSkeletalMesh - base mesh object
	 * @param DesiredLOD - LOD level
	 * @param bNeedToReregister - if true, re-register this skeletal mesh to shut down the skeletal mesh component that is previewing this mesh.
									But you can set this to false when in the first loading before rendering this mesh for a performance issue
	   @param ReregisterAssociatedComponents - if NULL, just re-registers all SkinnedMeshComponents but if you set the specific components, will only re-registers those components
	 */
	bool ImportSkeletalMeshLOD(USkeletalMesh* InSkeletalMesh, USkeletalMesh* BaseSkeletalMesh, int32 DesiredLOD, bool bNeedToReregister = true, TArray<UActorComponent*>* ReregisterAssociatedComponents = NULL);

	/**
	 * Empties the FBX scene, releasing its memory.
	 * Currently, we can't release KFbxSdkManager because Fbx Sdk2010.2 has a bug that FBX can only has one global sdkmanager.
	 * From Fbx Sdk2011, we can create multiple KFbxSdkManager, then we can release it.
	 */
	UNREALED_API void ReleaseScene();

	/**
	 * If the node model is a collision model, then fill it into collision model list
	 *
	 * @param Node Fbx node
	 * @return true if the node is a collision model
	 */
	bool FillCollisionModelList(FbxNode* Node);

	/**
	 * Import collision models for one static mesh if it has collision models
	 *
	 * @param StaticMesh - mesh object to import collision models
	 * @param NodeName - name of Fbx node that the static mesh constructed from
	 * @return return true if the static mesh has collision model and import successfully
	 */
	bool ImportCollisionModels(UStaticMesh* StaticMesh, const FbxString& NodeName);

	//help
	ANSICHAR* MakeName(const ANSICHAR* name);
	FName MakeNameForMesh(FString InName, FbxObject* FbxObject);

	// meshes

	/**
	* Get all Fbx skeletal mesh objects in the scene. these meshes are grouped by skeleton they bind to
	*
	* @param Node Root node to find skeletal meshes
	* @param outSkelMeshArray return Fbx meshes they are grouped by skeleton
	*/
	void FillFbxSkelMeshArrayInScene(FbxNode* Node, TArray< TArray<FbxNode*>* >& outSkelMeshArray, bool ExpandLOD);

	/**
	 * Find FBX meshes that match Unreal skeletal mesh according to the bone of mesh
	 *
	 * @param FillInMesh     Unreal skeletal mesh
	 * @param bExpandLOD     flag that if expand FBX LOD group when get the FBX node
	 * @param OutFBXMeshNodeArray  return FBX mesh nodes that match the Unreal skeletal mesh
	 *
	 * @return the root bone that bind to the FBX skeletal meshes
	 */
	FbxNode* FindFBXMeshesByBone(const FName& RootBoneName, bool bExpandLOD, TArray<FbxNode*>& OutFBXMeshNodeArray);

	/**
	* Get mesh count (including static mesh and skeletal mesh, except collision models) and find collision models
	*
	* @param Node			Root node to find meshes
	* @param bCountLODs		Whether or not to count meshes in LOD groups
	* @return int32 mesh count
	*/
	int32 GetFbxMeshCount(FbxNode* Node,bool bCountLODs, int32 &OutNumLODGroups );

	/**
	* Get all Fbx mesh objects
	*
	* @param Node Root node to find meshes
	* @param outMeshArray return Fbx meshes
	*/
	UNREALED_API void FillFbxMeshArray(FbxNode* Node, TArray<FbxNode*>& outMeshArray, UnFbx::FFbxImporter* FFbxImporter);

	/**
	* Fill FBX skeletons to OutSortedLinks recursively
	*
	* @param Link Fbx node of skeleton root
	* @param OutSortedLinks
	*/
	void RecursiveBuildSkeleton(FbxNode* Link, TArray<FbxNode*>& OutSortedLinks);

	/**
	 * Fill FBX skeletons to OutSortedLinks
	 *
	 * @param ClusterArray Fbx clusters of FBX skeletal meshes
	 * @param OutSortedLinks
	 */
	void BuildSkeletonSystem(TArray<FbxCluster*>& ClusterArray, TArray<FbxNode*>& OutSortedLinks);

	/**
	 * Get Unreal skeleton root from the FBX skeleton node.
	 * Mesh and dummy can be used as skeleton.
	 *
	 * @param Link one FBX skeleton node
	 */
	FbxNode* GetRootSkeleton(FbxNode* Link);

	/**
	 * Get the object of import options
	 *
	 * @return FBXImportOptions
	 */
	UNREALED_API FBXImportOptions* GetImportOptions() const;

	/** helper function **/
	UNREALED_API static void DumpFBXNode(FbxNode* Node);

	/**
	 * Apply asset import settings for transform to an FBX node
	 *
	 * @param Node Node to apply transform settings too
	 * @param AssetData the asset data object to get transform data from
	 */
	void ApplyTransformSettingsToFbxNode(FbxNode* Node, UFbxAssetImportData* AssetData);

	/**
	 * Remove asset import settings for transform to an FBX node
	 *
	 * @param Node Node to apply transform settings too
	 * @param AssetData the asset data object to get transform data from
	 */
	void RemoveTransformSettingsFromFbxNode(FbxNode* Node, UFbxAssetImportData* AssetData);

	/**
	 * Populate the given matrix with the correct information for the asset data, in
	 * a format that matches FBX internals or without conversion
	 *
	 * @param OutMatrix The matrix to fill
	 * @param AssetData The asset data to extract the transform info from
	 */
	void BuildFbxMatrixForImportTransform(FbxAMatrix& OutMatrix, UFbxAssetImportData* AssetData);

private:
	/**
	 * ActorX plug-in can export mesh and dummy as skeleton.
	 * For the mesh and dummy in the skeleton hierarchy, convert them to FBX skeleton.
	 *
	 * @param Node          root skeleton node
	 * @param SkelMeshes    skeletal meshes that bind to this skeleton
	 * @param bImportNestedMeshes	if true we will import meshes nested in bone hierarchies instead of converting them to bones
	 */
	void RecursiveFixSkeleton(FbxNode* Node, TArray<FbxNode*> &SkelMeshes, bool bImportNestedMeshes );

	/**
	* Get all Fbx skeletal mesh objects which are grouped by skeleton they bind to
	*
	* @param Node Root node to find skeletal meshes
	* @param outSkelMeshArray return Fbx meshes they are grouped by skeleton
	* @param SkeletonArray
	* @param ExpandLOD flag of expanding LOD to get each mesh
	*/
	void RecursiveFindFbxSkelMesh(FbxNode* Node, TArray< TArray<FbxNode*>* >& outSkelMeshArray, TArray<FbxNode*>& SkeletonArray, bool ExpandLOD);

	/**
	* Get all Fbx rigid mesh objects which are grouped by skeleton hierarchy
	*
	* @param Node Root node to find skeletal meshes
	* @param outSkelMeshArray return Fbx meshes they are grouped by skeleton hierarchy
	* @param SkeletonArray
	* @param ExpandLOD flag of expanding LOD to get each mesh
	*/
	void RecursiveFindRigidMesh(FbxNode* Node, TArray< TArray<FbxNode*>* >& outSkelMeshArray, TArray<FbxNode*>& SkeletonArray, bool ExpandLOD);

	/**
	 * Import Fbx Morph object for the Skeletal Mesh.  Each morph target import processing occurs in a different thread
	 *
	 * @param SkelMeshNodeArray - Fbx Nodes that the base Skeletal Mesh construct from
	 * @param BaseSkelMesh - base Skeletal Mesh
	 * @param LODIndex - LOD index of the skeletal mesh
	 */
	void ImportMorphTargetsInternal( TArray<FbxNode*>& SkelMeshNodeArray, USkeletalMesh* BaseSkelMesh, UObject* Parent, int32 LODIndex );

	/**
	* sub-method called from ImportSkeletalMeshLOD method
	*
	* @param InSkeletalMesh - newly created mesh used as LOD
	* @param BaseSkeletalMesh - the destination mesh object
	* @param DesiredLOD - the LOD index to import into. A new LOD entry is created if one doesn't exist
	*/
	void InsertNewLODToBaseSkeletalMesh(USkeletalMesh* InSkeletalMesh, USkeletalMesh* BaseSkeletalMesh, int32 DesiredLOD);

	/**
	* Method used to verify if the geometry is valid. For example, if the bounding box is tiny we should warn
	* @param StaticMesh - The imported static mesh which we'd like to verify
	*/
	void VerifyGeometry(UStaticMesh* StaticMesh);

public:
	// current Fbx scene we are importing. Make sure to release it after import
	FbxScene* Scene;
	FBXImportOptions* ImportOptions;

protected:
	enum IMPORTPHASE
	{
		NOTSTARTED,
		FILEOPENED,
		IMPORTED
	};

	static TSharedPtr<FFbxImporter> StaticInstance;

	struct FFbxMaterial
	{
		FbxSurfaceMaterial* FbxMaterial;
		UMaterialInterface* Material;

		FString GetName() const { return FbxMaterial ? ANSI_TO_TCHAR( FbxMaterial->GetName() ) : TEXT("None"); }
	};

	// scene management
	FFbxDataConverter Converter;
	FbxGeometryConverter* GeometryConverter;
	FbxManager* SdkManager;
	FbxImporter* Importer;
	IMPORTPHASE CurPhase;
	FString ErrorMessage;
	// base path of fbx file
	FString FileBasePath;
	TWeakObjectPtr<UObject> Parent;
	// Flag that the mesh is the first mesh to import in current FBX scene
	// FBX scene may contain multiple meshes, importer can import them at one time.
	// Initialized as true when start to import a FBX scene
	bool bFirstMesh;

	// Set when importing skeletal meshes if the merge bones step fails. Used to track
	// YesToAll and NoToAll for an entire scene
	EAppReturnType::Type LastMergeBonesChoice;

	/**
	 * Collision model list. The key is fbx node name
	 * If there is an collision model with old name format, the key is empty string("").
	 */
	FbxMap<FbxString, TSharedPtr< FbxArray<FbxNode* > > > CollisionModels;

	FFbxImporter();

	/**
	 * Set up the static mesh data from Fbx Mesh.
	 *
	 * @param FbxMesh  Fbx Mesh object
	 * @param StaticMesh Unreal static mesh object to fill data into
	 * @param LODIndex	LOD level to set up for StaticMesh
	 * @return bool true if set up successfully
	 */
	bool BuildStaticMeshFromGeometry(FbxMesh* Mesh, UStaticMesh* StaticMesh, TArray<FFbxMaterial>& MeshMaterials, int LODIndex,FRawMesh& RawMesh,
									 EVertexColorImportOption::Type VertexColorImportOption, const TMap<FVector, FColor>& ExistingVertexColorData, const FColor& VertexOverrideColor);

	/**
	 * Clean up for destroy the Importer.
	 */
	void CleanUp();

	/**
	* Compute the global matrix for Fbx Node
	*
	* @param Node	Fbx Node
	* @return KFbxXMatrix*	The global transform matrix
	*/
	FbxAMatrix ComputeTotalMatrix(FbxNode* Node);

	/**
	 * Check if there are negative scale in the transform matrix and its number is odd.
	 * @return bool True if there are negative scale and its number is 1 or 3.
	 */
	bool IsOddNegativeScale(FbxAMatrix& TotalMatrix);

	// various actors, current the Fbx importer don't importe them
	/**
	 * Import Fbx light
	 *
	 * @param FbxLight fbx light object
	 * @param World in which to create the light
	 * @return ALight*
	 */
	ALight* CreateLight(FbxLight* InLight, UWorld* InWorld );
	/**
	* Import Light detail info
	*
	* @param FbxLight
	* @param UnrealLight
	* @return  bool
	*/
	bool FillLightComponent(FbxLight* Light, ULightComponent* UnrealLight);
	/**
	* Import Fbx Camera object
	*
	* @param FbxCamera Fbx camera object
	* @param World in which to create the camera
	* @return ACameraActor*
	*/
	ACameraActor* CreateCamera(FbxCamera* InCamera, UWorld* InWorld);

	// meshes
	/**
	* Fill skeletal mesh data from Fbx Nodes.  If this function needs to triangulate the mesh, then it could invalidate the
	* original FbxMesh pointer.  Hence FbxMesh is a reference so this function can set the new pointer if need be.
	*
	* @param ImportData object to store skeletal mesh data
	* @param FbxMesh	Fbx mesh object belonging to Node
	* @param FbxSkin	Fbx Skin object belonging to FbxMesh
	* @param FbxShape	Fbx Morph object, if not NULL, we are importing a morph object.
	* @param SortedLinks    Fbx Links(bones) of this skeletal mesh
	* @param FbxMatList  All material names of the skeletal mesh
	*
	* @returns bool*	true if import successfully.
	*/
    bool FillSkelMeshImporterFromFbx(FSkeletalMeshImportData& ImportData, FbxMesh*& Mesh, FbxSkin* Skin,
										FbxShape* Shape, TArray<FbxNode*> &SortedLinks, const TArray<FbxSurfaceMaterial*>& FbxMaterials );

	/**
	 * Import bones from skeletons that NodeArray bind to.
	 *
	 * @param NodeArray Fbx Nodes to import, they are bound to the same skeleton system
	 * @param ImportData object to store skeletal mesh data
	 * @param OutSortedLinks return all skeletons sorted by depth traversal
	 * @param bOutDiffPose
	 * @param bDisableMissingBindPoseWarning
	 * @param bUseTime0AsRefPose	in/out - Use Time 0 as Ref Pose
	 */
	bool ImportBone(TArray<FbxNode*>& NodeArray, FSkeletalMeshImportData &ImportData, UFbxSkeletalMeshImportData* TemplateData, TArray<FbxNode*> &OutSortedLinks, bool& bOutDiffPose, bool bDisableMissingBindPoseWarning, bool & bUseTime0AsRefPose);

	/**
	 * Skins the control points of the given mesh or shape using either the default pose for skinning or the first frame of the
	 * default animation.  The results are saved as the last X verts in the given FSkeletalMeshBinaryImport
	 *
	 * @param SkelMeshImporter object to store skeletal mesh data
	 * @param FbxMesh	The Fbx mesh object with the control points to skin
	 * @param FbxShape	If a shape (aka morph) is provided, its control points will be used instead of the given meshes
	 * @param bUseT0	If true, then the pose at time=0 will be used instead of the ref pose
	 */
	void SkinControlPointsToPose(FSkeletalMeshImportData &ImportData, FbxMesh* Mesh, FbxShape* Shape, bool bUseT0 );

	// anims
	/**
	 * Check if the Fbx node contains animation
	 *
	 * @param Node Fbx node
	 * @return bool true if the Fbx node contains animation.
	 */
	//bool IsAnimated(FbxNode* Node);

	/**
	* Fill each Trace for AnimSequence with Fbx skeleton animation by key
	*
	* @param Node   Fbx skeleton node
	* @param AnimSequence
	* @param TakeName
	* @param bIsRoot if the Fbx skeleton node is root skeleton
	* @param Scale scale factor for this skeleton node
	*/
	bool FillAnimSequenceByKey(FbxNode* Node, UAnimSequence* AnimSequence, const char* TakeName, FbxTime& Start, FbxTime& End, bool bIsRoot, FbxVector4 Scale);
	/*bool CreateMatineeSkeletalAnimation(ASkeletalMeshActor* Actor, UAnimSet* AnimSet);
	bool CreateMatineeAnimation(FbxNode* Node, AActor* Actor, bool bInvertOrient, bool bAddDirectorTrack);*/

	// material
	/**
	 * Import each material Input from Fbx Material
	 *
	 * @param FbxMaterial	Fbx material object
	 * @param UnrealMaterial
	 * @param MaterialProperty The material component to import
	 * @param MaterialInput
	 * @param bSetupAsNormalMap
	 * @param UVSet
	 * @return bool
	 */
	bool CreateAndLinkExpressionForMaterialProperty(	FbxSurfaceMaterial& FbxMaterial,
														UMaterial* UnrealMaterial,
														const char* MaterialProperty ,
														FExpressionInput& MaterialInput,
														bool bSetupAsNormalMap,
														TArray<FString>& UVSet,
														const FVector2D& Location );
	/**
	 * Add a basic white diffuse color if no expression is linked to diffuse input.
	 *
	 * @param unMaterial Unreal material object.
	 */
	void FixupMaterial( FbxSurfaceMaterial& FbxMaterial, UMaterial* unMaterial);

	/**
	 * Get material mapping array according "Skinxx" flag in material name
	 *
	 * @param FSkeletalMeshBinaryImport& The unreal skeletal mesh.
	 */
	void SetMaterialSkinXXOrder(FSkeletalMeshImportData& ImportData);

	/**
	 * Create materials from Fbx node.
	 * Only setup channels that connect to texture, and setup the UV coordinate of texture.
	 * If diffuse channel has no texture, one default node will be created with constant.
	 *
	 * @param FbxNode  Fbx node
	 * @param outMaterials Unreal Materials we created
	 * @param UVSets UV set name list
	 * @return int32 material count that created from the Fbx node
	 */
	int32 CreateNodeMaterials(FbxNode* FbxNode, TArray<UMaterialInterface*>& outMaterials, TArray<FString>& UVSets);

	/**
	 * Make material Unreal asset name from the Fbx material
	 *
	 * @param FbxMaterial Material from the Fbx node
	 * @return Sanitized asset name
	 */
	FString GetMaterialFullName(FbxSurfaceMaterial& FbxMaterial);

	/**
	 * Create Unreal material from Fbx material.
	 * Only setup channels that connect to texture, and setup the UV coordinate of texture.
	 * If diffuse channel has no texture, one default node will be created with constant.
	 *
	 * @param KFbxSurfaceMaterial*  Fbx material
	 * @param outMaterials Unreal Materials we created
	 * @param outUVSets
	 */
	void CreateUnrealMaterial(FbxSurfaceMaterial& FbxMaterial, TArray<UMaterialInterface*>& OutMaterials, TArray<FString>& UVSets);

	/**
	 * Visit all materials of one node, import textures from materials.
	 *
	 * @param Node FBX node.
	 */
	void ImportTexturesFromNode(FbxNode* Node);

	/**
	 * Generate Unreal texture object from FBX texture.
	 *
	 * @param FbxTexture FBX texture object to import.
	 * @param bSetupAsNormalMap Flag to import this texture as normal map.
	 * @return UTexture* Unreal texture object generated.
	 */
	UTexture* ImportTexture(FbxFileTexture* FbxTexture, bool bSetupAsNormalMap);

	/**
	 *
	 *
	 * @param
	 * @return UMaterial*
	 */
	//UMaterial* GetImportedMaterial(KFbxSurfaceMaterial* pMaterial);

	/**
	* Check if the meshes in FBX scene contain smoothing group info.
	* It's enough to only check one of mesh in the scene because "Export smoothing group" option affects all meshes when export from DCC.
	* To ensure only check one time, use flag bFirstMesh to record if this is the first mesh to check.
	*
	* @param FbxMesh Fbx mesh to import
	*/
	void CheckSmoothingInfo(FbxMesh* FbxMesh);

	/**
	 * check if two faces belongs to same smoothing group
	 *
	 * @param ImportData
	 * @param Face1 one face of the skeletal mesh
	 * @param Face2 another face
	 * @return bool true if two faces belongs to same group
	 */
	bool FacesAreSmoothlyConnected( FSkeletalMeshImportData &ImportData, int32 Face1, int32 Face2 );

	/**
	 * Make un-smooth faces work.
	 *
	 * @param ImportData
	 * @return int32 number of points that added when process unsmooth faces
	*/
	int32 DoUnSmoothVerts(FSkeletalMeshImportData &ImportData);

	/**
	 * Merge all layers of one AnimStack to one layer.
	 *
	 * @param AnimStack     AnimStack which layers will be merged
	 * @param ResampleRate  resample rate for the animation
	 */
	void MergeAllLayerAnimation(FbxAnimStack* AnimStack, int32 ResampleRate);

	//
	// for matinee export
	//
public:
	/**
	 * Retrieves whether there are any unknown camera instances within the FBX document.
	 */
	UNREALED_API bool HasUnknownCameras( AMatineeActor* InMatineeActor ) const;

	/**
	 * Sets the camera creation flag. Call this function before the import in order to enforce
	 * the creation of FBX camera instances that do not exist in the current scene.
	 */
	inline void SetProcessUnknownCameras(bool bCreateMissingCameras)
	{
		bCreateUnknownCameras = bCreateMissingCameras;
	}

	/**
	 * Modifies the Matinee actor with the animations found in the FBX document.
	 *
	 * @return	true, if sucessful
	 */
	UNREALED_API bool ImportMatineeSequence(AMatineeActor* InMatineeActor);

	/** Create a new asset from the package and objectname and class */
	static UObject* CreateAssetOfClass(UClass* AssetClass, FString ParentPackageName, FString ObjectName, bool bAllowReplace = false);

	/* Templated function to create an asset with given package and name */
	template< class T>
	static T * CreateAsset( FString ParentPackageName, FString ObjectName, bool bAllowReplace = false )
	{
		return (T*)CreateAssetOfClass(T::StaticClass(), ParentPackageName, ObjectName, bAllowReplace);
	}

protected:
	bool bCreateUnknownCameras;

	/**
	 * Creates a Matinee group for a given actor within a given Matinee actor.
	 */
	UInterpGroupInst* CreateMatineeGroup(AMatineeActor* InMatineeActor, AActor* Actor, FString GroupName);
	/**
	 * Imports a FBX scene node into a Matinee actor group.
	 */
	float ImportMatineeActor(FbxNode* FbxNode, UInterpGroupInst* MatineeGroup);

	/**
	 * Imports an FBX transform curve into a movement subtrack
	 */
	void ImportMoveSubTrack( FbxAnimCurve* FbxCurve, int32 FbxDimension, UInterpTrackMoveAxis* SubTrack, int32 CurveIndex, bool bNegative, FbxAnimCurve* RealCurve, float DefaultVal );

	/**
	 * Imports a FBX animated element into a Matinee track.
	 */
	void ImportMatineeAnimated(FbxAnimCurve* FbxCurve, FInterpCurveVector& Curve, int32 CurveIndex, bool bNegative, FbxAnimCurve* RealCurve, float DefaultVal);
	/**
	 * Imports a FBX camera into properties tracks of a Matinee group for a camera actor.
	 */
	void ImportCamera(ACameraActor* Actor, UInterpGroupInst* MatineeGroup, FbxCamera* Camera);
	/**
	 * Imports a FBX animated value into a property track of a Matinee group.
	 */
	void ImportAnimatedProperty(float* Value, const TCHAR* ValueName, UInterpGroupInst* MatineeGroup, const float FbxValue, FbxProperty Property, bool bImportFOV = false, FbxCamera* Camera = NULL );
	/**
	 * Check if FBX node has transform animation (translation and rotation, not check scale animation)
	 */
	bool IsNodeAnimated(FbxNode* FbxNode, FbxAnimLayer* AnimLayer = NULL);

	/**
	 * As movement tracks in Unreal cannot have differing interpolation modes for position & rotation,
	 * we consolidate the two modes here.
	 */
	void ConsolidateMovementTrackInterpModes(UInterpTrackMove* MovementTrack);

	/**
	 * Get Unreal Interpolation mode from FBX interpolation mode
	 */
	EInterpCurveMode GetUnrealInterpMode(FbxAnimCurveKey FbxKey);

	/**
	 * Fill up and verify bone names for animation
	 */
	void FillAndVerifyBoneNames(USkeleton* Skeleton, TArray<FbxNode*>& SortedLinks, TArray<FName> & OutRawBoneNames, FString Filename);
	/**
	 * Is valid animation data
	 */
	bool IsValidAnimationData(TArray<FbxNode*>& SortedLinks, TArray<FbxNode*>& NodeArray, int32& ValidTakeCount);

	/**
	 * Retrieve pose array from bind pose
	 *
	 * Iterate through Scene:Poses, and find valid bind pose for NodeArray, and return those Pose if valid
	 *
	 */
	bool RetrievePoseFromBindPose(const TArray<FbxNode*>& NodeArray, FbxArray<FbxPose*> & PoseArray) const;

public:
	/** Import and set up animation related data from mesh **/
	void SetupAnimationDataFromMesh(USkeletalMesh * SkeletalMesh, UObject* InParent, TArray<FbxNode*>& NodeArray, UFbxAnimSequenceImportData* ImportData, const FString& Filename);

	/** error message handler */
	void AddTokenizedErrorMessage(TSharedRef<FTokenizedMessage> Error, FName FbxErrorName );
	void ClearTokenizedErrorMessages();
	void FlushToTokenizedErrorMessage(enum EMessageSeverity::Type Severity);

private:
	friend class FFbxLoggerSetter;

	// logger set/clear function
	class FFbxLogger * Logger;
	void SetLogger(class FFbxLogger * InLogger);
	void ClearLogger();

	FImportedMaterialData ImportedMaterialData;

private:
	/**
	 * Import FbxCurve to Curve
	 */
	bool ImportCurve(const FbxAnimCurve* FbxCurve, FFloatCurve * Curve, const FbxTimeSpan &AnimTimeSpan, const float ValueScale = 1.f) const;

	/**
	 * Import FbxCurve to anim sequence
	 */
	bool ImportCurveToAnimSequence(class UAnimSequence * TargetSequence, const FString& CurveName, const FbxAnimCurve* FbxCurve, int32 CurveFlags,const FbxTimeSpan AnimTimeSpan, const float ValueScale = 1.f) const;
};

/** message Logger for FBX. Saves all the messages and prints when it's destroyed */
class FFbxLogger
{
	FFbxLogger();
	~FFbxLogger();

	/** Error messages **/
	TArray<TSharedRef<FTokenizedMessage>> TokenizedErrorMessages;

	friend class FFbxImporter;
	friend class FFbxLoggerSetter;
};

/**
* This class is to make sure Logger isn't used by outside of purpose.
* We add this only top level of functions where it needs to be handled
* if the importer already has logger set, it won't set anymore
*/
class FFbxLoggerSetter
{
	class FFbxLogger Logger;
	FFbxImporter * Importer;

public:
	FFbxLoggerSetter(FFbxImporter * InImpoter)
		: Importer(InImpoter)
	{
		// if impoter doesn't have logger, sets it
		if(Importer->Logger == NULL)
		{
			Importer->SetLogger(&Logger);
		}
		else
		{
			// if impoter already has logger set
			// invalidated Importer to make sure it doesn't clear
			Importer = NULL;
		}
	}

	~FFbxLoggerSetter()
	{
		if(Importer)
		{
			Importer->ClearLogger();
		}
	}
};
} // namespace UnFbx


text:
<!DOCTYPE html>

<md-card flex>

            {{'WEEKDAYS_CHART_TITLE'| translate}}

        <md-button ng-click="showAlert($event, 'WEEKDAYS_CHART_TITLE', 'WEEKDAYS_CHART_DESCRIPTION')" class="md-icon-button md-accent" aria-label="Info">
            <md-icon class="material-icons  md-24">info</md-icon>
            <md-tooltip>
                {{'CLICK_FOR_MORE_INFO'| translate}}
            </md-tooltip>
        </md-button>

                {{ 'NO_TRACKS' | translate}}

        <md-card-content flex>
            <md-progress-circular class="loader_dashboard2" ng-if="!onload_weekdays" md-diameter="56"></md-progress-circular>

                <nvd3 options="optionsWeekdays" data="dataWeekdays" api="api" flex></nvd3>

        </md-card-content>

</md-card>

redpajama_set_name: RedPajamaGithub


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//-----------------------------------------------------------------------------
var BUGNUMBER = 290575;
var summary = 'Do not crash calling function with more than 32768 arguments';
var actual = 'No Crash';
var expect = 'No Crash';
printBugNumber(BUGNUMBER);
printStatus (summary);

function crashMe(n) {
  var nasty, fn;

  nasty = [];
  while (n--)
    nasty.push("a"+n);   // Function arguments
  nasty.push("void 0");  // Function body
  fn = Function.apply(null, nasty);
  fn.toString();
}

printStatus('crashMe(0x8001)');

crashMe(0x8001);

reportCompare(expect, actual, summary);

function crashMe2(n) {
  var nasty = [], fn

    while (n--) nasty[n] = "a"+n
      fn = Function(nasty.join(), "void 0")
      fn.toString()
      }

printStatus('crashMe2(0x10000)');

summary = 'Syntax Error Function to string when more than 65536 arguments';
expect = 'Error';
try
{
  crashMe2(0x10000);
  actual = 'No Error';
  reportCompare(expect, actual, summary);
}
catch(e)
{
  actual = 'Error';
  reportCompare(expect, actual, summary);
  expect = 'SyntaxError';
  actual = e.name;
  reportCompare(expect, actual, summary);
}


text:
package com.hannesdorfmann.mosby.mvp.delegate;

import android.os.Bundle;
import com.hannesdorfmann.mosby.mvp.MvpPresenter;
import com.hannesdorfmann.mosby.mvp.MvpView;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

/**
 * @author Hannes Dorfmann
 */
public class ActivityMvpDelegateImplTest {

  private MvpView view;
  private MvpPresenter<MvpView> presenter;
  private MvpDelegateCallback<MvpView, MvpPresenter<MvpView>> callback;
  private ActivityMvpDelegateImpl<MvpView, MvpPresenter<MvpView>> delegate;

  @Before public void initComponents() {
    view = new MvpView() {
    };

    presenter = Mockito.mock(MvpPresenter.class);
    callback = Mockito.mock(PartialMvpDelegateCallbackImpl.class);
    Mockito.doCallRealMethod().when(callback).setPresenter(presenter);
    Mockito.doCallRealMethod().when(callback).getPresenter();

    Mockito.when(callback.getMvpView()).thenReturn(view);

    delegate = new ActivityMvpDelegateImpl<>(callback);
  }

  @Test public void startActivityNullBundle() {
    testActivityStart(null);
  }

  @Test public void startActivityWithBundle() {
    testActivityStart(new Bundle());
  }

  private void testActivityStart(Bundle bundle) {
    Mockito.when(callback.createPresenter()).thenReturn(presenter);

    startActivity(bundle);

    Mockito.verify(callback, Mockito.times(1)).createPresenter();
    Mockito.verify(callback, Mockito.times(1)).setPresenter(presenter);
    Mockito.verify(presenter, Mockito.times(1)).attachView(view);
  }

  private void startActivity(Bundle bundle){
    delegate.onCreate(bundle);
    delegate.onContentChanged();
    delegate.onPostCreate(bundle);
    delegate.onStart();
    delegate.onResume();
  }

  @Test
  public void reuseRetainingPresenter(){
    Mockito.when(callback.getPresenter()).thenReturn(presenter);

    startActivity(null);

    Mockito.verify(callback, Mockito.never()).createPresenter();
    Mockito.verify(callback, Mockito.times(1)).setPresenter(presenter);
    Mockito.verify(presenter, Mockito.times(1)).attachView(view);
  }

  @Test public void finishActivityNotRetaining() {
    testFinishActivity(false);
  }

  @Test public void finishActivityIsRetaining() {
    testFinishActivity(true);
  }

  private void testFinishActivity(boolean retainingInstanceState) {
    Mockito.when(callback.getPresenter()).thenReturn(presenter);
    Mockito.when(callback.shouldInstanceBeRetained()).thenReturn(retainingInstanceState);

    delegate.onPause();
    delegate.onSaveInstanceState(new Bundle());
    delegate.onStop();
    delegate.onDestroy();
    delegate.onRestart();

    Mockito.verify(presenter, Mockito.times(1)).detachView(retainingInstanceState);
  }
}


text:
import JSONFeed from '../../eleventy/feed'

module.exports = class ElsewhereFeed extends JSONFeed {
   collection = 'elsewhere'
   title = 'Elsewhere'
}


text:
define(['app','config'],function(app,config){
    app.controller('storeProfileCtrl', ["$scope","$compile", function ($scope,$compile) {
        $scope.t="test";
    }]);
});


text:
<?php

use Kirby\Panel\Installer;

class InstallationController extends Kirby\Panel\Controllers\Base {

  public function index() {

    $installer = new Installer();

    if($installer->isCompleted()) {
      $this->redirect();
    } else if($problems = $installer->problems()) {
      return $this->problems($problems);
    } else {
      return $this->signup();
    }

  }

  protected function problems($problems) {
    $form = $this->form('installation/check', array($problems));
    return $this->modal('index', compact('form'));
  }

  protected function signup() {

    $self = $this;
    $form = $this->form('installation/signup', array(), function($form) use($self) {

      $form->validate();

      if(!$form->isValid()) {
        return false;
      }

      try {

        // fetch all the form data
        $data = $form->serialize();

        // make sure that the first user is an admin
        $data['role'] = 'admin';

        // try to create the new user
        $user = site()->users()->create($data);

        // store the new username for the login screen
        s::set('kirby_panel_username', $user->username());

        // try to login the user automatically
        if($user->hasPanelAccess()) {
          $user->login($data['password']);
        }

        // redirect to the login
        $self->redirect('login');

      } catch(Exception $e) {
        $form->alert($e->getMessage());
      }

    });

    return $this->modal('index', compact('form'));

  }

  public function modal($view, $data = array()) {
    return $this->layout('base', array(
      'bodyclass' => 'installation',
      'content'   => $this->view('installation/' . $view, $data)
    ));
  }

}


text:
class RatingsMigration < ActiveRecord::Migration
  def change
  	#Block to migrate the Rating with the event and User
    create_table :ratings do |t|
      t.integer :stars, :default => 0
      t.references :event
      t.references :user
    end
  end
end


text:
package jp.leafytree.sbt

import java.nio.charset.Charset
import java.util.Properties

import sbt._
import Keys._

import collection.JavaConversions._

@deprecated("Please use `PhantomJs`")
object SbtPhantomJs extends AutoPlugin {
  override def requires = PhantomJs
}


text: The GUI version of pyrecords app using PyQt5 as UI library.


text:
SYNONYM

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

#### Published in
Hausvater 5:230. 1770

#### Original name
null

### Remarks
null


text:
(function (window) {
    var angular = window.angular;
    angular.module('demoApp', ['ngResource'])
            .factory('demo_zone', [
                '$resource',
                function ($resource) {
                    //Makes a Resource and defines a custom method (update) and (add)
                    return $resource('/resful_api/www/demo_zone/user/:userId', {}, {
                        "update": {method: "PUT"},
                        "add": {'method': 'POST'}
                    });
                }
            ])
            .controller('AppController', [
                '$scope',
                'demo_zone',
                function ($scope, Demo_zone) {
                    $scope.log = [];

                    //---------------  A GET ONE AND PUT ONE DEMO
                    var demoOne = Demo_zone.get({'userId': 1}); // Calls: GET
                    demoOne.name = 'Steven Smith';
                    demoOne.$update({'userId': 1}); // Calls: PUT
                    demoOne.$promise.then(function (a) {
                        $scope.log.push('A GET ONE AND PUT ONE DEMO ->');
                        $scope.log.push('After GET and then PUT, the PUT Response: ' + angular.toJson(a));
                        $scope.log.push('-- BREAK --');
//                        console.log('GET AND PUT: ', angular.toJson(a));
                    });

                    //---------------  A GET ALL DEMO
                    var demoTwo = Demo_zone.query(); // Calls: GET
                    demoTwo.$promise.then(function (a) {
                        $scope.log.push('A GET ALL DEMO ->');
                        $scope.log.push('After GET the Response: ' + angular.toJson(a));
                        $scope.log.push('-- BREAK --');
                    });

                    //---------------  A DELETE ONE DEMO
                    var demoThree = Demo_zone.delete({'userId': 1}); // Calls: DELETE
                    demoThree.$promise.then(function (a) {
                        $scope.log.push('A DELETE ONE DEMO ->');
                        $scope.log.push('After DELETE the Response: ' + angular.toJson(a));
                        $scope.log.push('-- BREAK --');
                    });

                    //---------------  A ADD ONE DEMO
                    var demoFour = Demo_zone.add({'userId': 2}, {name: 'someone'});
                    demoFour.$promise.then(function (a) {
                        $scope.log.push('A ADD ONE DEMO ->');
                        $scope.log.push('After POST the Response: ' + angular.toJson(a));
                        $scope.log.push('-- BREAK --');
                    });
                }
            ]);
})(window);


text:
'use strict';

/**
 * @class
 * Initializes a new instance of the ServerMetricListResult class.
 * @constructor
 * Represents the response to a list server metrics request.
 *
 */
class ServerMetricListResult extends Array {
  constructor() {
    super();
  }

  /**
   * Defines the metadata of ServerMetricListResult
   *
   * @returns {object} metadata of ServerMetricListResult
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'ServerMetricListResult',
      type: {
        name: 'Composite',
        className: 'ServerMetricListResult',
        modelProperties: {
          value: {
            required: true,
            serializedName: '',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'ServerMetricElementType',
                  type: {
                    name: 'Composite',
                    className: 'ServerMetric'
                  }
              }
            }
          }
        }
      }
    };
  }
}

module.exports = ServerMetricListResult;


text:
package edu.wustl.catissuecore.ctrp;

import java.lang.annotation.Annotation;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.xml.bind.annotation.XmlType;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.iso._21090.AD;
import org.iso._21090.ADXP;
import org.iso._21090.DSETTEL;
import org.iso._21090.ENXP;
import org.iso._21090.II;
import org.iso._21090.TEL;

import edu.wustl.catissuecore.domain.Address;
import edu.wustl.catissuecore.domain.CollectionProtocol;
import edu.wustl.catissuecore.domain.Institution;
import edu.wustl.catissuecore.domain.User;
import edu.wustl.catissuecore.util.global.AppUtility;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.common.util.logger.Logger;
import gov.nih.nci.coppa.po.Entity;
import gov.nih.nci.coppa.po.Person;
import gov.nih.nci.coppa.services.pa.StudyProtocol;

/**
 * @author Ravi.Batchu
 *
 */
public class COPPAUtil {
	public static final String ISO_TEL_EMAIL_TYPE = "TEL.Email";
	public static final String ISO_LAST_NAME_TYPE = "FAM";
	public static final String ISO_FIRST_NAME_TYPE = "GIV";
	public static final String ISO_STREET_ADDRESS_TYPE = "AL";
	public static final String ISO_CITY_TYPE = "CTY";
	public static final String ISO_STATE_TYPE = "STA";
	public static final String ISO_ZIP_TYPE = "ZIP";
	public static final String ISO_COUNTRY_TYPE = "CNT";
	public static final String ISO_TEL_PHONE_TYPE = "TEL.Phone";
	public static final String ISO_EMAIL_PREFIX = "mailto:";
	public static final String ISO_TEL_PHONE_PREFIX = "tel:";
	public static final String ISO_TEL_FAX_PREFIX = "x-text-fax:";
	public static final String DATE_FORMAT = "yyyyMMddHHmmss.SSSSZ";

	private static final Logger logger = Logger
			.getCommonLogger(COPPAUtil.class);

	public static String getRemoteIdentifier(Entity entity) {
		String identifier = "";
		if (entity != null) {
			identifier = entity.getIdentifier().getExtension();
		}
		return identifier;
	}

	public static String getLastName(Person person) {
		String lastname = "";
		if (person != null) {
			List<ENXP> partList = person.getName().getPart();
			for (ENXP part : partList) {
				if (ISO_LAST_NAME_TYPE.equalsIgnoreCase(part.getType().value())) {
					lastname = part.getValue();
				}
			}
		}
		return lastname;
	}

	public static String getFirstName(Person person) {
		String firstname = "";
		if (person != null) {
			List<ENXP> partList = person.getName().getPart();
			for (ENXP part : partList) {
				if (ISO_FIRST_NAME_TYPE
						.equalsIgnoreCase(part.getType().value())) {
					if (AppUtility.isEmpty(firstname)) {
						firstname = part.getValue();
					} else {
						// Concatenate Middle Name
						firstname += Constants.SPACE_STR + part.getValue();
					}
				}// if GIV name
			}// for - part list
		}
		return firstname;
	}

	public static String getStreetAddress(Person person) {
		return getStreetAddress(person.getPostalAddress());
	}

	public static String getCity(Person person) {
		return getCity(person.getPostalAddress());
	}

	public static String getState(Person person) {
		return getState(person.getPostalAddress());
	}

	public static String getCountry(Person person) {
		return getCountry(person.getPostalAddress());
	}

	public static String getZipCode(Person person) {
		return getZipCode(person.getPostalAddress());
	}

	public static String getEmailAddress(Person person) {
		return getEmail(person.getTelecomAddress());
	}

	public static String getTelephoneNumber(Person person) {
		return getTelephoneNumber(person.getTelecomAddress());
	}

	public static String getFaxNumber(Person person) {
		return getFaxNumber(person.getTelecomAddress());
	}

	public static String getTelephoneNumber(DSETTEL telecomAddress) {
		return getPhoneNumber(telecomAddress, ISO_TEL_PHONE_PREFIX);
	}

	public static String getFaxNumber(DSETTEL telecomAddress) {
		return getPhoneNumber(telecomAddress, ISO_TEL_FAX_PREFIX);
	}

	public static String getStreetAddress(AD address) {
		String streetAddress = "";
		List<ADXP> partList = address.getPart();
		for (ADXP part : partList) {
			if (ISO_STREET_ADDRESS_TYPE
					.equalsIgnoreCase(part.getType().value())) {
				streetAddress = part.getValue();
			}
		}
		return streetAddress;
	}

	public static String getCity(AD address) {
		String city = "";
		List<ADXP> partList = address.getPart();
		for (ADXP part : partList) {
			if (ISO_CITY_TYPE.equalsIgnoreCase(part.getType().value())) {
				city = part.getValue();
			}
		}
		return city;
	}

	public static String getState(AD address) {
		String state = "";
		List<ADXP> partList = address.getPart();
		for (ADXP part : partList) {
			if (ISO_STATE_TYPE.equalsIgnoreCase(part.getType().value())) {
				state = part.getValue();
			}
		}
		return state;
	}

	public static String getCountry(AD address) {
		String country = "";
		List<ADXP> partList = address.getPart();
		for (ADXP part : partList) {
			if (ISO_COUNTRY_TYPE.equalsIgnoreCase(part.getType().value())) {
				country = part.getValue();
			}
		}
		return country;
	}

	public static String getZipCode(AD address) {
		String zipCode = "";
		List<ADXP> partList = address.getPart();
		for (ADXP part : partList) {
			if (ISO_ZIP_TYPE.equalsIgnoreCase(part.getType().value())) {
				zipCode = part.getValue();
			}
		}
		return zipCode;
	}

	public static String getEmail(DSETTEL telecomAddress) {
		String email = "";
		boolean emailTagFound = false;
		if (telecomAddress != null) {
			List<TEL> itemList = telecomAddress.getItem();
			for (TEL item : itemList) {
				Annotation[] tcomAnnotations = item.getClass().getAnnotations();
				for (Annotation a : tcomAnnotations) {
					if (a instanceof XmlType) {
						XmlType xmlType = (XmlType) a;
						if (ISO_TEL_EMAIL_TYPE.equalsIgnoreCase(xmlType.name())) {
							emailTagFound = true;
						}// if Tel.Email
					}// if xmlType
				}// for annotation
				if (emailTagFound) {
					email = item.getValue();
					if (email.indexOf(ISO_EMAIL_PREFIX) > -1) {
						email = email.substring(email.indexOf(ISO_EMAIL_PREFIX)
								+ ISO_EMAIL_PREFIX.length());
					}
					break;
				}// if email found
			}// for telecom item list
		}// if telecom address not null
		return email;
	}

	public static String getPhoneNumber(DSETTEL telecomAddress,
			String phonePrefixType) {
		String phoneNumber = "";
		boolean phoneNumberFound = false;
		if (telecomAddress != null) {
			List<TEL> itemList = telecomAddress.getItem();
			for (TEL item : itemList) {
				Annotation[] tcomAnnotations = item.getClass().getAnnotations();
				for (Annotation a : tcomAnnotations) {
					if (a instanceof XmlType) {
						XmlType xmlType = (XmlType) a;
						if (ISO_TEL_PHONE_TYPE.equalsIgnoreCase(xmlType.name())) {
							if (AppUtility.isNotEmpty(item.getValue())
									&& (item.getValue()
											.indexOf(phonePrefixType) > -1)) {
								phoneNumberFound = true;
								phoneNumber = item.getValue();
								phoneNumber = phoneNumber.substring(phoneNumber
										.indexOf(phonePrefixType)
										+ phonePrefixType.length());
								break;
							}// ISO_TEL_PHONE_PREFIX found
						}// if Tel.Phone
					}// if xmlType
				}// for annotation
				if (phoneNumberFound) {
					break;
				}// if email found
			}// for telecom item list
		}// if telecom address not null
		return phoneNumber;
	}

	public static String getRemoteIdentifier(StudyProtocol studyProtocol) {
		String identifier = "";
		if (studyProtocol != null) {
			identifier = studyProtocol.getIdentifier().getExtension();
		}
		return identifier;
	}

	public static String getTitle(StudyProtocol studyProtocol) {
		String title = "";
		if ((studyProtocol != null)
				&& (studyProtocol.getOfficialTitle() != null)) {
			title = studyProtocol.getOfficialTitle().getValue();
		}
		return title;
	}

	public static String getShortTitle(StudyProtocol studyProtocol) {
		String shortTitle = "";
		if ((studyProtocol != null) && (studyProtocol.getAcronym() != null)
				&& (studyProtocol.getAcronym().getValue() != null)) {
			shortTitle = studyProtocol.getAcronym().getValue();
		}
		return shortTitle;
	}

	public static String getNCIIdentitifer(StudyProtocol studyProtocol) {
		String identifier = "";
		if (studyProtocol != null) {
			List<II> secondaryIdentifierList = studyProtocol
					.getSecondaryIdentifiers().getItem();
			if (AppUtility.isNotEmpty(secondaryIdentifierList)) {
				identifier = secondaryIdentifierList.get(0).getExtension();
			}
		}
		return identifier;
	}

	/**
	 * Returns start date in mm-dd-yyyy format
	 *
	 * @param studyProtocol
	 * @return
	 */
	public static String getStartDateStr(StudyProtocol studyProtocol) {
		String startDateStr = "";
		if ((studyProtocol != null) && (studyProtocol.getStartDate() != null)) {
			String coppaDateStr = "";
			try {
				coppaDateStr = studyProtocol.getStartDate().getValue();
				startDateStr = convertDateFormatCOPPAToCaTissue(coppaDateStr);
			} catch (ParseException e) {
				logger.error("Unparseable date:" + coppaDateStr + ":"
						+ getTitle(studyProtocol));
				return coppaDateStr;
			}
		}
		return startDateStr;
	}

	/**
	 * Returns start date in mm-dd-yyyy format
	 *
	 * @param studyProtocol
	 * @return
	 */
	public static Date getStartDate(StudyProtocol studyProtocol) {
		Date startDate = null;
		if ((studyProtocol != null) && (studyProtocol.getStartDate() != null)) {
			String coppaDateStr = "";
			try {
				coppaDateStr = studyProtocol.getStartDate().getValue();
				startDate = parseCOPPADateFormat(coppaDateStr);
			} catch (ParseException e) {
				logger.error("Unparseable date:" + coppaDateStr + ":"
						+ getTitle(studyProtocol));
				return null;
			}
		}
		return startDate;
	}

	public static String convertDateFormatCOPPAToCaTissue(String coppaDateStr)
			throws ParseException {
		String caTissueDateStr = "";
		if (AppUtility.isEmpty(coppaDateStr)) {
			return caTissueDateStr;
		}
		SimpleDateFormat coppaDateFormat = new SimpleDateFormat(DATE_FORMAT);
		Date startDate = coppaDateFormat.parse(coppaDateStr);
		SimpleDateFormat caTissueDateFormat = new SimpleDateFormat(
				Constants.DATE_FORMAT);
		caTissueDateStr = caTissueDateFormat.format(startDate);
		return caTissueDateStr;
	}

	public static Date parseCOPPADateFormat(String coppaDateStr)
			throws ParseException {
		String caTissueDateStr = "";
		if (AppUtility.isEmpty(coppaDateStr)) {
			return null;
		}
		SimpleDateFormat coppaDateFormat = new SimpleDateFormat(DATE_FORMAT);
		Date startDate = coppaDateFormat.parse(coppaDateStr);
		return startDate;
	}

	public static boolean isCOPPAEnabled() {
		boolean isEnabledFlag = false;
		try {
			if (("Yes".equalsIgnoreCase(CTRPPropertyHandler
					.getProperty(CTRPConstants.CTRP_IS_ENABLED_KEY)))
					|| ("true".equalsIgnoreCase(CTRPPropertyHandler
							.getProperty(CTRPConstants.CTRP_IS_ENABLED_KEY)))) {
				isEnabledFlag = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			isEnabledFlag = false;
		}
		return isEnabledFlag;
	}

	public static String toCOPPAEmailFormat(String emailAddress) {
		if (AppUtility.isNotEmpty(emailAddress)) {
			return ISO_EMAIL_PREFIX + emailAddress;
		} else {
			return emailAddress;
		}
	}

	public static boolean compareAndSyncData(Institution localInstitution,
			Institution remoteInstitution) {
		boolean compareResult = true;
		try {
			if (!StringUtils.equals(localInstitution.getName(),
					remoteInstitution.getName())) {
				localInstitution.setName(remoteInstitution.getName());
				compareResult = false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			compareResult = false;
		}
		return compareResult;
	}

	public static boolean compareAndSyncData(User localUser, User remoteUser) {
		boolean compareResult = true;
		try {
			if (!StringUtils.equals(localUser.getEmailAddress(),
					remoteUser.getEmailAddress())) {
				localUser.setEmailAddress(remoteUser.getEmailAddress());
				compareResult = false;
			}
			if (!StringUtils.equals(localUser.getFirstName(),
					remoteUser.getFirstName())) {
				localUser.setFirstName(remoteUser.getFirstName());
				compareResult = false;
			}
			if (!StringUtils.equals(localUser.getLastName(),
					remoteUser.getLastName())) {
				localUser.setLastName(remoteUser.getLastName());
				compareResult = false;
			}
			if (!compareAndSyncData(localUser.getAddress(),
					remoteUser.getAddress())) {
				compareResult = false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			compareResult = false;
		}
		return compareResult;
	}

	public static boolean compareAndSyncData(Address localUserAddress,
			Address remoteUserAddress) {
		boolean compareResult = true;
		try {
			if (!StringUtils.equals(localUserAddress.getStreet(),
					remoteUserAddress.getStreet())) {
				localUserAddress.setStreet(remoteUserAddress.getStreet());
				compareResult = false;
			}
			if (!StringUtils.equals(localUserAddress.getCity(),
					remoteUserAddress.getCity())) {
				localUserAddress.setCity(remoteUserAddress.getCity());
				compareResult = false;
			}
			if (!StringUtils.equals(localUserAddress.getState(),
					remoteUserAddress.getState())) {
				localUserAddress.setState(remoteUserAddress.getState());
				compareResult = false;
			}
			if (!StringUtils.equals(localUserAddress.getCountry(),
					remoteUserAddress.getCountry())) {
				localUserAddress.setCountry(remoteUserAddress.getCountry());
				compareResult = false;
			}
			if (!StringUtils.equals(localUserAddress.getZipCode(),
					remoteUserAddress.getZipCode())) {
				localUserAddress.setZipCode(remoteUserAddress.getZipCode());
				compareResult = false;
			}
			if (!StringUtils.equals(localUserAddress.getPhoneNumber(),
					remoteUserAddress.getPhoneNumber())) {
				localUserAddress.setPhoneNumber(remoteUserAddress
						.getPhoneNumber());
				compareResult = false;
			}
			if (!StringUtils.equals(localUserAddress.getFaxNumber(),
					remoteUserAddress.getFaxNumber())) {
				localUserAddress.setFaxNumber(remoteUserAddress.getFaxNumber());
				compareResult = false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			compareResult = false;
		}
		return compareResult;
	}

	public static boolean compareAndSyncData(
			CollectionProtocol localCollectionProtocol,
			CollectionProtocol remoteCollectionProtocol) {
		boolean compareResult = true;
		try {
			if (!StringUtils.equals(localCollectionProtocol.getTitle(),
					remoteCollectionProtocol.getTitle())) {
				localCollectionProtocol.setTitle(remoteCollectionProtocol
						.getTitle());
				compareResult = false;
			}
			if (!StringUtils.equals(localCollectionProtocol.getShortTitle(),
					remoteCollectionProtocol.getShortTitle())) {
				localCollectionProtocol.setShortTitle(remoteCollectionProtocol
						.getShortTitle());
				compareResult = false;
			}
			if (!DateUtils.isSameDay(localCollectionProtocol.getStartDate(),
					remoteCollectionProtocol.getStartDate())) {
				localCollectionProtocol.setStartDate(remoteCollectionProtocol
						.getStartDate());
				compareResult = false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			compareResult = false;
		}
		return compareResult;
	}
}


text:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace QIP.IODomain.Input {
    public class InUpdateLine {
        [Required]
        [Range(0, long.MaxValue)]
        public long? Id { get; set; }

        [Required]
        [Range(0, long.MaxValue)]
        public long? BoardId { get; set; }

        [Required]
        public IEnumerable<InLinePoint> Points { get; set; }

        [Required]
        public bool? Closed { get; set; }

        [Required]
        public InCreateLineStyle Style { get; set; }
    }
}


text:
import path from "path";
import fs from "fs";
import homeOrTmp from "home-or-tmp";
import pathExists from "path-exists";

const FILENAME = process.env.BABEL_CACHE_PATH || path.join(homeOrTmp, ".babel.json");
var data = {};

export function save() {
  fs.writeFileSync(FILENAME, JSON.stringify(data, null, "  "));
}

export function load() {
  if (process.env.BABEL_DISABLE_CACHE) return;

  process.on("exit", save);
  process.nextTick(save);

  if (!pathExists.sync(FILENAME)) return;

  try {
    data = JSON.parse(fs.readFileSync(FILENAME));
  } catch (err) {
    return;
  }
}

export function get() {
  return data;
}


text:
<?PHP
/**
 * 列出虚拟网络站点
 *
 * http://msdn.microsoft.com/library/azure/jj157185.aspx
 */
require 'common.php';

use WindowsAzure\Common\ServicesBuilder;
use WindowsAzure\Common\ServiceException;

try {
    $serviceManagementRestProxy = ServicesBuilder::getInstance()->createServiceManagementService($conn_string);

    $sites = $serviceManagementRestProxy->listVirtualNetworkSites();
    print_r($sites);
} catch (ServiceException $e) {
    // Handle exception based on error codes and messages.
    // Error codes and messages are here:
    // http://msdn.microsoft.com/en-us/library/windowsazure/ee460801
    echo $e->getMessage();
}


text:
        Home

        Tables

        Datatables

        <button type="button" class="btn green btn-sm btn-outline dropdown-toggle" data-toggle="dropdown"> Actions

        </button>

               Action

               Another action

               Something else here

               Separated link

                     Default Form

                         Actions

                                     Edit

                                     Delete

                                     Ban

                                 Make admin

              <form class="" action="<?php echo base_url($action_add)?>" method="post">

                        Name
                        <input type="hidden" name="i_id" class="form-control"
                        value="<?php echo isset($customer_details->customer_id) ? $customer_details->customer_id : ""?>" required>
                        <input type="text" name="i_name" class="form-control"
                        value="<?php echo isset($customer_details->customer_name) ? $customer_details->customer_name : ""?>" required>

                        Customer Phone
                        <input type="" id="i_phone" name="i_phone" class="form-control"
                        value="<?php echo isset($customer_details->customer_phone) ? $customer_details->customer_phone : ""?>" required>

                        Customer Adress
                        <input type="" id="i_address" name="i_address" class="form-control"
                        value="<?php echo isset($customer_details->customer_address) ? $customer_details->customer_address : ""?>" required>

                        Customer Email
                        <input type="email" id="i_email" name="i_email" class="form-control"
                        value="<?php echo isset($customer_details->customer_email) ? $customer_details->customer_email : ""?>" required>

                      <button type="submit" name="button" class="btn btn-primary">Simpan</button>
                      <a href="<?php echo base_url($action_close)?>" class="btn btn-danger">Keluar

              </form>


text:
package it.org.sheinbergon.governator.configuration.subjects;

import com.google.inject.AbstractModule;

public class TestModule extends AbstractModule {

    @Override
    protected void configure() {
        bind(StaticConfigObject.class).toInstance(StaticConfigObject.empty());
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.

-->
<edmx:Edmx Version="4.0" xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx">
  <edmx:Reference Uri="http://docs.oasis-open.org/odata/odata/v4.0/os/vocabularies/Org.OData.Core.V1.xml">
    <edmx:Include Namespace="Org.OData.Core.V1" Alias="Core" />
  </edmx:Reference>
  <edmx:Reference Uri="/coco/vocabularies/Communication.xml">
    <edmx:Include Namespace="Org.OData.Communication.V1" Alias="vCard" />
  </edmx:Reference>
  <edmx:Reference Uri="/coco/vocabularies/Common.xml">
    <edmx:Include Namespace="Org.OData.Common.V1" Alias="Common" />
  </edmx:Reference>
  <edmx:DataServices>
    <Schema xmlns="http://docs.oasis-open.org/odata/ns/edm" Alias="UI" Namespace="com.vocabularies.UI.v1">
      <Annotation Term="Core.Description">
        <String>Terms for presenting data in user interfaces</String>
      </Annotation>
      <Annotation Term="Core.Description" Qualifier="Published">
        <String>2013-10-16 © Copyright 2013</String>
      </Annotation>

      <!-- Semantic Views / Perspectives -->

      <Term Name="HeaderInfo" Type="UI.HeaderInfoType" AppliesTo="EntityType">
        <Annotation Term="UI.ThingPerspective" />
        <Annotation Term="Core.Description">
          <String>HeaderInfos are mandatory and must be exposed on every thing of the model</String>
        </Annotation>
      </Term>
      <ComplexType Name="HeaderInfoType">
        <Property Name="TypeName" Type="Edm.String">
          <Annotation Term="Core.IsLanguageDependent" />
        </Property>
        <Property Name="TypeNamePlural" Type="Edm.String" Nullable="false">
          <Annotation Term="Core.IsLanguageDependent" />
        </Property>
        <Property Name="TypeImageUrl" Type="Edm.String" Nullable="true">
          <Annotation Term="Core.IsURL" />
        </Property>
        <Property Name="Title" Type="UI.DataField" Nullable="false" />
        <Property Name="Description" Type="UI.DataField" Nullable="true" />
        <Property Name="ImageUrl" Type="Edm.String" Nullable="true">
          <Annotation Term="Core.IsURL" />
        </Property>
      </ComplexType>

      <Term Name="Identification" Type="Collection(UI.DataFieldAbstract)" AppliesTo="EntityType">
        <Annotation Term="UI.ThingPerspective" />
        <Annotation Term="Core.Description">
          <String>HeaderInfo plus this set of attributes identifies the object</String>
        </Annotation>
      </Term>

      <Term Name="Badge" Type="UI.BadgeType" AppliesTo="EntityType">
        <Annotation Term="UI.ThingPerspective" />
        <Annotation Term="Core.Description">
          <String>Badge is similar to a business card view</String>
        </Annotation>
      </Term>
      <ComplexType Name="BadgeType">
        <Property Name="HeadLine" Type="UI.DataField" Nullable="false" />
        <Property Name="Title" Type="UI.DataField" Nullable="false" />
        <Property Name="ImageUrl" Type="Edm.String" Nullable="true">
          <Annotation Term="Core.IsURL" />
        </Property>
        <Property Name="TypeImageUrl" Type="Edm.String" Nullable="true">
          <Annotation Term="Core.IsURL" />
        </Property>
        <Property Name="MainInfo" Type="UI.DataField" Nullable="true" />
        <Property Name="SecondaryInfo" Type="UI.DataField" Nullable="true" />
      </ComplexType>

      <Term Name="LineItem" Type="Collection(UI.DataFieldAbstract)" AppliesTo="EntityType">
        <Annotation Term="UI.ThingPerspective" />
      </Term>

      <Term Name="StatusInfo" Type="Collection(UI.DataFieldAbstract)" AppliesTo="EntityType">
        <Annotation Term="UI.ThingPerspective" />
      </Term>

      <Term Name="FieldGroup" Type="UI.FieldGroupType" AppliesTo="EntityType">
        <Annotation Term="UI.ThingPerspective" />
      </Term>
      <ComplexType Name="FieldGroupType">
        <Property Name="Label" Type="Edm.String" Nullable="true">
          <Annotation Term="Core.IsLanguageDependent" />
        </Property>
        <Property Name="Data" Type="Collection(UI.DataFieldAbstract)" />
      </ComplexType>

      <!-- To be discussed, please don't deliver -->
      <Term Name="GeoPoints" Type="Collection(Edm.AnnotationPath)" AppliesTo="EntityType">
        <Annotation Term="Core.Description">
          <String>
            Each collection element MUST reference an annotation of a
              vCard.Contact or
              collection of vCard.ContactData or
              UI.Contacts or
              UI.GeoLocation or
               of UI.GeoLocationType
          </String>
        </Annotation>
        <Annotation Term="UI.ThingPerspective" />
      </Term>
      <!-- To be discussed, please don't deliver -->

      <Term Name="GeoLocations" Type="Collection(UI.GeoLocationType)" AppliesTo="EntityType">
        <Annotation Term="UI.ThingPerspective" />
      </Term>
      <Term Name="GeoLocation" Type="UI.GeoLocationType" AppliesTo="EntityType">
        <Annotation Term="UI.ThingPerspective" />
      </Term>
      <ComplexType Name="GeoLocationType">
        <Annotation Term="Core.Description">
          <String>Set of Attributes which defines the Localization of the object</String>
        </Annotation>
        <Property Name="Latitude" Type="Edm.Double" Nullable="true" />
        <Property Name="Longitude" Type="Edm.Double" Nullable="true" />
        <Property Name="Location" Type="Edm.GeographyPoint" Nullable="true" />
        <Property Name="Address" Type="vCard.AddressType" Nullable="true" />
      </ComplexType>

      <Term Name="Contacts" Type="Collection(Edm.AnnotationPath)" AppliesTo="EntityType">
        <Annotation Term="Core.Description" String="Each collection element MUST reference an annotation of a vCard.Contact" />
        <Annotation Term="UI.ThingPerspective" />
      </Term>

      <!-- To be discussed, please don't deliver -->
      <Term Name="MediaResource" Type="UI.MediaResourceType" AppliesTo="EntityType">
        <Annotation Term="UI.ThingPerspective" />
        <Annotation Term="Core.Description" String="Properties that are relevant for Media Resources" />
      </Term>
      <ComplexType Name="MediaResourceType">
        <Property Name="Url" Type="Edm.String" Nullable="false">
          <Annotation Term="Core.IsURL" />
        </Property>
        <Property Name="ContentType" Type="Edm.String" Nullable="true">
          <Annotation Term="Core.IsMediaType" />
        </Property>
        <Property Name="ByteSize" Type="Edm.Int64" Nullable="true" />
        <Property Name="ChangedAt" Type="Edm.DateTimeOffset" Nullable="true" />
        <Property Name="Thumbnail" Type="UI.ImageType" Nullable="true" />
        <Property Name="Title" Type="UI.DataField" Nullable="false" />
        <Property Name="Description" Type="UI.DataField" Nullable="true" />
      </ComplexType>
      <ComplexType Name="ImageType">
        <Property Name="Url" Type="Edm.String" Nullable="false">
          <Annotation Term="Core.IsURL" />
        </Property>
        <Property Name="Width" Type="Edm.String" Nullable="true" />
        <Property Name="Height" Type="Edm.String" Nullable="true" />
      </ComplexType>
      <!-- To be discussed, please don't deliver -->

      <!-- To be discussed, please don't deliver -->
      <Term Name="AdditionalInfo" Type="Edm.AnnotationPath" AppliesTo="Annotation">
        <Annotation Term="Core.Description">
          <String>
            Applies to UI.GeoLocation and vCard.Contact annotations only
            Provides additional related information for a UI.GeoLocation or vCard.Contact
            Reference to UI.HeaderInfo, UI.Badge, a qualified UI.FieldGroup, or a dedicated property tagged with Core.IsUrl
          </String>
        </Annotation>
      </Term>
      <!-- To be discussed, please don't deliver -->

      <Term Name="DataPoint" Type="UI.DataPointType" AppliesTo="EntityType">
        <Annotation Term="UI.ThingPerspective" />
      </Term>
      <ComplexType Name="DataPointType">
        <Property Name="Title" Type="Edm.String" Nullable="false">
          <Annotation Term="Core.IsLanguageDependent" />
        </Property>
        <Property Name="Description" Type="Edm.String" Nullable="true">
          <Annotation Term="Core.IsLanguageDependent" />
        </Property>
        <Property Name="LongDescription" Type="Edm.String" Nullable="true">
          <Annotation Term="Core.IsLanguageDependent" />
        </Property>
        <Property Name="Value" Type="Edm.PrimitiveType" Nullable="false">
          <Annotation Term="Core.Description" String="The numeric value of the DataPoint" />
          <Annotation Term="Core.LongDescription">
            <String>
              It could be annotated with either UoM.ISOCurrency or UoM.Unit.
              Percentage values are annotated with UoM.Unit = '%'.
              A renderer should take an optional Common.Text annotation into consideration.
            </String>
          </Annotation>
        </Property>
        <Property Name="ValueFormat" Type="UI.NumberFormat" Nullable="true" />
        <Property Name="ReferencePeriod" Type="UI.ReferencePeriod" Nullable="true" />
        <Property Name="Criticality" Type="UI.CriticalityType" Nullable="true" />
        <Property Name="CriticalityCalculation" Type="UI.CriticalityCalculationType" Nullable="true" />
        <Property Name="Trend" Type="UI.TrendType" Nullable="true" />
        <Property Name="TrendCalculation" Type="UI.TrendCalculationType" Nullable="true" />
        <Property Name="Responsible" Type="vCard.ContactType" Nullable="true" />
      </ComplexType>

      <ComplexType Name="NumberFormat">
        <Property Name="ScaleFactor" Type="Edm.Decimal" Scale="variable" Nullable="true" />
        <Property Name="NumberOfFractionalDigits" Type="Edm.Byte" Nullable="true" />
      </ComplexType>

      <ComplexType Name="ReferencePeriod">
        <Property Name="Description" Type="Edm.String" Nullable="true">
          <Annotation Term="Core.IsLanguageDependent" />
        </Property>
        <Property Name="Start" Type="Edm.DateTimeOffset" Nullable="true" />
        <Property Name="End" Type="Edm.DateTimeOffset" Nullable="true" />
      </ComplexType>

      <EnumType Name="CriticalityType">
        <Member Name="Negative" />
        <Member Name="Critical" />
        <Member Name="Positive" />
      </EnumType>

      <ComplexType Name="CriticalityCalculationType">
        <Annotation Term="Core.Description">
          <String>
              Direction: Target
               - Positive: ge ToleranceRangeLowValue and le ToleranceRangeHighValue
               - Critical: ge DeviationRangeLowValue  and lt ToleranceRangeLowValue or
                           gt ToleranceRangeHighValue and le DeviationRangeHighValue
               - Negative: lt DeviationRangeLowValue and gt DeviationRangeHighValue
              Direction: Minimize
               - Positive: le ToleranceRangeHighValue
               - Critical: gt ToleranceRangeHighValue and le DeviationRangeHighValue
               - Negative: gt DeviationRangeHighValue
              Direction: Maximize
               - Positive: ge ToleranceRangeLowValue
               - Critical: lt ToleranceRangeLowValue and ge DeviationRangeLowValue
               - Negative: lt DeviationRangeLowValue
            </String>
        </Annotation>
        <Property Name="ImprovementDirection" Type="UI.ImprovementDirectionType" Nullable="false">
        </Property>
        <Property Name="ToleranceRangeLowValue" Type="Edm.PrimitiveType" Nullable="true" />
        <Property Name="ToleranceRangeHighValue" Type="Edm.PrimitiveType" Nullable="true" />
        <Property Name="DeviationRangeLowValue" Type="Edm.PrimitiveType" Nullable="true" />
        <Property Name="DeviationRangeHighValue" Type="Edm.PrimitiveType" Nullable="true" />
      </ComplexType>

      <EnumType Name="ImprovementDirectionType">
        <Member Name="Minimize" />
        <Member Name="Target" />
        <Member Name="Maximize" />
      </EnumType>

      <EnumType Name="TrendType">
        <Member Name="StrongUp" />
        <Member Name="Up" />
        <Member Name="Sideways" />
        <Member Name="Down" />
        <Member Name="StrongDown" />
      </EnumType>

      <ComplexType Name="TrendCalculationType">
        <Annotation Term="Core.Description">
          <String>
            Value sub ReferenceValue ( div ReferenceValue if IsRelativeDifference ) must be
             - StrongUp:   ge StrongUpDifference
             - Up:         lt StrongUpDifference and ge UpDifference
             - Sideways:   lt UpDifference         and gt DownDifference
             - Down:       gt StrongDownDifference and le DownDifference
             - StrongDown: le StrongDownDifference
          </String>
        </Annotation>
        <Property Name="ReferenceValue" Type="Edm.PrimitiveType" Nullable="false" />
        <Property Name="IsRelativeDifference" Type="Edm.Boolean" DefaultValue="false" />
        <Property Name="UpDifference" Type="Edm.Decimal" Nullable="false" />
        <Property Name="StrongUpDifference" Type="Edm.Decimal" Nullable="false" />
        <Property Name="DownDifference" Type="Edm.Decimal" Nullable="false" />
        <Property Name="StrongDownDifference" Type="Edm.Decimal" Nullable="false" />
      </ComplexType>

      <Term Name="Chart" Type="UI.ChartDefinitionType" AppliesTo="EntityType">
        <Annotation Term="UI.ThingPerspective" />
      </Term>
      <ComplexType Name="ChartDefinitionType">
        <Property Name="Title" Type="Edm.String" Nullable="true">
          <Annotation Term="Core.IsLanguageDependent" />
        </Property>
        <Property Name="Description" Type="Edm.String" Nullable="true">
          <Annotation Term="Core.IsLanguageDependent" />
        </Property>
        <Property Name="ChartType" Type="UI.ChartType" Nullable="false" />
        <Property Name="Measures" Type="Collection(Edm.PropertyPath)" />
        <Property Name="Dimensions" Type="Collection(Edm.PropertyPath)" />
      </ComplexType>

      <EnumType Name="ChartType">
        <Member Name="Column" />
        <Member Name="ColumnStacked" />
        <Member Name="ColumnStacked100" />
        <Member Name="Bar" />
        <Member Name="BarStacked" />
        <Member Name="BarStacked100" />
        <Member Name="Area" />
        <Member Name="AreaStacked" />
        <Member Name="AreaStacked100" />
        <Member Name="HorizontalArea" />
        <Member Name="HorizontalAreaStacked" />
        <Member Name="HorizontalAreaStacked100" />
        <Member Name="Line" />
        <Member Name="Pie" />
        <Member Name="Donut" />
        <Member Name="Scatter" />
        <Member Name="Bubble" />
        <Member Name="Radar" />
        <Member Name="HeatMap" />
        <Member Name="TreeMap" />
        <Member Name="Waterfall" />
        <!-- Future: GeoPie, GeoBubble, ChoroplethMap -->
      </EnumType>

      <Term Name="SelectionFields" Type="Collection(Edm.PropertyPath)" AppliesTo="EntityType">
        <Annotation Term="UI.ThingPerspective" />
        <Annotation Term="Core.Description" String="Properties that might be relevant for filtering a listof entity instances" />
      </Term>

      <!-- Segmentation of content according to facets of the Object -->

      <Term Name="Facets" Type="Collection(UI.Facet)" AppliesTo="EntityType">
      </Term>

      <ComplexType Name="Facet" Abstract="true">
        <Annotation Term="Core.Description" String="Base type for facets" />
        <Property Name="Label" Type="Edm.String" Nullable="true">
          <Annotation Term="Core.IsLanguageDependent" />
        </Property>
      </ComplexType>
      <ComplexType Name="CollectionFacet" BaseType="UI.Facet">
        <Annotation Term="Core.Description" String="Collection of Facets" />
        <Property Name="Facets" Type="Collection(UI.Facet)" />
      </ComplexType>
      <ComplexType Name="ReferenceFacet" BaseType="UI.Facet">
        <Annotation Term="Core.Description" String="Facet that refers to a thing perspective, e.g. LineItem" />
        <Property Name="Target" Type="Edm.AnnotationPath" Nullable="false">
          <Annotation Term="Core.Description">
            <String>Path MUST end in vCard.Contact or vCard.Address or a term that is tagged with UI.ThingPerspective, e.g.  UI.StatusInfo, UI.LineItem, UI.Identification, UI.FieldGroup, UI.Badge</String>
          </Annotation>
        </Property>
      </ComplexType>
      <ComplexType Name="ReferenceURLFacet" BaseType="UI.Facet">
        <Property Name="Url" Type="Edm.String" Nullable="false">
          <Annotation Term="Core.IsURL" />
        </Property>
        <Property Name="UrlContentType" Type="Edm.String" Nullable="true">
          <Annotation Term="Core.IsMediaType" />
        </Property>
      </ComplexType>

      <!-- basic type definitions for reuse goes here -->

      <Term Name="ThingPerspective" Type="Core.Tag" DefaultValue="true" AppliesTo="Term">
        <Annotation Term="Core.Description" String="This Term is a Thing Perspective" />
      </Term>
      <Term Name="IsSummary" Type="Core.Tag" DefaultValue="true" AppliesTo="Record">
        <Annotation Term="Core.Description"
          String="This Facet and all included Facets are the summary of the thing. At most one Facet of a thing can be tagged with this term" />
        <Annotation Term="Core.RequiresType" String="UI.Facet" />
      </Term>
      <Term Name="PartOfPreview" Type="Core.Tag" DefaultValue="true" AppliesTo="Record">
        <Annotation Term="Core.Description" String="This Facet and all included Facets are part of the Thing preview" />
        <Annotation Term="Core.RequiresType" String="UI.Facet" />
      </Term>
      <Term Name="Map" Type="Core.Tag" DefaultValue="true" AppliesTo="Record">
        <Annotation Term="Core.Description" String="Target MUST reference a UI.GeoLocation, vCard.Address or a collection of these" />
        <Annotation Term="Core.RequiresType" String="UI.ReferenceFacet" />
      </Term>
      <!-- To be discussed, please don't deliver -->
      <Term Name="Gallery" Type="Core.Tag" DefaultValue="true" AppliesTo="Record">
        <Annotation Term="Core.Description" String="Target MUST reference a UI.MediaResource" />
        <Annotation Term="Core.RequiresType" String="UI.ReferenceFacet" />
      </Term>
      <!-- To be discussed, please don't deliver -->

      <Term Name="IsImageURL" Type="Core.Tag" DefaultValue="true" AppliesTo="Property Term">
        <Annotation Term="Core.Description"
          String="Properties and terms annotated with this term MUST contain a valid URL referencing an resource with a MIME type image" />
        <Annotation Term="Core.RequiresType" String="Edm.String" />
      </Term>
      <Term Name="MultiLineText" Type="Core.Tag" DefaultValue="true" AppliesTo="Property">
        <Annotation Term="Core.Description"
          String="Properties annotated with this annotation should be rendered as multi-line text (e.g. text area)" />
        <Annotation Term="Core.RequiresType" String="Edm.String" />
      </Term>
      <!-- To be discussed, please don't deliver -->
      <!-- not ready yet, wait for UI5 concerning the format of that value -->
      <Term Name="DisplayTimeZone" Type="Edm.Int32" AppliesTo="Property">
        <Annotation Term="Core.Description">
          <String>Contains information for time- or date-time-fields in which time zone the time value should be displayed.</String>
        </Annotation>
      </Term>
      <!-- To be discussed, please don't deliver -->

      <Term Name="Importance" Type="UI.ImportanceType" AppliesTo="Annotation Record">
        <Annotation Term="Core.Description"
          String="Expresses the importance, e.g. importance of a DataField or a the importance of a annotation" />
      </Term>
      <EnumType Name="ImportanceType">
        <Member Name="High" />
        <Member Name="Medium" />
        <Member Name="Low" />
      </EnumType>

      <ComplexType Name="DataFieldAbstract" Abstract="true">
        <Property Name="Label" Type="Edm.String" Nullable="true">
          <Annotation Term="Core.IsLanguageDependent" />
        </Property>
      </ComplexType>

      <ComplexType Name="DataFieldForAnnotation" BaseType="UI.DataFieldAbstract">
        <Property Name="Target" Type="Edm.AnnotationPath">
          <Annotation Term="Core.Description" String="Annotation path MUST end in vCard.Address or UI.DataPoint" />
        </Property>
      </ComplexType>
      <ComplexType Name="DataFieldForAction" BaseType="UI.DataFieldAbstract">
        <Property Name="Action" Type="Common.QualifiedName">
          <Annotation Term="Core.Description" String="Qualified name of an Action, Function, ActionImport or FunctionImport in scope" />
        </Property>
      </ComplexType>
      <ComplexType Name="DataField" BaseType="UI.DataFieldAbstract">
        <Property Name="Value" Type="Edm.PrimitiveType" Nullable="false">
          <Annotation Term="Core.IsLanguageDependent" />
        </Property>
      </ComplexType>
      <ComplexType Name="DataFieldWithNavigationPath" BaseType="UI.DataField">
        <Property Name="Target" Type="Edm.NavigationPropertyPath" Nullable="false">
          <Annotation Term="Core.Description">
            <String>Contains either a navigation property or a term cast, where term is of type Edm.EntityType or a concrete entity type or a collection of these types</String>
          </Annotation>
        </Property>
      </ComplexType>
      <ComplexType Name="DataFieldWithUrl" BaseType="UI.DataField">
        <Property Name="Url" Type="Edm.String" Nullable="false">
          <Annotation Term="Core.IsURL" />
        </Property>
        <Property Name="UrlContentType" Type="Edm.String" Nullable="true">
          <Annotation Term="Core.IsMediaType" />
        </Property>
      </ComplexType>

    </Schema>
  </edmx:DataServices>
</edmx:Edmx>


text:
/*globals Backbone:true, _:true, $:true*/
Backbone.Paginator = (function (Backbone, _, $) {
	"use strict";

	var Paginator = {};
	Paginator.version = "0.15";

	// @name: clientPager
	//
	// @tagline: Paginator for client-side data
	//
	// @description:
	// This paginator is responsible for providing pagination
	// and sort capabilities for a single payload of data
	// we wish to paginate by the UI for easier browsering.
	//
	Paginator.clientPager = Backbone.Collection.extend({

		sync: function (method, model, options) {

			var queryMap = {};
				queryMap[this.perPageAttribute] =  this.perPage;
				queryMap[this.skipAttribute] = this.page * this.perPage;
				queryMap[this.orderAttribute] =  this.sortField;
				queryMap[this.customAttribute1] =  this.customParam1;
				queryMap[this.formatAttribute] =  this.format;
				queryMap[this.customAttribute2] = this.customParam2;
				queryMap[this.queryAttribute] =  this.query;

			var params = _.extend({
				type: 'GET',
				dataType: 'jsonp',
				jsonpCallback: 'callback',
				data: decodeURIComponent($.param(queryMap)),
				url: this.url,
				processData: false
			}, options);

			return $.ajax(params);
		},

		nextPage: function () {
			this.page = ++this.page;
			this.pager();
		},

		previousPage: function () {
			this.page = --this.page || 1;
			this.pager();
		},

		goTo: function (page) {
			if(page !== undefined){
				this.page = parseInt(page, 10);
				this.pager();
			}
		},

		howManyPer: function (perPage) {
			if(perPage !== undefined){
				this.displayPerPage = parseInt(perPage, 10);
				this.pager();
			}
		},

		// where column is the key to sort on
		setSort: function (column, direction) {
			if(column !==undefined && direction !==undefined){
				this.pager(column, direction);
			}
		},

		pager: function (sort, direction) {
			var self = this,
				disp = this.displayPerPage,
				start = (self.page - 1) * disp,
				stop = start + disp;

			if (self.origModels === undefined) {
				self.origModels = self.models;
			}

			self.models = self.origModels;

			if (sort) {
				self.models = self._sort(self.models, sort, direction);
			}
			self.reset(self.models.slice(start, stop));
		},

		_sort: function (models, sort, direction) {
			models = models.sort(function (a, b) {
				var ac = a.get(sort),
					bc = b.get(sort);

				if (direction === 'desc') {
					if (ac > bc) {
						return -1;
					}

					if (ac < bc) {
						return 1;
					}
				} else {
					if (ac < bc) {
						return -1;
					}

					if (ac > bc) {
						return 1;
					}
				}

				return 0;
			});

			return models;
		},

		info: function () {
			var self = this,
				info = {},
				totalRecords = (self.origModels) ? self.origModels.length : self.length,
				totalPages = Math.ceil(totalRecords / self.displayPerPage);

			info = {
				totalRecords: totalRecords,
				page: self.page,
				perPage: this.displayPerPage,
				totalPages: totalPages,
				lastPage: totalPages,
				lastPagem1: totalPages - 1,
				previous: false,
				next: false,
				page_set: [],
				startRecord: (self.page - 1) * this.displayPerPage + 1,
				endRecord: Math.min(totalRecords, self.page * this.displayPerPage)
			};

			if (self.page > 1) {
				info.prev = self.page - 1;
			}

			if (self.page < info.totalPages) {
				info.next = self.page + 1;
			}

			info.pageSet = self.setPagination(info);

			self.information = info;
			return info;
		},

		setPagination: function (info) {
			var pages = [], i = 0, l = 0;

			// How many adjacent pages should be shown on each side?
			var ADJACENT = 3,
				ADJACENTx2 = ADJACENT * 2,
				LASTPAGE = Math.ceil(info.totalRecords / info.perPage),
				LPM1 = -1;

			if (LASTPAGE > 1) {
				// not enough pages to bother breaking it up
				if (LASTPAGE < (7 + ADJACENTx2)) {
					for (i = 1, l = LASTPAGE; i <= l; i++) {
						pages.push(i);
					}
				}
				// enough pages to hide some
				else if (LASTPAGE > (5 + ADJACENTx2)) {

					//close to beginning; only hide later pages
					if (info.page < (1 + ADJACENTx2)) {
						for (i = 1, l = 4 + ADJACENTx2; i < l; i++) {
							pages.push(i);
						}
					}

					// in middle; hide some front and some back
					else if (LASTPAGE - ADJACENTx2 > info.page && info.page > ADJACENTx2) {
						for (i = info.page - ADJACENT; i <= info.page + ADJACENT; i++) {
							pages.push(i);
						}
					}
					// close to end; only hide early pages
					else {
						for (i = LASTPAGE - (2 + ADJACENTx2); i <= LASTPAGE; i++) {
							pages.push(i);
						}
					}
				}
			}

			return pages;
		}

	});

	// @name: requestPager
	//
	// Paginator for server-side data being requested from a backend/API
	//
	// @description:
	// This paginator is responsible for providing pagination
	// and sort capabilities for requests to a server-side
	// data service (e.g an API)
	//
	Paginator.requestPager = Backbone.Collection.extend({

		sync: function (method, model, options) {

			var queryMap = {}, params;
				queryMap[this.perPageAttribute] =  this.perPage;
				queryMap[this.skipAttribute] = this.page * this.perPage;
				queryMap[this.orderAttribute] =  this.sortField;
				queryMap[this.customAttribute1] =  this.customParam1;
				queryMap[this.formatAttribute] =  this.format;
				queryMap[this.customAttribute2] = this.customParam2;
				queryMap[this.queryAttribute] =  this.query;

				params = _.extend({
				type: 'GET',
				dataType: 'jsonp',
				jsonpCallback: 'callback',
				data: decodeURIComponent($.param(queryMap)),
				url: this.url,
				processData: false
			}, options);

			return $.ajax(params);
		},

		requestNextPage: function () {
			if (this.page !== undefined) {
				this.page += 1;
				// customize as needed. For the Netflix API, skipping ahead based on
				// page * number of results per page was necessary. You may have a
				// simpler server-side pagination API where just updating
				// the 'page' value is all you need to do.
				// This applies similarly to requestPreviousPage()
				this.pager();
			}
		},

		requestPreviousPage: function () {
			if (this.page !== undefined) {
				this.page -= 1;
				// customize as needed.
				this.pager();
			}
		},

		updateOrder: function (column) {
			if (column !== undefined) {
				this.sortField = column;
				this.pager();
			}

		},

		goTo: function (page) {
			if(page !== undefined){
				this.page = parseInt(page, 10);
				this.pager();
			}
		},

		howManyPer: function (count) {
			if(count !== undefined){
				this.page = this.firstPage;
				this.perPage = count;
				this.pager();
			}
		},

		sort: function () {
			//assign to as needed.
		},

		info: function () {

			var info = {
				page: this.page,
				firstPage: this.firstPage,
				totalPages: this.totalPages,
				lastPage: this.totalPages,
				perPage: this.perPage
			};

			this.information = info;
			return info;
		},

		// fetches the latest results from the server
		pager: function () {
			this.fetch({});
		}

	});

	return Paginator;

}(Backbone, _, $));


text:
set -exu

# Vagrant specific
date > /etc/vagrant_box_build_time

mkdir -pm 700 /home/vagrant/.ssh
curl -o /home/vagrant/.ssh/authorized_keys 'https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub'
chown -R vagrant:vagrant /home/vagrant/.ssh
chmod -R go-rwsx /home/vagrant/.ssh