<commit_before>///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2003, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// *       Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// *       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.
// *       Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT
// OWNER 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.
//
///////////////////////////////////////////////////////////////////////////

//-----------------------------------------------------------------------------
//
//	Utility program to print an image file's header
//
//-----------------------------------------------------------------------------

#include <ImfInputFile.h>
#include <ImfBoxAttribute.h>
#include <ImfChannelListAttribute.h>
#include <ImfCompressionAttribute.h>
#include <ImfFloatAttribute.h>
#include <ImfIntAttribute.h>
#include <ImfLineOrderAttribute.h>
#include <ImfMatrixAttribute.h>
#include <ImfStringAttribute.h>
#include <ImfVecAttribute.h>
#include <iostream>

using namespace Imf;
using std::cout;
using std::endl;

void
printCompression (Compression c)
{
    switch (c)
    {
      case NO_COMPRESSION:
	cout << "none";
	break;

      case RLE_COMPRESSION:
	cout << "run-length encoding";
	break;

      case ZIPS_COMPRESSION:
	cout << "zip, individual scanlines";
	break;

      case ZIP_COMPRESSION:
	cout << "zip, multi-scanline blocks";
	break;

      case PIZ_COMPRESSION:
	cout << "piz";
	break;

      default:
	cout << int (c);
	break;
    }
}

void
printLineOrder (LineOrder lo)
{
    switch (lo)
    {
      case INCREASING_Y:
	cout << "increasing y";
	break;

      case DECREASING_Y:
	cout << "decreasing y";
	break;

      default:
	cout << int (lo);
	break;
    };
}

void
printPixelType (PixelType pt)
{
    switch (pt)
    {
      case UINT:
	cout << "32-bit unsigned integer";
	break;

      case HALF:
	cout << "16-bit floating-point";
	break;

      case FLOAT:
	cout << "32-bit floating-point";
	break;

      default:
	cout << "type " << int (pt);
	break;
    }
}

void
printChannelList (const ChannelList &cl)
{
    for (ChannelList::ConstIterator i = cl.begin(); i != cl.end(); ++i)
    {
	cout << "\n    " << i.name() << ", ";

	printPixelType (i.channel().type);

	cout << ", sampling " <<
		i.channel().xSampling << " " <<
		i.channel().ySampling;
    }
}

void
printInfo (const char fileName[])
{
    InputFile in (fileName);
    const Header &h = in.header();

    cout << "\n" << fileName << ":\n\n";

    cout << "file format version: " << in.version() << "\n";

    for (Header::ConstIterator i = h.begin(); i != h.end(); ++i)
    {
	const Attribute *a = &i.attribute();
	cout << i.name() << " (type " << a->typeName() << ")";

	if (const Box2iAttribute *ta =
		dynamic_cast <const Box2iAttribute *> (a))
	{
	    cout << ": " << ta->value().min << " - " << ta->value().max;
	}
	else if (const Box2fAttribute *ta =
		dynamic_cast <const Box2fAttribute *> (a))
	{
	    cout << ": " << ta->value().min << " - " << ta->value().max;
	}
	else if (const ChannelListAttribute *ta =
		dynamic_cast <const ChannelListAttribute *> (a))
	{
	    cout << ":";
	    printChannelList (ta->value());
	}
	else if (const CompressionAttribute *ta =
		dynamic_cast <const CompressionAttribute *> (a))
	{
	    cout << ": ";
	    printCompression (ta->value());
	}
	else if (const FloatAttribute *ta =
		dynamic_cast <const FloatAttribute *> (a))
	{
	    cout << ": " << ta->value();
	}
	else if (const IntAttribute *ta =
		dynamic_cast <const IntAttribute *> (a))
	{
	    cout << ": " << ta->value();
	}
	else if (const LineOrderAttribute *ta =
		dynamic_cast <const LineOrderAttribute *> (a))
	{
	    cout << ": ";
	    printLineOrder (ta->value());
	}
	else if (const M33fAttribute *ta =
		dynamic_cast <const M33fAttribute *> (a))
	{
	    cout << ":\n"
		    "   (" <<
		    ta->value()[0][0] << " " <<
		    ta->value()[0][1] << " " <<
		    ta->value()[0][2] << "\n    " <<
		    ta->value()[1][0] << " " <<
		    ta->value()[1][1] << " " <<
		    ta->value()[1][2] << "\n    " <<
		    ta->value()[2][0] << " " <<
		    ta->value()[2][1] << " " <<
		    ta->value()[2][2] << ")";
	}
	else if (const M44fAttribute *ta =
		dynamic_cast <const M44fAttribute *> (a))
	{
	    cout << ":\n"
		    "   (" <<
		    ta->value()[0][0] << " " <<
		    ta->value()[0][1] << " " <<
		    ta->value()[0][2] << " " <<
		    ta->value()[0][3] << "\n    " <<
		    ta->value()[1][0] << " " <<
		    ta->value()[1][1] << " " <<
		    ta->value()[1][2] << " " <<
		    ta->value()[1][3] << "\n    " <<
		    ta->value()[2][0] << " " <<
		    ta->value()[2][1] << " " <<
		    ta->value()[2][2] << " " <<
		    ta->value()[2][3] << "\n    " <<
		    ta->value()[3][0] << " " <<
		    ta->value()[3][1] << " " <<
		    ta->value()[3][2] << " " <<
		    ta->value()[3][3] << ")";
	}
	else if (const StringAttribute *ta =
		dynamic_cast <const StringAttribute *> (a))
	{
	    cout << ": \"" << ta->value() << "\"";
	}
	else if (const V2iAttribute *ta =
		dynamic_cast <const V2iAttribute *> (a))
	{
	    cout << ": " << ta->value();
	}
	else if (const V2fAttribute *ta =
		dynamic_cast <const V2fAttribute *> (a))
	{
	    cout << ": " << ta->value();
	}
	else if (const V3iAttribute *ta =
		dynamic_cast <const V3iAttribute *> (a))
	{
	    cout << ": " << ta->value();
	}
	else if (const V3fAttribute *ta =
		dynamic_cast <const V3fAttribute *> (a))
	{
	    cout << ": " << ta->value();
	}

	cout << '\n';
    }

    cout << endl;
}

int
main(int argc, char **argv)
{
    if (argc < 2)
    {
	std::cerr << "usage: " << argv[0] << " imagefile\n";
	return 1;
    }
    else
    {
	try
	{
	    printInfo (argv[1]);
	    return 0;
	}
	catch (const std::exception &e)
	{
	    std::cerr << e.what() << std::endl;
	    return 1;
	}
    }
}

<commit_msg><commit_after>///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2003, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// *       Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// *       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.
// *       Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT
// OWNER 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.
//
///////////////////////////////////////////////////////////////////////////

//-----------------------------------------------------------------------------
//
//	Utility program to print an image file's header
//
//-----------------------------------------------------------------------------

#include <ImfInputFile.h>
#include <ImfBoxAttribute.h>
#include <ImfChannelListAttribute.h>
#include <ImfChromaticitiesAttribute.h>
#include <ImfCompressionAttribute.h>
#include <ImfDoubleAttribute.h>
#include <ImfFloatAttribute.h>
#include <ImfIntAttribute.h>
#include <ImfLineOrderAttribute.h>
#include <ImfMatrixAttribute.h>
#include <ImfStringAttribute.h>
#include <ImfVecAttribute.h>
#include <iostream>

using namespace Imf;
using std::cout;
using std::endl;

void
printCompression (Compression c)
{
    switch (c)
    {
      case NO_COMPRESSION:
	cout << "none";
	break;

      case RLE_COMPRESSION:
	cout << "run-length encoding";
	break;

      case ZIPS_COMPRESSION:
	cout << "zip, individual scanlines";
	break;

      case ZIP_COMPRESSION:
	cout << "zip, multi-scanline blocks";
	break;

      case PIZ_COMPRESSION:
	cout << "piz";
	break;

      default:
	cout << int (c);
	break;
    }
}

void
printLineOrder (LineOrder lo)
{
    switch (lo)
    {
      case INCREASING_Y:
	cout << "increasing y";
	break;

      case DECREASING_Y:
	cout << "decreasing y";
	break;

      default:
	cout << int (lo);
	break;
    };
}

void
printPixelType (PixelType pt)
{
    switch (pt)
    {
      case UINT:
	cout << "32-bit unsigned integer";
	break;

      case HALF:
	cout << "16-bit floating-point";
	break;

      case FLOAT:
	cout << "32-bit floating-point";
	break;

      default:
	cout << "type " << int (pt);
	break;
    }
}

void
printChannelList (const ChannelList &cl)
{
    for (ChannelList::ConstIterator i = cl.begin(); i != cl.end(); ++i)
    {
	cout << "\n    " << i.name() << ", ";

	printPixelType (i.channel().type);

	cout << ", sampling " <<
		i.channel().xSampling << " " <<
		i.channel().ySampling;
    }
}

void
printInfo (const char fileName[])
{
    InputFile in (fileName);
    const Header &h = in.header();

    cout << "\n" << fileName << ":\n\n";

    cout << "file format version: " << in.version() << "\n";

    for (Header::ConstIterator i = h.begin(); i != h.end(); ++i)
    {
	const Attribute *a = &i.attribute();
	cout << i.name() << " (type " << a->typeName() << ")";

	if (const Box2iAttribute *ta =
		dynamic_cast <const Box2iAttribute *> (a))
	{
	    cout << ": " << ta->value().min << " - " << ta->value().max;
	}
	else if (const Box2fAttribute *ta =
		dynamic_cast <const Box2fAttribute *> (a))
	{
	    cout << ": " << ta->value().min << " - " << ta->value().max;
	}
	else if (const ChannelListAttribute *ta =
		dynamic_cast <const ChannelListAttribute *> (a))
	{
	    cout << ":";
	    printChannelList (ta->value());
	}
	else if (const ChromaticitiesAttribute *ta =
		dynamic_cast <const ChromaticitiesAttribute *> (a))
	{
	    cout << ":\n"
		    "    red   " << ta->value().red << "\n"
		    "    green " << ta->value().green << "\n"
		    "    blue  " << ta->value().blue << "\n"
		    "    white " << ta->value().white;
	}
	else if (const CompressionAttribute *ta =
		dynamic_cast <const CompressionAttribute *> (a))
	{
	    cout << ": ";
	    printCompression (ta->value());
	}
	else if (const DoubleAttribute *ta =
		dynamic_cast <const DoubleAttribute *> (a))
	{
	    cout << ": " << ta->value();
	}
	else if (const FloatAttribute *ta =
		dynamic_cast <const FloatAttribute *> (a))
	{
	    cout << ": " << ta->value();
	}
	else if (const IntAttribute *ta =
		dynamic_cast <const IntAttribute *> (a))
	{
	    cout << ": " << ta->value();
	}
	else if (const LineOrderAttribute *ta =
		dynamic_cast <const LineOrderAttribute *> (a))
	{
	    cout << ": ";
	    printLineOrder (ta->value());
	}
	else if (const M33fAttribute *ta =
		dynamic_cast <const M33fAttribute *> (a))
	{
	    cout << ":\n"
		    "   (" <<
		    ta->value()[0][0] << " " <<
		    ta->value()[0][1] << " " <<
		    ta->value()[0][2] << "\n    " <<
		    ta->value()[1][0] << " " <<
		    ta->value()[1][1] << " " <<
		    ta->value()[1][2] << "\n    " <<
		    ta->value()[2][0] << " " <<
		    ta->value()[2][1] << " " <<
		    ta->value()[2][2] << ")";
	}
	else if (const M44fAttribute *ta =
		dynamic_cast <const M44fAttribute *> (a))
	{
	    cout << ":\n"
		    "   (" <<
		    ta->value()[0][0] << " " <<
		    ta->value()[0][1] << " " <<
		    ta->value()[0][2] << " " <<
		    ta->value()[0][3] << "\n    " <<
		    ta->value()[1][0] << " " <<
		    ta->value()[1][1] << " " <<
		    ta->value()[1][2] << " " <<
		    ta->value()[1][3] << "\n    " <<
		    ta->value()[2][0] << " " <<
		    ta->value()[2][1] << " " <<
		    ta->value()[2][2] << " " <<
		    ta->value()[2][3] << "\n    " <<
		    ta->value()[3][0] << " " <<
		    ta->value()[3][1] << " " <<
		    ta->value()[3][2] << " " <<
		    ta->value()[3][3] << ")";
	}
	else if (const StringAttribute *ta =
		dynamic_cast <const StringAttribute *> (a))
	{
	    cout << ": \"" << ta->value() << "\"";
	}
	else if (const V2iAttribute *ta =
		dynamic_cast <const V2iAttribute *> (a))
	{
	    cout << ": " << ta->value();
	}
	else if (const V2fAttribute *ta =
		dynamic_cast <const V2fAttribute *> (a))
	{
	    cout << ": " << ta->value();
	}
	else if (const V3iAttribute *ta =
		dynamic_cast <const V3iAttribute *> (a))
	{
	    cout << ": " << ta->value();
	}
	else if (const V3fAttribute *ta =
		dynamic_cast <const V3fAttribute *> (a))
	{
	    cout << ": " << ta->value();
	}

	cout << '\n';
    }

    cout << endl;
}

int
main(int argc, char **argv)
{
    if (argc < 2)
    {
	std::cerr << "usage: " << argv[0] << " imagefile\n";
	return 1;
    }
    else
    {
	try
	{
	    printInfo (argv[1]);
	    return 0;
	}
	catch (const std::exception &e)
	{
	    std::cerr << e.what() << std::endl;
	    return 1;
	}
    }
}

<|endoftext|>


<commit_before>// Copyright 2018, Institute for Artificial Intelligence - University of Bremen
// Author: Andrei Haidu (http://haidu.eu)

#include "SLVisLoggerSpectatorPC.h"
#include "SLVisCamera.h"
#include "Engine/DemoNetDriver.h"
#include "EngineUtils.h"
#include "ImageUtils.h"
#include "Async.h"
#include "FileHelper.h"
#include "HighResScreenshot.h"
//#include "UnrealClient.h"
//#include "GameDelegates.h"
//#include "TimerManager.h"
//#include "GenericPlatform/GenericPlatformMisc.h"

// Ctor
ASLVisLoggerSpectatorPC::ASLVisLoggerSpectatorPC()
{
	PrimaryActorTick.bCanEverTick = true;
	PrimaryActorTick.bTickEvenWhenPaused = true;
	bShouldPerformFullTickWhenPaused = true;

	UpdateRate = 0.2214f;
	ViewTargetIndex = -1;
	ViewTypeIndex = -1;
	DemoTimeSeconds = 0.f;
	NumberOfSavedImages = -1;
	NumberOfTotalImages = -1;
	FilenameSuffix = TEXT("");
}

// Called when the game starts or when spawned
void ASLVisLoggerSpectatorPC::BeginPlay()
{
	Super::BeginPlay();

	if (GetWorld()->DemoNetDriver && GetWorld()->DemoNetDriver->IsPlaying())
	{
		// Init logger
		ASLVisLoggerSpectatorPC::Init();

		// Start logger
		ASLVisLoggerSpectatorPC::Start();
	}
}

// Called when actor removed from game or game ended
void ASLVisLoggerSpectatorPC::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
	// Finish logger
	ASLVisLoggerSpectatorPC::Finish();
}

// Called to bind functionality to input
void ASLVisLoggerSpectatorPC::SetupInputComponent()
{
	Super::SetupInputComponent();
	//InputComponent->BindAction("FinishPlayback", IE_Pressed, this, &ASLVisLoggerSpectatorPC::Finish).bExecuteWhenPaused = true;
}

// Called every frame
 void ASLVisLoggerSpectatorPC::Tick(float DeltaTime)
 {
	 Super::Tick(DeltaTime);

	 if (bIsInit)
	 {
		 UE_LOG(LogTemp, Warning, TEXT("%s::%d Demo: %f/%f; Imgs: %d/%d; World: Play=%f; Real=%f"),
			 TEXT(__FUNCTION__), __LINE__,
			 DemoTimeSeconds, NetDriver->DemoTotalTime,
			 NumberOfSavedImages, NumberOfTotalImages,
			 GetWorld()->GetTimeSeconds(),
			 GetWorld()->GetRealTimeSeconds());
	 }
 }

// Init logger
void ASLVisLoggerSpectatorPC::Init()
{
	if (!bIsInit)
	{
		// Continue only if driver and viewport is available
		NetDriver = GetWorld()->DemoNetDriver;
		ViewportClient = GetWorld()->GetGameViewport();
		if (NetDriver && ViewportClient)
		{
			// Disable noisy rendering;
			ASLVisLoggerSpectatorPC::SetupRenderingProperties();

			// Screenshot image size
			GetHighResScreenshotConfig().SetResolution(640, 480, 1.0f);

			// Set the array of the camera positions
			for (TActorIterator<ASLVisCamera>Itr(GetWorld()); Itr; ++Itr)
			{
				Cameras.Add(*Itr);
			}

			// Add buffer types to visualize
			ViewTypes.Add(NAME_None); // Default will be color
			ViewTypes.Add("SceneDepth");
			ViewTypes.Add("WorldNormal");

			// Set path to store the images
			EpisodePath = FPaths::ProjectDir() + TEXT("/SemLog/Episodes/") + GetWorld()->DemoNetDriver->GetActiveReplayName() + TEXT("/");
			FPaths::RemoveDuplicateSlashes(EpisodePath);

			NumberOfTotalImages = (uint32)(NetDriver->DemoTotalTime / UpdateRate) * Cameras.Num() * ViewTypes.Num();

			// Bind callback functions
			NetDriver->OnGotoTimeDelegate.AddUObject(this, &ASLVisLoggerSpectatorPC::DemoGotoCB);
			NetDriver->OnDemoFinishPlaybackDelegate.AddUObject(this, &ASLVisLoggerSpectatorPC::Finish);
			ViewportClient->OnScreenshotCaptured().AddUObject(this, &ASLVisLoggerSpectatorPC::ScreenshotCB);

			// Flag as initialized
			bIsInit = true;
		}
	}
}

// Start logger
void ASLVisLoggerSpectatorPC::Start()
{
	if (!bIsStarted && bIsInit)
	{
		// Set camera to first target and first rendering type
		if (ASLVisLoggerSpectatorPC::SetFirstViewTarget() && ASLVisLoggerSpectatorPC::SetFirstViewType())
		{
			// Go to the beginning of the demo and start requesting screenshots
			NetDriver->GotoTimeInSeconds(DemoTimeSeconds);
		}

		// Flag as started
		bIsStarted = true;
	}
}

// Finish logger
void ASLVisLoggerSpectatorPC::Finish()
{
	if (!bIsFinished && (bIsStarted || bIsInit))
	{
		//FGenericPlatformMisc::RequestExit(false);
		//
		//FGameDelegates::Get().GetExitCommandDelegate().Broadcast();
		//FPlatformMisc::RequestExit(0);

		if (GEngine)
		{
			GEngine->DeferredCommands.Add(TEXT("QUIT_EDITOR"));
		}

		// Flag as finished
		bIsStarted = false;
		bIsInit = false;
		bIsFinished = true;
	}
}

// Set rendered image quality
void ASLVisLoggerSpectatorPC::SetupRenderingProperties()
{
	// Which anti-aliasing mode is used by default
	// 	AAM_None=None, AAM_FXAA=FXAA, AAM_TemporalAA=TemporalAA, AAM_MSAA=MSAA (Only supported with forward shading.  MSAA sample count is controlled by r.MSAACount)
	IConsoleManager::Get().FindConsoleVariable(TEXT("r.DefaultFeature.AntiAliasing"))->Set(1);

	// Whether the default for AutoExposure is enabled or not (postprocess volume/camera/game setting can still override and enable or disable it independently)
	IConsoleManager::Get().FindConsoleVariable(TEXT("r.DefaultFeature.AutoExposure"))->Set(0);

	// Whether the default for MotionBlur is enabled or not (postprocess volume/camera/game setting can still override and enable or disable it independently)
	IConsoleManager::Get().FindConsoleVariable(TEXT("r.DefaultFeature.MotionBlur"))->Set(0);

	// Defines the postprocess anti aliasing method which allows to adjust for quality or performance.
	// 0:off, 1:very low (faster FXAA), 2:low (FXAA), 3:medium (faster TemporalAA), 4:high (default TemporalAA), 5:very high, 6:max
	IConsoleManager::Get().FindConsoleVariable(TEXT("r.PostProcessAAQuality"))->Set(6);

	// Defines the motion blur method which allows to adjust for quality or performance
	// 0:off, 1:low, 2:medium, 3:high (default), 4: very high
	IConsoleManager::Get().FindConsoleVariable(TEXT("r.MotionBlurQuality"))->Set(0);

	// Whether to use screen space reflections and at what quality setting.
	// (limits the setting in the post process settings which has a different scale)
	// (costs performance, adds more visual realism but the technique has limits)
	// 0: off (default), 1: low (no glossy), 2: medium (no glossy), 3: high (glossy/using roughness, few samples), 4: very high (likely too slow for real-time)
	IConsoleManager::Get().FindConsoleVariable(TEXT("r.SSR.Quality"))->Set(4);

	// Defines the eye adaptation quality which allows to adjust for quality or performance.
	// 0: off (fastest), 1: low quality (e.g. non histogram based, not yet implemented), 2: normal quality (default), 3: high quality (e.g. screen position localized, not yet implemented)
	IConsoleManager::Get().FindConsoleVariable(TEXT("r.EyeAdaptationQuality"))->Set(0);

	// Improve the visual depth and fidelity of the scene because of a more accurate approximation of shadowing
	// 0: disabled, 1: enabled
	IConsoleManager::Get().FindConsoleVariable(TEXT("r.ContactShadows"))->Set(1);

	// This will adjust the luminance intensity of the image to accurately reproduce colors. Raising or lowering this value will result in the image mid-tones being washed-out or too dark.
	// Default 0.0f;
	IConsoleManager::Get().FindConsoleVariable(TEXT("r.TonemapperGamma"))->Set(2.2f);
}

// Called after a successful scrub
void ASLVisLoggerSpectatorPC::DemoGotoCB()
{
	// Pause the replay
	ASLVisLoggerSpectatorPC::DemoPause();

	// Request screenshot on game thread
	AsyncTask(ENamedThreads::GameThread, [this]()
	{
		ViewportClient->Viewport->TakeHighResScreenShot();
	});
}

// Called when screenshot is captured
void ASLVisLoggerSpectatorPC::ScreenshotCB(int32 SizeX, int32 SizeY, const TArray<FColor>& Bitmap)
{
	// Make sure that all alpha values are opaque.
	TArray<FColor>& BitmapRef = const_cast<TArray<FColor>&>(Bitmap);
	for (auto& Color : BitmapRef)
	{
		Color.A = 255;
	}

	// Compress image
	TArray<uint8> CompressedBitmap;
	FImageUtils::CompressImageArray(SizeX, SizeY, BitmapRef, CompressedBitmap);

	// Set path and filename
	FString Ts = FString::SanitizeFloat(DemoTimeSeconds).Replace(TEXT("."), TEXT("-"));
	FString CurrFilename = FString::Printf(TEXT("V%d_%s_%s.png"), ViewTargetIndex, *Ts, *FilenameSuffix);
	FString CurrFullPath = EpisodePath + "/" + CurrFilename;
	FPaths::RemoveDuplicateSlashes(CurrFullPath);

	// Save to file
	FFileHelper::SaveArrayToFile(CompressedBitmap, *CurrFullPath);
	NumberOfSavedImages++;

	// Check if multiple view types are required
	if (ASLVisLoggerSpectatorPC::SetNextViewType())
	{
		// Request screenshot on game thread
		AsyncTask(ENamedThreads::GameThread, [this]()
		{
			ViewportClient->Viewport->TakeHighResScreenShot();
		});
	}
	else
	{
		// Go back to the first view type
		if (ASLVisLoggerSpectatorPC::SetFirstViewType())
		{
			// Check if more views are available
			if (ASLVisLoggerSpectatorPC::SetNextViewTarget())
			{
				// Request screenshot on game thread
				AsyncTask(ENamedThreads::GameThread,[this]()
				{
					ViewportClient->Viewport->TakeHighResScreenShot();
				});
			}
			else
			{
				// Go back to the first camera target and advance in the demo
				DemoTimeSeconds += UpdateRate;
				if (ASLVisLoggerSpectatorPC::SetFirstViewTarget())
				{
					// Unpause demo to be able to scrub
					ASLVisLoggerSpectatorPC::DemoUnPause();
					NetDriver->GotoTimeInSeconds(DemoTimeSeconds);
				}
			}
		}
	}
}

// Pause demo
void ASLVisLoggerSpectatorPC::DemoPause()
{
	// else, it is already paused
	if (GetWorld()->GetWorldSettings()->Pauser == nullptr)
	{
		if (GetWorld()->DemoNetDriver != nullptr &&
			GetWorld()->DemoNetDriver->ServerConnection != nullptr &&
			GetWorld()->DemoNetDriver->ServerConnection->OwningActor != nullptr)
		{
			GetWorld()->GetWorldSettings()->Pauser = PlayerState;
		}
	}
}

// Un-pause demo
void ASLVisLoggerSpectatorPC::DemoUnPause()
{
	// else, it is already un-paused
	if (GetWorld()->GetWorldSettings()->Pauser != nullptr)
	{
		GetWorld()->GetWorldSettings()->Pauser = nullptr;
	}
}

// Check if demo is paused
bool ASLVisLoggerSpectatorPC::IsDemoPaused()
{
	// Demo is paused if no player state is set as the Pauser
	return GetWorld()->GetWorldSettings()->Pauser == nullptr;
}

// Sets the first view, returns false if there are no views at all
bool ASLVisLoggerSpectatorPC::SetFirstViewTarget()
{
	ViewTargetIndex = 0;
	if (Cameras.IsValidIndex(ViewTargetIndex))
	{
		SetViewTarget(Cameras[ViewTargetIndex], FViewTargetTransitionParams());
		return true;
	}
	else
	{
		// 0 is not a valid index, i.e. array is empty
		return false;
	}
}

// Sets the next view, returns false there are no more views
bool ASLVisLoggerSpectatorPC::SetNextViewTarget()
{
	ViewTargetIndex++;
	if (Cameras.IsValidIndex(ViewTargetIndex))
	{
		SetViewTarget(Cameras[ViewTargetIndex], FViewTargetTransitionParams());
		return true;
	}
	else
	{
		ViewTargetIndex = -1;
		return false;
	}
}

// Sets the first visualization buffer type, false if none
bool ASLVisLoggerSpectatorPC::SetFirstViewType()
{
	ViewTypeIndex = 0;
	if (ViewTypes.IsValidIndex(ViewTypeIndex))
	{
		return ASLVisLoggerSpectatorPC::SetupViewType(ViewTypes[ViewTypeIndex]);
	}
	else
	{
		// 0 is not a valid index, i.e. array is empty
		return false;
	}
}

// Sets the next visualization buffer type, returns false there are no more views
bool ASLVisLoggerSpectatorPC::SetNextViewType()
{
	ViewTypeIndex++;
	if (ViewTypes.IsValidIndex(ViewTypeIndex))
	{
		return ASLVisLoggerSpectatorPC::SetupViewType(ViewTypes[ViewTypeIndex]);
	}
	else
	{
		ViewTypeIndex = -1;
		return false;
	}
}

// Render the given view type
bool ASLVisLoggerSpectatorPC::SetupViewType(FName ViewType)
{
	// Get the console variable for switching buffer views
	static IConsoleVariable* ICVarVisTarget = IConsoleManager::Get().FindConsoleVariable(TEXT("r.BufferVisualizationTarget"));

	// Switch between buffer visualization and its types
	if (ICVarVisTarget)
	{
		if (ViewportClient->GetEngineShowFlags())
		{
			ViewportClient->GetEngineShowFlags()->SetVisualizeBuffer(ViewType == NAME_None ? false : true);
			ViewportClient->GetEngineShowFlags()->SetTonemapper(ViewType == NAME_None ? false : true);
			ICVarVisTarget->Set(*ViewType.ToString());
			return ASLVisLoggerSpectatorPC::SetupFilenameSuffix(ViewType);
		}
	}
	return false;

	//static IConsoleVariable* ICVarVisBuffer = IConsoleManager::Get().FindConsoleVariable(TEXT("ShowFlag.Visualizebuffer"));
	//// Set rendering types
	//if (ViewType == NAME_None)
	//{
	//	// Disable buffer rendering
	//	if (ICVarVisBuffer->GetInt() != 0)
	//	{
	//		ICVarVisBuffer->Set(0);
	//		return true;
	//	}
	//}
	//else if (ICVarVisBuffer && ICVarVisTarget)
	//{
	//	// Enable buffer rendering
	//	if (ICVarVisBuffer->GetInt() == 0)
	//	{
	//		ICVarVisBuffer->Set(1);
	//		// Set buffer type
	//		if (ViewportClient->GetEngineShowFlags())
	//		{
	//			ViewportClient->GetEngineShowFlags()->SetVisualizeBuffer(ViewType == NAME_None ? false : true);
	//			ViewportClient->GetEngineShowFlags()->SetTonemapper(ViewType == NAME_None ? false : true);
	//		}
	//	}
	//}
	//return false;
}

// Set the suffix of the file depending on the view type
bool ASLVisLoggerSpectatorPC::SetupFilenameSuffix(FName ViewType)
{
	if (ViewType.IsEqual(NAME_None))
	{
		FilenameSuffix = "C"; // Color
		return true;
	}
	else if (ViewType.IsEqual("SceneDepth"))
	{
		FilenameSuffix = "D"; // Depth
		return true;
	}
	else if (ViewType.IsEqual("WorldNormal"))
	{
		FilenameSuffix = "N"; // Normal
		return true;
	}
	else
	{
		// Unsupported buffer type
		return false;
	}
}<commit_msg>set resolution in non editor runs<commit_after>// Copyright 2018, Institute for Artificial Intelligence - University of Bremen
// Author: Andrei Haidu (http://haidu.eu)

#include "SLVisLoggerSpectatorPC.h"
#include "SLVisCamera.h"
#include "Engine/DemoNetDriver.h"
#include "EngineUtils.h"
#include "ImageUtils.h"
#include "Async.h"
#include "FileHelper.h"
#include "HighResScreenshot.h"
//#include "UnrealClient.h"
//#include "GameDelegates.h"
//#include "TimerManager.h"
//#include "GenericPlatform/GenericPlatformMisc.h"

// Ctor
ASLVisLoggerSpectatorPC::ASLVisLoggerSpectatorPC()
{
	PrimaryActorTick.bCanEverTick = true;
	PrimaryActorTick.bTickEvenWhenPaused = true;
	bShouldPerformFullTickWhenPaused = true;

	UpdateRate = 0.2214f;
	ViewTargetIndex = -1;
	ViewTypeIndex = -1;
	DemoTimeSeconds = 0.f;
	NumberOfSavedImages = -1;
	NumberOfTotalImages = -1;
	FilenameSuffix = TEXT("");
}

// Called when the game starts or when spawned
void ASLVisLoggerSpectatorPC::BeginPlay()
{
	Super::BeginPlay();

	if (GetWorld()->DemoNetDriver && GetWorld()->DemoNetDriver->IsPlaying())
	{
		// Init logger
		ASLVisLoggerSpectatorPC::Init();

		// Start logger
		ASLVisLoggerSpectatorPC::Start();
	}
}

// Called when actor removed from game or game ended
void ASLVisLoggerSpectatorPC::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
	// Finish logger
	ASLVisLoggerSpectatorPC::Finish();
}

// Called to bind functionality to input
void ASLVisLoggerSpectatorPC::SetupInputComponent()
{
	Super::SetupInputComponent();
	//InputComponent->BindAction("FinishPlayback", IE_Pressed, this, &ASLVisLoggerSpectatorPC::Finish).bExecuteWhenPaused = true;
}

// Called every frame
 void ASLVisLoggerSpectatorPC::Tick(float DeltaTime)
 {
	 Super::Tick(DeltaTime);

	 if (bIsInit)
	 {
		 UE_LOG(LogTemp, Warning, TEXT("%s::%d Demo: %f/%f; Imgs: %d/%d; World: Play=%f; Real=%f"),
			 TEXT(__FUNCTION__), __LINE__,
			 DemoTimeSeconds, NetDriver->DemoTotalTime,
			 NumberOfSavedImages, NumberOfTotalImages,
			 GetWorld()->GetTimeSeconds(),
			 GetWorld()->GetRealTimeSeconds());
	 }
 }

// Init logger
void ASLVisLoggerSpectatorPC::Init()
{
	if (!bIsInit)
	{
		// Continue only if driver and viewport is available
		NetDriver = GetWorld()->DemoNetDriver;
		ViewportClient = GetWorld()->GetGameViewport();
		if (NetDriver && ViewportClient)
		{
			// Disable noisy rendering;
			ASLVisLoggerSpectatorPC::SetupRenderingProperties();

			// Set screenshot image and viewport resolution size
			GetHighResScreenshotConfig().SetResolution(640, 480, 1.0f);

			// Set the display resolution for the current game view. Has no effect in the editor
			// e.g. 1280x720w for windowed, 1920x1080f for fullscreen, 1920x1080wf for windowed fullscreen
			IConsoleManager::Get().FindConsoleVariable(TEXT("r.SetRes"))->Set(TEXT("640x480"));

			// Set the array of the camera positions
			for (TActorIterator<ASLVisCamera>Itr(GetWorld()); Itr; ++Itr)
			{
				Cameras.Add(*Itr);
			}

			// Add buffer types to visualize
			ViewTypes.Add(NAME_None); // Default will be color
			ViewTypes.Add("SceneDepth");
			ViewTypes.Add("WorldNormal");

			// Set path to store the images
			EpisodePath = FPaths::ProjectDir() + TEXT("/SemLog/Episodes/") + GetWorld()->DemoNetDriver->GetActiveReplayName() + TEXT("/");
			FPaths::RemoveDuplicateSlashes(EpisodePath);

			NumberOfTotalImages = (uint32)(NetDriver->DemoTotalTime / UpdateRate) * Cameras.Num() * ViewTypes.Num();

			// Bind callback functions
			NetDriver->OnGotoTimeDelegate.AddUObject(this, &ASLVisLoggerSpectatorPC::DemoGotoCB);
			NetDriver->OnDemoFinishPlaybackDelegate.AddUObject(this, &ASLVisLoggerSpectatorPC::Finish);
			ViewportClient->OnScreenshotCaptured().AddUObject(this, &ASLVisLoggerSpectatorPC::ScreenshotCB);

			// Flag as initialized
			bIsInit = true;
		}
	}
}

// Start logger
void ASLVisLoggerSpectatorPC::Start()
{
	if (!bIsStarted && bIsInit)
	{
		// Set camera to first target and first rendering type
		if (ASLVisLoggerSpectatorPC::SetFirstViewTarget() && ASLVisLoggerSpectatorPC::SetFirstViewType())
		{
			// Go to the beginning of the demo and start requesting screenshots
			NetDriver->GotoTimeInSeconds(DemoTimeSeconds);
		}

		// Flag as started
		bIsStarted = true;
	}
}

// Finish logger
void ASLVisLoggerSpectatorPC::Finish()
{
	if (!bIsFinished && (bIsStarted || bIsInit))
	{
		//FGenericPlatformMisc::RequestExit(false);
		//
		//FGameDelegates::Get().GetExitCommandDelegate().Broadcast();
		//FPlatformMisc::RequestExit(0);

		if (GEngine)
		{
			GEngine->DeferredCommands.Add(TEXT("QUIT_EDITOR"));
		}

		// Flag as finished
		bIsStarted = false;
		bIsInit = false;
		bIsFinished = true;
	}
}

// Set rendered image quality
void ASLVisLoggerSpectatorPC::SetupRenderingProperties()
{
	// Which anti-aliasing mode is used by default
	// 	AAM_None=None, AAM_FXAA=FXAA, AAM_TemporalAA=TemporalAA, AAM_MSAA=MSAA (Only supported with forward shading.  MSAA sample count is controlled by r.MSAACount)
	IConsoleManager::Get().FindConsoleVariable(TEXT("r.DefaultFeature.AntiAliasing"))->Set(1);

	// Whether the default for AutoExposure is enabled or not (postprocess volume/camera/game setting can still override and enable or disable it independently)
	IConsoleManager::Get().FindConsoleVariable(TEXT("r.DefaultFeature.AutoExposure"))->Set(0);

	// Whether the default for MotionBlur is enabled or not (postprocess volume/camera/game setting can still override and enable or disable it independently)
	IConsoleManager::Get().FindConsoleVariable(TEXT("r.DefaultFeature.MotionBlur"))->Set(0);

	// Defines the postprocess anti aliasing method which allows to adjust for quality or performance.
	// 0:off, 1:very low (faster FXAA), 2:low (FXAA), 3:medium (faster TemporalAA), 4:high (default TemporalAA), 5:very high, 6:max
	IConsoleManager::Get().FindConsoleVariable(TEXT("r.PostProcessAAQuality"))->Set(6);

	// Defines the motion blur method which allows to adjust for quality or performance
	// 0:off, 1:low, 2:medium, 3:high (default), 4: very high
	IConsoleManager::Get().FindConsoleVariable(TEXT("r.MotionBlurQuality"))->Set(0);

	// Whether to use screen space reflections and at what quality setting.
	// (limits the setting in the post process settings which has a different scale)
	// (costs performance, adds more visual realism but the technique has limits)
	// 0: off (default), 1: low (no glossy), 2: medium (no glossy), 3: high (glossy/using roughness, few samples), 4: very high (likely too slow for real-time)
	IConsoleManager::Get().FindConsoleVariable(TEXT("r.SSR.Quality"))->Set(4);

	// Defines the eye adaptation quality which allows to adjust for quality or performance.
	// 0: off (fastest), 1: low quality (e.g. non histogram based, not yet implemented), 2: normal quality (default), 3: high quality (e.g. screen position localized, not yet implemented)
	IConsoleManager::Get().FindConsoleVariable(TEXT("r.EyeAdaptationQuality"))->Set(0);

	// Improve the visual depth and fidelity of the scene because of a more accurate approximation of shadowing
	// 0: disabled, 1: enabled
	IConsoleManager::Get().FindConsoleVariable(TEXT("r.ContactShadows"))->Set(1);

	// This will adjust the luminance intensity of the image to accurately reproduce colors. Raising or lowering this value will result in the image mid-tones being washed-out or too dark.
	// Default 0.0f;
	IConsoleManager::Get().FindConsoleVariable(TEXT("r.TonemapperGamma"))->Set(2.2f);
}

// Called after a successful scrub
void ASLVisLoggerSpectatorPC::DemoGotoCB()
{
	// Pause the replay
	ASLVisLoggerSpectatorPC::DemoPause();

	// Request screenshot on game thread
	AsyncTask(ENamedThreads::GameThread, [this]()
	{
		ViewportClient->Viewport->TakeHighResScreenShot();
	});
}

// Called when screenshot is captured
void ASLVisLoggerSpectatorPC::ScreenshotCB(int32 SizeX, int32 SizeY, const TArray<FColor>& Bitmap)
{
	// Make sure that all alpha values are opaque.
	TArray<FColor>& BitmapRef = const_cast<TArray<FColor>&>(Bitmap);
	for (auto& Color : BitmapRef)
	{
		Color.A = 255;
	}

	// Compress image
	TArray<uint8> CompressedBitmap;
	FImageUtils::CompressImageArray(SizeX, SizeY, BitmapRef, CompressedBitmap);

	// Set path and filename
	FString Ts = FString::SanitizeFloat(DemoTimeSeconds).Replace(TEXT("."), TEXT("-"));
	FString CurrFilename = FString::Printf(TEXT("V%d_%s_%s.png"), ViewTargetIndex, *Ts, *FilenameSuffix);
	FString CurrFullPath = EpisodePath + "/" + CurrFilename;
	FPaths::RemoveDuplicateSlashes(CurrFullPath);

	// Save to file
	FFileHelper::SaveArrayToFile(CompressedBitmap, *CurrFullPath);
	NumberOfSavedImages++;

	// Check if multiple view types are required
	if (ASLVisLoggerSpectatorPC::SetNextViewType())
	{
		// Request screenshot on game thread
		AsyncTask(ENamedThreads::GameThread, [this]()
		{
			ViewportClient->Viewport->TakeHighResScreenShot();
		});
	}
	else
	{
		// Go back to the first view type
		if (ASLVisLoggerSpectatorPC::SetFirstViewType())
		{
			// Check if more views are available
			if (ASLVisLoggerSpectatorPC::SetNextViewTarget())
			{
				// Request screenshot on game thread
				AsyncTask(ENamedThreads::GameThread,[this]()
				{
					ViewportClient->Viewport->TakeHighResScreenShot();
				});
			}
			else
			{
				// Go back to the first camera target and advance in the demo
				DemoTimeSeconds += UpdateRate;
				if (ASLVisLoggerSpectatorPC::SetFirstViewTarget())
				{
					// Unpause demo to be able to scrub
					ASLVisLoggerSpectatorPC::DemoUnPause();
					NetDriver->GotoTimeInSeconds(DemoTimeSeconds);
				}
			}
		}
	}
}

// Pause demo
void ASLVisLoggerSpectatorPC::DemoPause()
{
	// else, it is already paused
	if (GetWorld()->GetWorldSettings()->Pauser == nullptr)
	{
		if (GetWorld()->DemoNetDriver != nullptr &&
			GetWorld()->DemoNetDriver->ServerConnection != nullptr &&
			GetWorld()->DemoNetDriver->ServerConnection->OwningActor != nullptr)
		{
			GetWorld()->GetWorldSettings()->Pauser = PlayerState;
		}
	}
}

// Un-pause demo
void ASLVisLoggerSpectatorPC::DemoUnPause()
{
	// else, it is already un-paused
	if (GetWorld()->GetWorldSettings()->Pauser != nullptr)
	{
		GetWorld()->GetWorldSettings()->Pauser = nullptr;
	}
}

// Check if demo is paused
bool ASLVisLoggerSpectatorPC::IsDemoPaused()
{
	// Demo is paused if no player state is set as the Pauser
	return GetWorld()->GetWorldSettings()->Pauser == nullptr;
}

// Sets the first view, returns false if there are no views at all
bool ASLVisLoggerSpectatorPC::SetFirstViewTarget()
{
	ViewTargetIndex = 0;
	if (Cameras.IsValidIndex(ViewTargetIndex))
	{
		SetViewTarget(Cameras[ViewTargetIndex], FViewTargetTransitionParams());
		return true;
	}
	else
	{
		// 0 is not a valid index, i.e. array is empty
		return false;
	}
}

// Sets the next view, returns false there are no more views
bool ASLVisLoggerSpectatorPC::SetNextViewTarget()
{
	ViewTargetIndex++;
	if (Cameras.IsValidIndex(ViewTargetIndex))
	{
		SetViewTarget(Cameras[ViewTargetIndex], FViewTargetTransitionParams());
		return true;
	}
	else
	{
		ViewTargetIndex = -1;
		return false;
	}
}

// Sets the first visualization buffer type, false if none
bool ASLVisLoggerSpectatorPC::SetFirstViewType()
{
	ViewTypeIndex = 0;
	if (ViewTypes.IsValidIndex(ViewTypeIndex))
	{
		return ASLVisLoggerSpectatorPC::SetupViewType(ViewTypes[ViewTypeIndex]);
	}
	else
	{
		// 0 is not a valid index, i.e. array is empty
		return false;
	}
}

// Sets the next visualization buffer type, returns false there are no more views
bool ASLVisLoggerSpectatorPC::SetNextViewType()
{
	ViewTypeIndex++;
	if (ViewTypes.IsValidIndex(ViewTypeIndex))
	{
		return ASLVisLoggerSpectatorPC::SetupViewType(ViewTypes[ViewTypeIndex]);
	}
	else
	{
		ViewTypeIndex = -1;
		return false;
	}
}

// Render the given view type
bool ASLVisLoggerSpectatorPC::SetupViewType(FName ViewType)
{
	// Get the console variable for switching buffer views
	static IConsoleVariable* ICVarVisTarget = IConsoleManager::Get().FindConsoleVariable(TEXT("r.BufferVisualizationTarget"));

	// Switch between buffer visualization and its types
	if (ICVarVisTarget)
	{
		if (ViewportClient->GetEngineShowFlags())
		{
			ViewportClient->GetEngineShowFlags()->SetVisualizeBuffer(ViewType == NAME_None ? false : true);
			ViewportClient->GetEngineShowFlags()->SetTonemapper(ViewType == NAME_None ? false : true);
			ICVarVisTarget->Set(*ViewType.ToString());
			return ASLVisLoggerSpectatorPC::SetupFilenameSuffix(ViewType);
		}
	}
	return false;
}

// Set the suffix of the file depending on the view type
bool ASLVisLoggerSpectatorPC::SetupFilenameSuffix(FName ViewType)
{
	if (ViewType.IsEqual(NAME_None))
	{
		FilenameSuffix = "C"; // Color
		return true;
	}
	else if (ViewType.IsEqual("SceneDepth"))
	{
		FilenameSuffix = "D"; // Depth
		return true;
	}
	else if (ViewType.IsEqual("WorldNormal"))
	{
		FilenameSuffix = "N"; // Normal
		return true;
	}
	else
	{
		// Unsupported buffer type
		return false;
	}
}<|endoftext|>


<commit_before>#include "MyString.h"
#include <sstream>
#include <algorithm>

std::string NarrowString(const std::wstring& str)
{
	std::stringstream ss;
	for (size_t x = 0; x < str.length(); x++)
		ss << ss.narrow((char)str[x], '?');
	return ss.str();
}

std::wstring WidenString(const std::string& str)
{
	std::wstringstream ss;
	for (size_t x = 0; x < str.length(); x++)
		ss << ss.widen(str[x]);
	return ss.str();
}

void ToLowercase(std::string& str)
{
	std::transform(str.begin(), str.end(),str.begin(), tolower);
}

std::string FormatVarArgs(const char* fmt, va_list marker)
{
	// http://www.codeproject.com/Articles/15115/How-to-Format-a-String
	using std::string;
	using std::vector;
	string retStr;
	if (fmt) {
		// Get formatted string length adding one for NULL
		size_t len = _vscprintf(fmt, marker) + 1;

		// Create a char vector to hold the formatted string.
		vector<char> buffer(len, '\0');
		int nWritten = _vsnprintf_s(&buffer[0], buffer.size(), len, fmt, marker);
		if (nWritten > 0) retStr = &buffer[0];
	}

	return retStr;
}

std::wstring FormatVarArgsW(const wchar_t* fmt, va_list marker)
{
	// http://www.codeproject.com/Articles/15115/How-to-Format-a-String
	using std::wstring;
	using std::vector;
	wstring retStr;
	if (fmt) {
		// Get formatted string length adding one for NULL
		size_t len = _vscwprintf(fmt, marker) + 1;

		// Create a char vector to hold the formatted string.
		vector<wchar_t> buffer(len, '\0');
		int nWritten = _vsnwprintf_s(&buffer[0], buffer.size(), len, fmt, marker);
		if (nWritten > 0) retStr = &buffer[0];
	}

	return retStr;
}

std::wstring m_swprintf(const wchar_t *fmt, ...)
{
	va_list ArgList;
	va_start(ArgList, fmt);
	std::wstring str = FormatVarArgsW(fmt, ArgList);
	va_end(ArgList);
	return str;
}

std::string m_sprintf(const char *fmt, ...)
{
	va_list ArgList;
	va_start(ArgList, fmt);
	std::string str = FormatVarArgs(fmt, ArgList);
	va_end(ArgList);
	return str;
}
template <>
const std::string ArgsSearchString<std::string>()
{
	return std::string("\"' ");
}

template <>
const std::wstring ArgsSearchString<std::wstring>()
{
	return std::wstring(L"\"' ");
}
// Get the substring ending at the next occurrence of c.
// start is the position (inclusive) where to start searching from.
// end is the position after the next occurrence, or npos if none.
/*template <class T, class _Tc>
T GetStringEndingAtNext(const T& input, _Tc c, size_t start, size_t& end)
{
	size_t found = input.find_first_of(c, start);
	T out = input.substr(start, found - start);
	end = found == input.npos ? input.npos : found + 1;
	return out;
}

std::vector<std::string> TokenizeArgs(const std::string& in)
{
	using namespace std;
	vector<string> out;
	const string tofind = "\"' "; // " ' or space

	size_t curpos = 0;
	while (curpos != in.npos)
	{
		curpos = in.find_first_not_of(' ', curpos);
		if (curpos == in.npos) break;
		size_t nextpos = in.find_first_of(tofind, curpos);
		if (nextpos == in.npos) { // no more matches, copy everything.
			out.push_back(in.substr(curpos, in.npos));
			break;
		}
		char c = in.at(nextpos);
		size_t startfrom = c == ' ' ? curpos : curpos + 1;
		string token = GetStringEndingAtNext<string, char>(in, c, startfrom, curpos);
		if (token.size()) out.push_back(token);
	}
	return out;
}

std::vector<std::wstring> TokenizeWArgs(const std::wstring& in)
{
	using namespace std;
	vector<wstring> out;
	const wstring tofind = L"\"' "; // " ' or space

	size_t curpos = 0;
	while (curpos != in.npos)
	{
		curpos = in.find_first_not_of(' ', curpos);
		if (curpos == in.npos) break;
		size_t nextpos = in.find_first_of(tofind, curpos);
		if (nextpos == in.npos) { // no more matches, copy everything.
			out.push_back(in.substr(curpos, in.npos));
			break;
		}
		wchar_t c = in.at(nextpos);
		size_t startfrom = c == ' ' ? curpos : curpos + 1;
		wstring token = GetStringEndingAtNext<wstring, wchar_t>(in, c, startfrom, curpos);
		if (token.size()) out.push_back(token);
	}
	return out;
}
*/<commit_msg>templated TokenizeArgs, removed old code.<commit_after>#include "MyString.h"
#include <sstream>
#include <algorithm>

std::string NarrowString(const std::wstring& str)
{
	std::stringstream ss;
	for (size_t x = 0; x < str.length(); x++)
		ss << ss.narrow((char)str[x], '?');
	return ss.str();
}

std::wstring WidenString(const std::string& str)
{
	std::wstringstream ss;
	for (size_t x = 0; x < str.length(); x++)
		ss << ss.widen(str[x]);
	return ss.str();
}

void ToLowercase(std::string& str)
{
	std::transform(str.begin(), str.end(),str.begin(), tolower);
}

std::string FormatVarArgs(const char* fmt, va_list marker)
{
	// http://www.codeproject.com/Articles/15115/How-to-Format-a-String
	using std::string;
	using std::vector;
	string retStr;
	if (fmt) {
		// Get formatted string length adding one for NULL
		size_t len = _vscprintf(fmt, marker) + 1;

		// Create a char vector to hold the formatted string.
		vector<char> buffer(len, '\0');
		int nWritten = _vsnprintf_s(&buffer[0], buffer.size(), len, fmt, marker);
		if (nWritten > 0) retStr = &buffer[0];
	}

	return retStr;
}

std::wstring FormatVarArgsW(const wchar_t* fmt, va_list marker)
{
	// http://www.codeproject.com/Articles/15115/How-to-Format-a-String
	using std::wstring;
	using std::vector;
	wstring retStr;
	if (fmt) {
		// Get formatted string length adding one for NULL
		size_t len = _vscwprintf(fmt, marker) + 1;

		// Create a char vector to hold the formatted string.
		vector<wchar_t> buffer(len, '\0');
		int nWritten = _vsnwprintf_s(&buffer[0], buffer.size(), len, fmt, marker);
		if (nWritten > 0) retStr = &buffer[0];
	}

	return retStr;
}

std::wstring m_swprintf(const wchar_t *fmt, ...)
{
	va_list ArgList;
	va_start(ArgList, fmt);
	std::wstring str = FormatVarArgsW(fmt, ArgList);
	va_end(ArgList);
	return str;
}

std::string m_sprintf(const char *fmt, ...)
{
	va_list ArgList;
	va_start(ArgList, fmt);
	std::string str = FormatVarArgs(fmt, ArgList);
	va_end(ArgList);
	return str;
}

// Used in TokenizeArgs
template <>
const std::string ArgsSearchString<std::string>()
{
	return std::string("\"' ");
}

// Used in TokenizeArgs
template <>
const std::wstring ArgsSearchString<std::wstring>()
{
	return std::wstring(L"\"' ");
}
<|endoftext|>


<commit_before>#include "../common.h"
#include "String.h"
#include "UtfUtil.h"

namespace ax_gen {

std::ostream& StrView::onStreamOut(std::ostream& s) const {
	const int n = 512;
	char tmp[n+1];
	if (_size < n) {
		memcpy(tmp, _data, _size);
		tmp[_size] = 0;
		s << tmp;
	}else{
		String tmp = *this;
		s << tmp.c_str();
	}
	return s;
}

StrView StrView::getFromPrefix(const StrView& prefix) {
	if (prefix._size <= _size) {
		if (strncmp(_data, prefix._data, (size_t)prefix._size) == 0) {
			return slice(prefix._size);
		}
	}
	return StrView();
}

StrView StrView::slice(int from) const {
	if (from < 0) from = 0;
	return slice(from, _size - from);
}

StrView StrView::slice(int from, int size) const {
	if (from < 0) from = 0;
	if (from >= _size) return StrView();
	auto end = from + size;
	if (end > _size) end = _size;
	return StrView(_data + from, end - from);
}

bool StrView::startsWith(const StrView& v) const {
	auto n = v.size();
	if (n < v.size()) return false;
	auto t = slice(0, n);
	return t == v;
}

int StrView::indexOfChar(char ch) const {
	auto* end = _data + _size;
	for (auto* p = _data; p < end; p++) {
		if (*p == ch) {
			return (int)(p - _data);
		}
	}
	return -1;
}

int StrView::lastIndexOfChar(char ch) const {
	if (_size <= 0) return false;
	auto* end = _data + _size;
	for (auto* p = end - 1; p >= _data; p--) {
		if (*p == ch) {
			return (int)(p - _data);
		}
	}
	return -1;
}

int StrView::indexOfAnyCharIn(const StrView& charList) const {
	auto* end = _data + _size;
	for (auto* p = _data; p < end; p++) {
		if (charList.indexOfChar(*p) >= 0) {
			return (int)(p - _data);
		}
	}
	return -1;
}

int StrView::lastIndexOfAnyCharIn(const StrView& charList) const {
	if (_size <= 0) return false;
	auto* end = _data + _size;
	for (auto* p = end - 1; p >= _data; p--) {
		if (charList.lastIndexOfChar(*p) >= 0) {
			return (int)(p - _data);
		}
	}
	return -1;
}

StrView::SplitResult StrView::splitByChar(char ch) const {
	auto index = indexOfChar(ch);
	if (index < 0) {
		return SplitResult(*this, StrView());
	}
	return SplitResult(slice(0, index), slice(index + 1));
}

StrView::SplitResult StrView::splitByCharInList(const StrView& charList) const {
	auto index = indexOfAnyCharIn(charList);
	if (index < 0) {
		return SplitResult(*this, StrView());
	}
	return SplitResult(slice(0, index), slice(index + 1));
}

StrView::SplitResult StrView::splitEndByChar(char ch) const {
	auto index = lastIndexOfChar(ch);
	if (index < 0) {
		return SplitResult(*this, StrView());
	}
	return SplitResult(slice(0, index), slice(index + 1));
}

StrView::SplitResult StrView::splitEndByAnyCharIn(const StrView& charList) const {
	auto index = lastIndexOfAnyCharIn(charList);
	if (index < 0) {
		return SplitResult(*this, StrView());
	}
	return SplitResult(slice(0, index), slice(index + 1));
}

void String::replaceChars(char from, char to) {
	int n = size();
	for (int i = 0; i < n; i++) {
		auto& ch = _p[(size_t)i];
		if ( ch == from) ch = to;
	}
}

void String::_append(int v) {
	char buf[63+1];
	snprintf(buf, 63, "%d", v);
	buf[63] = 0;
	_append(StrView_c_str(buf));
}

void String::_append(double v) {
	char buf[63+1];
	snprintf(buf, 63, "%f", v);
	buf[63] = 0;
	_append(StrView_c_str(buf));
}

void String::appendUtf(const wchar_t* wc, int wc_len) {
	int oldSize = size();
	int n = UtfUtil::getConvertedCount<wchar_t, char>(wc, wc_len);

	int newSize = oldSize + n;

	Vector<char> buf;
	buf.resize(newSize);

	UtfUtil::convert(buf.data(), buf.size(), wc, wc_len);
	_append( StrView(buf.data(), buf.size()) );
}

void String::appendUtf(const WString& w) {
	appendUtf(w.c_str(), w.size());
}

void String::setQuoted(StrView v) {
	clear();
	append('\"');
	for (auto ch : v) {
		switch (ch) {
			case '\"':	append("\\\"");	break;
			case '\\':	append("\\\\");	break;
			default:	append(ch);		break;
		}
	}
	append('\"');
}

void WString::appendUtf(const StrView& v) {
	int oldSize = size();
	int n = UtfUtil::getConvertedCount<char, wchar_t>(v.data(), v.size());

	int newSize = oldSize + n;

	Vector<wchar_t> buf;
	buf.resize(newSize);

	UtfUtil::convert(buf.data(), buf.size(), v.data(), v.size());
	_p.append(buf.data(), (size_t)buf.size());
}

} //namespace
<commit_msg>xcode build<commit_after>#include "../common.h"
#include "String.h"
#include "UtfUtil.h"

namespace ax_gen {

std::ostream& StrView::onStreamOut(std::ostream& s) const {
	const int n = 512;
	char tmp[n+1];
	if (_size < n) {
		memcpy(tmp, _data, (size_t)_size);
		tmp[_size] = 0;
		s << tmp;
	}else{
		String tmp = *this;
		s << tmp.c_str();
	}
	return s;
}

StrView StrView::getFromPrefix(const StrView& prefix) {
	if (prefix._size <= _size) {
		if (strncmp(_data, prefix._data, (size_t)prefix._size) == 0) {
			return slice(prefix._size);
		}
	}
	return StrView();
}

StrView StrView::slice(int from) const {
	if (from < 0) from = 0;
	return slice(from, _size - from);
}

StrView StrView::slice(int from, int size) const {
	if (from < 0) from = 0;
	if (from >= _size) return StrView();
	auto end = from + size;
	if (end > _size) end = _size;
	return StrView(_data + from, end - from);
}

bool StrView::startsWith(const StrView& v) const {
	auto n = v.size();
	if (n < v.size()) return false;
	auto t = slice(0, n);
	return t == v;
}

int StrView::indexOfChar(char ch) const {
	auto* end = _data + _size;
	for (auto* p = _data; p < end; p++) {
		if (*p == ch) {
			return (int)(p - _data);
		}
	}
	return -1;
}

int StrView::lastIndexOfChar(char ch) const {
	if (_size <= 0) return false;
	auto* end = _data + _size;
	for (auto* p = end - 1; p >= _data; p--) {
		if (*p == ch) {
			return (int)(p - _data);
		}
	}
	return -1;
}

int StrView::indexOfAnyCharIn(const StrView& charList) const {
	auto* end = _data + _size;
	for (auto* p = _data; p < end; p++) {
		if (charList.indexOfChar(*p) >= 0) {
			return (int)(p - _data);
		}
	}
	return -1;
}

int StrView::lastIndexOfAnyCharIn(const StrView& charList) const {
	if (_size <= 0) return false;
	auto* end = _data + _size;
	for (auto* p = end - 1; p >= _data; p--) {
		if (charList.lastIndexOfChar(*p) >= 0) {
			return (int)(p - _data);
		}
	}
	return -1;
}

StrView::SplitResult StrView::splitByChar(char ch) const {
	auto index = indexOfChar(ch);
	if (index < 0) {
		return SplitResult(*this, StrView());
	}
	return SplitResult(slice(0, index), slice(index + 1));
}

StrView::SplitResult StrView::splitByCharInList(const StrView& charList) const {
	auto index = indexOfAnyCharIn(charList);
	if (index < 0) {
		return SplitResult(*this, StrView());
	}
	return SplitResult(slice(0, index), slice(index + 1));
}

StrView::SplitResult StrView::splitEndByChar(char ch) const {
	auto index = lastIndexOfChar(ch);
	if (index < 0) {
		return SplitResult(*this, StrView());
	}
	return SplitResult(slice(0, index), slice(index + 1));
}

StrView::SplitResult StrView::splitEndByAnyCharIn(const StrView& charList) const {
	auto index = lastIndexOfAnyCharIn(charList);
	if (index < 0) {
		return SplitResult(*this, StrView());
	}
	return SplitResult(slice(0, index), slice(index + 1));
}

void String::replaceChars(char from, char to) {
	int n = size();
	for (int i = 0; i < n; i++) {
		auto& ch = _p[(size_t)i];
		if ( ch == from) ch = to;
	}
}

void String::_append(int v) {
	char buf[63+1];
	snprintf(buf, 63, "%d", v);
	buf[63] = 0;
	_append(StrView_c_str(buf));
}

void String::_append(double v) {
	char buf[63+1];
	snprintf(buf, 63, "%f", v);
	buf[63] = 0;
	_append(StrView_c_str(buf));
}

void String::appendUtf(const wchar_t* wc, int wc_len) {
	int oldSize = size();
	int n = UtfUtil::getConvertedCount<wchar_t, char>(wc, wc_len);

	int newSize = oldSize + n;

	Vector<char> buf;
	buf.resize(newSize);

	UtfUtil::convert(buf.data(), buf.size(), wc, wc_len);
	_append( StrView(buf.data(), buf.size()) );
}

void String::appendUtf(const WString& w) {
	appendUtf(w.c_str(), w.size());
}

void String::setQuoted(StrView v) {
	clear();
	append('\"');
	for (auto ch : v) {
		switch (ch) {
			case '\"':	append("\\\"");	break;
			case '\\':	append("\\\\");	break;
			default:	append(ch);		break;
		}
	}
	append('\"');
}

void WString::appendUtf(const StrView& v) {
	int oldSize = size();
	int n = UtfUtil::getConvertedCount<char, wchar_t>(v.data(), v.size());

	int newSize = oldSize + n;

	Vector<wchar_t> buf;
	buf.resize(newSize);

	UtfUtil::convert(buf.data(), buf.size(), v.data(), v.size());
	_p.append(buf.data(), (size_t)buf.size());
}

} //namespace
<|endoftext|>


<commit_before>namespace plb{

  inline PlbCaseTimer::PlbCaseTimer()
  {
    index_t global("global",GLOBAL_IND);
    indexMap.insert(global);

    clockVec.push_back(clock());
    timeVec.push_back(0);
    activeVec.push_back(false);
  }

  inline void PlbCaseTimer::registerCustom(char const *name_)
  {
    std::string name(name_);

    index_map_t::const_iterator it = indexMap.find(name);

    if(it != indexMap.end()){
      std::string errmsg("Error: custom timer ");
      errmsg.append(name);
      errmsg.append(" registered twice\n");
      throw PlbCaseTimerException(errmsg.c_str());
    }

    int index = clockVec.size();
    index_t ins(name,index);
    indexMap.insert(ins);

    clockVec.push_back(clock());
    timeVec.push_back(0.);
    activeVec.push_back(false);
  }

  inline void PlbCaseTimer::startGlobal()
  {
    if(!global::mpi().isMainProcessor()) return;
    start(GLOBAL_IND);
  }

  inline void PlbCaseTimer::stopGlobal()
  {
    if(!global::mpi().isMainProcessor()) return;
    stop(GLOBAL_IND);
  }

  inline void PlbCaseTimer::startCustom(char const *name_)
  {
    if(!global::mpi().isMainProcessor()) return;
    int index = getIndex(name_);
    start(index);
  }

  inline void PlbCaseTimer::stopCustom(char const *name_)
  {
    if(!global::mpi().isMainProcessor()) return;
    int index = getIndex(name_);
    stop(index);
  }

  // get index for custom name

  inline int PlbCaseTimer::getIndex(char const *name_)
  {
    std::string name(name_);

    index_map_t::const_iterator it = indexMap.find(name);

    if(it == indexMap.end()){
      std::string errmsg("Error: custom timer ");
      errmsg.append(name);
      errmsg.append(" not found\n");
      throw PlbCaseTimerException(errmsg.c_str());
    }

    return it->second;
  }

  // generic start/stop functions that actually handle
  // the bookkeeping with clock_t

  inline void PlbCaseTimer::start(int const index)
  {
    if(activeVec[index]){
      std::string errmsg("Error: custom timer started twice");
      throw PlbCaseTimerException(errmsg.c_str());
    }

    clockVec[index] = clock();
    activeVec[index] = true;
  }

  inline void PlbCaseTimer::stop(int const index)
  {
    if(!activeVec[index]){
      std::string errmsg("Error: custom timer that should be stopped was not started before");
      throw PlbCaseTimerException(errmsg.c_str());
    }

    clock_t now = clock();

    timeVec[index] += now - clockVec[index];
    activeVec[index] = false;
  }

  inline double PlbCaseTimer::computeOther()
  {
    clock_t sum(0);
    for(pluint i=1;i<timeVec.size();i++)
      sum += timeVec[i];

    clock_t other = timeVec[0] - sum;
    return other/CPS;
  }

  inline void PlbCaseTimer::writeLog(Parallel_ostream &out)
  {
    for(index_map_t::iterator it = indexMap.begin();it!=indexMap.end();++it){
      out << "Timer " << it->first << " : "
          << timeVec[it->second]/CPS << " seconds, "
          << (double)timeVec[it->second]/(double)timeVec[GLOBAL_IND]*100 << "%" << std::endl;
    }

    double other = computeOther();
    out << "Timer other : " << other << " seconds, "
        << other/(timeVec[GLOBAL_IND]/CPS) << "%" << std::endl;

  }

  inline void PlbCaseTimer::writeLogJSON(std::string fname)
  {
    fname.insert(0,global::directories().getOutputDir());

    plb_ofstream out(fname.c_str());

    out << "{\n";
    out << "  \"timer\" : [\n";

    index_map_t::iterator it = indexMap.begin();
    for(index_map_t::iterator it = indexMap.begin();it!=indexMap.end();++it){
      out << "    {";
      out << " \"name\" : \"" << it->first << "\","
          << " \"time\" : " << timeVec[it->second]/CPS
          << " \"fraction\" : " << (double)timeVec[it->second]/(double)timeVec[GLOBAL_IND];
      out << " },\n";
    }

    out << "    {";
    out << "\"name\" : \"other\", ";
    out << "\"time\" : " << computeOther() << ", ";
    out << "\"fraction\" : " << computeOther()/(timeVec[GLOBAL_IND]/CPS);
    out << " }\n";

    out << "  ]\n";
    out << "}\n";

    out.close();
  }
}; // namespace plb
<commit_msg>corrected json output of plbCaseTimer<commit_after>namespace plb{

  inline PlbCaseTimer::PlbCaseTimer()
  {
    index_t global("global",GLOBAL_IND);
    indexMap.insert(global);

    clockVec.push_back(clock());
    timeVec.push_back(0);
    activeVec.push_back(false);
  }

  inline void PlbCaseTimer::registerCustom(char const *name_)
  {
    std::string name(name_);

    index_map_t::const_iterator it = indexMap.find(name);

    if(it != indexMap.end()){
      std::string errmsg("Error: custom timer ");
      errmsg.append(name);
      errmsg.append(" registered twice\n");
      throw PlbCaseTimerException(errmsg.c_str());
    }

    int index = clockVec.size();
    index_t ins(name,index);
    indexMap.insert(ins);

    clockVec.push_back(clock());
    timeVec.push_back(0.);
    activeVec.push_back(false);
  }

  inline void PlbCaseTimer::startGlobal()
  {
    if(!global::mpi().isMainProcessor()) return;
    start(GLOBAL_IND);
  }

  inline void PlbCaseTimer::stopGlobal()
  {
    if(!global::mpi().isMainProcessor()) return;
    stop(GLOBAL_IND);
  }

  inline void PlbCaseTimer::startCustom(char const *name_)
  {
    if(!global::mpi().isMainProcessor()) return;
    int index = getIndex(name_);
    start(index);
  }

  inline void PlbCaseTimer::stopCustom(char const *name_)
  {
    if(!global::mpi().isMainProcessor()) return;
    int index = getIndex(name_);
    stop(index);
  }

  // get index for custom name

  inline int PlbCaseTimer::getIndex(char const *name_)
  {
    std::string name(name_);

    index_map_t::const_iterator it = indexMap.find(name);

    if(it == indexMap.end()){
      std::string errmsg("Error: custom timer ");
      errmsg.append(name);
      errmsg.append(" not found\n");
      throw PlbCaseTimerException(errmsg.c_str());
    }

    return it->second;
  }

  // generic start/stop functions that actually handle
  // the bookkeeping with clock_t

  inline void PlbCaseTimer::start(int const index)
  {
    if(activeVec[index]){
      std::string errmsg("Error: custom timer started twice");
      throw PlbCaseTimerException(errmsg.c_str());
    }

    clockVec[index] = clock();
    activeVec[index] = true;
  }

  inline void PlbCaseTimer::stop(int const index)
  {
    if(!activeVec[index]){
      std::string errmsg("Error: custom timer that should be stopped was not started before");
      throw PlbCaseTimerException(errmsg.c_str());
    }

    clock_t now = clock();

    timeVec[index] += now - clockVec[index];
    activeVec[index] = false;
  }

  inline double PlbCaseTimer::computeOther()
  {
    clock_t sum(0);
    for(pluint i=1;i<timeVec.size();i++)
      sum += timeVec[i];

    clock_t other = timeVec[0] - sum;
    return other/CPS;
  }

  inline void PlbCaseTimer::writeLog(Parallel_ostream &out)
  {
    for(index_map_t::iterator it = indexMap.begin();it!=indexMap.end();++it){
      out << "Timer " << it->first << " : "
          << timeVec[it->second]/CPS << " seconds, "
          << (double)timeVec[it->second]/(double)timeVec[GLOBAL_IND]*100 << "%" << std::endl;
    }

    double other = computeOther();
    out << "Timer other : " << other << " seconds, "
        << other/(timeVec[GLOBAL_IND]/CPS) << "%" << std::endl;

  }

  inline void PlbCaseTimer::writeLogJSON(std::string fname)
  {
    fname.insert(0,global::directories().getOutputDir());

    plb_ofstream out(fname.c_str());

    out << "{\n";
    out << "  \"timer\" : [\n";

    index_map_t::iterator it = indexMap.begin();
    for(index_map_t::iterator it = indexMap.begin();it!=indexMap.end();++it){
      out << "    {";
      out << " \"name\" : \"" << it->first << "\","
          << " \"time\" : " << timeVec[it->second]/CPS
          << " \"fraction\" : " << (double)timeVec[it->second]/(double)timeVec[GLOBAL_IND];
      out << " },\n";
    }

    out << "    {";
    out << " \"name\" : \"other\",";
    out << " \"time\" : " << computeOther() << ",";
    out << " \"fraction\" : " << computeOther()/(timeVec[GLOBAL_IND]/CPS);
    out << " }\n";

    out << "  ]\n";
    out << "}\n";

    out.close();
  }
}; // namespace plb
<|endoftext|>


<commit_before>/////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009-2010 Alan Wright. All rights reserved.
// Distributable under the terms of either the Apache License (Version 2.0)
// or the GNU Lesser General Public License.
/////////////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "TestUtils.h"
#include "FileUtils.h"

#define BOOST_TEST_MODULE "Lucene"
#define BOOST_TEST_NO_MAIN

#include <boost/test/included/unit_test.hpp>

using namespace Lucene;

int main(int argc, char* argv[])
{
    String testDir;
    uint64_t startTime = MiscUtils::currentTimeMillis();

    for (int32_t i = 0; i < argc; ++i)
    {
        if (strncmp(argv[i], "--test_dir", 9) == 0)
        {
            String testParam = StringUtils::toUnicode(argv[i]);
            Collection<String> vals = StringUtils::split(testParam, L"=");
            if (vals.size() == 2)
            {
                testDir = vals[1];
                boost::replace_all(testDir, L"\"", L"");
                boost::trim(testDir);
                break;
            }
        }
    }

    if (testDir.empty())
        testDir = L"../test/testfiles";

    if (!FileUtils::isDirectory(testDir))
    {
        std::wcout << L"Test directory not found. (override default by using --test_dir=\"test/testfiles\")\n";
        return 1;
    }

    setTestDir(testDir);

    int testMain = boost::unit_test::unit_test_main(init_unit_test_suite, argc, argv);

    std::wcout << L"*** Test duration: " << (MiscUtils::currentTimeMillis() - startTime) / 1000 << L" sec\n";

    return testMain;
}
<commit_msg>simplify test_dir parameter<commit_after>/////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009-2010 Alan Wright. All rights reserved.
// Distributable under the terms of either the Apache License (Version 2.0)
// or the GNU Lesser General Public License.
/////////////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "TestUtils.h"
#include "FileUtils.h"

#define BOOST_TEST_MODULE "Lucene"
#define BOOST_TEST_NO_MAIN

#include <boost/test/included/unit_test.hpp>

using namespace Lucene;

int main(int argc, char* argv[])
{
    String testDir;
    uint64_t startTime = MiscUtils::currentTimeMillis();

    for (int32_t i = 0; i < argc; ++i)
    {
        if (strncmp(argv[i], "--test_dir", 9) == 0)
        {
            String testParam = StringUtils::toUnicode(argv[i]);
            Collection<String> vals = StringUtils::split(testParam, L"=");
            if (vals.size() == 2)
            {
                testDir = vals[1];
                boost::replace_all(testDir, L"\"", L"");
                boost::trim(testDir);
                break;
            }
        }
    }

    if (testDir.empty())
    {
        testDir = L"../../test/testfiles";
        if (!FileUtils::isDirectory(testDir))
        {
            testDir = L"../test/testfiles";
            if (!FileUtils::isDirectory(testDir))
                testDir = L"./test/testfiles";
        }
    }

    if (!FileUtils::isDirectory(testDir))
    {
        std::wcout << L"Test directory not found. (override default by using --test_dir=\"./test/testfiles\")\n";
        return 1;
    }

    setTestDir(testDir);

    int testMain = boost::unit_test::unit_test_main(init_unit_test_suite, argc, argv);

    std::wcout << L"*** Test duration: " << (MiscUtils::currentTimeMillis() - startTime) / 1000 << L" sec\n";

    return testMain;
}
<|endoftext|>


<commit_before>/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay                     *
*                                                                          *
* Distributed under the terms of the BSD 3-Clause License.                 *
*                                                                          *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/

#include <fstream>
#include <iostream>
#include <map>
#include <string>

#include "gtest/gtest.h"
#include "xsimd/config/xsimd_instruction_set.hpp"

using info_map_type = std::map<int, std::string>;

info_map_type init_instruction_map()
{
    info_map_type res;
    res[XSIMD_X86_SSE_VERSION] = "Intel SSE";
    res[XSIMD_X86_SSE2_VERSION] = "Intel SSE2";
    res[XSIMD_X86_SSE3_VERSION] = "Intel SSE3";
    res[XSIMD_X86_SSSE3_VERSION] = "Intel SSSE3";
    res[XSIMD_X86_SSE4_1_VERSION] = "Intel SSE4.1";
    res[XSIMD_X86_SSE4_2_VERSION] = "Intel SSE4.2";
    res[XSIMD_X86_AVX_VERSION] = "Intel AVX";
    res[XSIMD_X86_FMA3_VERSION] = "Intel FMA3";
    res[XSIMD_X86_AVX2_VERSION] = "Intel AVX2";
    res[XSIMD_X86_MIC_VERSION] = "Intel MIC";
    res[XSIMD_X86_AMD_SSE4A_VERSION] = "AMD SSE4A";
    res[XSIMD_X86_AMD_FMA4_VERSION] = "AMD FMA4";
    res[XSIMD_X86_AMD_XOP_VERSION] = "AMD XOP";
    res[XSIMD_PPC_VMX_VERSION] = "PowerPC VM";
    res[XSIMD_PPC_VSX_VERSION] = "PowerPC VSX";
    res[XSIMD_PPC_QPX_VERSION] = "PowerPC QPX";
    res[XSIMD_ARM7_NEON_VERSION] = "ARMv7 Neon";
    res[XSIMD_ARM8_32_NEON_VERSION] = "ARMv8 32bit Neon";
    res[XSIMD_ARM8_64_NEON_VERSION] = "ARMv8 64bit Neon";
    res[XSIMD_VERSION_NUMBER_NOT_AVAILABLE] = "No SIMD available";
    return res;
}

std::string get_instruction_set_name()
{
    static info_map_type info_map(init_instruction_map());
    return info_map[XSIMD_INSTR_SET];
}

int main(int argc, char* argv[])
{
    std::ofstream out("log/xsimd_info.log", std::ios_base::out);
    std::string instruction_set = get_instruction_set_name();
    out << "Instruction set: " << instruction_set << std::endl;
    std::cout << "Instruction set: " << instruction_set << std::endl;

    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
<commit_msg>overwriting of instruction set fixed<commit_after>/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay                     *
*                                                                          *
* Distributed under the terms of the BSD 3-Clause License.                 *
*                                                                          *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/

#include <fstream>
#include <iostream>
#include <map>
#include <string>

#include "gtest/gtest.h"
#include "xsimd/config/xsimd_instruction_set.hpp"

using info_map_type = std::map<int, std::string>;

info_map_type init_instruction_map()
{
    info_map_type res;
#ifdef XSIMD_X86_INSTR_SET_AVAILABLE
    res[XSIMD_X86_SSE_VERSION] = "Intel SSE";
    res[XSIMD_X86_SSE2_VERSION] = "Intel SSE2";
    res[XSIMD_X86_SSE3_VERSION] = "Intel SSE3";
    res[XSIMD_X86_SSSE3_VERSION] = "Intel SSSE3";
    res[XSIMD_X86_SSE4_1_VERSION] = "Intel SSE4.1";
    res[XSIMD_X86_SSE4_2_VERSION] = "Intel SSE4.2";
    res[XSIMD_X86_AVX_VERSION] = "Intel AVX";
    res[XSIMD_X86_FMA3_VERSION] = "Intel FMA3";
    res[XSIMD_X86_AVX2_VERSION] = "Intel AVX2";
    res[XSIMD_X86_MIC_VERSION] = "Intel MIC";
    res[XSIMD_X86_AMD_SSE4A_VERSION] = "AMD SSE4A";
    res[XSIMD_X86_AMD_FMA4_VERSION] = "AMD FMA4";
    res[XSIMD_X86_AMD_XOP_VERSION] = "AMD XOP";
#elif defined(XSIMD_PPC_INSTR_SET_AVAILABLE)
    res[XSIMD_PPC_VMX_VERSION] = "PowerPC VM";
    res[XSIMD_PPC_VSX_VERSION] = "PowerPC VSX";
    res[XSIMD_PPC_QPX_VERSION] = "PowerPC QPX";
#else
    res[XSIMD_ARM7_NEON_VERSION] = "ARMv7 Neon";
    res[XSIMD_ARM8_32_NEON_VERSION] = "ARMv8 32bit Neon";
    res[XSIMD_ARM8_64_NEON_VERSION] = "ARMv8 64bit Neon";
    res[XSIMD_VERSION_NUMBER_NOT_AVAILABLE] = "No SIMD available";
#endif
    return res;
}

std::string get_instruction_set_name()
{
    static info_map_type info_map(init_instruction_map());
    return info_map[XSIMD_INSTR_SET];
}

int main(int argc, char* argv[])
{
    std::ofstream out("log/xsimd_info.log", std::ios_base::out);
    std::string instruction_set = get_instruction_set_name();
    out << "Instruction set: " << instruction_set << std::endl;
    std::cout << "Instruction set: " << instruction_set << std::endl;

    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>/*

Copyright (c) 2008, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * 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.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.

*/

#include <iostream>
#include <boost/config.hpp>

int test_main();

extern bool tests_failure;

int main()
{
#ifdef O_NONBLOCK
	// on darwin, stdout is set to non-blocking mode by default
	// which sometimes causes tests to fail with EAGAIN just
	// by printing logs
	int flags = fcntl(stdout, F_GETFL, 0);
	fcntl(stdout, F_SETFL, flags & ~O_NONBLOCK);
#endif

#ifndef BOOST_NO_EXCEPTIONS
	try
	{
#endif
		test_main();
		return tests_failure ? 1 : 0;
#ifndef BOOST_NO_EXCEPTIONS
	}
	catch (std::exception const& e)
	{
		std::cerr << "Terminated with exception: \"" << e.what() << "\"\n";
		return 1;
	}
	catch (...)
	{
		std::cerr << "Terminated with unknown exception\n";
		return 1;
	}
#endif
}

<commit_msg>stdout non-blocking fix for tests<commit_after>/*

Copyright (c) 2008, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * 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.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.

*/

#include <iostream>
#include <boost/config.hpp>
#include <fcntl.h>

int test_main();

extern bool tests_failure;

int main()
{
#ifdef O_NONBLOCK
	// on darwin, stdout is set to non-blocking mode by default
	// which sometimes causes tests to fail with EAGAIN just
	// by printing logs
	int flags = fcntl(fileno(stdout), F_GETFL, 0);
	fcntl(fileno(stdout), F_SETFL, flags & ~O_NONBLOCK);
	flags = fcntl(fileno(stderr), F_GETFL, 0);
	fcntl(fileno(stderr), F_SETFL, flags & ~O_NONBLOCK);
#endif

#ifndef BOOST_NO_EXCEPTIONS
	try
	{
#endif
		test_main();
#ifndef BOOST_NO_EXCEPTIONS
	}
	catch (std::exception const& e)
	{
		std::cerr << "Terminated with exception: \"" << e.what() << "\"\n";
		tests_failure = true;
	}
	catch (...)
	{
		std::cerr << "Terminated with unknown exception\n";
		tests_failure = true;
	}
#endif
	fflush(stdout);
	fflush(stderr);
	return tests_failure ? 1 : 0;
}

<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <time.h>

#include "fakescript.h"
#ifndef WIN32
#include "gperftools/profiler.h"
#endif

int cfunc1(int a, int b)
{
    return a - b;
}

class class1
{
public:
    class1()
    {
        b = 10;
    }
    int memfunc1(int a)
    {
        return a - b;
    }
private:
    int b;
};

int main(int argc, const char *argv[])
{
    if (argc < 2)
    {
        return 0;
    }

    fake * fk = newfake();

    fkopenbaselib(fk);

    fkreg(fk, "cfunc1", cfunc1);
    class1 c1;
    fkreg(fk, "memfunc1", &class1::memfunc1);

    for (int i = 0; i < 10000; i++)
        fkparse(fk, argv[1]);
    if (fkerror(fk))
    {
        printf("parse error %d, %s\n", fkerror(fk), fkerrorstr(fk));
        return 0;
    }

	int ret = 0;

	unsigned int begin,end;

    // inter
	begin = time(0);

#ifndef WIN32
	ProfilerStart("testinter.prof");
#endif

#ifndef _DEBUG
	for (int i = 0; i < 9000000; i++)
#else
	for (int i = 0; i < 1; i++)
#endif
	{
		ret = fkrun<int>(fk, "myfunc1", 1, 2);
		if (fkerror(fk))
		{
			printf("call fail errorno %d, %s\n", fkerror(fk), fkerrorstr(fk));
			return 0;
		}
	}

#ifndef WIN32
	ProfilerStop();
#endif

	end = time(0);

	printf("call ret %d %d\n", ret, end - begin);

	delfake(fk);

	char c;
	std::cin >> c;

    return 0;
}

<commit_msg>asasgasg<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <time.h>

#include "fakescript.h"
#ifndef WIN32
#include "gperftools/profiler.h"
#endif

int cfunc1(int a, int b)
{
    return a - b;
}

class class1
{
public:
    class1()
    {
        b = 10;
    }
    int memfunc1(int a)
    {
        return a - b;
    }
private:
    int b;
};

int main(int argc, const char *argv[])
{
    if (argc < 2)
    {
        return 0;
    }

    fake * fk = newfake();

    fkopenbaselib(fk);

    fkreg(fk, "cfunc1", cfunc1);
    class1 c1;
    fkreg(fk, "memfunc1", &class1::memfunc1);

    fkparse(fk, argv[1]);
    if (fkerror(fk))
    {
        printf("parse error %d, %s\n", fkerror(fk), fkerrorstr(fk));
        return 0;
    }

	int ret = 0;

	unsigned int begin,end;

    // inter
	begin = time(0);

#ifndef WIN32
	ProfilerStart("testinter.prof");
#endif

#ifndef _DEBUG
	for (int i = 0; i < 9000000; i++)
#else
	for (int i = 0; i < 1; i++)
#endif
	{
		ret = fkrun<int>(fk, "myfunc1", 1, 2);
		if (fkerror(fk))
		{
			printf("call fail errorno %d, %s\n", fkerror(fk), fkerrorstr(fk));
			return 0;
		}
	}

#ifndef WIN32
	ProfilerStop();
#endif

	end = time(0);

	printf("call ret %d %d\n", ret, end - begin);

	delfake(fk);

	char c;
	std::cin >> c;

    return 0;
}

<|endoftext|>


<commit_before>
#include <cstring>
#include <cstdlib>

#include "lest.hpp"
#include "z85.h"
#include "z85.hpp"

using namespace std;

const string c_badfood = "baadfoodbaadfoodbaadfoodbaadfood";

// Checks for buffer overruns
class strict_buf
{
   string m_buf;

public:
   explicit strict_buf(size_t i_size)
      : m_buf(c_badfood + string(i_size + 1, '\0') + c_badfood)
   {
   }

   char* p()
   {
      return &m_buf[0] + c_badfood.size();
   }

   std::string str() const
   {
      size_t count = c_badfood.size();

      return m_buf.substr(count, m_buf.size() - 2 * count - 1);
   }

   ~strict_buf()
   {
      size_t count = c_badfood.size();

      const bool strict_buf_bad_food =
         m_buf.substr(0, count)           != c_badfood ||
         m_buf[m_buf.size()-1-count]      != '\0'      ||
         m_buf.substr(m_buf.size()-count) != c_badfood;

      EXPECT(strict_buf_bad_food == false);
   }
};

template<typename Fn>
void for_random_data(size_t divisibleBy, Fn f)
{
   srand(0); //magic seed)

   std::string data;

   for (size_t i = 0; i < 10000; ++i)
   {
      const char ch = rand() % 256;
      data += ch;

      if (data.size() % divisibleBy == 0)
      {
         f(data);
      }
   }
}

const lest::test specification[] =
{
   "Hello world!", []
   {
      EXPECT(z85::encode(string("\x86\x4F\xD2\x6F\xB5\x59\xF7\x5B")) == "HelloWorld");
   },

   "Test strict buffer", []
   {
      {
         strict_buf buf_holder(0);
         char* buf = buf_holder.p();

         EXPECT(buf[-1] != '\0');
         EXPECT(buf[0]  == '\0');
         EXPECT(buf[1]  != '\0');
      }
      {
         strict_buf buf_holder(1);
         char* buf = buf_holder.p();

         EXPECT(buf[-1] != '\0');
         EXPECT(buf[0]  == '\0');
         EXPECT(buf[1]  == '\0');
         EXPECT(buf[2]  != '\0');
      }
   },

   "Test unsafe", []
   {
      auto test = [](const string& bin, const string& txt)
      {
         strict_buf txt_buf(txt.size());
         strict_buf bin_buf(bin.size());

         char* txt_end = Z85_encode_unsafe(bin.c_str(), bin.c_str() + bin.size(), txt_buf.p());
         char* bin_end = Z85_decode_unsafe(txt_buf.p(), txt_end, bin_buf.p());

         EXPECT((txt_end - txt_buf.p()) == (int)txt.size());
         EXPECT((bin_end - bin_buf.p()) == (int)bin.size());
         return bin_buf.str() == bin && txt_buf.str() == txt;
      };

      EXPECT(test("", ""));
      EXPECT(test("\x86\x4F\xD2\x6F\xB5\x59\xF7\x5B", "HelloWorld"));
      EXPECT(test("\x8E\x0B\xDD\x69\x76\x28\xB9\x1D\x8F\x24\x55\x87\xEE\x95\xC5\xB0"
                  "\x4D\x48\x96\x3F\x79\x25\x98\x77\xB4\x9C\xD9\x06\x3A\xEA\xD3\xB7",
                  "JTKVSB%%)wK0E.X)V>+}o?pNmC{O&4W4b!Ni{Lh6"));
   },

   "Test no padding", []
   {
      auto test = [](const string& bin, const string& txt)
      {
         strict_buf txt_buf(txt.size());
         strict_buf bin_buf(bin.size());

         size_t txt_written = Z85_encode(bin.c_str(), txt_buf.p(), bin.size());
         size_t bin_written = Z85_decode(txt_buf.p(), bin_buf.p(), txt_written);

         EXPECT(txt_written == txt.size());
         EXPECT(bin_written == bin.size());
         return bin_buf.str() == bin && txt_buf.str() == txt;
      };

      EXPECT(test("", ""));
      EXPECT(test("\x86\x4F\xD2\x6F", "Hello"));
      EXPECT(test("\x86\x4F\xD2\x6F\xB5\x59\xF7\x5B", "HelloWorld"));
      EXPECT(test("\x8E\x0B\xDD\x69\x76\x28\xB9\x1D\x8F\x24\x55\x87\xEE\x95\xC5\xB0"
                  "\x4D\x48\x96\x3F\x79\x25\x98\x77\xB4\x9C\xD9\x06\x3A\xEA\xD3\xB7",
                  "JTKVSB%%)wK0E.X)V>+}o?pNmC{O&4W4b!Ni{Lh6"));
   },

   "Test with padding", []
   {
      auto test = [](const string& bin, const string& txt)
      {
         strict_buf txt_buf(txt.size());
         strict_buf bin_buf(bin.size());

         size_t txt_written = Z85_encode_with_padding(bin.c_str(), txt_buf.p(), bin.size());
         size_t bin_written = Z85_decode_with_padding(txt_buf.p(), bin_buf.p(), txt_written);

         EXPECT(txt_written == txt.size());
         EXPECT(bin_written == bin.size());
         return bin_buf.str() == bin && txt_buf.str() == txt;
      };

      EXPECT(test("", ""));
//!!! ABORT TRAP, CHECK THIS      EXPECT(test("\x86\x4F\xD2\x6F\xB5\x59\xF7\x5B", "HelloWorld"));
      EXPECT(test("\x86\x4F\xD2\x6F\xB5\x59\xF7\x5B", "4HelloWorld"));
      EXPECT(test("\x8E\x0B\xDD\x69\x76\x28\xB9\x1D\x8F\x24\x55\x87\xEE\x95\xC5\xB0"
                  "\x4D\x48\x96\x3F\x79\x25\x98\x77\xB4\x9C\xD9\x06\x3A\xEA\xD3\xB7",
                  "4JTKVSB%%)wK0E.X)V>+}o?pNmC{O&4W4b!Ni{Lh6"));
   },

   "Test no padding roundtrip", []
   {
      for_random_data(4, [](const string& bin)
      {
         const string txt     = z85::encode(bin);
         const string new_bin = z85::decode(txt);

         EXPECT(new_bin == bin);
      });
   },

   "Test with padding roundtrip", []
   {
      for_random_data(1, [](const string& bin)
      {
         const string txt     = z85::encode_with_padding(bin);
         const string new_bin = z85::decode_with_padding(txt);

         EXPECT(new_bin == bin);
      });
   },

   "Test Z85_encode_bound()", []
   {
      char buf[1300];
      std::string input;
      for (size_t i = 0; i < 1000; i += 4)
      {
         const size_t estimate = Z85_encode_bound(input.size());
         const size_t encoded = Z85_encode(input.c_str(), buf, input.size());
         EXPECT(estimate == encoded);
         input += i       % 256;
         input += (i + 1) % 256;
         input += (i + 2) % 256;
         input += (i + 3) % 256;
      }
   },

   "Test Z85_decode_bound()", []
   {
      char buf[1300];
      std::string input;
      for (size_t i = 0; i < 1000; i += 5)
      {
         const size_t estimate = Z85_decode_bound(input.size());
         const size_t decoded = Z85_decode(input.c_str(), buf, input.size());
         EXPECT(estimate == decoded);
         input += i       % 256;
         input += (i + 1) % 256;
         input += (i + 2) % 256;
         input += (i + 3) % 256;
         input += (i + 4) % 256;
      }
   },

   "Test Z85_encode_with_padding_bound()", []
   {
      char buf[1300];
      std::string input;
      for (size_t i = 0; i < 1000; ++i)
      {
         const size_t estimate = Z85_encode_with_padding_bound(input.size());
         const size_t encoded = Z85_encode_with_padding(input.c_str(), buf, input.size());
         EXPECT(estimate == encoded);
         input += i % 256;
      }
   },

   "Test Z85_decode_with_padding_bound()", []
   {
      char buf[1300];
      char buf2[1300];
      std::string input;
      for (size_t i = 0; i < 1000; ++i)
      {
         const size_t encoded = Z85_encode_with_padding(input.c_str(), buf, input.size());
         const size_t estimate = Z85_decode_with_padding_bound(buf, encoded);
         const size_t decoded = Z85_decode_with_padding(buf, buf2, encoded);
         EXPECT(estimate == decoded);
         input += i % 256;
      }
   }

};

int main()
{
   return lest::run(specification);
}

<commit_msg>Abort trap in tests due throwing exception in strict_buf destructor by EXPECT(). Added with_strict_buf and using it to check buffer.<commit_after>
#include <cstring>
#include <cstdlib>

#include "lest.hpp"
#include "z85.h"
#include "z85.hpp"

using namespace std;

const string c_badfood = "baadfoodbaadfoodbaadfoodbaadfood";

// Checks for buffer overruns
class strict_buf
{
   string m_buf;

public:
   explicit strict_buf(size_t i_size)
      : m_buf(c_badfood + string(i_size + 1, '\0') + c_badfood)
   {
   }

   char* p()
   {
      return &m_buf[0] + c_badfood.size();
   }

   std::string data() const
   {
      size_t count = c_badfood.size();

      return m_buf.substr(count, m_buf.size() - 2 * count - 1);
   }

   void check_buffer()
   {
      size_t count = c_badfood.size();

      const bool strict_buf_bad_food =
         m_buf.substr(0, count)           != c_badfood ||
         m_buf[m_buf.size()-1-count]      != '\0'      ||
         m_buf.substr(m_buf.size()-count) != c_badfood;

      EXPECT(strict_buf_bad_food == false);
   }
};

template<typename Fn>
void with_strict_buf(size_t bufSize, Fn f)
{
   strict_buf buf(bufSize);
   f(buf);
   buf.check_buffer();
}

template<typename Fn>
void for_random_data(size_t divisibleBy, Fn f)
{
   srand(0); //magic seed)

   std::string data;

   for (size_t i = 0; i < 10000; ++i)
   {
      const char ch = rand() % 256;
      data += ch;

      if (data.size() % divisibleBy == 0)
      {
         f(data);
      }
   }
}

const lest::test specification[] =
{
   "Hello world!", []
   {
      EXPECT(z85::encode(string("\x86\x4F\xD2\x6F\xB5\x59\xF7\x5B")) == "HelloWorld");
   },

   "Test strict buffer", []
   {
      {
         strict_buf buf_holder(0);
         char* buf = buf_holder.p();

         EXPECT(buf[-1] != '\0');
         EXPECT(buf[0]  == '\0');
         EXPECT(buf[1]  != '\0');
      }
      {
         strict_buf buf_holder(1);
         char* buf = buf_holder.p();

         EXPECT(buf[-1] != '\0');
         EXPECT(buf[0]  == '\0');
         EXPECT(buf[1]  == '\0');
         EXPECT(buf[2]  != '\0');
      }
   },

   "Test unsafe", []
   {
      auto test = [](const string& bin, const string& txt)
      {
         with_strict_buf(txt.size(), [&](strict_buf& txt_buf) {
         with_strict_buf(bin.size(), [&](strict_buf& bin_buf) {

         char* txt_end = Z85_encode_unsafe(bin.c_str(), bin.c_str() + bin.size(), txt_buf.p());
         char* bin_end = Z85_decode_unsafe(txt_buf.p(), txt_end, bin_buf.p());

         EXPECT((txt_end - txt_buf.p()) == (int)txt.size());
         EXPECT((bin_end - bin_buf.p()) == (int)bin.size());
         EXPECT(bin_buf.data() == bin);
         EXPECT(txt_buf.data() == txt);

         });});
      };

      test("", "");
      test("\x86\x4F\xD2\x6F\xB5\x59\xF7\x5B", "HelloWorld");
      test("\x8E\x0B\xDD\x69\x76\x28\xB9\x1D\x8F\x24\x55\x87\xEE\x95\xC5\xB0"
           "\x4D\x48\x96\x3F\x79\x25\x98\x77\xB4\x9C\xD9\x06\x3A\xEA\xD3\xB7",
           "JTKVSB%%)wK0E.X)V>+}o?pNmC{O&4W4b!Ni{Lh6");
   },

   "Test no padding", []
   {
      auto test = [](const string& bin, const string& txt)
      {
         with_strict_buf(txt.size(), [&](strict_buf& txt_buf) {
         with_strict_buf(bin.size(), [&](strict_buf& bin_buf) {

         size_t txt_written = Z85_encode(bin.c_str(), txt_buf.p(), bin.size());
         size_t bin_written = Z85_decode(txt_buf.p(), bin_buf.p(), txt_written);

         EXPECT(txt_written == txt.size());
         EXPECT(bin_written == bin.size());
         EXPECT(bin_buf.data() == bin);
         EXPECT(txt_buf.data() == txt);

         });});
      };

      test("", "");
      test("\x86\x4F\xD2\x6F", "Hello");
      test("\x86\x4F\xD2\x6F\xB5\x59\xF7\x5B", "HelloWorld");
      test("\x8E\x0B\xDD\x69\x76\x28\xB9\x1D\x8F\x24\x55\x87\xEE\x95\xC5\xB0"
           "\x4D\x48\x96\x3F\x79\x25\x98\x77\xB4\x9C\xD9\x06\x3A\xEA\xD3\xB7",
           "JTKVSB%%)wK0E.X)V>+}o?pNmC{O&4W4b!Ni{Lh6");
   },

   "Test with padding", []
   {
      auto test = [](const string& bin, const string& txt)
      {
         with_strict_buf(txt.size(), [&](strict_buf& txt_buf) {
         with_strict_buf(bin.size(), [&](strict_buf& bin_buf) {

         size_t txt_written = Z85_encode_with_padding(bin.c_str(), txt_buf.p(), bin.size());
         size_t bin_written = Z85_decode_with_padding(txt_buf.p(), bin_buf.p(), txt_written);

         EXPECT(txt_written == txt.size());
         EXPECT(bin_written == bin.size());
         EXPECT(bin_buf.data() == bin);
         EXPECT(txt_buf.data() == txt);

         });});
      };

      test("", "");
      test("\x86\x4F\xD2\x6F\xB5\x59\xF7\x5B", "4HelloWorld");
      test("\x8E\x0B\xDD\x69\x76\x28\xB9\x1D\x8F\x24\x55\x87\xEE\x95\xC5\xB0"
           "\x4D\x48\x96\x3F\x79\x25\x98\x77\xB4\x9C\xD9\x06\x3A\xEA\xD3\xB7",
           "4JTKVSB%%)wK0E.X)V>+}o?pNmC{O&4W4b!Ni{Lh6");
   },

   "Test no padding roundtrip", []
   {
      for_random_data(4, [](const string& bin)
      {
         const string txt     = z85::encode(bin);
         const string new_bin = z85::decode(txt);

         EXPECT(new_bin == bin);
      });
   },

   "Test with padding roundtrip", []
   {
      for_random_data(1, [](const string& bin)
      {
         const string txt     = z85::encode_with_padding(bin);
         const string new_bin = z85::decode_with_padding(txt);

         EXPECT(new_bin == bin);
      });
   },

   "Test Z85_encode_bound()", []
   {
      char buf[1300];
      std::string input;
      for (size_t i = 0; i < 1000; i += 4)
      {
         const size_t estimate = Z85_encode_bound(input.size());
         const size_t encoded = Z85_encode(input.c_str(), buf, input.size());
         EXPECT(estimate == encoded);
         input += i       % 256;
         input += (i + 1) % 256;
         input += (i + 2) % 256;
         input += (i + 3) % 256;
      }
   },

   "Test Z85_decode_bound()", []
   {
      char buf[1300];
      std::string input;
      for (size_t i = 0; i < 1000; i += 5)
      {
         const size_t estimate = Z85_decode_bound(input.size());
         const size_t decoded = Z85_decode(input.c_str(), buf, input.size());
         EXPECT(estimate == decoded);
         input += i       % 256;
         input += (i + 1) % 256;
         input += (i + 2) % 256;
         input += (i + 3) % 256;
         input += (i + 4) % 256;
      }
   },

   "Test Z85_encode_with_padding_bound()", []
   {
      char buf[1300];
      std::string input;
      for (size_t i = 0; i < 1000; ++i)
      {
         const size_t estimate = Z85_encode_with_padding_bound(input.size());
         const size_t encoded = Z85_encode_with_padding(input.c_str(), buf, input.size());
         EXPECT(estimate == encoded);
         input += i % 256;
      }
   },

   "Test Z85_decode_with_padding_bound()", []
   {
      char buf[1300];
      char buf2[1300];
      std::string input;
      for (size_t i = 0; i < 1000; ++i)
      {
         const size_t encoded = Z85_encode_with_padding(input.c_str(), buf, input.size());
         const size_t estimate = Z85_decode_with_padding_bound(buf, encoded);
         const size_t decoded = Z85_decode_with_padding(buf, buf2, encoded);
         EXPECT(estimate == decoded);
         input += i % 256;
      }
   }

};

int main()
{
   return lest::run(specification);
}

<|endoftext|>


<commit_before>#include "vtk.h"

main ()
{
  vtkRenderMaster rm;
  vtkRenderWindow *renWin;
  vtkRenderer *ren1;
  vtkRenderWindowInteractor *iren;
  vtkActor *outlineActor;
  vtkActor *contActor;
  vtkPolyMapper *outlineMapper, *contMapper;
  vtkSampleFunction *sample;
  vtkQuadric *quadric;
  vtkOutlineFilter *outline;
  vtkContourFilter *contours;

  renWin = rm.MakeRenderWindow();
  iren = renWin->MakeRenderWindowInteractor();
  ren1 = renWin->MakeRenderer();

  // Quadric definition
  quadric = new vtkQuadric;
    quadric->SetCoefficients(.5,1,.2,0,.1,0,0,.2,0,0);

  sample = new vtkSampleFunction;
    sample->SetSampleDimensions(50,50,50);
    sample->SetImplicitFunction(quadric);

  // Create five surfaces F(x,y,z) = constant between range specified
  contours = new vtkContourFilter;
    contours->SetInput(sample->GetOutput());
    contours->GenerateValues(5, 0.0, 1.2);

  contMapper = vtkPolyMapper::New();
    contMapper->SetInput(contours->GetOutput());
    contMapper->SetScalarRange(0.0, 1.2);

  contActor = vtkActor::New();
    contActor->SetMapper(contMapper);

  // Create outline
  outline = new vtkOutlineFilter;
    outline->SetInput(sample->GetOutput());

  outlineMapper = vtkPolyMapper::New();
    outlineMapper->SetInput(outline->GetOutput());

  outlineActor = vtkActor::New();
    outlineActor->SetMapper(outlineMapper);
    outlineActor->GetProperty()->SetColor(0,0,0);

  ren1->SetBackground(1,1,1);
  ren1->AddActors(contActor);
  ren1->AddActors(outlineActor);

  renWin->Render();

  // interact with data
  iren->Start();
}
<commit_msg>brought up to date<commit_after>#include "vtk.h"

main ()
{
  vtkRenderWindow *renWin;
  vtkRenderer *ren1;
  vtkRenderWindowInteractor *iren;
  vtkActor *outlineActor;
  vtkActor *contActor;
  vtkPolyMapper *outlineMapper, *contMapper;
  vtkSampleFunction *sample;
  vtkQuadric *quadric;
  vtkOutlineFilter *outline;
  vtkContourFilter *contours;

  ren1 = vtkRenderer::New();
  renWin = vtkRenderWindow::New();
  renWin->AddRenderer(ren1);
  iren = vtkRenderWindowInteractor::New();
  iren->SetRenderWindow(renWin);

  // Quadric definition
  quadric = vtkQuadric::New();
    quadric->SetCoefficients(.5,1,.2,0,.1,0,0,.2,0,0);

  sample = vtkSampleFunction::New();
    sample->SetSampleDimensions(50,50,50);
    sample->SetImplicitFunction(quadric);

  // Create five surfaces F(x,y,z) = constant between range specified
  contours = vtkContourFilter::New();
    contours->SetInput(sample->GetOutput());
    contours->GenerateValues(5, 0.0, 1.2);

  contMapper = vtkPolyMapper::New();
    contMapper->SetInput(contours->GetOutput());
    contMapper->SetScalarRange(0.0, 1.2);

  contActor = vtkActor::New();
    contActor->SetMapper(contMapper);

  // Create outline
  outline = vtkOutlineFilter::New();
    outline->SetInput(sample->GetOutput());

  outlineMapper = vtkPolyMapper::New();
    outlineMapper->SetInput(outline->GetOutput());

  outlineActor = vtkActor::New();
    outlineActor->SetMapper(outlineMapper);
    outlineActor->GetProperty()->SetColor(0,0,0);

  ren1->SetBackground(1,1,1);
  ren1->AddActor(contActor);
  ren1->AddActor(outlineActor);

  renWin->Render();

  // interact with data
  iren->Start();
}
<|endoftext|>


<commit_before>#include "VarExp.h"
#include "Context.h"

namespace sexp_cpp
{

  int VarExp::Evaluate(Context& context) const
  {
    return context.Lookup(getVarName());
  }

  const std::string& VarExp::getVarName() const
  {
    return mVarName;
  }

} // sexp_cpp

<commit_msg>removing old file<commit_after><|endoftext|>