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

#include "EnginePrivate.h"
#include "ParticleDefinitions.h"
#include "SoundDefinitions.h"
#include "Particles/EmitterCameraLensEffectBase.h"
#include "IHeadMountedDisplay.h"
#include "Particles/EmitterCameraLensEffectBase.h"
#include "Camera/CameraActor.h"
#include "Camera/CameraAnim.h"
#include "Camera/CameraAnimInst.h"
#include "Camera/CameraComponent.h"
#include "Camera/CameraModifier_CameraShake.h"
#include "GameFramework/PlayerState.h"

DEFINE_LOG_CATEGORY_STATIC(LogPlayerCameraManager, Log, All);

//////////////////////////////////////////////////////////////////////////
// APlayerCameraManager

APlayerCameraManager::APlayerCameraManager(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)
{
	static FName NAME_Default(TEXT("Default"));

	DefaultFOV = 90.0f;
	DefaultAspectRatio = 1.33333f;
	DefaultOrthoWidth = 512.0f;
	bHidden = true;
	bReplicates = false;
	FreeCamDistance = 256.0f;
	bDebugClientSideCamera = false;
	ViewPitchMin = -89.99f;
	ViewPitchMax = 89.99f;
	ViewYawMin = 0.f;
	ViewYawMax = 359.999f;
	ViewRollMin = -89.99f;
	ViewRollMax = 89.99f;
	bUseClientSideCameraUpdates = true;
	CameraStyle = NAME_Default;
	bCanBeDamaged = false;

	bFollowHmdOrientation = false;

	// create dummy transform component
	TransformComponent = CreateDefaultSubobject<USceneComponent>(TEXT("TransformComponent0"));
	RootComponent = TransformComponent;

	// support camerashakes by default
	DefaultModifiers.Add(UCameraModifier_CameraShake::StaticClass());
}

APlayerController* APlayerCameraManager::GetOwningPlayerController() const
{
	return PCOwner;
}

void APlayerCameraManager::SetViewTarget(class AActor* NewTarget, struct FViewTargetTransitionParams TransitionParams)
{
	// Make sure view target is valid
	if( NewTarget == NULL )
	{
		NewTarget = PCOwner;
	}

	// Update current ViewTargets
	ViewTarget.CheckViewTarget(PCOwner);
	if( PendingViewTarget.Target )
	{
		PendingViewTarget.CheckViewTarget(PCOwner);
	}

	// If we're already transitioning to this new target, don't interrupt.
	if( PendingViewTarget.Target != NULL && NewTarget == PendingViewTarget.Target )
	{
		return;
	}

	// if viewtarget different then new one or we're transitioning from the same target with locked outgoing, then assign it
	if((NewTarget != ViewTarget.Target) || (PendingViewTarget.Target && BlendParams.bLockOutgoing))
	{
		// if a transition time is specified, then set pending view target accordingly
		if( TransitionParams.BlendTime > 0 )
		{
			// band-aid fix so that EndViewTarget() gets called properly in this case
			if (PendingViewTarget.Target == NULL)
			{
				PendingViewTarget.Target = ViewTarget.Target;
			}

			// use last frame's POV
			ViewTarget.POV = LastFrameCameraCache.POV;
			BlendParams = TransitionParams;
			BlendTimeToGo = TransitionParams.BlendTime;

			AssignViewTarget(NewTarget, PendingViewTarget, TransitionParams);
			PendingViewTarget.CheckViewTarget(PCOwner);
		}
		else
		{
			// otherwise, assign new viewtarget instantly
			AssignViewTarget(NewTarget, ViewTarget);
			ViewTarget.CheckViewTarget(PCOwner);
			// remove old pending ViewTarget so we don't still try to switch to it
			PendingViewTarget.Target = NULL;
		}
	}
	else
	{
		// we're setting the viewtarget to the viewtarget we were transitioning away from,
		// just abort the transition.
		// @fixme, investigate if we want this case to go through the above code, so AssignViewTarget et al
		// get called
		if (PendingViewTarget.Target != NULL)
		{
			if (!PCOwner->IsPendingKillPending() && !PCOwner->IsLocalPlayerController() && GetNetMode() != NM_Client)
			{
				PCOwner->ClientSetViewTarget(NewTarget, TransitionParams);
			}
		}
		PendingViewTarget.Target = NULL;
	}
}

void APlayerCameraManager::AssignViewTarget(AActor* NewTarget, FTViewTarget& VT, struct FViewTargetTransitionParams TransitionParams)
{
	if( !NewTarget || (NewTarget == VT.Target) )
	{
		return;
	}

// 	UE_LOG(LogPlayerCameraManager, Log, TEXT("%f AssignViewTarget OldTarget: %s, NewTarget: %s, BlendTime: %f"), GetWorld()->TimeSeconds, VT.Target ? *VT.Target->GetFName().ToString() : TEXT("NULL"),
// 		NewTarget ? *NewTarget->GetFName().ToString() : TEXT("NULL"),
// 		TransitionParams.BlendTime);

	AActor* OldViewTarget = VT.Target;
	VT.Target = NewTarget;

	// Use default FOV and aspect ratio.
	VT.POV.AspectRatio = DefaultAspectRatio;
	VT.POV.FOV = DefaultFOV;

	if (OldViewTarget)
	{
		OldViewTarget->EndViewTarget(PCOwner);
	}

	VT.Target->BecomeViewTarget(PCOwner);

	if (!PCOwner->IsLocalPlayerController() && (GetNetMode() != NM_Client))
	{
		PCOwner->ClientSetViewTarget(VT.Target, TransitionParams);
	}
}

AActor* APlayerCameraManager::GetViewTarget() const
{
	// to handle verification/caching behavior while preserving constness upstream
	APlayerCameraManager* const NonConstThis = const_cast<APlayerCameraManager*>(this);

	// if blending to another view target, return this one first
	if( PendingViewTarget.Target )
	{
		NonConstThis->PendingViewTarget.CheckViewTarget(NonConstThis->PCOwner);
		if( PendingViewTarget.Target )
		{
			return PendingViewTarget.Target;
		}
	}

	NonConstThis->ViewTarget.CheckViewTarget(NonConstThis->PCOwner);
	return ViewTarget.Target;
}

APawn* APlayerCameraManager::GetViewTargetPawn() const
{
	// to handle verification/caching behavior while preserving constness upstream
	APlayerCameraManager* const NonConstThis = const_cast<APlayerCameraManager*>(this);

	// if blending to another view target, return this one first
	if (PendingViewTarget.Target)
	{
		NonConstThis->PendingViewTarget.CheckViewTarget(NonConstThis->PCOwner);
		if (PendingViewTarget.Target)
		{
			return PendingViewTarget.GetTargetPawn();
		}
	}

	NonConstThis->ViewTarget.CheckViewTarget(NonConstThis->PCOwner);
	return ViewTarget.GetTargetPawn();
}

bool APlayerCameraManager::ShouldTickIfViewportsOnly() const
{
	return (PCOwner != NULL);
}

void APlayerCameraManager::ApplyCameraModifiers(float DeltaTime, FMinimalViewInfo& InOutPOV)
{
	ClearCachedPPBlends();

	// Loop through each camera modifier
	for (int32 ModifierIdx = 0; ModifierIdx < ModifierList.Num(); ++ModifierIdx)
	{
		// Apply camera modification and output into DesiredCameraOffset/DesiredCameraRotation
		if ((ModifierList[ModifierIdx] != NULL) && !ModifierList[ModifierIdx]->IsDisabled())
		{
			// If ModifyCamera returns true, exit loop
			// Allows high priority things to dictate if they are
			// the last modifier to be applied
			if (ModifierList[ModifierIdx]->ModifyCamera(DeltaTime, InOutPOV))
			{
				break;
			}
		}
	}

	// Now apply CameraAnims
	// these essentially behave as the highest-pri modifier.
	for (int32 Idx = 0; Idx < ActiveAnims.Num(); ++Idx)
	{
		UCameraAnimInst* const AnimInst = ActiveAnims[Idx];

		if (AnimCameraActor && !AnimInst->bFinished)
		{
			// clear out animated camera actor
			InitTempCameraActor(AnimCameraActor, AnimInst);

			// evaluate the animation at the new time
			AnimInst->AdvanceAnim(DeltaTime, false);

			// Add weighted properties to the accumulator actor
			if (AnimInst->CurrentBlendWeight > 0.f)
			{
				ApplyAnimToCamera(AnimCameraActor, AnimInst, InOutPOV);
			}
		}

		// handle animations that have finished
		if (AnimInst->bFinished && AnimInst->bAutoReleaseWhenFinished)
		{
			ReleaseCameraAnimInst(AnimInst);
			Idx--;		// we removed this from the ActiveAnims array
		}

		// changes to this are good for a single update, so reset this to 1.f after processing
		AnimInst->TransientScaleModifier = 1.f;
	}

	// need to zero this when we are done with it.  playing another animation
	// will calc a new InitialTM for the move track instance based on these values.
	if (AnimCameraActor)
	{
		AnimCameraActor->TeleportTo(FVector::ZeroVector, FRotator::ZeroRotator);
	}
}

void APlayerCameraManager::AddCachedPPBlend(struct FPostProcessSettings& PPSettings, float BlendWeight)
{
	check(PostProcessBlendCache.Num() == PostProcessBlendCacheWeights.Num());
	PostProcessBlendCache.Add(PPSettings);
	PostProcessBlendCacheWeights.Add(BlendWeight);
}

void APlayerCameraManager::ClearCachedPPBlends()
{
	PostProcessBlendCache.Empty();
	PostProcessBlendCacheWeights.Empty();
}

void APlayerCameraManager::GetCachedPostProcessBlends(TArray<FPostProcessSettings> const*& OutPPSettings, TArray<float> const*& OutBlendWeigthts) const
{
	OutPPSettings = &PostProcessBlendCache;
	OutBlendWeigthts = &PostProcessBlendCacheWeights;
}

void APlayerCameraManager::ApplyAnimToCamera(ACameraActor const* AnimatedCamActor, UCameraAnimInst const* AnimInst, FMinimalViewInfo& InOutPOV)
{
	if (AnimInst->CamAnim->bRelativeToInitialTransform)
	{
		// move animated cam actor to initial-relative position
		FTransform const AnimatedCamToWorld = AnimatedCamActor->GetTransform();
		FTransform const AnimatedCamToInitialCam = AnimatedCamToWorld * AnimInst->InitialCamToWorld.Inverse();
		ACameraActor* const MutableCamActor = const_cast<ACameraActor*>(AnimatedCamActor);
		MutableCamActor->SetActorTransform(AnimatedCamToInitialCam);
	}

	float const Scale = AnimInst->CurrentBlendWeight;
	FRotationMatrix const CameraToWorld(InOutPOV.Rotation);

	if (AnimInst->PlaySpace == ECameraAnimPlaySpace::CameraLocal)
	{
		// the code in the else block will handle this just fine, but this path provides efficiency and simplicity for the most common case

		// loc
		FVector const LocalOffset = CameraToWorld.TransformVector( AnimatedCamActor->GetActorLocation()*Scale );
		InOutPOV.Location += LocalOffset;

		// rot
		FRotationMatrix const AnimRotMat( AnimatedCamActor->GetActorRotation()*Scale );
		InOutPOV.Rotation = (AnimRotMat * CameraToWorld).Rotator();
	}
	else
	{
		// handle playing the anim in an arbitrary space relative to the camera

		// find desired space
		FMatrix const PlaySpaceToWorld = (AnimInst->PlaySpace == ECameraAnimPlaySpace::UserDefined) ? AnimInst->UserPlaySpaceMatrix : FMatrix::Identity;

		// loc
		FVector const LocalOffset = PlaySpaceToWorld.TransformVector( AnimatedCamActor->GetActorLocation()*Scale );
		InOutPOV.Location += LocalOffset;

		// rot
		// find transform from camera to the "play space"
		FMatrix const CameraToPlaySpace = CameraToWorld * PlaySpaceToWorld.Inverse();	// CameraToWorld * WorldToPlaySpace

		// find transform from anim (applied in playspace) back to camera
		FRotationMatrix const AnimToPlaySpace(AnimatedCamActor->GetActorRotation()*Scale);
		FMatrix const AnimToCamera = AnimToPlaySpace * CameraToPlaySpace.Inverse();			// AnimToPlaySpace * PlaySpaceToCamera

		// RCS = rotated camera space, meaning camera space after it's been animated
		// this is what we're looking for, the diff between rotated cam space and regular cam space.
		// apply the transform back to camera space from the post-animated transform to get the RCS
		FMatrix const RCSToCamera = CameraToPlaySpace * AnimToCamera;

		// now apply to real camera
		FRotationMatrix const RealCamToWorld(InOutPOV.Rotation);
		InOutPOV.Rotation = (RCSToCamera * RealCamToWorld).Rotator();
	}

	// fov
	const float FOVMin = 5.f;
	const float FOVMax = 170.f;
	InOutPOV.FOV += (AnimatedCamActor->GetCameraComponent()->FieldOfView - AnimInst->InitialFOV) * Scale;
	InOutPOV.FOV = FMath::Clamp<float>(InOutPOV.FOV, FOVMin, FOVMax);

	// postprocess
	if (AnimatedCamActor->GetCameraComponent()->PostProcessBlendWeight > 0.f)
	{
		AddCachedPPBlend(AnimatedCamActor->GetCameraComponent()->PostProcessSettings, AnimatedCamActor->GetCameraComponent()->PostProcessBlendWeight);
	}
}

UCameraAnimInst* APlayerCameraManager::AllocCameraAnimInst()
{
	UCameraAnimInst* FreeAnim = (FreeAnims.Num() > 0) ? FreeAnims.Pop() : NULL;
	if (FreeAnim)
	{
		UCameraAnimInst const* const DefaultInst = GetDefault<UCameraAnimInst>();

		ActiveAnims.Push(FreeAnim);

		// reset some defaults
		if (DefaultInst)
		{
			FreeAnim->TransientScaleModifier = DefaultInst->TransientScaleModifier;
			FreeAnim->PlaySpace = DefaultInst->PlaySpace;
		}

		// make sure any previous anim has been terminated correctly
		check( (FreeAnim->MoveTrack == NULL) && (FreeAnim->MoveInst == NULL) );
	}

	return FreeAnim;
}

void APlayerCameraManager::ReleaseCameraAnimInst(UCameraAnimInst* Inst)
{
	ActiveAnims.Remove(Inst);
	FreeAnims.Push(Inst);
}

UCameraAnimInst* APlayerCameraManager::FindInstanceOfCameraAnim(UCameraAnim const* Anim) const
{
	int32 const NumActiveAnims = ActiveAnims.Num();
	for (int32 Idx=0; Idx<NumActiveAnims; Idx++)
	{
		if (ActiveAnims[Idx]->CamAnim == Anim)
		{
			return ActiveAnims[Idx];
		}
	}

	return NULL;
}

UCameraAnimInst* APlayerCameraManager::PlayCameraAnim(UCameraAnim* Anim, float Rate, float Scale, float BlendInTime, float BlendOutTime, bool bLoop, bool bRandomStartTime, float Duration, ECameraAnimPlaySpace::Type PlaySpace, FRotator UserPlaySpaceRot)
{
	// get a new instance and play it
	if (AnimCameraActor != NULL)
	{
		UCameraAnimInst* const Inst = AllocCameraAnimInst();
		if (Inst)
		{
			Inst->LastCameraLoc = FVector::ZeroVector;		// clear LastCameraLoc
			Inst->Play(Anim, AnimCameraActor, Rate, Scale, BlendInTime, BlendOutTime, bLoop, bRandomStartTime, Duration);
			Inst->SetPlaySpace(PlaySpace, UserPlaySpaceRot);
			return Inst;
		}
	}

	return NULL;
}

void APlayerCameraManager::StopAllInstancesOfCameraAnim(UCameraAnim* Anim, bool bImmediate)
{
	// find cameraaniminst for this.
	for (int32 Idx=0; Idx<ActiveAnims.Num(); ++Idx)
	{
		if (ActiveAnims[Idx]->CamAnim == Anim)
		{
			ActiveAnims[Idx]->Stop(bImmediate);
		}
	}
}

void APlayerCameraManager::StopAllCameraAnims(bool bImmediate)
{
	for (int32 Idx=0; Idx<ActiveAnims.Num(); ++Idx)
	{
		ActiveAnims[Idx]->Stop(bImmediate);
	}
}

void APlayerCameraManager::StopCameraAnimInst(class UCameraAnimInst* AnimInst, bool bImmediate)
{
	if (AnimInst != NULL)
	{
		AnimInst->Stop(bImmediate);
	}
}

void APlayerCameraManager::InitTempCameraActor(ACameraActor* CamActor, UCameraAnimInst const* AnimInstToInitFor) const
{
	if (CamActor)
	{
		CamActor->TeleportTo(FVector::ZeroVector, FRotator::ZeroRotator);

		if (AnimInstToInitFor)
		{
			ACameraActor const* const DefaultCamActor = GetDefault<ACameraActor>();
			if (DefaultCamActor)
			{
				CamActor->GetCameraComponent()->AspectRatio = DefaultCamActor->GetCameraComponent()->AspectRatio;
				CamActor->GetCameraComponent()->FieldOfView = AnimInstToInitFor->CamAnim->BaseFOV;
				CamActor->GetCameraComponent()->PostProcessSettings = AnimInstToInitFor->CamAnim->BasePostProcessSettings;
				CamActor->GetCameraComponent()->PostProcessBlendWeight = AnimInstToInitFor->CamAnim->BasePostProcessBlendWeight;
			}
		}
	}
}

void APlayerCameraManager::UpdateViewTargetInternal(FTViewTarget& OutVT, float DeltaTime)
{
	if (OutVT.Target)
	{
		const bool bK2Camera = BlueprintUpdateCamera(OutVT.Target, OutVT.POV.Location, OutVT.POV.Rotation, OutVT.POV.FOV);
		if (bK2Camera == false)
		{
			OutVT.Target->CalcCamera(DeltaTime, OutVT.POV);
		}
	}
}

void APlayerCameraManager::UpdateViewTarget(FTViewTarget& OutVT, float DeltaTime)
{
	// Don't update outgoing viewtarget during an interpolation
	if ((PendingViewTarget.Target != NULL) && BlendParams.bLockOutgoing && OutVT.Equal(ViewTarget))
	{
		return;
	}

	// store previous POV, in case we need it later
	FMinimalViewInfo OrigPOV = OutVT.POV;

	//@TODO: CAMERA: Should probably reset the view target POV fully here
	OutVT.POV.FOV = DefaultFOV;
	OutVT.POV.OrthoWidth = DefaultOrthoWidth;
	OutVT.POV.bConstrainAspectRatio = false;
	OutVT.POV.bUseFieldOfViewForLOD = true;
	OutVT.POV.ProjectionMode = bIsOrthographic ? ECameraProjectionMode::Orthographic : ECameraProjectionMode::Perspective;
	OutVT.POV.PostProcessSettings.SetBaseValues();
	OutVT.POV.PostProcessBlendWeight = 1.0f;

	bool bDoNotApplyModifiers = false;

	if (ACameraActor* CamActor = Cast<ACameraActor>(OutVT.Target))
	{
		// Viewing through a camera actor.
		CamActor->GetCameraComponent()->GetCameraView(DeltaTime, OutVT.POV);
	}
	else
	{

		static const FName NAME_Fixed = FName(TEXT("Fixed"));
		static const FName NAME_ThirdPerson = FName(TEXT("ThirdPerson"));
		static const FName NAME_FreeCam = FName(TEXT("FreeCam"));
		static const FName NAME_FreeCam_Default = FName(TEXT("FreeCam_Default"));
		static const FName NAME_FirstPerson = FName(TEXT("FirstPerson"));

		if (CameraStyle == NAME_Fixed)
		{
			// do not update, keep previous camera position by restoring
			// saved POV, in case CalcCamera changes it but still returns false
			OutVT.POV = OrigPOV;

			// don't apply modifiers when using this debug camera mode
			bDoNotApplyModifiers = true;
		}
		else if (CameraStyle == NAME_ThirdPerson || CameraStyle == NAME_FreeCam || CameraStyle == NAME_FreeCam_Default)
		{
			// Simple third person view implementation
			FVector Loc = OutVT.Target->GetActorLocation();
			FRotator Rotator = OutVT.Target->GetActorRotation();

			if (OutVT.Target == PCOwner)
			{
				Loc = PCOwner->GetFocalLocation();
			}

			// Take into account Mesh Translation so it takes into account the PostProcessing we do there.
			// @fixme, can crash in certain BP cases where default mesh is null
//			APawn* TPawn = Cast<APawn>(OutVT.Target);
// 			if ((TPawn != NULL) && (TPawn->Mesh != NULL))
// 			{
// 				Loc += FQuatRotationMatrix(OutVT.Target->GetActorQuat()).TransformVector(TPawn->Mesh->RelativeLocation - GetDefault<APawn>(TPawn->GetClass())->Mesh->RelativeLocation);
// 			}

			//OutVT.Target.GetActorEyesViewPoint(Loc, Rot);
			if( CameraStyle == NAME_FreeCam || CameraStyle == NAME_FreeCam_Default )
			{
				Rotator = PCOwner->GetControlRotation();
			}

			FVector Pos = Loc + ViewTargetOffset + FRotationMatrix(Rotator).TransformVector(FreeCamOffset) - Rotator.Vector() * FreeCamDistance;
			FCollisionQueryParams BoxParams(NAME_FreeCam, false, this);
			BoxParams.AddIgnoredActor(OutVT.Target);
			FHitResult Result;

			GetWorld()->SweepSingleByChannel(Result, Loc, Pos, FQuat::Identity, ECC_Camera, FCollisionShape::MakeBox(FVector(12.f)), BoxParams);
			OutVT.POV.Location = !Result.bBlockingHit ? Pos : Result.Location;
			OutVT.POV.Rotation = Rotator;

			// don't apply modifiers when using this debug camera mode
			bDoNotApplyModifiers = true;
		}
		else if (CameraStyle == NAME_FirstPerson)
		{
			// Simple first person, view through viewtarget's 'eyes'
			OutVT.Target->GetActorEyesViewPoint(OutVT.POV.Location, OutVT.POV.Rotation);

			// don't apply modifiers when using this debug camera mode
			bDoNotApplyModifiers = true;
		}
		else
		{
			UpdateViewTargetInternal(OutVT, DeltaTime);
		}
	}

	if (!bDoNotApplyModifiers || bAlwaysApplyModifiers)
	{
		// Apply camera modifiers at the end (view shakes for example)
		ApplyCameraModifiers(DeltaTime, OutVT.POV);
	}

	if (bFollowHmdOrientation)
	{
		if (GEngine->HMDDevice.IsValid() && GEngine->HMDDevice->IsHeadTrackingAllowed())
		{
			GEngine->HMDDevice->UpdatePlayerCameraRotation(this, OutVT.POV);
		}
	}

	// Synchronize the actor with the view target results
	SetActorLocationAndRotation(OutVT.POV.Location, OutVT.POV.Rotation, false);

	UpdateCameraLensEffects(OutVT);
}

void APlayerCameraManager::UpdateCameraLensEffects(const FTViewTarget& OutVT)
{
	for (int32 Idx=0; Idx<CameraLensEffects.Num(); ++Idx)
	{
		if (CameraLensEffects[Idx] != NULL)
		{
			CameraLensEffects[Idx]->UpdateLocation(OutVT.POV.Location, OutVT.POV.Rotation, OutVT.POV.FOV);
		}
	}
}

void APlayerCameraManager::ApplyAudioFade()
{
	if (GEngine)
	{
		UWorld* World = GetWorld();
		if (World)
		{
			if (FAudioDevice* AudioDevice = World->GetAudioDevice())
			{
				AudioDevice->TransientMasterVolume = 1.0f - FadeAmount;
			}
		}
	}
}

void APlayerCameraManager::StopAudioFade()
{
	if (GEngine)
	{
		UWorld* World = GetWorld();
		if (World)
		{
			if (FAudioDevice* AudioDevice = World->GetAudioDevice())
			{
				AudioDevice->TransientMasterVolume = 1.0f;
			}
		}
	}
}

UCameraModifier* APlayerCameraManager::AddNewCameraModifier(TSubclassOf<UCameraModifier> ModifierClass)
{
	UCameraModifier* const NewMod = NewObject<UCameraModifier>(this, ModifierClass);
	if (NewMod)
	{
		if (AddCameraModifierToList(NewMod) == true)
		{
			return NewMod;
		}
	}

	return nullptr;
}

UCameraModifier* APlayerCameraManager::FindCameraModifierByClass(TSubclassOf<UCameraModifier> ModifierClass)
{
	for (UCameraModifier* Mod : ModifierList)
	{
		if (Mod->GetClass() == ModifierClass)
		{
			return Mod;
		}
	}

	return nullptr;
}

bool APlayerCameraManager::AddCameraModifierToList(UCameraModifier* NewModifier)
{
	if (NewModifier)
	{
		// Look through current modifier list and find slot for this priority
		int32 BestIdx = 0;
		for (int32 ModifierIdx = 0; ModifierIdx < ModifierList.Num(); ModifierIdx++)
		{
			UCameraModifier* const M = ModifierList[ModifierIdx];
			if (M)
			{
				if (M == NewModifier)
				{
					// already in list, just bail
					return false;
				}

				// If priority of current index has passed or equaled ours - we have the insert location
				if (NewModifier->Priority <= M->Priority)
				{
					// Disallow addition of exclusive modifier if priority is already occupied
					if (NewModifier->bExclusive && NewModifier->Priority == M->Priority)
					{
						return false;
					}

					break;
				}
			}

			// Update best index
			BestIdx = ModifierIdx;
		}

		// Insert self into best index
		ModifierList.InsertUninitialized(BestIdx, 1);
		ModifierList[BestIdx] = NewModifier;

		// Save camera
		NewModifier->AddedToCamera(this);
		return true;
	}

	return false;
}

bool APlayerCameraManager::RemoveCameraModifier(UCameraModifier* ModifierToRemove)
{
	if (ModifierToRemove)
	{
		// Loop through each modifier in camera
		for (int32 ModifierIdx = 0; ModifierIdx < ModifierList.Num(); ModifierIdx++)
		{
			// If we found ourselves, remove ourselves from the list and return
			if (ModifierList[ModifierIdx] == ModifierToRemove)
			{
				ModifierList.RemoveAt(ModifierIdx, 1);
				return true;
			}
		}
	}

	// Didn't find it in the list, nothing removed
	return false;
}

void APlayerCameraManager::PostInitializeComponents()
{
	Super::PostInitializeComponents();

 	// Setup default camera modifiers
	if (DefaultModifiers.Num() > 0)
	{
		for (auto ModifierClass : DefaultModifiers)
		{
			// empty entries are not valid here, do work only for actual classes
			if (ModifierClass)
			{
				UCameraModifier* const NewMod = AddNewCameraModifier(ModifierClass);

				// cache ref to camera shake if this is it
				UCameraModifier_CameraShake* const ShakeMod = Cast<UCameraModifier_CameraShake>(NewMod);
				if (ShakeMod)
				{
					CachedCameraShakeMod = ShakeMod;
				}
			}
		}
	}

 	// create CameraAnimInsts in pool
	for (int32 Idx=0; Idx<MAX_ACTIVE_CAMERA_ANIMS; ++Idx)
	{
		AnimInstPool[Idx] = NewObject<UCameraAnimInst>(this);

		// add everything to the free list initially
		FreeAnims.Add(AnimInstPool[Idx]);
	}

	// spawn the temp CameraActor used for updating CameraAnims
	FActorSpawnParameters SpawnInfo;
	SpawnInfo.Owner = this;
	SpawnInfo.Instigator = Instigator;
	SpawnInfo.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
	SpawnInfo.ObjectFlags |= RF_Transient;	// We never want to save these temp actors into a map
	AnimCameraActor = GetWorld()->SpawnActor<ACameraActor>(SpawnInfo);
}

void APlayerCameraManager::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
	// clean up the temp camera actor
	if (AnimCameraActor)
	{
		if (EndPlayReason == EEndPlayReason::Destroyed)
		{
			AnimCameraActor->Destroy();
		}
		AnimCameraActor = NULL;
	}
	Super::EndPlay(EndPlayReason);
}

void APlayerCameraManager::InitializeFor(APlayerController* PC)
{
	CameraCache.POV.FOV = DefaultFOV;
	PCOwner = PC;

	SetViewTarget(PC);

	// set the level default scale
	SetDesiredColorScale(GetWorldSettings()->DefaultColorScale, 5.f);

	// Force camera update so it doesn't sit at (0,0,0) for a full tick.
	// This can have side effects with streaming.
	UpdateCamera(0.f);
}

float APlayerCameraManager::GetFOVAngle() const
{
	return (LockedFOV > 0.f) ? LockedFOV : CameraCache.POV.FOV;
}

void APlayerCameraManager::SetFOV(float NewFOV)
{
	LockedFOV = NewFOV;
}

void APlayerCameraManager::UnlockFOV()
{
	LockedFOV = 0.f;
}

bool APlayerCameraManager::IsOrthographic() const
{
	return bIsOrthographic;
}

float APlayerCameraManager::GetOrthoWidth() const
{
	return (LockedOrthoWidth > 0.f) ? LockedOrthoWidth : DefaultOrthoWidth;
}

void APlayerCameraManager::SetOrthoWidth(float OrthoWidth)
{
	LockedOrthoWidth = OrthoWidth;
}

void APlayerCameraManager::UnlockOrthoWidth()
{
	LockedOrthoWidth = 0.f;
}

void APlayerCameraManager::GetCameraViewPoint(FVector& OutCamLoc, FRotator& OutCamRot) const
{
	OutCamLoc = CameraCache.POV.Location;
	OutCamRot = CameraCache.POV.Rotation;
}

FRotator APlayerCameraManager::GetCameraRotation() const
{
	return CameraCache.POV.Rotation;
}

FVector APlayerCameraManager::GetCameraLocation() const
{
	return CameraCache.POV.Location;
}

void APlayerCameraManager::SetDesiredColorScale(FVector NewColorScale, float InterpTime)
{
	// if color scaling is not enabled
	if (!bEnableColorScaling)
	{
		// set the default color scale
		bEnableColorScaling = true;
		ColorScale.X = 1.f;
		ColorScale.Y = 1.f;
		ColorScale.Z = 1.f;
	}

	// Don't bother interpolating if we're already scaling at the desired color
	if( NewColorScale != ColorScale )
	{
		// save the current as original
		OriginalColorScale = ColorScale;
		// set the new desired scale
		DesiredColorScale = NewColorScale;
		// set the interpolation duration/time
		ColorScaleInterpStartTime = GetWorld()->TimeSeconds;
		ColorScaleInterpDuration = InterpTime;
		// and enable color scale interpolation
		bEnableColorScaleInterp = true;
	}
}

void APlayerCameraManager::UpdateCamera(float DeltaTime)
{
	if ((PCOwner->Player && PCOwner->IsLocalPlayerController()) || !bUseClientSideCameraUpdates || bDebugClientSideCamera)
	{
		DoUpdateCamera(DeltaTime);

		if (GetNetMode() == NM_Client && bShouldSendClientSideCameraUpdate)
		{
			// compress the rotation down to 4 bytes
			int32 const ShortYaw = FRotator::CompressAxisToShort(CameraCache.POV.Rotation.Yaw);
			int32 const ShortPitch = FRotator::CompressAxisToShort(CameraCache.POV.Rotation.Pitch);
			int32 const CompressedRotation = (ShortYaw << 16) | ShortPitch;

			PCOwner->ServerUpdateCamera(CameraCache.POV.Location, CompressedRotation);
			bShouldSendClientSideCameraUpdate = false;
		}
	}
}

void APlayerCameraManager::DoUpdateCamera(float DeltaTime)
{
	// update color scale interpolation
	if (bEnableColorScaleInterp)
	{
		float BlendPct = FMath::Clamp((GetWorld()->TimeSeconds - ColorScaleInterpStartTime) / ColorScaleInterpDuration, 0.f, 1.0f);
		ColorScale = FMath::Lerp(OriginalColorScale, DesiredColorScale, BlendPct);
		// if we've maxed
		if (BlendPct == 1.0f)
		{
			// disable further interpolation
			bEnableColorScaleInterp = false;
		}
	}

	// Don't update outgoing viewtarget during an interpolation when bLockOutgoing is set.
	if ((PendingViewTarget.Target == NULL) || !BlendParams.bLockOutgoing)
	{
		// Update current view target
		ViewTarget.CheckViewTarget(PCOwner);
		UpdateViewTarget(ViewTarget, DeltaTime);
	}

	// our camera is now viewing there
	FMinimalViewInfo NewPOV = ViewTarget.POV;

	// if we have a pending view target, perform transition from one to another.
	if (PendingViewTarget.Target != NULL)
	{
		BlendTimeToGo -= DeltaTime;

		// Update pending view target
		PendingViewTarget.CheckViewTarget(PCOwner);
		UpdateViewTarget(PendingViewTarget, DeltaTime);

		// blend....
		if (BlendTimeToGo > 0)
		{
			float DurationPct = (BlendParams.BlendTime - BlendTimeToGo) / BlendParams.BlendTime;

			float BlendPct = 0.f;
			switch (BlendParams.BlendFunction)
			{
			case VTBlend_Linear:
				BlendPct = FMath::Lerp(0.f, 1.f, DurationPct);
				break;
			case VTBlend_Cubic:
				BlendPct = FMath::CubicInterp(0.f, 0.f, 1.f, 0.f, DurationPct);
				break;
			case VTBlend_EaseIn:
				BlendPct = FMath::Lerp(0.f, 1.f, FMath::Pow(DurationPct, BlendParams.BlendExp));
				break;
			case VTBlend_EaseOut:
				BlendPct = FMath::Lerp(0.f, 1.f, FMath::Pow(DurationPct, 1.f / BlendParams.BlendExp));
				break;
			case VTBlend_EaseInOut:
				BlendPct = FMath::InterpEaseInOut(0.f, 1.f, DurationPct, BlendParams.BlendExp);
				break;
			default:
				break;
			}

			// Update pending view target blend
			NewPOV = ViewTarget.POV;
			NewPOV.BlendViewInfo(PendingViewTarget.POV, BlendPct);//@TODO: CAMERA: Make sure the sense is correct!  BlendViewTargets(ViewTarget, PendingViewTarget, BlendPct);
		}
		else
		{
			// we're done blending, set new view target
			ViewTarget = PendingViewTarget;

			// clear pending view target
			PendingViewTarget.Target = NULL;

			BlendTimeToGo = 0;

			// our camera is now viewing there
			NewPOV = PendingViewTarget.POV;
		}
	}

	// Cache results
	FillCameraCache(NewPOV);

	if (bEnableFading)
	{
		if (bAutoAnimateFade)
		{
			FadeTimeRemaining = FMath::Max(FadeTimeRemaining - DeltaTime, 0.0f);
			if (FadeTime > 0.0f)
			{
				FadeAmount = FadeAlpha.X + ((1.f - FadeTimeRemaining / FadeTime) * (FadeAlpha.Y - FadeAlpha.X));
			}

			if ((bHoldFadeWhenFinished == false) && (FadeTimeRemaining <= 0.f))
			{
				// done
				StopCameraFade();
			}
		}

		if (bFadeAudio)
		{
			ApplyAudioFade();
		}
	}
}

FPOV APlayerCameraManager::BlendViewTargets(const FTViewTarget& A,const FTViewTarget& B, float Alpha)
{
	FPOV POV;
	POV.Location = FMath::Lerp(A.POV.Location, B.POV.Location, Alpha);
	POV.FOV = (A.POV.FOV +  Alpha * ( B.POV.FOV - A.POV.FOV));

	FRotator DeltaAng = (B.POV.Rotation - A.POV.Rotation).GetNormalized();
	POV.Rotation = A.POV.Rotation + Alpha * DeltaAng;

	return POV;
}

void APlayerCameraManager::FillCameraCache(const FMinimalViewInfo& NewInfo)
{
	// Backup last frame results.
	if (CameraCache.TimeStamp != GetWorld()->TimeSeconds)
	{
		LastFrameCameraCache = CameraCache;
	}

	CameraCache.TimeStamp = GetWorld()->TimeSeconds;
	CameraCache.POV = NewInfo;
}

void APlayerCameraManager::ProcessViewRotation(float DeltaTime, FRotator& OutViewRotation, FRotator& OutDeltaRot)
{
	for( int32 ModifierIdx = 0; ModifierIdx < ModifierList.Num(); ModifierIdx++ )
	{
		if( ModifierList[ModifierIdx] != NULL &&
			!ModifierList[ModifierIdx]->IsDisabled() )
		{
			if( ModifierList[ModifierIdx]->ProcessViewRotation(ViewTarget.Target, DeltaTime, OutViewRotation, OutDeltaRot) )
			{
				break;
			}
		}
	}

	// Add Delta Rotation
	OutViewRotation += OutDeltaRot;
	OutDeltaRot = FRotator::ZeroRotator;

	if(GEngine->HMDDevice.IsValid() && GEngine->IsStereoscopic3D())
	{
		// With the HMD devices, we can't limit the view pitch, because it's bound to the player's head.  A simple normalization will suffice
		OutViewRotation.Normalize();
	}
	else
	{
		// Limit Player View Axes
		LimitViewPitch( OutViewRotation, ViewPitchMin, ViewPitchMax );
		LimitViewYaw( OutViewRotation, ViewYawMin, ViewYawMax );
		LimitViewRoll( OutViewRotation, ViewRollMin, ViewRollMax );
	}
}

void APlayerCameraManager::LimitViewPitch( FRotator& ViewRotation, float InViewPitchMin, float InViewPitchMax )
{
	ViewRotation.Pitch = FMath::ClampAngle(ViewRotation.Pitch, InViewPitchMin, InViewPitchMax);
	ViewRotation.Pitch = FRotator::ClampAxis(ViewRotation.Pitch);
}

void APlayerCameraManager::LimitViewRoll( FRotator&  ViewRotation, float InViewRollMin, float InViewRollMax)
{
	ViewRotation.Roll = FMath::ClampAngle(ViewRotation.Roll, InViewRollMin, InViewRollMax);
	ViewRotation.Roll = FRotator::ClampAxis(ViewRotation.Roll);
}

void APlayerCameraManager::LimitViewYaw(FRotator& ViewRotation, float InViewYawMin, float InViewYawMax)
{
	ViewRotation.Yaw = FMath::ClampAngle(ViewRotation.Yaw, InViewYawMin, InViewYawMax);
	ViewRotation.Yaw = FRotator::ClampAxis(ViewRotation.Yaw);
}

void APlayerCameraManager::DisplayDebug(class UCanvas* Canvas, const FDebugDisplayInfo& DebugDisplay, float& YL, float& YPos)
{
	Canvas->SetDrawColor(255,255,255);

	UFont* RenderFont = GEngine->GetSmallFont();
	YL = Canvas->DrawText(RenderFont, FString::Printf(TEXT("   Camera Style:%s main ViewTarget:%s"), *CameraStyle.ToString(), *ViewTarget.Target->GetName()), 4.0f, YPos );
	YPos += YL;

	//@TODO: Print out more information
	YL = Canvas->DrawText(RenderFont, FString::Printf(TEXT("   CamLoc:%s CamRot:%s FOV:%f"), *CameraCache.POV.Location.ToCompactString(), *CameraCache.POV.Rotation.ToCompactString(), CameraCache.POV.FOV), 4.0f, YPos );
	YPos += YL;

	YL = Canvas->DrawText(RenderFont, FString::Printf(TEXT("   AspectRatio: %1.3f"), CameraCache.POV.AspectRatio), 4.0f, YPos );
	YPos += YL;
}

void APlayerCameraManager::ApplyWorldOffset(const FVector& InOffset, bool bWorldShift)
{
	Super::ApplyWorldOffset(InOffset, bWorldShift);

	CameraCache.POV.Location+= InOffset;
	LastFrameCameraCache.POV.Location+= InOffset;

	ViewTarget.POV.Location+= InOffset;
	PendingViewTarget.POV.Location+= InOffset;
}

AEmitterCameraLensEffectBase* APlayerCameraManager::FindCameraLensEffect(TSubclassOf<AEmitterCameraLensEffectBase> LensEffectEmitterClass)
{
	for (int32 i = 0; i < CameraLensEffects.Num(); ++i)
	{
		AEmitterCameraLensEffectBase* LensEffect = CameraLensEffects[i];
		if ( !LensEffect->IsPendingKill() &&
			( (LensEffect->GetClass() == LensEffectEmitterClass) ||
			(LensEffect->EmittersToTreatAsSame.Find(LensEffectEmitterClass) != INDEX_NONE) ||
			(GetDefault<AEmitterCameraLensEffectBase>(LensEffectEmitterClass)->EmittersToTreatAsSame.Find(LensEffect->GetClass()) != INDEX_NONE ) ) )
		{
			return LensEffect;
		}
	}

	return NULL;
}

AEmitterCameraLensEffectBase* APlayerCameraManager::AddCameraLensEffect(TSubclassOf<AEmitterCameraLensEffectBase> LensEffectEmitterClass)
{
	if (LensEffectEmitterClass != NULL)
	{
		AEmitterCameraLensEffectBase* LensEffect = NULL;
		if (!GetDefault<AEmitterCameraLensEffectBase>(LensEffectEmitterClass)->bAllowMultipleInstances)
		{
			LensEffect = FindCameraLensEffect(LensEffectEmitterClass);

			if (LensEffect != NULL)
			{
				LensEffect->NotifyRetriggered();
			}
		}

		if (LensEffect == NULL)
		{
			// spawn with viewtarget as the owner so bOnlyOwnerSee works as intended
			FActorSpawnParameters SpawnInfo;
			SpawnInfo.Owner = PCOwner->GetViewTarget();
			SpawnInfo.Instigator = Instigator;
			SpawnInfo.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
			SpawnInfo.ObjectFlags |= RF_Transient;	// We never want to save these into a map
			LensEffect = GetWorld()->SpawnActor<AEmitterCameraLensEffectBase>(LensEffectEmitterClass, SpawnInfo);
			if (LensEffect != NULL)
			{
				FVector CamLoc;
				FRotator CamRot;
				GetCameraViewPoint(CamLoc, CamRot);
				LensEffect->RegisterCamera(this);
				LensEffect->UpdateLocation(CamLoc, CamRot, GetFOVAngle());

				CameraLensEffects.Add(LensEffect);
			}
		}

		return LensEffect;
	}

	return NULL;
}

void APlayerCameraManager::RemoveCameraLensEffect(AEmitterCameraLensEffectBase* Emitter)
{
	CameraLensEffects.Remove(Emitter);
}

void APlayerCameraManager::ClearCameraLensEffects()
{
	for (int32 i = 0; i < CameraLensEffects.Num(); ++i)
	{
		CameraLensEffects[i]->Destroy();
	}

	// empty the array.  unnecessary, since destruction will call RemoveCameraLensEffect,
	// but this gets it done in one fell swoop.
	CameraLensEffects.Empty();
}

/** ------------------------------------------------------------
 *  Camera Shakes
 *  ------------------------------------------------------------ */

UCameraShake* APlayerCameraManager::PlayCameraShake(TSubclassOf<UCameraShake> ShakeClass, float Scale, ECameraAnimPlaySpace::Type PlaySpace, FRotator UserPlaySpaceRot)
{
	if (ShakeClass && CachedCameraShakeMod && (Scale > 0.0f) )
	{
		return CachedCameraShakeMod->AddCameraShake(ShakeClass, Scale, PlaySpace, UserPlaySpaceRot);
	}

	return nullptr;
}

void APlayerCameraManager::StopCameraShake(UCameraShake* ShakeInst)
{
	if (ShakeInst && CachedCameraShakeMod)
	{
		CachedCameraShakeMod->RemoveCameraShake(ShakeInst);
	}
}

void APlayerCameraManager::StopAllInstancesOfCameraShake(TSubclassOf<class UCameraShake> ShakeClass)
{
	if (ShakeClass && CachedCameraShakeMod)
	{
		CachedCameraShakeMod->RemoveAllCameraShakesOfClass(ShakeClass);
	}
}

void APlayerCameraManager::StopAllCameraShakes()
{
	if (CachedCameraShakeMod)
	{
		CachedCameraShakeMod->RemoveAllCameraShakes();
	}
}

float APlayerCameraManager::CalcRadialShakeScale(APlayerCameraManager* Camera, FVector Epicenter, float InnerRadius, float OuterRadius, float Falloff)
{
	// using camera location so stuff like spectator cameras get shakes applied sensibly as well
	// need to ensure server has reasonably accurate camera position
	FVector POVLoc = Camera->GetActorLocation();

	if (InnerRadius < OuterRadius)
	{
		float DistPct = ((Epicenter - POVLoc).Size() - InnerRadius) / (OuterRadius - InnerRadius);
		DistPct = 1.f - FMath::Clamp(DistPct, 0.f, 1.f);
		return FMath::Pow(DistPct, Falloff);
	}
	else
	{
		// ignore OuterRadius and do a cliff falloff at InnerRadius
		return ((Epicenter - POVLoc).Size() < InnerRadius) ? 1.f : 0.f;
	}
}

void APlayerCameraManager::PlayWorldCameraShake(UWorld* InWorld, TSubclassOf<class UCameraShake> Shake, FVector Epicenter, float InnerRadius, float OuterRadius, float Falloff, bool bOrientShakeTowardsEpicenter )
{
	for( FConstPlayerControllerIterator Iterator = InWorld->GetPlayerControllerIterator(); Iterator; ++Iterator )
	{
		APlayerController* PlayerController = *Iterator;
		if (PlayerController && PlayerController->PlayerCameraManager != NULL)
		{
			float ShakeScale = CalcRadialShakeScale(PlayerController->PlayerCameraManager, Epicenter, InnerRadius, OuterRadius, Falloff);

			if (bOrientShakeTowardsEpicenter && PlayerController->GetPawn() != NULL)
			{
				FVector CamLoc;
				FRotator CamRot;
				PlayerController->PlayerCameraManager->GetCameraViewPoint(CamLoc, CamRot);
				PlayerController->ClientPlayCameraShake(Shake, ShakeScale, ECameraAnimPlaySpace::UserDefined, (Epicenter - CamLoc).Rotation());
			}
			else
			{
				PlayerController->ClientPlayCameraShake(Shake, ShakeScale);
			}
		}
	}
}

/** ------------------------------------------------------------
 *  Camera fades
 *  ------------------------------------------------------------ */

void APlayerCameraManager::StartCameraFade(float FromAlpha, float ToAlpha, float InFadeTime, FLinearColor InFadeColor, bool bInFadeAudio, bool bInHoldWhenFinished)
{
	bEnableFading = true;

	FadeColor = InFadeColor;
	FadeAlpha = FVector2D(FromAlpha, ToAlpha);
	FadeTime = InFadeTime;
	FadeTimeRemaining = InFadeTime;
	bFadeAudio = bInFadeAudio;

	bAutoAnimateFade = true;
	bHoldFadeWhenFinished = bInHoldWhenFinished;
}

void APlayerCameraManager::StopCameraFade()
{
	if (bEnableFading == true)
	{
		// Make sure FadeAmount finishes at the desired value
		FadeAmount = FadeAlpha.Y;
		bEnableFading = false;
		StopAudioFade();
	}
}

void APlayerCameraManager::SetManualCameraFade(float InFadeAmount, FLinearColor Color, bool bInFadeAudio)
{
	bEnableFading = true;
	FadeColor = Color;
	FadeAmount = InFadeAmount;
	bFadeAudio = bInFadeAudio;

	bAutoAnimateFade = false;
	StopAudioFade();
	FadeTimeRemaining = 0.0f;
}

//////////////////////////////////////////////////////////////////////////
// FTViewTarget

void FTViewTarget::SetNewTarget(AActor* NewTarget)
{
	Target = NewTarget;
}

APawn* FTViewTarget::GetTargetPawn() const
{
	if (APawn* Pawn = Cast<APawn>(Target))
	{
		return Pawn;
	}
	else if (AController* Controller = Cast<AController>(Target))
	{
		return Controller->GetPawn();
	}
	else
	{
		return NULL;
	}
}

bool FTViewTarget::Equal(const FTViewTarget& OtherTarget) const
{
	//@TODO: Should I compare Controller too?
	return (Target == OtherTarget.Target) && (PlayerState == OtherTarget.PlayerState) && POV.Equals(OtherTarget.POV);
}

void FTViewTarget::CheckViewTarget(APlayerController* OwningController)
{
	if (Target == NULL)
	{
		Target = OwningController;
	}

	// Update ViewTarget PlayerState (used to follow same player through pawn transitions, etc., when spectating)
	if (Target == OwningController)
	{
		PlayerState = NULL;
	}
	else if (AController* TargetAsController = Cast<AController>(Target))
	{
		PlayerState = TargetAsController->PlayerState;
	}
	else if (APawn* TargetAsPawn = Cast<APawn>(Target))
	{
		PlayerState = TargetAsPawn->PlayerState;
	}
	else if (APlayerState* TargetAsPlayerState = Cast<APlayerState>(Target))
	{
		PlayerState = TargetAsPlayerState;
	}
	else
	{
		PlayerState = NULL;
	}

	if ((PlayerState != NULL) && !PlayerState->IsPendingKill())
	{
		if ((Target == NULL) || Target->IsPendingKill() || !Cast<APawn>(Target) || (Cast<APawn>(Target)->PlayerState != PlayerState) )
		{
			Target = NULL;

			// not viewing pawn associated with VT.PlayerState, so look for one
			// Assuming on server, so PlayerState Owner is valid
			if (PlayerState->GetOwner() == NULL)
			{
				PlayerState = NULL;
			}
			else
			{
				if (AController* PlayerStateOwner = Cast<AController>(PlayerState->GetOwner()))
				{
					AActor* PlayerStateViewTarget = PlayerStateOwner->GetPawn();
					if( PlayerStateViewTarget && !PlayerStateViewTarget->IsPendingKill() )
					{
						OwningController->PlayerCameraManager->AssignViewTarget(PlayerStateViewTarget, *this);
					}
					else
					{
						Target = PlayerState; // this will cause it to update to the next Pawn possessed by the player being viewed
					}
				}
				else
				{
					PlayerState = NULL;
				}
			}
		}
	}

	if ((Target == NULL) || Target->IsPendingKill())
	{
		check(OwningController);
		if (OwningController->GetPawn() && !OwningController->GetPawn()->IsPendingKillPending() )
		{
			OwningController->PlayerCameraManager->AssignViewTarget(OwningController->GetPawn(), *this);
		}
		else
		{
			OwningController->PlayerCameraManager->AssignViewTarget(OwningController, *this);
		}
	}
}

/** Returns TransformComponent subobject **/
USceneComponent* APlayerCameraManager::GetTransformComponent() const { return TransformComponent; }


text:
package com.eleks.service;

import com.eleks.exception.AuthenticationException;

public interface AuthService {
	void validateCredentials(String userName, String userPass) throws AuthenticationException;
}

redpajama_set_name: RedPajamaGithub


text:
/* -*-C++-*-
******************************************************************************
*
* File:         RuSimpleRefreshTaskExecutor.cpp
* Description:  Implementation of class CRUSimpleRefreshTaskExecutor.
*
*
* Created:      08/14/2000
* Language:     C++
*
*
*
******************************************************************************
*/

#include "RuSimpleRefreshTaskExecutor.h"
#include "RuSimpleRefreshSQLComposer.h"

#include "RuMV.h"
#include "RuTbl.h"
#include "RuGlobals.h"
#include "RuJournal.h"
#include "uofsIpcMessageTranslator.h"

//--------------------------------------------------------------------------//
//	Constructor and destructor
//--------------------------------------------------------------------------//

CRUSimpleRefreshTaskExecutor::
CRUSimpleRefreshTaskExecutor(CRURefreshTask *pParentTask) :
	inherited(pParentTask),
	isSingleDeltaRefresh_(TRUE),
	simpleRefreshTEDynamicContainer_(NUM_OF_SQL_STMT),
	numOfPhases_(0)
{}

//--------------------------------------------------------------------------//
//	CRUSimpleRefreshTaskExecutor::StoreRequest()
//--------------------------------------------------------------------------//
void CRUSimpleRefreshTaskExecutor::
	StoreRequest(CUOFsIpcMessageTranslator &translator)
{
	inherited::StoreRequest(translator);

	// Handle isSingleDeltaRefresh_ data member
	translator.WriteBlock(&isSingleDeltaRefresh_,sizeof(BOOL));

	// Handle refresh executor sql dynamic container
	simpleRefreshTEDynamicContainer_.StoreData(translator);
}

//--------------------------------------------------------------------------//
//	CRUSimpleRefreshTaskExecutor::StoreReply()
//--------------------------------------------------------------------------//
void CRUSimpleRefreshTaskExecutor::
	StoreReply(CUOFsIpcMessageTranslator &translator)
{
	inherited::StoreReply(translator);

	// Handle numOfPhases_ data member
	translator.WriteBlock(&numOfPhases_,sizeof(short));
}

//--------------------------------------------------------------------------//
//	CRUSimpleRefreshTaskExecutor::LoadRequest()
//--------------------------------------------------------------------------//
void CRUSimpleRefreshTaskExecutor::
	LoadRequest(CUOFsIpcMessageTranslator &translator)
{
	inherited::LoadRequest(translator);

	// Handle isSingleDeltaRefresh_ data member
	translator.ReadBlock(&isSingleDeltaRefresh_,sizeof(BOOL));

	// Handle refresh executor sql dynamic container
	simpleRefreshTEDynamicContainer_.LoadData(translator);
}

//--------------------------------------------------------------------------//
//	CRUSimpleRefreshTaskExecutor::LoadReply()
//--------------------------------------------------------------------------//
void CRUSimpleRefreshTaskExecutor::
	LoadReply(CUOFsIpcMessageTranslator &translator)
{
	inherited::LoadReply(translator);

	// Handle numOfPhases_ data member
	translator.ReadBlock(&numOfPhases_,sizeof(short));
}

//--------------------------------------------------------------------------//
//	CRUSimpleRefreshTaskExecutor::Init()
//
//	Initialize data members by analyzing the RefreshTask
//--------------------------------------------------------------------------//

void CRUSimpleRefreshTaskExecutor::Init()
{
	inherited::Init();

	RUASSERT(TRUE == HasWork());

	if (FALSE == GetRefreshTask()->NeedToExecuteInternalRefresh())
	{
		// This is an incremental refresh that does not have any delta
		// We do nothing here and the proper treatment is done in the
		// derived classes
		return;
	}

	CRURefreshTask *pRefreshTask = GetRefreshTask();

	isSingleDeltaRefresh_ = pRefreshTask->IsSingleDeltaRefresh();

	ComposeMySql();
}

//--------------------------------------------------------------------------//
//	CRUSimpleRefreshTaskExecutor::ComposeMySql()
//--------------------------------------------------------------------------//

void CRUSimpleRefreshTaskExecutor::ComposeMySql()
{
	CRUSimpleRefreshSQLComposer myComposer(GetRefreshTask());

	BOOL isRecompute = IsRecompute();

	if (FALSE == isRecompute)
	{
		// THE INTERNAL REFRESH (incremental) statement
		myComposer.ComposeRefresh();
		simpleRefreshTEDynamicContainer_.SetStatementText(
			INTERNAL_REFRESH,myComposer.GetSQL());
	}

	// Always compose the INTERNAL REFRESH RECOMPUTE syntax
	// (because we might revert to it during the MIN/MAX refresh)
	if (0 != (GetRootMV().GetRefreshPatternMap() & CRUMV::NODELETE))
	{
		RUASSERT(TRUE == isRecompute);
		myComposer.ComposeRecompute(CRUSimpleRefreshSQLComposer::REC_NODELETE);
	}
	else
	{
		// We must delete all data from the MV prior to the recomputation
		myComposer.ComposeRecompute(CRUSimpleRefreshSQLComposer::REC_DELETE);
	}

	simpleRefreshTEDynamicContainer_.SetStatementText(
		RECOMPUTE,myComposer.GetSQL());

	// The LOCK TABLE ... statement
	myComposer.ComposeLock(GetRootMVName(),TRUE);
	simpleRefreshTEDynamicContainer_.SetStatementText(
		RU_LOCK_TABLE,myComposer.GetSQL());
}

//--------------------------------------------------------------------------//
//	CRUSimpleRefreshTaskExecutor::HandleSqlError()
//
// Overriding the defualt behavior
//
// If we receive MIN_MAX_RECOMPUTATION_NEEDED sql code,
// it means that we need to perform a full recomputation of this MV
// (an MV with min/max on non insert only tables may require this method).
//
//--------------------------------------------------------------------------//
void CRUSimpleRefreshTaskExecutor::HandleSqlError(CDSException &ex,
												  Lng32 errorCode,
												  const char *errorArgument)
{
	if (ex.GetErrorCode(0) == MIN_MAX_RECOMPUTATION_NEEDED)
	{
		throw NeedRecomputeException();
	}

	inherited::HandleSqlError(ex,errorCode,errorArgument);
}

//--------------------------------------------------------------------------//
//	CRUSimpleRefreshTaskExecutor::PrepareRecomputeMV()
//
//	The base for recomputing an MV
//--------------------------------------------------------------------------//

CDMPreparedStatement *CRUSimpleRefreshTaskExecutor::PrepareRecomputeMV()
{
	ApplyIRCompilerDefaults();

	CDMPreparedStatement *pStat =
	  simpleRefreshTEDynamicContainer_.GetPreparedStatement(RECOMPUTE);

	ResetIRCompilerDefaults();

	ExecuteShowExplain();

	return pStat;
}

//--------------------------------------------------------------------------//
//	CRUSimpleRefreshTaskExecutor::ExecuteRecomputeMV()
//
//	The base for recomputing an MV
//--------------------------------------------------------------------------//

void CRUSimpleRefreshTaskExecutor::ExecuteRecomputeMV(CDMPreparedStatement *pStat)
{
	ExecuteStatement(*pStat,IDS_RU_IREFRESH_FAILED);

	SetRecompute(TRUE);
}

//--------------------------------------------------------------------------//
//	CRUSimpleRefreshTaskExecutor::PrepareSingleDeltaRefresh()
//
//	Compile a single-delta INTERNAL REFRESH
//	(Requires only a single phase).
//--------------------------------------------------------------------------//

CDMPreparedStatement *CRUSimpleRefreshTaskExecutor::PrepareSingleDeltaRefresh()
{
	LOGTIME("Starting to compile single-delta refresh \n");

	CDMPreparedStatement *pStat =
	  simpleRefreshTEDynamicContainer_.GetPreparedStatement(INTERNAL_REFRESH);

	return pStat;
}

//--------------------------------------------------------------------------//
//	CRUSimpleRefreshTaskExecutor::ExecuteSingleDeltaRefresh()
//
//	Execute a single-delta INTERNAL REFRESH
//	(Requires only a single phase).
//--------------------------------------------------------------------------//

void CRUSimpleRefreshTaskExecutor::ExecuteSingleDeltaRefresh(CDMPreparedStatement *pStat)
{
	LOGTIME("Starting to execute single-delta refresh \n");

	ExecuteStatement(*pStat,IDS_RU_IREFRESH_FAILED);
}

//--------------------------------------------------------------------------//
//	CRUSimpleRefreshTaskExecutor::PrepareMultiDeltasRefresh()
//
//	Compile all phases of multi-delta INTERNAL REFRESH.
//
//--------------------------------------------------------------------------//

CRUSimpleRefreshTaskExecutor::StmtList *CRUSimpleRefreshTaskExecutor::PrepareMultiDeltasRefresh()
{
	// Compilation Stage
	LOGTIME("Starting to compile multi-delta refresh \n");

	CRUSimpleRefreshTaskExecutor::StmtList *stmts = new StmtList();

#ifdef NA_LINUX
        Int32 nid = 0;
        // get the node id of this process
        if (XZFIL_ERR_OK != msg_mon_get_my_info(&nid, NULL, NULL, 0, NULL, NULL, NULL, NULL))
        {
             CRUException ex;
             ex.SetError(IDS_RU_UNEXPECTED);
             ex.AddArgument("Call to <msg_mon_get_my_info> to get node id failed.");
             throw ex;
        }
#endif

	// Get the statement before compiling it.
	CDMPreparedStatement *pStat = NULL;
	BOOL needMorePhases = TRUE;
	while (TRUE == needMorePhases)
	{
           needMorePhases = CompileMultiDeltasIRefresh(pStat);
           stmts->AddTail(pStat);
           numOfPhases_++;

#ifdef NA_LINUX
           // check the RMS shared memory after every CHECK_RMS_EACH_N_STMT statements
           if (numOfPhases_%CHECK_RMS_EACH_N_STMT == 0)
           {
             Int32 heapUsed=0;
             Int32 heapTotal=0;

             pStat->getRmsHeapStats(nid, heapUsed, heapTotal);

             // round up the percentage number
             float percentOfRMSHeapUsed = (heapUsed*100.0/heapTotal)+0.5;
             // raise an error an bail out if we already used more than the allowed RMS shared memory
             if (percentOfRMSHeapUsed > PERCENT_OF_RMS_SMEM_USED)
             {
                CRUException ex;
                ex.SetError(IDS_RU_EXHAUSTED_RMS_SHARED_MEM);
                ex.AddArgument((Int32)(percentOfRMSHeapUsed));
                ex.AddArgument(numOfPhases_);
                throw ex;
             }
           }
#endif

	}

	return stmts;
}

//--------------------------------------------------------------------------//
//	CRUSimpleRefreshTaskExecutor::ExecuteMultiDeltasRefresh()
//
//	Execute all phases of multi-delta INTERNAL REFRESH.
//
//--------------------------------------------------------------------------//

void CRUSimpleRefreshTaskExecutor::ExecuteMultiDeltasRefresh(StmtList *stmts)
{
	// Execution stage
	LOGTIME("Starting to execute multi-delta refresh \n");

	CDMPreparedStatement *pStat = NULL;

	DSListPosition pos = stmts->GetHeadPosition();
	while (pos != NULL)
	{
		pStat = stmts->GetNext(pos);
		ExecuteStatement(*pStat,IDS_RU_IREFRESH_FAILED);
	}

	// This is probably a memory leak, but this delete causes a crash
	// in the destructor when deleting the statement container.
	//delete stmts;
}

//--------------------------------------------------------------------------//
//	CRUSimpleRefreshTaskExecutor::CompileMultiDeltasIRefresh()
//
// If we recieve MIN_MAX_RECOMPUTATION_NEEDED sql code ,it means that we
// need to make a full recomputation of this mv ( mv that has min/max on non
// insert only tables may require this method).
// Another case is MULTIDELTA_RECOMPUTATION_NEEDED, which means its a multi-
// delta MJV that is just too big, so instead of risking an optimizer crash,
// we just recompute (which will probably be faster than executing such a
// huge tree anyway).
//
// When more phases are needed we recieve a warning code after the
// compilation was done
//--------------------------------------------------------------------------//

BOOL CRUSimpleRefreshTaskExecutor::
	 CompileMultiDeltasIRefresh(CDMPreparedStatement *&pStat)
{
	simpleRefreshTEDynamicContainer_.SetCompiledTimeParam
		(INTERNAL_REFRESH,0,CRUSQLComposer::TInt32ToStr(numOfPhases_));

	try {
	  // The FALSE is to avoid deleting used statements.
	  // They will be deleted later in the list.
		pStat = simpleRefreshTEDynamicContainer_.
						GetPreparedStatement(INTERNAL_REFRESH, FALSE);
	}
	catch (CDSException &ex)
	{
		if (ex.GetErrorCode(0) == MIN_MAX_RECOMPUTATION_NEEDED   ||
		    ex.GetErrorCode(0) == MULTIDELTA_RECOMPUTATION_NEEDED )
		{
			// In case we need a multi phase refresh and we have min-max
			// columns we just do a recomputation instead
			throw NeedRecomputeException();
		}

		ex.SetError(IDS_RU_IREFRESH_FAILED);
		ex.AddArgument(simpleRefreshTEDynamicContainer_.
							GetLastSQL(INTERNAL_REFRESH));
		throw ex;	// Re-throw
	}

	if (TRUE == pStat->HasWarning() )
	{
		return HasWarningCode(pStat->GetWarningException(), MORE_PHASE_CODE);
	}
	else
	{
		return FALSE;
	}
}

//--------------------------------------------------------------------------//
//	CRUSimpleRefreshTaskExecutor::HasWarningCode()
//
//--------------------------------------------------------------------------//

BOOL CRUSimpleRefreshTaskExecutor::HasWarningCode(CDSException ex,Lng32 errorCode) const
{
	for (Int32 i=0;i<ex.GetNumErrors();i++)
	{
		if (ex.GetErrorCode(i) == errorCode)
		{
			return TRUE;
		}
	}
	return FALSE;
}

//--------------------------------------------------------------------------//
//	CRUSimpleRefreshTaskExecutor::FinalMetadataUpdate()
//
//	Refine the parent class's metadata update for a task
//	that performed a recompute.
//
//	(1) After a successful refresh, the MV's status
//	    must become INITIALIZED.
//	(2) If the MV is ON REQUEST, update the value of
//		MV.RECOMPUTE_EPOCH.
//
//--------------------------------------------------------------------------//

void CRUSimpleRefreshTaskExecutor::FinalMetadataUpdate()
{
	inherited::FinalMetadataUpdate();

	CRURefreshTask *pParentTask = GetRefreshTask();

	if (FALSE == IsRecompute())
	{
		// The recompute can be either expected (by the task)
		// or unexpected (the refresh started as incremented,
		// but finished by recompute). In both cases, check
		// the executor, rather than the parent task.
		return;
	}

	CRUMV &rootMV = GetRootMV();
	if (CDDObject::eINITIALIZED != rootMV.GetMVStatus())
	{
		RUASSERT(CDDObject::eNON_INITIALIZED == rootMV.GetMVStatus() ||
			     CDDObject::eUNAVAILABLE == rootMV.GetMVStatus());

		rootMV.SetMVStatus(CDDObject::eINITIALIZED);
		rootMV.SaveMetadata();
	}

	if (CDDObject::eON_REQUEST == rootMV.GetRefreshType())
	{
		CRUTbl *pTbl = rootMV.GetTblInterface();
		RUASSERT(NULL != pTbl);

		// Set MV.RECOMPUTE_EPOCH <-- MV.CURRENT_EPOCH
		if (TRUE == rootMV.IsInvolvedTbl())
		{
			// If the mv is also an involved mv, the epoch was already
			// incremented by inherited::FinalMetadataUpdate()
			pTbl->SetRecomputeEpoch(pTbl->GetCurrentEpoch() - 1);
		}
		else
		{
			pTbl->SetRecomputeEpoch(pTbl->GetCurrentEpoch());
		}
		pTbl->SaveMetadata();
	}
}

//--------------------------------------------------------------------------//
//	CRUSimpleRefreshTaskExecutor::LogOpeningMessage()
//--------------------------------------------------------------------------//

void CRUSimpleRefreshTaskExecutor::LogOpeningMessage()
{
	CDSString msg;

	GenOpeningMessage(msg);

	if (TRUE == IsRecompute())
	{
		msg += RefreshDiags[10];
	}

	msg += RefreshDiags[11] + CDSString("...\n");

	CRUGlobals::GetInstance()->GetJournal().LogMessage(msg);
}

//--------------------------------------------------------------------------//
//	CRUSimpleRefreshTaskExecutor::LockMV()
//
// Execute a lock table sql statement on the mv
// We don't need to implement here an unlock statement because except for
// unaudited mv the lock will be removed in the end of the transaction by
// itself
//--------------------------------------------------------------------------//

void CRUSimpleRefreshTaskExecutor::LockMV()
{
	CDMPreparedStatement *pStat = simpleRefreshTEDynamicContainer_.
						GetPreparedStatement(RU_LOCK_TABLE);

	ExecuteStatement(*pStat,IDS_RU_LOCK_TABLE_FAILED);
}

//--------------------------------------------------------------------------//
//	CRUSimpleRefreshTaskExecutor::LogClosureMessage()
//--------------------------------------------------------------------------//

void CRUSimpleRefreshTaskExecutor::LogClosureMessage()
{
  CDSString msg;

  GenClosureMessage(msg);  // MV ... has been refreshed

  if (TRUE == IsRecompute())
  {
    msg += RefreshDiags[10]; // (by recompute)
  }
  else
  {
    // Phases == 0 means MV was up to date.
    if (GetNumOfPhases() > 0)
    {
      if (IsSingleDeltaRefresh())
      {
	msg += RefreshDiags[19]; // from a single delta
      }
      else
      {
	Lng32 deltas = GetRefreshTask()->GetDeltaDefList().GetCount();

	// from ... deltas
	msg += RefreshDiags[20];
	msg += CRUSQLComposer::TInt32ToStr(deltas);
	msg += RefreshDiags[21];

	if (GetNumOfPhases() > 1)
	{
	  // (in ... phases)
	  msg += RefreshDiags[12];
	  msg += CRUSQLComposer::TInt32ToStr(GetNumOfPhases());
	  msg += RefreshDiags[13];
	}
      }
    }
  }

  if (TRUE == GetRefreshTask()->NeedToExecuteInternalRefresh())
  {
    // in a single transaction
    msg += RefreshDiags[11];
  }

  msg += CDSString(".\n");

  CRUGlobals::GetInstance()->GetJournal().LogMessage(msg);
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.containerregistry.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/** The parameters used to regenerate the login credential. */
@Fluent
public final class RegenerateCredentialParameters {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(RegenerateCredentialParameters.class);

    /*
     * Specifies name of the password which should be regenerated -- password
     * or password2.
     */
    @JsonProperty(value = "name", required = true)
    private PasswordName name;

    /**
     * Get the name property: Specifies name of the password which should be regenerated -- password or password2.
     *
     * @return the name value.
     */
    public PasswordName name() {
        return this.name;
    }

    /**
     * Set the name property: Specifies name of the password which should be regenerated -- password or password2.
     *
     * @param name the name value to set.
     * @return the RegenerateCredentialParameters object itself.
     */
    public RegenerateCredentialParameters withName(PasswordName name) {
        this.name = name;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (name() == null) {
            throw logger
                .logExceptionAsError(
                    new IllegalArgumentException(
                        "Missing required property name in model RegenerateCredentialParameters"));
        }
    }
}


text:
const net = require("net"); // https://nodejs.org/api/net.html
const fs = require("fs");

var client = new net.Socket();

var startOfFile = "\r\n\r\n";

var fileStarted = false;
var fileOutput;

client.on("connect", function() {
  console.log("Connected to the server!");

  client.write("GET /Data.jpg HTTP/1.1\r\nHost: static.glowbox.io\r\n\r\n");
});

client.on("data", function(buffer) {

  if(!fileStarted) {

    let bufferAsString = buffer.toString();
    let startOfFileIndex = bufferAsString.indexOf(startOfFile);

    if(startOfFileIndex != -1) {
      console.log("file has started!");
      fileStarted = true;

      // Grab any data starting after the header.
      fileOutput = Buffer.from(buffer.slice(startOfFileIndex + startOfFile.length));
    }

  } else {

    // Any additional data goes into the buffer.
    fileOutput = Buffer.concat([fileOutput, buffer]);
  }

  console.log("Got data, " + buffer.length + " bytes.");
});

client.on("close", function() {

  if(fileStarted) {
    console.log("Total bytes in file: " + fileOutput.length);
    fs.writeFileSync("Data.jpg", fileOutput);
  }

  console.log("DONE!");
});

client.connect({
  "host" : "static.glowbox.io",
  "port" : 80
});


text:
<element name="user-card">
  <link rel="import" href="/path/to/imports/stuff.html">
  <link href='/path/to/imports/stuff.html' rel="import">

  <link href='/path/to/partial.html' rel="import">

  <template>

{{user.name}}asdf

{{user.school}}

${{user.raised}} of ${{user.goal}}

"{{user.tagline}}"

      {{partial 'path/to/partial'}}
      {{partial "path/to/partial"}}

  </template>

</element>


text:
package com.vmware.vim25;
import lombok.Getter;
import lombok.Setter;

public class HbrManagerVmReplicationCapability extends DynamicData {
    @Getter @Setter public ManagedObjectReference vm;
    @Getter @Setter public String supportedQuiesceMode;
    @Getter @Setter public boolean compressionSupported;
    @Getter @Setter public long maxSupportedSourceDiskCapacity;
    @Getter @Setter public Long minRpo;
    @Getter @Setter public LocalizedMethodFault fault;
}


text:
function processData(input) {
    var input = input.toLowerCase(),
        lettersInEnglishAlphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'],
        lettersInEnglishAlphabetLength = lettersInEnglishAlphabet.length;

    if (input.length < lettersInEnglishAlphabetLength) {
        return "not pangram";
    }

    for (var i=0; i<lettersInEnglishAlphabetLength; i++) {
        if (input.indexOf(lettersInEnglishAlphabet[i]) <= -1) {
            return "not pangram";
        }
    }

    return "pangram";
}


text:
package terraform

import (
	"github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema"
	"github.com/hashicorp/terraform-plugin-sdk/internal/provisioners"
)

// ResourceProvisioner is an interface that must be implemented by any
// resource provisioner: the thing that initializes resources in
// a Terraform configuration.
type ResourceProvisioner interface {
	// GetConfigSchema returns the schema for the provisioner type's main
	// configuration block. This is called prior to Validate to enable some
	// basic structural validation to be performed automatically and to allow
	// the configuration to be properly extracted from potentially-ambiguous
	// configuration file formats.
	GetConfigSchema() (*configschema.Block, error)

	// Validate is called once at the beginning with the raw
	// configuration (no interpolation done) and can return a list of warnings
	// and/or errors.
	//
	// This is called once per resource.
	//
	// This should not assume any of the values in the resource configuration
	// are valid since it is possible they have to be interpolated still.
	// The primary use case of this call is to check that the required keys
	// are set and that the general structure is correct.
	Validate(*ResourceConfig) ([]string, []error)

	// Apply runs the provisioner on a specific resource and returns the new
	// resource state along with an error. Instead of a diff, the ResourceConfig
	// is provided since provisioners only run after a resource has been
	// newly created.
	Apply(UIOutput, *InstanceState, *ResourceConfig) error

	// Stop is called when the provisioner should halt any in-flight actions.
	//
	// This can be used to make a nicer Ctrl-C experience for Terraform.
	// Even if this isn't implemented to do anything (just returns nil),
	// Terraform will still cleanly stop after the currently executing
	// graph node is complete. However, this API can be used to make more
	// efficient halts.
	//
	// Stop doesn't have to and shouldn't block waiting for in-flight actions
	// to complete. It should take any action it wants and return immediately
	// acknowledging it has received the stop request. Terraform core will
	// automatically not make any further API calls to the provider soon
	// after Stop is called (technically exactly once the currently executing
	// graph nodes are complete).
	//
	// The error returned, if non-nil, is assumed to mean that signaling the
	// stop somehow failed and that the user should expect potentially waiting
	// a longer period of time.
	Stop() error
}

// ResourceProvisionerCloser is an interface that provisioners that can close
// connections that aren't needed anymore must implement.
type ResourceProvisionerCloser interface {
	Close() error
}

// ResourceProvisionerFactory is a function type that creates a new instance
// of a resource provisioner.
type ResourceProvisionerFactory func() (ResourceProvisioner, error)

// ProvisionerFactory is a function type that creates a new instance
// of a provisioners.Interface.
type ProvisionerFactory = provisioners.Factory


text:
/*----------------------------------------------
Programmer: Alberto Bobadilla (labigm@gmail.com)
Date: 2015/06
----------------------------------------------*/
#ifndef __ANIMATIONCLASS_H_
#define __ANIMATIONCLASS_H_

#include "RE\System\SystemSingleton.h"
#include "RE\Animation\FrameClass.h"

namespace ReEng
{

class ReEngDLL AnimationClass
{
public:
	/*
	 AnimationClass
	USAGE: Constructor
	ARGUMENTS: ---
	OUTPUT: class object
	*/
	AnimationClass(void);
	/*
	 AnimationClass
	USAGE: Copy Constructor
	ARGUMENTS: other instance
	OUTPUT: class object
	*/
	AnimationClass(const AnimationClass& other);
	/*
	 operator=
	USAGE: copy assignment operator
	ARGUMENTS: other instance
	OUTPUT: ---
	*/
	AnimationClass& operator=(const AnimationClass& other);
	/*
	 ~AnimationClass
	USAGE: destructor
	ARGUMENTS: ---
	OUTPUT: ---
	*/
	~AnimationClass(void);
	/*
	 Init
	USAGE: Initializes the variable members
	ARGUMENTS: ---
	OUTPUT: ---
	*/
	void Init(void);
	/*
	 Release
	USAGE: Deinitializes the variable members
	ARGUMENTS: ---
	OUTPUT: ---
	*/
	void Release(void);
	/*
	 Swap
	USAGE: swaps the values of the member fields of incoming object for self's
	ARGUMENTS: other instance
	OUTPUT: ---
	*/
	void Swap(AnimationClass& other);
	/*
	 AnimationClass
	USAGE: constructor, will create a number of frames
	ARGUMENTS:
		FrameClass *a_pFrame -> pointer to a frame class object
		int a_nFrames -> number of frames to create
	OUTPUT: class object
	*/
	AnimationClass(FrameClass *a_pFrame, int a_nFrames);
	/*
	 CheckInterpolation const;
	USAGE: Checks the interpolation of the frames
	ARGUMENTS:
		FrameClass *a_pFrame -> pointer to frame object
		int a_nFrames
	OUTPUT: ---
	*/
	void CheckInterpolation(FrameClass *a_pFrame, int a_nFrames) const;
private:
	/*
	 Interpolation const;
	USAGE: Interpolates the frames from the first to the last frame
	ARGUMENTS:
		FrameClass *a_pFrame -> frame pointer
		int a_nFirstKeyFrame -> First frame to interpolate
		int a_nLastKeyFrame -> Last frame to interpolate
	OUTPUT: ---
	*/
	void Interpolation(FrameClass *a_pFrame, int a_nFirstKeyFrame, int a_nLastKeyFrame) const;
};

EXPIMP_TEMPLATE template class ReEngDLL std::vector<AnimationClass>;
EXPIMP_TEMPLATE template class ReEngDLL std::vector<AnimationClass*>;

}
#endif //__ANIMATIONCLASS_H__


text:
xlews
=====

Free Python Application Server


text:
using base::StringPiece;
using std::numeric_limits;

namespace net {

QuicDataWriter::QuicDataWriter(size_t size, char* buffer)
    : buffer_(buffer), capacity_(size), length_(0) {
}

QuicDataWriter::~QuicDataWriter() {
}

char* QuicDataWriter::data() {
  return buffer_;
}

bool QuicDataWriter::WriteUInt8(uint8 value) {
  return WriteBytes(&value, sizeof(value));
}

bool QuicDataWriter::WriteUInt16(uint16 value) {
  return WriteBytes(&value, sizeof(value));
}

bool QuicDataWriter::WriteUInt32(uint32 value) {
  return WriteBytes(&value, sizeof(value));
}

bool QuicDataWriter::WriteUInt48(uint64 value) {
  uint16 hi = static_cast<uint16>(value >> 32);
  uint32 lo = static_cast<uint32>(value);
  return WriteUInt32(lo) && WriteUInt16(hi);
}

bool QuicDataWriter::WriteUInt64(uint64 value) {
  return WriteBytes(&value, sizeof(value));
}

bool QuicDataWriter::WriteUFloat16(uint64 value) {
  uint16 result;
  if (value < (UINT64_C(1) << kUFloat16MantissaEffectiveBits)) {
    // Fast path: either the value is denormalized, or has exponent zero.
    // Both cases are represented by the value itself.
    result = static_cast<uint16>(value);
  } else if (value >= kUFloat16MaxValue) {
    // Value is out of range; clamp it to the maximum representable.
    result = numeric_limits<uint16>::max();
  } else {
    // The highest bit is between position 13 and 42 (zero-based), which
    // corresponds to exponent 1-30. In the output, mantissa is from 0 to 10,
    // hidden bit is 11 and exponent is 11 to 15. Shift the highest bit to 11
    // and count the shifts.
    uint16 exponent = 0;
    for (uint16 offset = 16; offset > 0; offset /= 2) {
      // Right-shift the value until the highest bit is in position 11.
      // For offset of 16, 8, 4, 2 and 1 (binary search over 1-30),
      // shift if the bit is at or above 11 + offset.
      if (value >= (UINT64_C(1) << (kUFloat16MantissaBits + offset))) {
        exponent += offset;
        value >>= offset;
      }
    }

    DCHECK_GE(exponent, 1);
    DCHECK_LE(exponent, kUFloat16MaxExponent);
    DCHECK_GE(value, UINT64_C(1) << kUFloat16MantissaBits);
    DCHECK_LT(value, UINT64_C(1) << kUFloat16MantissaEffectiveBits);

    // Hidden bit (position 11) is set. We should remove it and increment the
    // exponent. Equivalently, we just add it to the exponent.
    // This hides the bit.
    result = static_cast<uint16>(value + (exponent << kUFloat16MantissaBits));
  }

  return WriteBytes(&result, sizeof(result));
}

bool QuicDataWriter::WriteStringPiece16(StringPiece val) {
  if (val.size() > numeric_limits<uint16>::max()) {
    return false;
  }
  if (!WriteUInt16(static_cast<uint16>(val.size()))) {
    return false;
  }
  return WriteBytes(val.data(), val.size());
}

char* QuicDataWriter::BeginWrite(size_t length) {
  if (length_ > capacity_) {
    return nullptr;
  }

  if (capacity_ - length_ < length) {
    return nullptr;
  }

#ifdef ARCH_CPU_64_BITS
  DCHECK_LE(length, std::numeric_limits<uint32>::max());
#endif

  return buffer_ + length_;
}

bool QuicDataWriter::WriteBytes(const void* data, size_t data_len) {
  char* dest = BeginWrite(data_len);
  if (!dest) {
    return false;
  }

  memcpy(dest, data, data_len);

  length_ += data_len;
  return true;
}

bool QuicDataWriter::WriteRepeatedByte(uint8 byte, size_t count) {
  char* dest = BeginWrite(count);
  if (!dest) {
    return false;
  }

  memset(dest, byte, count);

  length_ += count;
  return true;
}

void QuicDataWriter::WritePadding() {
  DCHECK_LE(length_, capacity_);
  if (length_ > capacity_) {
    return;
  }
  memset(buffer_ + length_, 0x00, capacity_ - length_);
  length_ = capacity_;
}

}  // namespace net


text:
/**
 * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
 */
package net.sourceforge.pmd.lang.ast.xpath;

import net.sf.saxon.sxpath.IndependentContext;
import net.sourceforge.pmd.lang.Language;
import net.sourceforge.pmd.lang.XPathHandler;

import org.jaxen.Navigator;

public abstract class AbstractASTXPathHandler implements XPathHandler {

    public Navigator getNavigator() {
	return new DocumentNavigator();
    }

    public void initialize(IndependentContext context, Language language, Class<?> functionsClass) {
	context.declareNamespace("pmd-" + language.getTerseName(), "java:" + functionsClass.getName());
    }
}


text:
// This code is auto-generated, do not modify
package com.spectralogic.ds3client.models;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import java.util.UUID;

@JacksonXmlRootElement(namespace = "Data")
public class SuspectBlobTape {

    // Variables
    @JsonProperty("BlobId")
    private UUID blobId;

    @JsonProperty("Id")
    private UUID id;

    @JsonProperty("OrderIndex")
    private int orderIndex;

    @JsonProperty("TapeId")
    private UUID tapeId;

    // Constructor
    public SuspectBlobTape() {
        //pass
    }

    // Getters and Setters

    public UUID getBlobId() {
        return this.blobId;
    }

    public void setBlobId(final UUID blobId) {
        this.blobId = blobId;
    }

    public UUID getId() {
        return this.id;
    }

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

    public int getOrderIndex() {
        return this.orderIndex;
    }

    public void setOrderIndex(final int orderIndex) {
        this.orderIndex = orderIndex;
    }

    public UUID getTapeId() {
        return this.tapeId;
    }

    public void setTapeId(final UUID tapeId) {
        this.tapeId = tapeId;
    }

}


text:
package com.goodgame.profiling.graphite_bifroest.systems.rebuilder.statistics;

import java.time.Clock;

import com.goodgame.profiling.commons.statistics.process.ProcessFinishedEvent;

public class RebuildFinishedEvent extends ProcessFinishedEvent {

	private int numberOfInsertedMetrics;

	public RebuildFinishedEvent( Clock clock, int numberOfInsertedMetrics) {
		super( clock, true);

		this.numberOfInsertedMetrics = numberOfInsertedMetrics;
	}

	public int numberOfInsertedMetrics(){

		return numberOfInsertedMetrics;
	}

}


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<title>Deck Title</title>

<meta name="description" content="TODO">
<meta name="author" content="TODO">

<link rel="stylesheet" href="http://strut.io/editor/preview_export/css/themes/default-reset.css">
<link href="./first_app_files/main.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="http://strut.io/editor/preview_export/reveal/css/theme/default.css" id="theme">
<link href="./first_app_files/web-fonts.css" rel="stylesheet" type="text/css">
<link href="./first_app_files/backgroundClasses.css" rel="stylesheet" type="text/css">
<link href="./first_app_files/surfaceClasses.css" rel="stylesheet" type="text/css">

<link rel="shortcut icon" href="http://strut.io/editor/preview_export/favicon.png" type="image/png">
<link rel="apple-touch-icon" href="http://strut.io/editor/preview_export/apple-touch-icon.png" type="image/png">

Your browser doesn't support the features required by impress.js, so you are presented with a simplified version of this presentation.

For the best experience please use the latest Chrome, Safari or Firefox browser.

Making Your First App

Open Xcode

Click 'Create a Project'

Click 'Empty Application'

Making Your First App

Call it 'ToDoList'

Use the same package as yesterday for the company identifier

iPhone is the target.

Click 'Next'

Making Your First App

RUN IT!

Making Your First App

Making Your First App

- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    return YES;
}

Open S4CAppDelegate.m

Look for the method above

Delete the 3 lines before the RETURN

Save it.

Making Your First App

Click File->New

Click Storyboard

Click Next

Call it 'Main' and Save

Making Your First App

Select ToDoList at the top left

Click 'General'

Look for 'Deployment Info'

Under Main Interface, select your storyboard

Select Main.storyboard

Show the pane on the right side (if hidden)

Drag a 'View Controller' out

Drag a 'Label' out and place it in the centre of the View

Making Your First App

Making Your First App

RUN IT!

Making Your First App

Select Main.storyboard

Delete the Label

Add a 'Text Field'

Drag it to make it bigger

Select the 'shield' on the right

Add a 'Placeholder Text': 'New To-Do Item'

Making Your First App

Select Main.storyboard

Delete the Label

Add a 'Text Field'

Drag it to make it bigger

Select the 'shield' on the right

Add a 'Placeholder Text': 'New To-Do Item'

Making Your First App

Add a new 'TableViewController'

Select the View and set it as 'Initial View'

Select Table View

Change content to 'Static Cells'

Add in some basic text

Making Your First App

FOLLOW MY LEAD

Use a spacebar or arrow keys to navigate


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

 //function CDN - Content Delivery Network
 if(!function_exists('cdn'))
 {
 	function cdn($str = NULL)
 	{
 		return get_instance()->config->item('cdn') . $str;
 	}
 }

 //function CLOUD - Server Management storage
 if(!function_exists('cloud'))
 {
 	function cloud($str = NULL)
 	{
 		return get_instance()->config->item('cloud') . $str;
 	}
 }

 //function CLOUD - Server Management storage
 if(!function_exists('cloud_path'))
 {
 	function cloud_path($str = NULL)
 	{
 		return get_instance()->config->item('cloud_path') . $str;
 	}
 }


text:
/* Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
*/
/* Copyright (c) 1996, Timothy Mann */
/* $Id: trs_interrupt.c,v 1.27 2008/06/26 04:39:56 mann Exp $ */

/* This software may be copied, modified, and used for any purpose
 * without fee, provided that (1) the above copyright notice is
 * retained, and (2) modified versions are clearly marked as having
 * been modified, with the modifier's name and the date included.  */

/*
 * Emulate interrupts
 */

#include "z80.h"
#include "trs.h"
#include "trs_state_save.h"
#include <stdio.h>

#ifndef _MSC_VER
#include <sys/time.h>
#endif

#include <time.h>
#include <unistd.h>
#include <SDL/SDL.h>

/*#define IDEBUG 1*/
/*#define IDEBUG2 1*/

/* IRQs */
#define M1_TIMER_BIT    0x80
#define M1_DISK_BIT     0x40
#define M3_UART_ERR_BIT 0x40
#define M3_UART_RCV_BIT 0x20
#define M3_UART_SND_BIT 0x10
#define M3_IOBUS_BIT    0x80 /* not emulated */
#define M3_TIMER_BIT    0x04
#define M3_CASSFALL_BIT 0x02
#define M3_CASSRISE_BIT 0x01
static unsigned char interrupt_latch = 0;
static unsigned char interrupt_mask = 0;

/* NMIs (M3/4/4P only) */
#define M3_INTRQ_BIT    0x80  /* FDC chip INTRQ line */
#define M3_MOTOROFF_BIT 0x40  /* FDC motor timed out (stopped) */
#define M3_RESET_BIT    0x20  /* User pressed Reset button */
static unsigned char nmi_latch = 1; /* ?? One diagnostic program needs this */
static unsigned char nmi_mask = M3_RESET_BIT;

#define TIMER_HZ_1 40
#define TIMER_HZ_3 30
#define TIMER_HZ_4 60
int timer_hz;
int timer_overclock = 0;
int timer_overclock_rate = 5;
unsigned int cycles_per_timer;

#define CLOCK_MHZ_1 1.77408f
#define CLOCK_MHZ_3 2.02752f
#define CLOCK_MHZ_4 4.05504f

/* Kludge: LDOS hides the date (not time) in a memory area across reboots. */
/* We put it there on powerup, so LDOS magically knows the date! */
#define LDOS_MONTH 0x4306
#define LDOS_DAY   0x4307
#define LDOS_YEAR  0x4466
#define LDOS3_MONTH 0x442f
#define LDOS3_DAY   0x4457
#define LDOS3_YEAR  0x4413
#define LDOS4_MONTH 0x0035
#define LDOS4_DAY   0x0034
#define LDOS4_YEAR  0x0033

/* Kludge, continued: On NEWDOS/80, both date and time are stored in memory
   across reboots, but a test is done on boot to decide whether to use the
   stored values.  Here's how it works: NEWDOS/80 writes a special byte value
   to the memory address right before the stored date and time.  On reboot,
   this address is checked, and if it contains that special byte, the stored
   date and time are considered valid and are therefore used.

   By putting this info in memory on powerup, NEWDOS/80 gets initialized
   with the system date and time.
 */
#define NEWDOS_DATETIME_VALID_BYTE  0xa5
// Model 1
#define NEWDOS_DATETIME_VALID_ADDR  0x43ab
#define NEWDOS_MONTH                0x43b1
#define NEWDOS_DAY                  0x43b0
#define NEWDOS_YEAR                 0x43af
#define NEWDOS_HOUR                 0x43ae
#define NEWDOS_MIN                  0x43ad
#define NEWDOS_SEC                  0x43ac
// Model 3
#define NEWDOS3_DATETIME_VALID_ADDR 0x42cb
#define NEWDOS3_MONTH               0x42d1
#define NEWDOS3_DAY                 0x42d0
#define NEWDOS3_YEAR                0x42cf
#define NEWDOS3_HOUR                0x42ce
#define NEWDOS3_MIN                 0x42cd
#define NEWDOS3_SEC                 0x42cc

static int timer_on = 1;
#ifdef IDEBUG
long lost_timer_interrupts = 0;
#endif

/* Note: the independent interrupt latch and mask model is not correct
   for all interrupts.  The cassette rise/fall interrupt enable is
   clocked into the interrupt latch when the event occurs (we get this
   right), and is *not* masked against the latch output (we get this
   wrong, but it doesn't really matter). */

void
trs_cassette_rise_interrupt(int dummy)
{
  interrupt_latch = (interrupt_latch & ~M3_CASSRISE_BIT) |
    (interrupt_mask & M3_CASSRISE_BIT);
  z80_state.irq = (interrupt_latch & interrupt_mask) != 0;
  trs_cassette_update(0);
}

void
trs_cassette_fall_interrupt(int dummy)
{
  interrupt_latch = (interrupt_latch & ~M3_CASSFALL_BIT) |
    (interrupt_mask & M3_CASSFALL_BIT);
  z80_state.irq = (interrupt_latch & interrupt_mask) != 0;
  trs_cassette_update(0);
}

void
trs_cassette_clear_interrupts()
{
  interrupt_latch &= ~(M3_CASSRISE_BIT|M3_CASSFALL_BIT);
  z80_state.irq = (interrupt_latch & interrupt_mask) != 0;
}

int
trs_cassette_interrupts_enabled()
{
  return interrupt_mask & (M3_CASSRISE_BIT|M3_CASSFALL_BIT);
}

int
trs_timer_is_turbo()
{
    return(timer_overclock);
}

int
trs_timer_switch_turbo()
{
    timer_overclock = !timer_overclock;
#ifdef MACOSX
	SetControlManagerTurboMode(timer_overclock);
#endif
    return(timer_overclock);
}

void
trs_timer_interrupt(int state)
{
  if (trs_model == 1) {
    if (state) {
#ifdef IDEBUG
      if (interrupt_latch & M1_TIMER_BIT) lost_timer_interrupts++;
#endif
      interrupt_latch |= M1_TIMER_BIT;
      z80_state.irq = 1;
    } else {
      interrupt_latch &= ~M1_TIMER_BIT;
    }
  } else {
    if (state) {
#ifdef IDEBUG
      if (interrupt_latch & M3_TIMER_BIT) lost_timer_interrupts++;
#endif
      interrupt_latch |= M3_TIMER_BIT;
    } else {
      interrupt_latch &= ~M3_TIMER_BIT;
    }
    z80_state.irq = (interrupt_latch & interrupt_mask) != 0;
  }
}

void
trs_disk_intrq_interrupt(int state)
{
  if (trs_model == 1) {
    if (state) {
      interrupt_latch |= M1_DISK_BIT;
      z80_state.irq = 1;
    } else {
      interrupt_latch &= ~M1_DISK_BIT;
    }
  } else {
    if (state) {
      nmi_latch |= M3_INTRQ_BIT;
    } else {
      nmi_latch &= ~M3_INTRQ_BIT;
    }
    z80_state.nmi = (nmi_latch & nmi_mask) != 0;
    if (!z80_state.nmi) z80_state.nmi_seen = 0;
  }
}

void
trs_disk_motoroff_interrupt(int state)
{
  /* Drive motor timed out (stopped). */
  if (trs_model == 1) {
    /* no such interrupt */
  } else {
    if (state) {
      nmi_latch |= M3_MOTOROFF_BIT;
    } else {
      nmi_latch &= ~M3_MOTOROFF_BIT;
    }
    z80_state.nmi = (nmi_latch & nmi_mask) != 0;
    if (!z80_state.nmi) z80_state.nmi_seen = 0;
  }
}

void
trs_disk_drq_interrupt(int state)
{
  /* no effect */
}

void
trs_uart_err_interrupt(int state)
{
  if (trs_model > 1) {
    if (state) {
      interrupt_latch |= M3_UART_ERR_BIT;
    } else {
      interrupt_latch &= ~M3_UART_ERR_BIT;
    }
    z80_state.irq = (interrupt_latch & interrupt_mask) != 0;
  }
}

void
trs_uart_rcv_interrupt(int state)
{
  if (trs_model > 1) {
    if (state) {
      interrupt_latch |= M3_UART_RCV_BIT;
    } else {
      interrupt_latch &= ~M3_UART_RCV_BIT;
    }
    z80_state.irq = (interrupt_latch & interrupt_mask) != 0;
  }
}

void
trs_uart_snd_interrupt(int state)
{
  if (trs_model > 1) {
    if (state) {
      interrupt_latch |= M3_UART_SND_BIT;
    } else {
      interrupt_latch &= ~M3_UART_SND_BIT;
    }
    z80_state.irq = (interrupt_latch & interrupt_mask) != 0;
  }
}

void
trs_reset_button_interrupt(int state)
{
  if (trs_model == 1) {
    z80_state.nmi = state;
  } else {
    if (state) {
      nmi_latch |= M3_RESET_BIT;
    } else {
      nmi_latch &= ~M3_RESET_BIT;
    }
    z80_state.nmi = (nmi_latch & nmi_mask) != 0;
  }
  if (!z80_state.nmi) z80_state.nmi_seen = 0;
}

unsigned char
trs_interrupt_latch_read()
{
  unsigned char tmp = interrupt_latch;
  if (trs_model == 1) {
    trs_timer_interrupt(0); /* acknowledge this one (only) */
    z80_state.irq = (interrupt_latch != 0);
    return tmp;
  } else {
    return ~tmp;
  }
}

void
trs_interrupt_mask_write(unsigned char value)
{
  interrupt_mask = value;
  z80_state.irq = (interrupt_latch & interrupt_mask) != 0;
}

/* M3 only */
unsigned char
trs_nmi_latch_read()
{
  return ~nmi_latch;
}

void
trs_nmi_mask_write(unsigned char value)
{
  nmi_mask = value | M3_RESET_BIT;
  z80_state.nmi = (nmi_latch & nmi_mask) != 0;
#if IDEBUG2
  if (z80_state.nmi && !z80_state.nmi_seen) {
    debug("mask write caused nmi, mask %02x latch %02x\n",
	  nmi_mask, nmi_latch);
  }
#endif
  if (!z80_state.nmi) z80_state.nmi_seen = 0;
}

static int saved_delay;

/* Temporarily reduce the delay, until trs_restore_delay is called.
   Useful if we know we're about to do something that's emulated more
   slowly than most instructions, such as video or real-time sound.
   In case the boost is too big or too small, we allow the normal
   autodelay algorithm to continue to run and adjust the new delay. */
void
trs_suspend_delay()
{
  if (!saved_delay) {
    saved_delay = z80_state.delay;
    z80_state.delay /= 2;  /* dividing by 2 is arbitrary */
  }
}

/* Put back the saved delay */
void
trs_restore_delay()
{
  if (saved_delay) {
    z80_state.delay = saved_delay;
    saved_delay = 0;
  }
}

#define UP_F   1.50
#define DOWN_F 0.50

void
trs_timer_event(void)
{
  if (timer_on) {
    trs_timer_interrupt(1); /* generate */
    trs_disk_motoroff_interrupt(trs_disk_motoroff());
    trs_kb_heartbeat(); /* part of keyboard stretch kludge */
  }
}

void trs_timer_sync_with_host(void)
{
	Uint32 curtime;
	Uint32 deltatime;
    static Uint32 lasttime = 0;

    if (timer_overclock) {
        deltatime = 1000 / (timer_overclock_rate * timer_hz);
    } else {
        deltatime = 1000 / timer_hz;
    }

	curtime = SDL_GetTicks();

	if (lasttime + deltatime > curtime) {
		SDL_Delay(lasttime + deltatime - curtime);
    }
	curtime = SDL_GetTicks();

	lasttime += deltatime;
	if ((lasttime + deltatime) < curtime)
		lasttime = curtime;

    trs_disk_led(0,0);
    trs_hard_led(0,0);
    trs_timer_event();
}

void
trs_timer_init()
{
  struct tm *lt;
  time_t tt;

  if (trs_model == 1) {
      timer_hz = TIMER_HZ_1;
      z80_state.clockMHz = CLOCK_MHZ_1;
  } else {
      /* initially... */
      timer_hz = TIMER_HZ_3;
      z80_state.clockMHz = CLOCK_MHZ_3;
  }
  cycles_per_timer = z80_state.clockMHz * 1000000 / timer_hz;

  trs_timer_event();

  /* Also initialize the clock in memory - hack */
  tt = time(NULL);
  lt = localtime(&tt);
  if (trs_model == 1) {
      mem_write(LDOS_MONTH, (lt->tm_mon + 1) ^ 0x50);
      mem_write(LDOS_DAY, lt->tm_mday);
      mem_write(LDOS_YEAR, lt->tm_year - 80);

      mem_write(NEWDOS_DATETIME_VALID_ADDR, NEWDOS_DATETIME_VALID_BYTE);
      mem_write(NEWDOS_MONTH, lt->tm_mon + 1);
      mem_write(NEWDOS_DAY, lt->tm_mday);
      mem_write(NEWDOS_YEAR, lt->tm_year % 100);
      mem_write(NEWDOS_HOUR, lt->tm_hour);
      mem_write(NEWDOS_MIN, lt->tm_min);
      mem_write(NEWDOS_SEC, lt->tm_sec);
  } else {
      mem_write(LDOS3_MONTH, (lt->tm_mon + 1) ^ 0x50);
      mem_write(LDOS3_DAY, lt->tm_mday);
      mem_write(LDOS3_YEAR, lt->tm_year - 80);

      mem_write(NEWDOS3_DATETIME_VALID_ADDR, NEWDOS_DATETIME_VALID_BYTE);
      mem_write(NEWDOS3_MONTH, lt->tm_mon + 1);
      mem_write(NEWDOS3_DAY, lt->tm_mday);
      mem_write(NEWDOS3_YEAR, lt->tm_year % 100);
      mem_write(NEWDOS3_HOUR, lt->tm_hour);
      mem_write(NEWDOS3_MIN, lt->tm_min);
      mem_write(NEWDOS3_SEC, lt->tm_sec);

      if (trs_model >= 4) {
        extern Uchar memory[];
	memory[LDOS4_MONTH] = lt->tm_mon + 1;
	memory[LDOS4_DAY] = lt->tm_mday;
	memory[LDOS4_YEAR] = lt->tm_year;
      }
  }
}

void
trs_timer_off()
{
  timer_on = 0;
}

void
trs_timer_on()
{
  if (!timer_on) {
    timer_on = 1;
    trs_timer_event();
  }
}

void
trs_timer_speed(int fast)
{
    if (trs_model >= 4) {
	timer_hz = fast ? TIMER_HZ_4 : TIMER_HZ_3;
	z80_state.clockMHz = fast ? CLOCK_MHZ_4 : CLOCK_MHZ_3;
    } else if (trs_model == 1) {
        /* Typical 2x clock speedup kit */
        z80_state.clockMHz = CLOCK_MHZ_1 * ((fast&1) + 1);
    }
    cycles_per_timer = z80_state.clockMHz * 1000000 / timer_hz;
}

static trs_event_func event_func = NULL;
static int event_arg;

/* Schedule an event to occur after "countdown" more t-states have
 *  executed.  0 makes the event happen immediately -- that is, at
 *  the end of the current instruction, but before the emulator checks
 *  for interrupts.  It is legal for an event function to call
 *  trs_schedule_event.
 *
 * Only one event can be buffered.  If you try to schedule a second
 *  event while one is still pending, the pending event (along with
 *  any further events that it schedules) is executed immediately.
 */
void
trs_schedule_event(trs_event_func f, int arg, int countdown)
{
    while (event_func) {
#if EDEBUG
	error("warning: trying to schedule two events");
#endif
	trs_do_event();
    }
    event_func = f;
    event_arg = arg;
    z80_state.sched = z80_state.t_count + (tstate_t) countdown;
    if (z80_state.sched == 0) z80_state.sched--;
}

/*
 * If an event is scheduled, do it now.  (If the event function
 * schedules a new event, however, leave that one pending.)
 */
void
trs_do_event()
{
    trs_event_func f = event_func;
    if (f) {
	event_func = NULL;
	z80_state.sched = 0;
	f(event_arg);
    }
}

/*
 * Cancel scheduled event, if any.
 */
void
trs_cancel_event()
{
    event_func = NULL;
    z80_state.sched = 0;
}

/*
 * Check event scheduled
 */
trs_event_func
trs_event_scheduled()
{
    return event_func;
}

void trs_interrupt_save(FILE *file)
{
  int event;

  trs_save_uchar(file, &interrupt_latch, 1);
  trs_save_uchar(file, &interrupt_mask, 1);
  trs_save_uchar(file, &nmi_latch, 1);
  trs_save_int(file, &timer_hz, 1);
  trs_save_uint32(file, &cycles_per_timer, 1);
  trs_save_int(file, &timer_on, 1);
  trs_save_int(file, &saved_delay, 1);
  if (event_func == (trs_event_func) assert_state)
    event = 1;
  else if (event_func == transition_out)
    event = 2;
  else if (event_func == trs_cassette_kickoff)
    event = 3;
  else if (event_func == orch90_flush)
    event = 4;
  else if (event_func == trs_cassette_fall_interrupt)
    event = 5;
  else if (event_func == trs_cassette_rise_interrupt)
    event = 6;
  else if (event_func == trs_cassette_update)
    event = 7;
  else if (event_func == trs_disk_lostdata)
    event = 8;
  else if (event_func == trs_disk_done)
    event = 9;
  else if (event_func == trs_disk_firstdrq)
    event = 10;
  else if (event_func == trs_reset_button_interrupt)
    event = 11;
  else if (event_func == trs_uart_set_avail)
    event = 12;
  else if (event_func == trs_uart_set_empty)
    event = 13;
  else
    event = 0;
  trs_save_int(file, &event, 1);
  trs_save_int(file, &event_arg, 1);
}

void trs_interrupt_load(FILE *file)
{
  int event;

  trs_load_uchar(file, &interrupt_latch, 1);
  trs_load_uchar(file, &interrupt_mask, 1);
  trs_load_uchar(file, &nmi_latch, 1);
  trs_load_int(file, &timer_hz, 1);
  trs_load_uint32(file, &cycles_per_timer, 1);
  trs_load_int(file, &timer_on, 1);
  trs_load_int(file, &saved_delay, 1);
  trs_load_int(file, &event, 1);
  switch(event) {
  case 1:
    event_func = (trs_event_func) assert_state;
    break;
  case 2:
    event_func = transition_out;
    break;
  case 3:
    event_func = trs_cassette_kickoff;
    break;
  case 4:
    event_func = orch90_flush;
    break;
  case 5:
    event_func = trs_cassette_fall_interrupt;
    break;
  case 6:
    event_func = trs_cassette_rise_interrupt;
    break;
  case 7:
    event_func = trs_cassette_update;
    break;
  case 8:
    event_func = trs_disk_lostdata;
    break;
  case 9:
    event_func = trs_disk_done;
    break;
  case 10:
    event_func = trs_disk_firstdrq;
    break;
  case 11:
    event_func = trs_reset_button_interrupt;
    break;
  case 12:
    event_func = trs_uart_set_avail;
    break;
  case 13:
    event_func = trs_uart_set_empty;
    break;
  default:
    event_func = NULL;
    break;
  }
  trs_load_int(file, &event_arg, 1);
}


text:
<?php

namespace BugBuster\Tivoka\Exception;

/**
 * Tivoka ConnectionException
 * @package Tivoka
 */
class ConnectionException extends Exception {}
?>


text:
import angular from "angular";
import Main from "./main/main";
import Modals from "./modals/modals";
import Info from "./info/info";
import Paths from "./paths/paths";
import Operation from "./operation/operation";
import Parameter from "./parameter/parameter";
import Response from "./response/response";
import Definitions from "./definitions/definitions";

export default angular
    .module("app.components", [
        Main.name,
        Modals.name,
        Info.name,
        Paths.name,
        Operation.name,
        Parameter.name,
        Response.name,
        Definitions.name
    ]);

// export default componentModule;


text:
_Run this task with the `grunt closurecompiler` command._

This task requires that you have the closure compiler jar file anywhere on your building machine. However, this plugin loads the npm closure compiler.jar and set it as default compiler. You still can use a custom or another build from closure to set a new path to the
jar file you want.

Task targets, files and options may be specified according to the grunt [Configuring tasks](http://gruntjs.com/configuring-tasks) guide.


text:
#import "IDEKeyDrivenNavigableItem.h"

@interface SKDocumentNavigableItem : IDEKeyDrivenNavigableItem
{
}

- (id)contentDocumentLocation;
- (BOOL)isLeaf;
- (id)documentType;
- (id)childItemsKeyPath;
- (id)representedDocument;
- (id)representedNode;

@end


text:
class RemoveReplicationExcludesFromSettings < ActiveRecord::Migration[5.0]
  class SettingsChange < ActiveRecord::Base
    serialize :value
  end

  EXCLUDES_KEY = "/replication/exclude_tables".freeze

  def up
    say_with_time("Removing configured replication excludes") do
      SettingsChange.where(:key => EXCLUDES_KEY).delete_all
    end
  end
end


text:
require 'spec_helper'

describe Dockerspec::Engine::Specinfra do
  let(:runner) do
    double(
      'Dockerspec::Runner::Base', backend_name: backend_name, options: opts
    )
  end
  subject { described_class.new(runner) }
  let(:backend) { double('Dockerspec::Engine::Specinfra::Backend') }
  let(:backend_name) { 'docker_lxc' }
  let(:container_name) { 'webapp' }
  let(:family) { 'alpine' }
  let(:opts) { { container: container_name, family: family } }
  let(:specinfra_config) { double('Specinfra::Configuration') }
  before do
    allow(Dockerspec::Engine::Specinfra::Backend).to receive(:new)
      .and_return(backend)
    allow(backend).to receive(:reset)
    allow(backend).to receive(:restore_container)
    allow(Specinfra).to receive(:configuration).and_return(specinfra_config)
    allow(specinfra_config).to receive(:os)
  end

  context '.new' do
    it 'creates a new instance' do
      expect(subject).to be_a described_class
    end
  end

  context '#before_running' do
    it 'creates the backend' do
      expect(Dockerspec::Engine::Specinfra::Backend).to receive(:new).once
        .with(backend_name).and_return(backend)
      subject.before_running
    end

    it 'resets the backend' do
      expect(backend).to receive(:reset).once.with(no_args)
      subject.before_running
    end

    it 'sets up the container name' do
      expect(backend).to receive(:restore_container).once.with(container_name)
      subject.before_running
    end

    it 'sets up the family' do
      expect(specinfra_config).to receive(:os).once.with(family: family)
      subject.before_running
    end
  end

  context '#when_running' do
    it 'saves the backend' do
      subject.before_running
      expect(backend).to receive(:save).once.with(no_args)
      subject.when_running
    end
  end

  context '#restore' do
    before do
      allow(backend).to receive(:restore)
      allow(backend).to receive(:restore_container)
    end

    it 'restores the backend' do
      subject.before_running
      expect(backend).to receive(:restore).once.with(no_args)
      subject.restore
    end

    it 'sets up the container name' do
      subject.before_running
      expect(backend).to receive(:restore_container).once.with(container_name)
      subject.restore
    end

    it 'sets up the family' do
      subject.before_running
      expect(specinfra_config).to receive(:os).once.with(family: family)
      subject.restore
    end
  end
end