<commit_before>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------

#include "cling/Interpreter/CIFactory.h"

#include "ChainedConsumer.h"

#include "clang/AST/ASTContext.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Version.h"
#include "clang/Driver/ArgList.h"
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Job.h"
#include "clang/Driver/Tool.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Lex/Preprocessor.h"

#include "llvm/LLVMContext.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"

using namespace clang;

namespace cling {
  //
  //  Dummy function so we can use dladdr to find the executable path.
  //
  void locate_cling_executable()
  {
  }

   /// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs.
   /// Returns NULL on error.
   static const clang::driver::ArgStringList
   *GetCC1Arguments(clang::DiagnosticsEngine *Diagnostics,
                    clang::driver::Compilation *Compilation) {
      // We expect to get back exactly one Command job, if we didn't something
      // failed. Extract that job from the Compilation.
      const clang::driver::JobList &Jobs = Compilation->getJobs();
      if (!Jobs.size() || !isa<clang::driver::Command>(*Jobs.begin())) {
         // diagnose this...
         return NULL;
      }

      // The one job we find should be to invoke clang again.
      const clang::driver::Command *Cmd = cast<clang::driver::Command>(*Jobs.begin());
      if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
         // diagnose this...
         return NULL;
      }

      return &Cmd->getArguments();
   }

   CompilerInstance* CIFactory::createCI(llvm::StringRef code,
                                         int argc,
                                         const char* const *argv,
                                         const char* llvmdir) {
      return createCI(llvm::MemoryBuffer::getMemBuffer(code), argc, argv,
                      llvmdir);
   }

  CompilerInstance* CIFactory::createCI(llvm::MemoryBuffer* buffer,
                                        int argc,
                                        const char* const *argv,
                                        const char* llvmdir){
    // Create an instance builder, passing the llvmdir and arguments.
    //
    //  Initialize the llvm library.
    //
    // If not set, exception handling will not be turned on
    llvm::JITExceptionHandling = true;
    llvm::InitializeNativeTarget();
    llvm::InitializeAllAsmPrinters();
    llvm::sys::Path resource_path;
    if (llvmdir) {
      resource_path = llvmdir;
      resource_path.appendComponent("lib");
      resource_path.appendComponent("clang");
      resource_path.appendComponent(CLANG_VERSION_STRING);
    } else {
      // FIXME: The first arg really does need to be argv[0] on FreeBSD.
      //
      // Note: The second arg is not used for Apple, FreeBSD, Linux,
      //       or cygwin, and can only be used on systems which support
      //       the use of dladdr().
      //
      // Note: On linux and cygwin this uses /proc/self/exe to find the path.
      //
      // Note: On Apple it uses _NSGetExecutablePath().
      //
      // Note: On FreeBSD it uses getprogpath().
      //
      // Note: Otherwise it uses dladdr().
      //
      resource_path = CompilerInvocation::GetResourcesPath("cling",
                                       (void*)(intptr_t) locate_cling_executable
                                                           );
    }

     //______________________________________
     DiagnosticOptions DefaultDiagnosticOptions;
     DefaultDiagnosticOptions.ShowColors = 1;
     TextDiagnosticPrinter* DiagnosticPrinter
     = new TextDiagnosticPrinter(llvm::errs(), DefaultDiagnosticOptions);
     DiagnosticsEngine* Diagnostics = new DiagnosticsEngine(
       llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs>(
          new DiagnosticIDs()), DiagnosticPrinter, /*Owns it*/ true); // LEAKS!

     std::vector<const char*> argvCompile(argv, argv + argc);
     // We do C++ by default; append right after argv[0] name
     // Only insert it if there is no other "-x":
     bool haveMinusX = false;
     for (const char* const* iarg = argv; !haveMinusX && iarg < argv + argc; ++iarg) {
        haveMinusX = !strcmp(*iarg, "-x");
     }
     if (!haveMinusX) {
        argvCompile.insert(argvCompile.begin() + 1,"-x");
        argvCompile.insert(argvCompile.begin() + 2, "c++");
     }
     argvCompile.push_back("-c");
     argvCompile.push_back("-");

     bool IsProduction = false;
     assert(IsProduction = true && "set IsProduction if asserts are on.");
     clang::driver::Driver Driver(argv[0], llvm::sys::getDefaultTargetTriple(),
                                  "cling.out",
                                  IsProduction,
                                  *Diagnostics);
     //Driver.setWarnMissingInput(false);
     Driver.setCheckInputsExist(false); // think foo.C(12)
     llvm::OwningPtr<clang::driver::Compilation>
       Compilation(Driver.BuildCompilation(
         llvm::ArrayRef<const char*>(&(argvCompile[0]), argvCompile.size())));
     const clang::driver::ArgStringList* CC1Args
       = GetCC1Arguments(Diagnostics, Compilation.get());
     if (CC1Args == NULL) {
          return 0;
     }
     clang::CompilerInvocation*
       Invocation = new clang::CompilerInvocation; // LEAKS!
     clang::CompilerInvocation::CreateFromArgs(*Invocation, CC1Args->data() + 1,
                                               CC1Args->data() + CC1Args->size(),
                                               *Diagnostics);
     Invocation->getFrontendOpts().DisableFree = true;

     // Update ResourceDir
     if (Invocation->getHeaderSearchOpts().UseBuiltinIncludes &&
         !resource_path.empty()) {
        // header search opts' entry for resource_path/include isn't
        // updated by providing a new resource path; update it manually.
        clang::HeaderSearchOptions& Opts = Invocation->getHeaderSearchOpts();
        llvm::sys::Path oldResInc(Opts.ResourceDir);
        oldResInc.appendComponent("include");
        llvm::sys::Path newResInc(resource_path);
        newResInc.appendComponent("include");
        bool foundOldResInc = false;
        for (unsigned i = 0, e = Opts.UserEntries.size();
             !foundOldResInc && i != e; ++i) {
           HeaderSearchOptions::Entry &E = Opts.UserEntries[i];
           if (!E.IsUserSupplied && !E.IsFramework
               && E.Group == clang::frontend::System && E.IgnoreSysRoot
               && E.IsInternal && !E.ImplicitExternC
               && oldResInc.str() == E.Path) {
              E.Path = newResInc.str();
              foundOldResInc = true;
           }
        }
        if (!foundOldResInc) {
           llvm::report_fatal_error("Cannot update include for resource path (old entry not found)!");
        }
        Opts.ResourceDir = resource_path.str();
     }

    // Create and setup a compiler instance.
    CompilerInstance* CI = new CompilerInstance();
    CI->setInvocation(Invocation);

    CI->createDiagnostics(CC1Args->size(), CC1Args->data() + 1);
    {
      //
      //  Buffer the error messages while we process
      //  the compiler options.
      //

      // Set the language options, which cling needs
      SetClingCustomLangOpts(CI->getLangOpts());

      CI->getInvocation().getPreprocessorOpts().addMacroDef("__CLING__");
      if (CI->getDiagnostics().hasErrorOccurred()) {
        delete CI;
        CI = 0;
        return 0;
      }
    }
     CI->setTarget(TargetInfo::CreateTargetInfo(CI->getDiagnostics(),
                                               Invocation->getTargetOpts()));
    if (!CI->hasTarget()) {
      delete CI;
      CI = 0;
      return 0;
    }
    CI->getTarget().setForcedLangOptions(CI->getLangOpts());
    SetClingTargetLangOpts(CI->getLangOpts(), CI->getTarget());

    // Set up source and file managers
    CI->createFileManager();
    CI->createSourceManager(CI->getFileManager());

    // Set up the memory buffer
    if (buffer)
      CI->getSourceManager().createMainFileIDForMemBuffer(buffer);

    // Set up the preprocessor
    CI->createPreprocessor();
    Preprocessor& PP = CI->getPreprocessor();
    PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
                                           PP.getLangOptions());

    // Set up the ASTContext
    ASTContext *Ctx = new ASTContext(CI->getLangOpts(),
                                     PP.getSourceManager(), &CI->getTarget(), PP.getIdentifierTable(),
                                     PP.getSelectorTable(), PP.getBuiltinInfo(), 0);
    CI->setASTContext(Ctx);

    // Set up the ASTConsumers
    CI->setASTConsumer(new ChainedConsumer());

    // Set up Sema
    CodeCompleteConsumer* CCC = 0;
    CI->createSema(TU_Prefix, CCC);

    // Set CodeGen options
    // CI->getCodeGenOpts().DebugInfo = 1; // want debug info
    // CI->getCodeGenOpts().EmitDeclMetadata = 1; // For unloading, for later
    CI->getCodeGenOpts().OptimizationLevel = 0; // see pure SSA, that comes out
    // When asserts are on, TURN ON not compare the VerifyModule
    assert(CI->getCodeGenOpts().VerifyModule = 1);
    return CI;
  }

  void CIFactory::SetClingCustomLangOpts(LangOptions& Opts) {
    Opts.EmitAllDecls = 1;
    Opts.ObjCNonFragileABI2 = 0;
    Opts.Exceptions = 1;
    Opts.CXXExceptions = 1;
    Opts.Deprecated = 1;
  }

  void CIFactory::SetClingTargetLangOpts(LangOptions& Opts,
                                         const TargetInfo& Target) {
    if (Target.getTriple().getOS() == llvm::Triple::Win32) {
      Opts.MicrosoftExt = 1;
      Opts.MSCVersion = 1300;
      // Should fix http://llvm.org/bugs/show_bug.cgi?id=10528
      Opts.DelayedTemplateParsing = 1;
    } else {
      Opts.MicrosoftExt = 0;
    }
    if (Target.getTriple().getArch() == llvm::Triple::x86) {
       Opts.ObjCNonFragileABI = 1;
    } else {
       Opts.ObjCNonFragileABI = 0;
    }
    if (Target.getTriple().isOSDarwin()) {
       Opts.NeXTRuntime = 1;
    } else {
       Opts.NeXTRuntime = 0;
    }
  }
} // end namespace
<commit_msg>80 column rule 2 spaces indentation<commit_after>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------

#include "cling/Interpreter/CIFactory.h"

#include "ChainedConsumer.h"

#include "clang/AST/ASTContext.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Version.h"
#include "clang/Driver/ArgList.h"
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Job.h"
#include "clang/Driver/Tool.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Lex/Preprocessor.h"

#include "llvm/LLVMContext.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"

using namespace clang;

namespace cling {
  //
  //  Dummy function so we can use dladdr to find the executable path.
  //
  void locate_cling_executable()
  {
  }

  /// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs
  /// Returns NULL on error.
  static const clang::driver::ArgStringList
  *GetCC1Arguments(clang::DiagnosticsEngine *Diagnostics,
		   clang::driver::Compilation *Compilation) {
    // We expect to get back exactly one Command job, if we didn't something
    // failed. Extract that job from the Compilation.
    const clang::driver::JobList &Jobs = Compilation->getJobs();
    if (!Jobs.size() || !isa<clang::driver::Command>(*Jobs.begin())) {
      // diagnose this...
      return NULL;
    }

    // The one job we find should be to invoke clang again.
    const clang::driver::Command *Cmd
      = cast<clang::driver::Command>(*Jobs.begin());
    if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
      // diagnose this...
      return NULL;
    }

    return &Cmd->getArguments();
  }

  CompilerInstance* CIFactory::createCI(llvm::StringRef code,
					int argc,
					const char* const *argv,
					const char* llvmdir) {
    return createCI(llvm::MemoryBuffer::getMemBuffer(code), argc, argv,
		    llvmdir);
  }

  CompilerInstance* CIFactory::createCI(llvm::MemoryBuffer* buffer,
					int argc,
					const char* const *argv,
					const char* llvmdir) {
    // Create an instance builder, passing the llvmdir and arguments.
    //
    //  Initialize the llvm library.
    //
    // If not set, exception handling will not be turned on
    llvm::JITExceptionHandling = true;
    llvm::InitializeNativeTarget();
    llvm::InitializeAllAsmPrinters();
    llvm::sys::Path resource_path;
    if (llvmdir) {
      resource_path = llvmdir;
      resource_path.appendComponent("lib");
      resource_path.appendComponent("clang");
      resource_path.appendComponent(CLANG_VERSION_STRING);
    } else {
      // FIXME: The first arg really does need to be argv[0] on FreeBSD.
      //
      // Note: The second arg is not used for Apple, FreeBSD, Linux,
      //       or cygwin, and can only be used on systems which support
      //       the use of dladdr().
      //
      // Note: On linux and cygwin this uses /proc/self/exe to find the path.
      //
      // Note: On Apple it uses _NSGetExecutablePath().
      //
      // Note: On FreeBSD it uses getprogpath().
      //
      // Note: Otherwise it uses dladdr().
      //
      resource_path
	= CompilerInvocation::GetResourcesPath("cling",
				       (void*)(intptr_t) locate_cling_executable
					       );
    }

    //______________________________________
    DiagnosticOptions DefaultDiagnosticOptions;
    DefaultDiagnosticOptions.ShowColors = 1;
    TextDiagnosticPrinter* DiagnosticPrinter
      = new TextDiagnosticPrinter(llvm::errs(), DefaultDiagnosticOptions);
    llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagIDs(new DiagnosticIDs());
    DiagnosticsEngine* Diagnostics
      = new DiagnosticsEngine(DiagIDs, DiagnosticPrinter, /*Owns it*/ true); // LEAKS!

    std::vector<const char*> argvCompile(argv, argv + argc);
    // We do C++ by default; append right after argv[0] name
    // Only insert it if there is no other "-x":
    bool haveMinusX = false;
    for (const char* const* iarg = argv; !haveMinusX && iarg < argv + argc;
	 ++iarg) {
      haveMinusX = !strcmp(*iarg, "-x");
    }
    if (!haveMinusX) {
      argvCompile.insert(argvCompile.begin() + 1,"-x");
      argvCompile.insert(argvCompile.begin() + 2, "c++");
    }
    argvCompile.push_back("-c");
    argvCompile.push_back("-");

    bool IsProduction = false;
    assert(IsProduction = true && "set IsProduction if asserts are on.");
    clang::driver::Driver Driver(argv[0], llvm::sys::getDefaultTargetTriple(),
                                 "cling.out",
                                 IsProduction,
                                 *Diagnostics);
    //Driver.setWarnMissingInput(false);
    Driver.setCheckInputsExist(false); // think foo.C(12)
    llvm::ArrayRef<const char*>RF(&(argvCompile[0]), argvCompile.size());
    llvm::OwningPtr<clang::driver::Compilation>
      Compilation(Driver.BuildCompilation(RF));
    const clang::driver::ArgStringList* CC1Args
      = GetCC1Arguments(Diagnostics, Compilation.get());
    if (CC1Args == NULL) {
      return 0;
    }
    clang::CompilerInvocation*
      Invocation = new clang::CompilerInvocation; // LEAKS!
    clang::CompilerInvocation::CreateFromArgs(*Invocation, CC1Args->data() + 1,
                                              CC1Args->data() + CC1Args->size(),
                                              *Diagnostics);
    Invocation->getFrontendOpts().DisableFree = true;

    // Update ResourceDir
    if (Invocation->getHeaderSearchOpts().UseBuiltinIncludes &&
	!resource_path.empty()) {
      // header search opts' entry for resource_path/include isn't
      // updated by providing a new resource path; update it manually.
      clang::HeaderSearchOptions& Opts = Invocation->getHeaderSearchOpts();
      llvm::sys::Path oldResInc(Opts.ResourceDir);
      oldResInc.appendComponent("include");
      llvm::sys::Path newResInc(resource_path);
      newResInc.appendComponent("include");
      bool foundOldResInc = false;
      for (unsigned i = 0, e = Opts.UserEntries.size();
	   !foundOldResInc && i != e; ++i) {
	HeaderSearchOptions::Entry &E = Opts.UserEntries[i];
	if (!E.IsUserSupplied && !E.IsFramework
	    && E.Group == clang::frontend::System && E.IgnoreSysRoot
	    && E.IsInternal && !E.ImplicitExternC
	    && oldResInc.str() == E.Path) {
	  E.Path = newResInc.str();
	  foundOldResInc = true;
	}
      }
      if (!foundOldResInc) {
	llvm::report_fatal_error("Cannot update include for resource path (old entry not found)!");
      }
      Opts.ResourceDir = resource_path.str();
    }

    // Create and setup a compiler instance.
    CompilerInstance* CI = new CompilerInstance();
    CI->setInvocation(Invocation);

    CI->createDiagnostics(CC1Args->size(), CC1Args->data() + 1);
    {
      //
      //  Buffer the error messages while we process
      //  the compiler options.
      //

      // Set the language options, which cling needs
      SetClingCustomLangOpts(CI->getLangOpts());

      CI->getInvocation().getPreprocessorOpts().addMacroDef("__CLING__");
      if (CI->getDiagnostics().hasErrorOccurred()) {
	delete CI;
	CI = 0;
	return 0;
      }
    }
    CI->setTarget(TargetInfo::CreateTargetInfo(CI->getDiagnostics(),
					       Invocation->getTargetOpts()));
    if (!CI->hasTarget()) {
      delete CI;
      CI = 0;
      return 0;
    }
    CI->getTarget().setForcedLangOptions(CI->getLangOpts());
    SetClingTargetLangOpts(CI->getLangOpts(), CI->getTarget());

    // Set up source and file managers
    CI->createFileManager();
    CI->createSourceManager(CI->getFileManager());

    // Set up the memory buffer
    if (buffer)
      CI->getSourceManager().createMainFileIDForMemBuffer(buffer);

    // Set up the preprocessor
    CI->createPreprocessor();
    Preprocessor& PP = CI->getPreprocessor();
    PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
					   PP.getLangOptions());

    // Set up the ASTContext
    ASTContext *Ctx = new ASTContext(CI->getLangOpts(),
				     PP.getSourceManager(), &CI->getTarget(),
				     PP.getIdentifierTable(),
				     PP.getSelectorTable(), PP.getBuiltinInfo(),
				     /*size_reserve*/0, /*DelayInit*/false);
    CI->setASTContext(Ctx);

    // Set up the ASTConsumers
    CI->setASTConsumer(new ChainedConsumer());

    // Set up Sema
    CodeCompleteConsumer* CCC = 0;
    CI->createSema(TU_Prefix, CCC);

    // Set CodeGen options
    // CI->getCodeGenOpts().DebugInfo = 1; // want debug info
    // CI->getCodeGenOpts().EmitDeclMetadata = 1; // For unloading, for later
    CI->getCodeGenOpts().OptimizationLevel = 0; // see pure SSA, that comes out
    // When asserts are on, TURN ON not compare the VerifyModule
    assert(CI->getCodeGenOpts().VerifyModule = 1);
    return CI;
  }

  void CIFactory::SetClingCustomLangOpts(LangOptions& Opts) {
    Opts.EmitAllDecls = 1;
    Opts.ObjCNonFragileABI2 = 0;
    Opts.Exceptions = 1;
    Opts.CXXExceptions = 1;
    Opts.Deprecated = 1;
  }

  void CIFactory::SetClingTargetLangOpts(LangOptions& Opts,
					 const TargetInfo& Target) {
    if (Target.getTriple().getOS() == llvm::Triple::Win32) {
      Opts.MicrosoftExt = 1;
      Opts.MSCVersion = 1300;
      // Should fix http://llvm.org/bugs/show_bug.cgi?id=10528
      Opts.DelayedTemplateParsing = 1;
    } else {
      Opts.MicrosoftExt = 0;
    }
    if (Target.getTriple().getArch() == llvm::Triple::x86) {
      Opts.ObjCNonFragileABI = 1;
    } else {
      Opts.ObjCNonFragileABI = 0;
    }
    if (Target.getTriple().isOSDarwin()) {
      Opts.NeXTRuntime = 1;
    } else {
      Opts.NeXTRuntime = 0;
    }
  }
} // end namespace
<|endoftext|>


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

#define MAXNUM 10

int main(int argc, char *argv[]){

  int sucesion[MAXNUM];
  int potencia;

  potencia = atoi(argv[1]);

  // Rellenar la matriz 'sucesion'
  for (int i=0; i<MAXNUM; i++){
    sucesion[i] = 1;
    for (int p=0; p<potencia; p++)
      sucesion[i] *= i + 1;
  }

  // Imprimir la matriz 'sucesion'
  for (int i=0; i<MAXNUM; i++)
    printf("%i ", sucesion[i]);
  printf("\n");

  return EXIT_SUCCESS;
}
<commit_msg>Delete numeros.cpp<commit_after><|endoftext|>


<commit_before>#include "TestUtils.h"
#include "gtest/gtest.h"

#include <Cards/Cards.h>
#include <Cards/Minion.h>
#include <cards/Weapon.h>
#include <Tasks/TaskSerializer.h>

#include <random>

using namespace Hearthstonepp;

TEST(TaskSerializer, CreateAndConvertCard)
{
    std::random_device rd;
    std::default_random_engine engine(rd());

    Cards* cards = Cards::GetInstance();
    const std::vector<Card*> allCards = cards->GetAllCards();

    auto cardTest = [](Card* card) {
        flatbuffers::FlatBufferBuilder builder(1024);

        auto serialized = Serializer::CreateCard(builder, card);
        builder.Finish(serialized);

        auto buffer = builder.GetBufferPointer();
        auto deserialized = flatbuffers::GetRoot<FlatData::Card>(buffer);

        std::unique_ptr<Card> converted = Serializer::ConvertCardFrom(deserialized);
        TestUtils::ExpectCardEqual(card, converted.get());
    };

    constexpr size_t zero = 0;

    // Rogue Minion : Nerubian
    const Card* nerubian = cards->FindCardByID("AT_036t");
    EXPECT_EQ(nerubian->name, "Nerubian");

    const auto * minionNerubian = dynamic_cast<const Minion*>(nerubian);
    EXPECT_NE(minionNerubian, nullptr);
    EXPECT_EQ(nerubian->name, "Nerubian");
    EXPECT_EQ(minionNerubian->cardType, +CardType::MINION);
    EXPECT_NE(minionNerubian->attack, zero);
    EXPECT_NE(minionNerubian->health, zero);

    Minion copiedNerubian = *minionNerubian;
    cardTest(&copiedNerubian);

    // Rogue Weapon : Poisoned Blade
    const Card* poisonedBlade = cards->FindCardByID("AT_034");
    const Weapon* weaponPoisonedBlade = dynamic_cast<const Weapon*>(poisonedBlade);
    EXPECT_NE(weaponPoisonedBlade, nullptr);
    EXPECT_EQ(weaponPoisonedBlade->cardType, +CardType::WEAPON);

    Weapon copiedPoisonedBlade = *weaponPoisonedBlade;
    cardTest(&copiedPoisonedBlade);

    Card* randomCard = allCards[engine() % allCards.size()];
    cardTest(randomCard);
}<commit_msg>[ci skip] Update TaskSerializerTests - Add Enchantment Converting Test<commit_after>#include "TestUtils.h"
#include "gtest/gtest.h"

#include <Cards/Cards.h>
#include <Cards/Minion.h>
#include <Enchants/Enchant.h>
#include <Tasks/TaskSerializer.h>
#include <cards/Weapon.h>

#include <random>

using namespace Hearthstonepp;

TEST(TaskSerializer, CreateAndConvertCard)
{
    std::random_device rd;
    std::default_random_engine engine(rd());

    Cards* cards = Cards::GetInstance();
    const std::vector<Card*> allCards = cards->GetAllCards();

    auto cardTest = [](Card* card) {
        flatbuffers::FlatBufferBuilder builder(1024);

        auto serialized = Serializer::CreateCard(builder, card);
        builder.Finish(serialized);

        auto buffer = builder.GetBufferPointer();
        auto deserialized = flatbuffers::GetRoot<FlatData::Card>(buffer);

        std::unique_ptr<Card> converted =
            Serializer::ConvertCardFrom(deserialized);
        TestUtils::ExpectCardEqual(card, converted.get());
    };

    constexpr size_t zero = 0;

    // Rogue Minion : Nerubian
    const Card* nerubian = cards->FindCardByID("AT_036t");
    EXPECT_EQ(nerubian->name, "Nerubian");

    const auto* minionNerubian = dynamic_cast<const Minion*>(nerubian);
    EXPECT_NE(minionNerubian, nullptr);

    Minion copiedNerubian = *minionNerubian;
    cardTest(&copiedNerubian);

    // Rogue Weapon : Poisoned Blade
    const Card* poisonedBlade = cards->FindCardByID("AT_034");
    EXPECT_EQ(poisonedBlade->name, "Poisoned Blade");

    const Weapon* weaponPoisonedBlade =
        dynamic_cast<const Weapon*>(poisonedBlade);
    EXPECT_NE(weaponPoisonedBlade, nullptr);

    Weapon copiedPoisonedBlade = *weaponPoisonedBlade;
    cardTest(&copiedPoisonedBlade);

    const Card* dreadsteed = cards->FindCardByID("AT_019e");
    EXPECT_EQ(dreadsteed->name, "Dreadsteed");

    const auto* enchantmentDreadsteed =
        dynamic_cast<const Enchantment*>(dreadsteed);
    EXPECT_NE(enchantmentDreadsteed, nullptr);

    Enchantment copiedDreadsteed = *enchantmentDreadsteed;
    cardTest(&copiedDreadsteed);

    Card* randomCard = allCards[engine() % allCards.size()];
    cardTest(randomCard);
}<|endoftext|>


<commit_before>#include <SimpleITKTestHarness.h>

#include <sitkImage.h>
#include <sitkImageFileReader.h>
#include <sitkImageFileWriter.h>
#include <sitkHashImageFilter.h>
#include <sitkRecursiveGaussianImageFilter.h>
#include <sitkCastImageFilter.h>
#include <sitkPixelIDValues.h>

#include "itkRecursiveGaussianImageFilter.h"

TEST(BasicFilters,RecursiveGaussian_ENUMCHECK) {

  typedef itk::RecursiveGaussianImageFilter< itk::Image<float,3> > ITKRecursiveGausianType;
  EXPECT_EQ( ITKRecursiveGausianType::ZeroOrder, itk::simple::RecursiveGaussianImageFilter::ZeroOrder );
  EXPECT_EQ( ITKRecursiveGausianType::FirstOrder, itk::simple::RecursiveGaussianImageFilter::FirstOrder );
  EXPECT_EQ( ITKRecursiveGausianType::SecondOrder, itk::simple::RecursiveGaussianImageFilter::SecondOrder );
}

TEST(BasicFilters,Cast) {
  itk::simple::HashImageFilter hasher;
  itk::simple::ImageFileReader reader;

  reader.SetFileName ( dataFinder.GetFile ( "Input/RA-Float.nrrd" ) );
  itk::simple::Image image = reader.Execute();
  ASSERT_TRUE ( image.GetImageBase() != NULL );
  hasher.SetHashFunction ( itk::simple::HashImageFilter::MD5 );
  EXPECT_EQ ( "3ccccde44efaa3d688a86e94335c1f16", hasher.Execute ( image ) );

  EXPECT_EQ ( image.GetPixelIDValue(), itk::simple::sitkFloat32 );
  EXPECT_EQ ( image.GetPixelIDTypeAsString(), "32-bit float" );

  typedef std::map<std::string,itk::simple::PixelIDValueType> MapType;
  MapType mapping;
  mapping["2f27e9260baeba84fb83dd35de23fa2d"] = (itk::simple::PixelIDValueType)itk::simple::sitkUInt8;
  mapping["2f27e9260baeba84fb83dd35de23fa2d"] = (itk::simple::PixelIDValueType)itk::simple::sitkInt8;
  mapping["a963bd6a755b853103a2d195e01a50d3"] = (itk::simple::PixelIDValueType)itk::simple::sitkUInt16;
  mapping["a963bd6a755b853103a2d195e01a50d3"] = (itk::simple::PixelIDValueType)itk::simple::sitkInt16;
  mapping["6ceea0011178a955b5be2d545d107199"] = (itk::simple::PixelIDValueType)itk::simple::sitkUInt32;
  mapping["6ceea0011178a955b5be2d545d107199"] = (itk::simple::PixelIDValueType)itk::simple::sitkInt32;
  mapping["efa4c3b27349b97b02a64f3d2b5ca9ed"] = (itk::simple::PixelIDValueType)itk::simple::sitkUInt64;
  mapping["sitkInt64"] = (itk::simple::PixelIDValueType)itk::simple::sitkInt64;
  mapping["3ccccde44efaa3d688a86e94335c1f16"] = (itk::simple::PixelIDValueType)itk::simple::sitkFloat32;
  mapping["ac0228acc17038fd1f1ed28eb2841c73"] = (itk::simple::PixelIDValueType)itk::simple::sitkFloat64;
  mapping["226dabda8fc07f20e2b9e44ca1c83955"] = (itk::simple::PixelIDValueType)itk::simple::sitkComplexFloat32;
  mapping["e92cbb187a92610068d7de0cb23364db"] = (itk::simple::PixelIDValueType)itk::simple::sitkComplexFloat64;
  mapping["2f27e9260baeba84fb83dd35de23fa2d"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorUInt8;
  mapping["2f27e9260baeba84fb83dd35de23fa2d"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorInt8;
  mapping["a963bd6a755b853103a2d195e01a50d3"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorUInt16;
  mapping["a963bd6a755b853103a2d195e01a50d3"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorInt16;
  mapping["sitkVectorUInt32"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorUInt32;
  mapping["sitkVectorInt32"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorInt32;
  mapping["sitkVectorUInt64"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorUInt64;
  mapping["sitkVectorInt64"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorInt64;
  mapping["3ccccde44efaa3d688a86e94335c1f16"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorFloat32;
  mapping["ac0228acc17038fd1f1ed28eb2841c73"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorFloat64;
  mapping["sitkLabelUInt8"] = (itk::simple::PixelIDValueType)itk::simple::sitkLabelUInt8;
  mapping["sitkLabelUInt16"] = (itk::simple::PixelIDValueType)itk::simple::sitkLabelUInt16;
  mapping["sitkLabelUInt32"] = (itk::simple::PixelIDValueType)itk::simple::sitkLabelUInt32;
  mapping["sitkLabelUInt64"] = (itk::simple::PixelIDValueType)itk::simple::sitkLabelUInt64;

  bool failed = false;

  // Loop over the map, load each file, and compare the hash value
  for ( MapType::iterator it = mapping.begin(); it != mapping.end(); ++it )
    {
    itk::simple::PixelIDValueType pixelID = it->second;
    std::string hash = it->first;

    std::cerr << std::flush;
    std::cerr << std::flush;
    if ( pixelID == itk::simple::sitkUnknown )
      {
      std::cerr << "Enum value: " << pixelID << " (" << hash << ") is unknown and not instantiated" << std::endl;
      continue;
      }

    std::cerr << "Testing casting to pixelID: " << pixelID << " is " << itk::simple::GetPixelIDValueAsString ( pixelID ) << std::endl;

    try
      {
      itk::simple::CastImageFilter caster;
      itk::simple::Image test = caster.SetOutputPixelType ( pixelID ).Execute ( image );

      hasher.SetHashFunction ( itk::simple::HashImageFilter::MD5 );
      EXPECT_EQ ( hash, hasher.Execute ( test ) ) << "Cast to " << itk::simple::GetPixelIDValueAsString ( pixelID );

      }
    catch ( ::itk::simple::GenericException &e )
      {

      // hashing currently doesn't work for label images
      if ( hash.find( "sitkLabel" ) == 0 )
        {
        std::cerr << "Hashing currently is not implemented for Label Images" << std::endl;
        }
      else
        {
        failed = true;
        std::cerr << "Failed to hash: " << e.what() << std::endl;
        }

      continue;
      }

  }
  EXPECT_FALSE ( failed ) << "Cast failed, or could not take the hash of the imoge";

}

TEST(BasicFilters,HashImageFilter) {
  itk::simple::HashImageFilter hasher;
  EXPECT_NE ( "", hasher.ToString() );
  EXPECT_EQ ( itk::simple::HashImageFilter::SHA1, hasher.SetHashFunction ( itk::simple::HashImageFilter::SHA1 ).GetHashFunction() );
  EXPECT_EQ ( itk::simple::HashImageFilter::MD5, hasher.SetHashFunction ( itk::simple::HashImageFilter::MD5 ).GetHashFunction() );
}
<commit_msg>COMP: Fixing compile warnings<commit_after>#include <SimpleITKTestHarness.h>

#include <sitkImage.h>
#include <sitkImageFileReader.h>
#include <sitkImageFileWriter.h>
#include <sitkHashImageFilter.h>
#include <sitkRecursiveGaussianImageFilter.h>
#include <sitkCastImageFilter.h>
#include <sitkPixelIDValues.h>

#include "itkRecursiveGaussianImageFilter.h"

TEST(BasicFilters,RecursiveGaussian_ENUMCHECK) {

  typedef itk::RecursiveGaussianImageFilter< itk::Image<float,3> > ITKRecursiveGausianType;
  EXPECT_EQ( (int)ITKRecursiveGausianType::ZeroOrder, (int)itk::simple::RecursiveGaussianImageFilter::ZeroOrder );
  EXPECT_EQ( (int)ITKRecursiveGausianType::FirstOrder, (int)itk::simple::RecursiveGaussianImageFilter::FirstOrder );
  EXPECT_EQ( (int)ITKRecursiveGausianType::SecondOrder, (int)itk::simple::RecursiveGaussianImageFilter::SecondOrder );
}

TEST(BasicFilters,Cast) {
  itk::simple::HashImageFilter hasher;
  itk::simple::ImageFileReader reader;

  reader.SetFileName ( dataFinder.GetFile ( "Input/RA-Float.nrrd" ) );
  itk::simple::Image image = reader.Execute();
  ASSERT_TRUE ( image.GetImageBase() != NULL );
  hasher.SetHashFunction ( itk::simple::HashImageFilter::MD5 );
  EXPECT_EQ ( "3ccccde44efaa3d688a86e94335c1f16", hasher.Execute ( image ) );

  EXPECT_EQ ( image.GetPixelIDValue(), itk::simple::sitkFloat32 );
  EXPECT_EQ ( image.GetPixelIDTypeAsString(), "32-bit float" );

  typedef std::map<std::string,itk::simple::PixelIDValueType> MapType;
  MapType mapping;
  mapping["2f27e9260baeba84fb83dd35de23fa2d"] = (itk::simple::PixelIDValueType)itk::simple::sitkUInt8;
  mapping["2f27e9260baeba84fb83dd35de23fa2d"] = (itk::simple::PixelIDValueType)itk::simple::sitkInt8;
  mapping["a963bd6a755b853103a2d195e01a50d3"] = (itk::simple::PixelIDValueType)itk::simple::sitkUInt16;
  mapping["a963bd6a755b853103a2d195e01a50d3"] = (itk::simple::PixelIDValueType)itk::simple::sitkInt16;
  mapping["6ceea0011178a955b5be2d545d107199"] = (itk::simple::PixelIDValueType)itk::simple::sitkUInt32;
  mapping["6ceea0011178a955b5be2d545d107199"] = (itk::simple::PixelIDValueType)itk::simple::sitkInt32;
  mapping["efa4c3b27349b97b02a64f3d2b5ca9ed"] = (itk::simple::PixelIDValueType)itk::simple::sitkUInt64;
  mapping["sitkInt64"] = (itk::simple::PixelIDValueType)itk::simple::sitkInt64;
  mapping["3ccccde44efaa3d688a86e94335c1f16"] = (itk::simple::PixelIDValueType)itk::simple::sitkFloat32;
  mapping["ac0228acc17038fd1f1ed28eb2841c73"] = (itk::simple::PixelIDValueType)itk::simple::sitkFloat64;
  mapping["226dabda8fc07f20e2b9e44ca1c83955"] = (itk::simple::PixelIDValueType)itk::simple::sitkComplexFloat32;
  mapping["e92cbb187a92610068d7de0cb23364db"] = (itk::simple::PixelIDValueType)itk::simple::sitkComplexFloat64;
  mapping["2f27e9260baeba84fb83dd35de23fa2d"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorUInt8;
  mapping["2f27e9260baeba84fb83dd35de23fa2d"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorInt8;
  mapping["a963bd6a755b853103a2d195e01a50d3"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorUInt16;
  mapping["a963bd6a755b853103a2d195e01a50d3"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorInt16;
  mapping["sitkVectorUInt32"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorUInt32;
  mapping["sitkVectorInt32"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorInt32;
  mapping["sitkVectorUInt64"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorUInt64;
  mapping["sitkVectorInt64"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorInt64;
  mapping["3ccccde44efaa3d688a86e94335c1f16"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorFloat32;
  mapping["ac0228acc17038fd1f1ed28eb2841c73"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorFloat64;
  mapping["sitkLabelUInt8"] = (itk::simple::PixelIDValueType)itk::simple::sitkLabelUInt8;
  mapping["sitkLabelUInt16"] = (itk::simple::PixelIDValueType)itk::simple::sitkLabelUInt16;
  mapping["sitkLabelUInt32"] = (itk::simple::PixelIDValueType)itk::simple::sitkLabelUInt32;
  mapping["sitkLabelUInt64"] = (itk::simple::PixelIDValueType)itk::simple::sitkLabelUInt64;

  bool failed = false;

  // Loop over the map, load each file, and compare the hash value
  for ( MapType::iterator it = mapping.begin(); it != mapping.end(); ++it )
    {
    itk::simple::PixelIDValueType pixelID = it->second;
    std::string hash = it->first;

    std::cerr << std::flush;
    std::cerr << std::flush;
    if ( pixelID == itk::simple::sitkUnknown )
      {
      std::cerr << "Enum value: " << pixelID << " (" << hash << ") is unknown and not instantiated" << std::endl;
      continue;
      }

    std::cerr << "Testing casting to pixelID: " << pixelID << " is " << itk::simple::GetPixelIDValueAsString ( pixelID ) << std::endl;

    try
      {
      itk::simple::CastImageFilter caster;
      itk::simple::Image test = caster.SetOutputPixelType ( pixelID ).Execute ( image );

      hasher.SetHashFunction ( itk::simple::HashImageFilter::MD5 );
      EXPECT_EQ ( hash, hasher.Execute ( test ) ) << "Cast to " << itk::simple::GetPixelIDValueAsString ( pixelID );

      }
    catch ( ::itk::simple::GenericException &e )
      {

      // hashing currently doesn't work for label images
      if ( hash.find( "sitkLabel" ) == 0 )
        {
        std::cerr << "Hashing currently is not implemented for Label Images" << std::endl;
        }
      else
        {
        failed = true;
        std::cerr << "Failed to hash: " << e.what() << std::endl;
        }

      continue;
      }

  }
  EXPECT_FALSE ( failed ) << "Cast failed, or could not take the hash of the imoge";

}

TEST(BasicFilters,HashImageFilter) {
  itk::simple::HashImageFilter hasher;
  EXPECT_NE ( "", hasher.ToString() );
  EXPECT_EQ ( itk::simple::HashImageFilter::SHA1, hasher.SetHashFunction ( itk::simple::HashImageFilter::SHA1 ).GetHashFunction() );
  EXPECT_EQ ( itk::simple::HashImageFilter::MD5, hasher.SetHashFunction ( itk::simple::HashImageFilter::MD5 ).GetHashFunction() );
}
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2014 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "StringTests.h"
#include "OgreStringConverter.h"
#include "OgreVector3.h"
#include "OgreQuaternion.h"
#include "OgreMatrix4.h"
#include "OgreColourValue.h"

using namespace Ogre;

// Register the test suite

//--------------------------------------------------------------------------
void StringTests::SetUp()
{
    testFileNoPath = "testfile.txt";
    testFileRelativePathUnix = "this/is/relative/testfile.txt";
    testFileRelativePathWindows = "this\\is\\relative\\testfile.txt";
    testFileAbsolutePathUnix = "/this/is/absolute/testfile.txt";
    testFileAbsolutePathWindows = "c:\\this\\is\\absolute\\testfile.txt";
    setlocale(LC_NUMERIC, "");
}
//--------------------------------------------------------------------------
void StringTests::TearDown()
{
}
//--------------------------------------------------------------------------
TEST_F(StringTests,SplitFileNameNoPath)
{
    String basename, path;
    StringUtil::splitFilename(testFileNoPath, basename, path);

    EXPECT_EQ(testFileNoPath, basename);
    EXPECT_TRUE(path.empty());
}
//--------------------------------------------------------------------------
TEST_F(StringTests,SplitFileNameRelativePath)
{
    String basename, path;

    // Unix
    StringUtil::splitFilename(testFileRelativePathUnix, basename, path);
    EXPECT_EQ(String("testfile.txt"), basename);
    EXPECT_EQ(String("this/is/relative/"), path);

    // Windows
    StringUtil::splitFilename(testFileRelativePathWindows, basename, path);
    EXPECT_EQ(String("testfile.txt"), basename);
    EXPECT_EQ(String("this/is/relative/"), path);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,SplitFileNameAbsolutePath)
{
    String basename, path;

    // Unix
    StringUtil::splitFilename(testFileAbsolutePathUnix, basename, path);
    EXPECT_EQ(String("testfile.txt"), basename);
    EXPECT_EQ(String("/this/is/absolute/"), path);

    // Windows
    StringUtil::splitFilename(testFileAbsolutePathWindows, basename, path);
    EXPECT_EQ(String("testfile.txt"), basename);
    EXPECT_EQ(String("c:/this/is/absolute/"), path);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchCaseSensitive)
{
    // Test positive
    EXPECT_TRUE(StringUtil::match(testFileNoPath, testFileNoPath, true));

    // Test negative
    String upperCase = testFileNoPath;
    StringUtil::toUpperCase(upperCase);
    EXPECT_TRUE(!StringUtil::match(testFileNoPath, upperCase, true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchCaseInSensitive)
{
    // Test positive
    EXPECT_TRUE(StringUtil::match(testFileNoPath, testFileNoPath, false));

    // Test positive
    String upperCase = testFileNoPath;
    StringUtil::toUpperCase(upperCase);
    EXPECT_TRUE(StringUtil::match(testFileNoPath, upperCase, false));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchGlobAll)
{
    EXPECT_TRUE(StringUtil::match(testFileNoPath, "*", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchGlobStart)
{
    EXPECT_TRUE(StringUtil::match(testFileNoPath, "*stfile.txt", true));
    EXPECT_TRUE(!StringUtil::match(testFileNoPath, "*astfile.txt", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchGlobEnd)
{
    EXPECT_TRUE(StringUtil::match(testFileNoPath, "testfile.*", true));
    EXPECT_TRUE(!StringUtil::match(testFileNoPath, "testfile.d*", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchGlobStartAndEnd)
{
    EXPECT_TRUE(StringUtil::match(testFileNoPath, "*stfile.*", true));
    EXPECT_TRUE(!StringUtil::match(testFileNoPath, "*astfile.d*", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchGlobMiddle)
{
    EXPECT_TRUE(StringUtil::match(testFileNoPath, "test*.txt", true));
    EXPECT_TRUE(!StringUtil::match(testFileNoPath, "last*.txt*", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchSuperGlobtastic)
{
    EXPECT_TRUE(StringUtil::match(testFileNoPath, "*e*tf*e.t*t", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchSuperGlobEnd)
{
    EXPECT_TRUE(StringUtil::match("normal", "*normal*", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseReal)
{
    Real r = 23.454;

    String s = StringConverter::toString(r);

    EXPECT_EQ(r, StringConverter::parseReal(s));
    EXPECT_EQ(r, StringConverter::parseReal("23.454"));
    EXPECT_NE(r, StringConverter::parseReal("23,454"));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseInt)
{
    int r = -223546;

    String s = StringConverter::toString(r);
    int t = StringConverter::parseInt(s);

    EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseLong)
{
    long r = -2147483647;

    String s = StringConverter::toString(r);
    long t = StringConverter::parseLong(s);

    EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseUnsignedLong)
{
    unsigned long r = 4294967295UL;

    String s = StringConverter::toString(r);
    unsigned long t = StringConverter::parseUnsignedLong(s);

    EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseSizeT)
{
    size_t r = 223546;

    String s = StringConverter::toString(r);
    size_t t = StringConverter::parseSizeT(s);

    EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseVector3)
{
    Vector3 r(0.12, 3.22, -4.04);

    String s = StringConverter::toString(r);
    Vector3 t = StringConverter::parseVector3(s);

    EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseMatrix4)
{
    Matrix4 r(1.12, 0, 0, 34, 0, 0.87, 0, 20, 0, 0, 0.56, 10, 0, 0, 0, 1);

    String s = StringConverter::toString(r);
    Matrix4 t = StringConverter::parseMatrix4(s);

    EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseQuaternion)
{
    Quaternion r(1.12, 0.87, 0.67, 1);

    String s = StringConverter::toString(r);
    Quaternion t = StringConverter::parseQuaternion(s);

    EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseBool)
{
    bool r = true;
    String s = StringConverter::toString(r);
    bool t = StringConverter::parseBool(s);
    EXPECT_EQ(r, t);

    r = false;
    s = StringConverter::toString(r);
    t = StringConverter::parseBool(s);
    EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseColourValue)
{
    ColourValue r(0.34, 0.44, 0.77, 1.0);

    String s = StringConverter::toString(r);
    ColourValue t = StringConverter::parseColourValue(s);
    EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,EndsWith)
{
    String s = "Hello World!";

    EXPECT_TRUE(StringUtil::endsWith(s, "world!"));
    EXPECT_FALSE(StringUtil::endsWith(s, "hello"));
    EXPECT_FALSE(StringUtil::endsWith(s, "world!", false));
    EXPECT_FALSE(StringUtil::endsWith(s, "", false));
}

TEST_F(StringTests,StartsWith)
{
    String s = "Hello World!";

    EXPECT_TRUE(StringUtil::startsWith(s, "hello"));
    EXPECT_FALSE(StringUtil::startsWith(s, "world"));
    EXPECT_FALSE(StringUtil::startsWith(s, "hello", false));
    EXPECT_FALSE(StringUtil::startsWith(s, "", false));
}
<commit_msg>Tests: make unsigned parsing tests more useful<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2014 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "StringTests.h"
#include "OgreStringConverter.h"
#include "OgreVector3.h"
#include "OgreQuaternion.h"
#include "OgreMatrix4.h"
#include "OgreColourValue.h"

using namespace Ogre;

// Register the test suite

//--------------------------------------------------------------------------
void StringTests::SetUp()
{
    testFileNoPath = "testfile.txt";
    testFileRelativePathUnix = "this/is/relative/testfile.txt";
    testFileRelativePathWindows = "this\\is\\relative\\testfile.txt";
    testFileAbsolutePathUnix = "/this/is/absolute/testfile.txt";
    testFileAbsolutePathWindows = "c:\\this\\is\\absolute\\testfile.txt";
    setlocale(LC_NUMERIC, "");
}
//--------------------------------------------------------------------------
void StringTests::TearDown()
{
}
//--------------------------------------------------------------------------
TEST_F(StringTests,SplitFileNameNoPath)
{
    String basename, path;
    StringUtil::splitFilename(testFileNoPath, basename, path);

    EXPECT_EQ(testFileNoPath, basename);
    EXPECT_TRUE(path.empty());
}
//--------------------------------------------------------------------------
TEST_F(StringTests,SplitFileNameRelativePath)
{
    String basename, path;

    // Unix
    StringUtil::splitFilename(testFileRelativePathUnix, basename, path);
    EXPECT_EQ(String("testfile.txt"), basename);
    EXPECT_EQ(String("this/is/relative/"), path);

    // Windows
    StringUtil::splitFilename(testFileRelativePathWindows, basename, path);
    EXPECT_EQ(String("testfile.txt"), basename);
    EXPECT_EQ(String("this/is/relative/"), path);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,SplitFileNameAbsolutePath)
{
    String basename, path;

    // Unix
    StringUtil::splitFilename(testFileAbsolutePathUnix, basename, path);
    EXPECT_EQ(String("testfile.txt"), basename);
    EXPECT_EQ(String("/this/is/absolute/"), path);

    // Windows
    StringUtil::splitFilename(testFileAbsolutePathWindows, basename, path);
    EXPECT_EQ(String("testfile.txt"), basename);
    EXPECT_EQ(String("c:/this/is/absolute/"), path);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchCaseSensitive)
{
    // Test positive
    EXPECT_TRUE(StringUtil::match(testFileNoPath, testFileNoPath, true));

    // Test negative
    String upperCase = testFileNoPath;
    StringUtil::toUpperCase(upperCase);
    EXPECT_TRUE(!StringUtil::match(testFileNoPath, upperCase, true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchCaseInSensitive)
{
    // Test positive
    EXPECT_TRUE(StringUtil::match(testFileNoPath, testFileNoPath, false));

    // Test positive
    String upperCase = testFileNoPath;
    StringUtil::toUpperCase(upperCase);
    EXPECT_TRUE(StringUtil::match(testFileNoPath, upperCase, false));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchGlobAll)
{
    EXPECT_TRUE(StringUtil::match(testFileNoPath, "*", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchGlobStart)
{
    EXPECT_TRUE(StringUtil::match(testFileNoPath, "*stfile.txt", true));
    EXPECT_TRUE(!StringUtil::match(testFileNoPath, "*astfile.txt", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchGlobEnd)
{
    EXPECT_TRUE(StringUtil::match(testFileNoPath, "testfile.*", true));
    EXPECT_TRUE(!StringUtil::match(testFileNoPath, "testfile.d*", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchGlobStartAndEnd)
{
    EXPECT_TRUE(StringUtil::match(testFileNoPath, "*stfile.*", true));
    EXPECT_TRUE(!StringUtil::match(testFileNoPath, "*astfile.d*", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchGlobMiddle)
{
    EXPECT_TRUE(StringUtil::match(testFileNoPath, "test*.txt", true));
    EXPECT_TRUE(!StringUtil::match(testFileNoPath, "last*.txt*", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchSuperGlobtastic)
{
    EXPECT_TRUE(StringUtil::match(testFileNoPath, "*e*tf*e.t*t", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchSuperGlobEnd)
{
    EXPECT_TRUE(StringUtil::match("normal", "*normal*", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseReal)
{
    Real r = 23.454;

    String s = StringConverter::toString(r);

    EXPECT_EQ(r, StringConverter::parseReal(s));
    EXPECT_EQ(r, StringConverter::parseReal("23.454"));
    EXPECT_NE(r, StringConverter::parseReal("23,454"));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseInt)
{
    int r = -223546;

    String s = StringConverter::toString(r);
    int t = StringConverter::parseInt(s);

    EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseLong)
{
    long r = -2147483647;

    String s = StringConverter::toString(r);
    long t = StringConverter::parseLong(s);

    EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseUnsignedLong)
{
    unsigned long r = ~0;

    String s = StringConverter::toString(r);
    unsigned long t = StringConverter::parseUnsignedLong(s);

    EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseSizeT)
{
    size_t r = ~0;

    String s = StringConverter::toString(r);
    size_t t = StringConverter::parseSizeT(s);

    EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseVector3)
{
    Vector3 r(0.12, 3.22, -4.04);

    String s = StringConverter::toString(r);
    Vector3 t = StringConverter::parseVector3(s);

    EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseMatrix4)
{
    Matrix4 r(1.12, 0, 0, 34, 0, 0.87, 0, 20, 0, 0, 0.56, 10, 0, 0, 0, 1);

    String s = StringConverter::toString(r);
    Matrix4 t = StringConverter::parseMatrix4(s);

    EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseQuaternion)
{
    Quaternion r(1.12, 0.87, 0.67, 1);

    String s = StringConverter::toString(r);
    Quaternion t = StringConverter::parseQuaternion(s);

    EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseBool)
{
    bool r = true;
    String s = StringConverter::toString(r);
    bool t = StringConverter::parseBool(s);
    EXPECT_EQ(r, t);

    r = false;
    s = StringConverter::toString(r);
    t = StringConverter::parseBool(s);
    EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseColourValue)
{
    ColourValue r(0.34, 0.44, 0.77, 1.0);

    String s = StringConverter::toString(r);
    ColourValue t = StringConverter::parseColourValue(s);
    EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,EndsWith)
{
    String s = "Hello World!";

    EXPECT_TRUE(StringUtil::endsWith(s, "world!"));
    EXPECT_FALSE(StringUtil::endsWith(s, "hello"));
    EXPECT_FALSE(StringUtil::endsWith(s, "world!", false));
    EXPECT_FALSE(StringUtil::endsWith(s, "", false));
}

TEST_F(StringTests,StartsWith)
{
    String s = "Hello World!";

    EXPECT_TRUE(StringUtil::startsWith(s, "hello"));
    EXPECT_FALSE(StringUtil::startsWith(s, "world"));
    EXPECT_FALSE(StringUtil::startsWith(s, "hello", false));
    EXPECT_FALSE(StringUtil::startsWith(s, "", false));
}
<|endoftext|>


<commit_before>/*******************************************************************************
 * Copyright (c) 2014, Andrew "Art" Clarke.  All rights reserved.
 *
 * This file is part of Humble-Video.
 *
 * Humble-Video is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Humble-Video is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Humble-Video.  If not, see <http://www.gnu.org/licenses/>.
 *******************************************************************************/
/*
 * HumbleException.cpp
 *
 *  Created on: Jul 14, 2013
 *      Author: aclarke
 */

#ifdef __GNUC__
/** We are compiling in GCC */
#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) || defined(VS_OS_WINDOWS)
# else
#include <execinfo.h>
#endif
#endif // __GNUC__
#include "HumbleException.h"
#include <cstring>
#include <cstdlib>

namespace io {
namespace humble {
namespace ferry {

HumbleStackTrace::HumbleStackTrace() {
  mSymbols = 0;
  mNumFrames = 0;
  // time to generate a stack trace
#ifdef __GNUC__
#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) || defined(VS_OS_WINDOWS)
#else
  mNumFrames = backtrace(mFrames, sizeof(mFrames)/sizeof(*mFrames));
  if (mNumFrames > 0)
    mSymbols = backtrace_symbols(mFrames, mNumFrames);
#endif
#endif
}

HumbleStackTrace::HumbleStackTrace(const HumbleStackTrace & e) {
  mNumFrames = e.mNumFrames;
  memcpy(mFrames, e.mFrames, mNumFrames);
  if (e.mSymbols) {
    mSymbols = (char**)malloc(mNumFrames * sizeof(char*));
    if (mSymbols)
      memcpy(mSymbols, e.mSymbols, mNumFrames);
    // if there was a malloc error, just let it pass.
  }
}

HumbleStackTrace::~HumbleStackTrace() {
  if (mSymbols) {
    free(mSymbols);
  }
}

VS_EXCEPTION_MAKE_MAKER(HumbleRuntimeError);
VS_EXCEPTION_MAKE_MAKER(HumbleInterruptedException);
VS_EXCEPTION_MAKE_MAKER(HumbleIOException);
VS_EXCEPTION_MAKE_MAKER(HumbleInvalidArgument);

} /* namespace ferry */
} /* namespace humble */
} /* namespace io */
<commit_msg>Initialize `mSymbols` to NULL if symbols of referenced `HumbleStackTrace` is empty<commit_after>/*******************************************************************************
 * Copyright (c) 2014, Andrew "Art" Clarke.  All rights reserved.
 *
 * This file is part of Humble-Video.
 *
 * Humble-Video is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Humble-Video is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Humble-Video.  If not, see <http://www.gnu.org/licenses/>.
 *******************************************************************************/
/*
 * HumbleException.cpp
 *
 *  Created on: Jul 14, 2013
 *      Author: aclarke
 */

#ifdef __GNUC__
/** We are compiling in GCC */
#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) || defined(VS_OS_WINDOWS)
# else
#include <execinfo.h>
#endif
#endif // __GNUC__
#include "HumbleException.h"
#include <cstring>
#include <cstdlib>

namespace io {
namespace humble {
namespace ferry {

HumbleStackTrace::HumbleStackTrace() {
  mSymbols = 0;
  mNumFrames = 0;
  // time to generate a stack trace
#ifdef __GNUC__
#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) || defined(VS_OS_WINDOWS)
#else
  mNumFrames = backtrace(mFrames, sizeof(mFrames)/sizeof(*mFrames));
  if (mNumFrames > 0)
    mSymbols = backtrace_symbols(mFrames, mNumFrames);
#endif
#endif
}

HumbleStackTrace::HumbleStackTrace(const HumbleStackTrace & e) {
  mNumFrames = e.mNumFrames;
  memcpy(mFrames, e.mFrames, mNumFrames);
  if (e.mSymbols) {
    mSymbols = (char**)malloc(mNumFrames * sizeof(char*));
    if (mSymbols)
      memcpy(mSymbols, e.mSymbols, mNumFrames);
    // if there was a malloc error, just let it pass.
  } else {
    mSymbols = 0;
  }
}

HumbleStackTrace::~HumbleStackTrace() {
  if (mSymbols) {
    free(mSymbols);
  }
}

VS_EXCEPTION_MAKE_MAKER(HumbleRuntimeError);
VS_EXCEPTION_MAKE_MAKER(HumbleInterruptedException);
VS_EXCEPTION_MAKE_MAKER(HumbleIOException);
VS_EXCEPTION_MAKE_MAKER(HumbleInvalidArgument);

} /* namespace ferry */
} /* namespace humble */
} /* namespace io */
<|endoftext|>


<commit_before>/*
* Copyright 2008, 2009 Free Software Foundation, Inc.
*
* This software is distributed under multiple licenses; see the COPYING file in the main directory for licensing information for this specific distribuion.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

*/

//#define NDEBUG
#include "radioInterface.h"
#include <Logger.h>

GSM::Time VectorQueue::nextTime() const
{
  GSM::Time retVal;
  ScopedLock lock(mLock);
  while (mQ.size()==0) mWriteSignal.wait(mLock);
  return mQ.top()->time();
}

radioVector* VectorQueue::getStaleBurst(const GSM::Time& targTime)
{
  ScopedLock lock(mLock);
  if ((mQ.size()==0)) {
    return NULL;
  }
  if (mQ.top()->time() < targTime) {
    radioVector* retVal = mQ.top();
    mQ.pop();
    return retVal;
  }
  return NULL;
}

radioVector* VectorQueue::getCurrentBurst(const GSM::Time& targTime)
{
  ScopedLock lock(mLock);
  if ((mQ.size()==0)) {
    return NULL;
  }
  if (mQ.top()->time() == targTime) {
    radioVector* retVal = mQ.top();
    mQ.pop();
    return retVal;
  }
  return NULL;
}

RadioInterface::RadioInterface(RadioDevice *wRadio,
                               int wReceiveOffset,
			       int wRadioOversampling,
			       int wTransceiverOversampling,
			       bool wLoadTest,
			       unsigned int wNumARFCNs,
			       GSM::Time wStartTime)

{
  underrun = false;

  sendCursor = 0;
  rcvCursor = 0;
  mOn = false;

  mRadio = wRadio;
  receiveOffset = wReceiveOffset;
  samplesPerSymbol = wRadioOversampling;
  mClock.set(wStartTime);
  powerScaling = 1.0;
  mNumARFCNs = wNumARFCNs;

  loadTest = wLoadTest;
}

RadioInterface::~RadioInterface(void) {
  if (rcvBuffer!=NULL) delete rcvBuffer;
  //mReceiveFIFO.clear();
}

double RadioInterface::fullScaleInputValue(void) {
  return mRadio->fullScaleInputValue();
}

double RadioInterface::fullScaleOutputValue(void) {
  return mRadio->fullScaleOutputValue();
}

void RadioInterface::setPowerAttenuation(double dBAtten)
{
  float HWdBAtten = mRadio->setTxGain(-dBAtten);
  dBAtten -= (-HWdBAtten);
  float linearAtten = powf(10.0F,0.1F*dBAtten);
  if (linearAtten < 1.0)
    powerScaling = 1.0;
  else
    powerScaling = 1.0/sqrt(linearAtten);
  LOG(INFO) << "setting HW gain to " << HWdBAtten << " and power scaling to " << powerScaling;
}

short *RadioInterface::radioifyVector(signalVector &wVector, short *retVector, double scale, bool zeroOut)
{

  signalVector::iterator itr = wVector.begin();
  short *shortItr = retVector;
  if (zeroOut) {
    while (itr < wVector.end()) {
      *shortItr++ = 0;
      *shortItr++ = 0;
      itr++;
    }
  }
  else if (scale != 1.0) {
    while (itr < wVector.end()) {
      *shortItr++ = (short) (itr->real()*scale);
      *shortItr++ = (short) (itr->imag()*scale);
      itr++;
    }
  }
  else {
    while (itr < wVector.end()) {
      *shortItr++ = (short) (itr->real());
      *shortItr++ = (short) (itr->imag());
      itr++;
    }
  }

  return retVector;

}

void RadioInterface::unRadioifyVector(short *shortVector, signalVector& newVector)
{

  signalVector::iterator itr = newVector.begin();
  short *shortItr = shortVector;
  while (itr < newVector.end()) {
    *itr++ = Complex<float>(*shortItr,*(shortItr+1));
    //LOG(DEBUG) << (*(itr-1));
    shortItr += 2;
  }

}

bool started = false;

void RadioInterface::pushBuffer(void) {

  if (sendCursor < 2*INCHUNK*samplesPerSymbol) return;

  // send resampleVector
  int samplesWritten = mRadio->writeSamples(sendBuffer,
					  INCHUNK*samplesPerSymbol,
					  &underrun,
					  writeTimestamp);
  //LOG(DEBUG) << "writeTimestamp: " << writeTimestamp << ", samplesWritten: " << samplesWritten;

  writeTimestamp += (TIMESTAMP) samplesWritten;

  if (sendCursor > 2*samplesWritten)
    memcpy(sendBuffer,sendBuffer+samplesWritten*2,sizeof(short)*2*(sendCursor-2*samplesWritten));
  sendCursor = sendCursor - 2*samplesWritten;
}

void RadioInterface::pullBuffer(void)
{

  bool localUnderrun;

   // receive receiveVector
  short* shortVector = rcvBuffer+rcvCursor;
  //LOG(DEBUG) << "Reading USRP samples at timestamp " << readTimestamp;
  int samplesRead = mRadio->readSamples(shortVector,OUTCHUNK*samplesPerSymbol,&overrun,readTimestamp,&localUnderrun);
  underrun |= localUnderrun;
  readTimestamp += (TIMESTAMP) samplesRead;
  while (samplesRead < OUTCHUNK*samplesPerSymbol) {
    int oldSamplesRead = samplesRead;
    samplesRead += mRadio->readSamples(shortVector+2*samplesRead,
				     OUTCHUNK*samplesPerSymbol-samplesRead,
				     &overrun,
				     readTimestamp,
				     &localUnderrun);
    underrun |= localUnderrun;
    readTimestamp += (TIMESTAMP) (samplesRead - oldSamplesRead);
  }
  //LOG(DEBUG) << "samplesRead " << samplesRead;

  rcvCursor += samplesRead*2;

}

bool RadioInterface::setVCTCXO(unsigned int tuneVoltage)
{
  return mRadio->setVCTCXO(tuneVoltage);

}

bool RadioInterface::tuneTx(double freq, double adjFreq)
{
  return mRadio->setTxFreq(freq, adjFreq);
}

bool RadioInterface::tuneRx(double freq, double adjFreq)
{
  return mRadio->setRxFreq(freq, adjFreq);
}

void RadioInterface::start()
{
  LOG(INFO) << "starting radio interface...";
  mAlignRadioServiceLoopThread.start((void * (*)(void*))AlignRadioServiceLoopAdapter,
                                     (void*)this);
  writeTimestamp = mRadio->initialWriteTimestamp();
  readTimestamp = mRadio->initialReadTimestamp();
  mRadio->start();
  LOG(DEBUG) << "Radio started";
  mRadio->updateAlignment(writeTimestamp-10000);
  mRadio->updateAlignment(writeTimestamp-10000);

  sendBuffer = new short[2*2*INCHUNK*samplesPerSymbol];
  rcvBuffer = new short[2*2*OUTCHUNK*samplesPerSymbol];

  mOn = true;

  if (loadTest) {
    int mOversamplingRate = samplesPerSymbol;
    int numARFCN = mNumARFCNs;
    signalVector *gsmPulse = generateGSMPulse(2,1);
    BitVector normalBurstSeg = "0000101010100111110010101010010110101110011000111001101010000";
    BitVector normalBurst(BitVector(normalBurstSeg,gTrainingSequence[2]),normalBurstSeg);
    signalVector *modBurst = modulateBurst(normalBurst,*gsmPulse,8,1);
    signalVector *modBurst9 = modulateBurst(normalBurst,*gsmPulse,9,1);
    signalVector *interpolationFilter = createLPF(0.6/mOversamplingRate,6*mOversamplingRate,1);
    scaleVector(*modBurst,mRadio->fullScaleInputValue());
    scaleVector(*modBurst9,mRadio->fullScaleInputValue());
    double beaconFreq = -1.0*(numARFCN-1)*200e3;
    finalVec = new signalVector(156*mOversamplingRate);
    finalVec9 = new signalVector(157*mOversamplingRate);
    for (int j = 0; j < numARFCN; j++) {
        signalVector *frequencyShifter = new signalVector(157*mOversamplingRate);
        frequencyShifter->fill(1.0);
        frequencyShift(frequencyShifter,frequencyShifter,2.0*M_PI*(beaconFreq+j*400e3)/(1625.0e3/6.0*mOversamplingRate));
        signalVector *interpVec = polyphaseResampleVector(*modBurst,mOversamplingRate,1,interpolationFilter);
        multVector(*interpVec,*frequencyShifter);
        addVector(*finalVec,*interpVec);
        interpVec = polyphaseResampleVector(*modBurst9,mOversamplingRate,1,interpolationFilter);
        multVector(*interpVec,*frequencyShifter);
        addVector(*finalVec9,*interpVec);
    }
  }

}

void *AlignRadioServiceLoopAdapter(RadioInterface *radioInterface)
{
  while (1) {
    radioInterface->alignRadio();
    pthread_testcancel();
  }
  return NULL;
}

void RadioInterface::alignRadio() {
  sleep(60);
  mRadio->updateAlignment(writeTimestamp+ (TIMESTAMP) 10000);
}

void RadioInterface::driveTransmitRadio(signalVector &radioBurst, bool zeroBurst) {

  if (!mOn) return;

  radioifyVector(radioBurst, sendBuffer+sendCursor, powerScaling, zeroBurst);

  sendCursor += (radioBurst.size()*2);

  pushBuffer();
}

void RadioInterface::driveReceiveRadio() {

  if (!mOn) return;

  if (mReceiveFIFO.size() > 8) return;

  pullBuffer();

  GSM::Time rcvClock = mClock.get();
  rcvClock.decTN(receiveOffset);
  unsigned tN = rcvClock.TN();
  int rcvSz = rcvCursor/2;
  int readSz = 0;
  const int symbolsPerSlot = gSlotLen + 8;

  // while there's enough data in receive buffer, form received
  //    GSM bursts and pass up to Transceiver
  // Using the 157-156-156-156 symbols per timeslot format.
  while (rcvSz > (symbolsPerSlot + (tN % 4 == 0))*samplesPerSymbol) {
    signalVector rxVector((symbolsPerSlot + (tN % 4 == 0))*samplesPerSymbol);
    unRadioifyVector(rcvBuffer+readSz*2,rxVector);
    GSM::Time tmpTime = rcvClock;
    if (rcvClock.FN() >= 0) {
      //LOG(DEBUG) << "FN: " << rcvClock.FN();
      int dummyARFCN = 0;
      radioVector *rxBurst = NULL;
      if (!loadTest)
        rxBurst = new radioVector(rxVector,tmpTime,dummyARFCN);
      else {
	if (tN % 4 == 0)
	  rxBurst = new radioVector(*finalVec9,tmpTime,dummyARFCN);
        else
          rxBurst = new radioVector(*finalVec,tmpTime,dummyARFCN);
      }
      mReceiveFIFO.put(rxBurst);
    }
    mClock.incTN();
    rcvClock.incTN();
    //if (mReceiveFIFO.size() >= 16) mReceiveFIFO.wait(8);
    //LOG(DEBUG) << "receiveFIFO: wrote radio vector at time: " << mClock.get() << ", new size: " << mReceiveFIFO.size() ;
    readSz += (symbolsPerSlot+(tN % 4 == 0))*samplesPerSymbol;
    rcvSz -= (symbolsPerSlot+(tN % 4 == 0))*samplesPerSymbol;

    tN = rcvClock.TN();
  }

  if (readSz > 0) {
    memcpy(rcvBuffer,rcvBuffer+2*readSz,sizeof(short)*2*(rcvCursor-readSz));
    rcvCursor = rcvCursor-2*readSz;
  }
}

<commit_msg>Fix incorrect buffer management in send and rcv buffering.<commit_after>/*
* Copyright 2008, 2009 Free Software Foundation, Inc.
*
* This software is distributed under multiple licenses; see the COPYING file in the main directory for licensing information for this specific distribuion.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

*/

//#define NDEBUG
#include "radioInterface.h"
#include <Logger.h>

GSM::Time VectorQueue::nextTime() const
{
  GSM::Time retVal;
  ScopedLock lock(mLock);
  while (mQ.size()==0) mWriteSignal.wait(mLock);
  return mQ.top()->time();
}

radioVector* VectorQueue::getStaleBurst(const GSM::Time& targTime)
{
  ScopedLock lock(mLock);
  if ((mQ.size()==0)) {
    return NULL;
  }
  if (mQ.top()->time() < targTime) {
    radioVector* retVal = mQ.top();
    mQ.pop();
    return retVal;
  }
  return NULL;
}

radioVector* VectorQueue::getCurrentBurst(const GSM::Time& targTime)
{
  ScopedLock lock(mLock);
  if ((mQ.size()==0)) {
    return NULL;
  }
  if (mQ.top()->time() == targTime) {
    radioVector* retVal = mQ.top();
    mQ.pop();
    return retVal;
  }
  return NULL;
}

RadioInterface::RadioInterface(RadioDevice *wRadio,
                               int wReceiveOffset,
			       int wRadioOversampling,
			       int wTransceiverOversampling,
			       bool wLoadTest,
			       unsigned int wNumARFCNs,
			       GSM::Time wStartTime)

{
  underrun = false;

  sendCursor = 0;
  rcvCursor = 0;
  mOn = false;

  mRadio = wRadio;
  receiveOffset = wReceiveOffset;
  samplesPerSymbol = wRadioOversampling;
  mClock.set(wStartTime);
  powerScaling = 1.0;
  mNumARFCNs = wNumARFCNs;

  loadTest = wLoadTest;
}

RadioInterface::~RadioInterface(void) {
  if (rcvBuffer!=NULL) delete rcvBuffer;
  //mReceiveFIFO.clear();
}

double RadioInterface::fullScaleInputValue(void) {
  return mRadio->fullScaleInputValue();
}

double RadioInterface::fullScaleOutputValue(void) {
  return mRadio->fullScaleOutputValue();
}

void RadioInterface::setPowerAttenuation(double dBAtten)
{
  float HWdBAtten = mRadio->setTxGain(-dBAtten);
  dBAtten -= (-HWdBAtten);
  float linearAtten = powf(10.0F,0.1F*dBAtten);
  if (linearAtten < 1.0)
    powerScaling = 1.0;
  else
    powerScaling = 1.0/sqrt(linearAtten);
  LOG(INFO) << "setting HW gain to " << HWdBAtten << " and power scaling to " << powerScaling;
}

short *RadioInterface::radioifyVector(signalVector &wVector, short *retVector, double scale, bool zeroOut)
{

  signalVector::iterator itr = wVector.begin();
  short *shortItr = retVector;
  if (zeroOut) {
    while (itr < wVector.end()) {
      *shortItr++ = 0;
      *shortItr++ = 0;
      itr++;
    }
  }
  else if (scale != 1.0) {
    while (itr < wVector.end()) {
      *shortItr++ = (short) (itr->real()*scale);
      *shortItr++ = (short) (itr->imag()*scale);
      itr++;
    }
  }
  else {
    while (itr < wVector.end()) {
      *shortItr++ = (short) (itr->real());
      *shortItr++ = (short) (itr->imag());
      itr++;
    }
  }

  return retVector;

}

void RadioInterface::unRadioifyVector(short *shortVector, signalVector& newVector)
{

  signalVector::iterator itr = newVector.begin();
  short *shortItr = shortVector;
  while (itr < newVector.end()) {
    *itr++ = Complex<float>(*shortItr,*(shortItr+1));
    //LOG(DEBUG) << (*(itr-1));
    shortItr += 2;
  }

}

bool started = false;

void RadioInterface::pushBuffer(void) {

  if (sendCursor < 2*INCHUNK*samplesPerSymbol) return;

  // send resampleVector
  int samplesWritten = mRadio->writeSamples(sendBuffer,
					  INCHUNK*samplesPerSymbol,
					  &underrun,
					  writeTimestamp);
  //LOG(DEBUG) << "writeTimestamp: " << writeTimestamp << ", samplesWritten: " << samplesWritten;

  writeTimestamp += (TIMESTAMP) samplesWritten;

  if (sendCursor > 2*samplesWritten)
    memcpy(sendBuffer,sendBuffer+samplesWritten*2,sizeof(short)*(sendCursor-2*samplesWritten));
  sendCursor = sendCursor - 2*samplesWritten;
}

void RadioInterface::pullBuffer(void)
{

  bool localUnderrun;

   // receive receiveVector
  short* shortVector = rcvBuffer+rcvCursor;
  //LOG(DEBUG) << "Reading USRP samples at timestamp " << readTimestamp;
  int samplesRead = mRadio->readSamples(shortVector,OUTCHUNK*samplesPerSymbol,&overrun,readTimestamp,&localUnderrun);
  underrun |= localUnderrun;
  readTimestamp += (TIMESTAMP) samplesRead;
  while (samplesRead < OUTCHUNK*samplesPerSymbol) {
    int oldSamplesRead = samplesRead;
    samplesRead += mRadio->readSamples(shortVector+2*samplesRead,
				     OUTCHUNK*samplesPerSymbol-samplesRead,
				     &overrun,
				     readTimestamp,
				     &localUnderrun);
    underrun |= localUnderrun;
    readTimestamp += (TIMESTAMP) (samplesRead - oldSamplesRead);
  }
  //LOG(DEBUG) << "samplesRead " << samplesRead;

  rcvCursor += samplesRead*2;

}

bool RadioInterface::setVCTCXO(unsigned int tuneVoltage)
{
  return mRadio->setVCTCXO(tuneVoltage);

}

bool RadioInterface::tuneTx(double freq, double adjFreq)
{
  return mRadio->setTxFreq(freq, adjFreq);
}

bool RadioInterface::tuneRx(double freq, double adjFreq)
{
  return mRadio->setRxFreq(freq, adjFreq);
}

void RadioInterface::start()
{
  LOG(INFO) << "starting radio interface...";
  mAlignRadioServiceLoopThread.start((void * (*)(void*))AlignRadioServiceLoopAdapter,
                                     (void*)this);
  writeTimestamp = mRadio->initialWriteTimestamp();
  readTimestamp = mRadio->initialReadTimestamp();
  mRadio->start();
  LOG(DEBUG) << "Radio started";
  mRadio->updateAlignment(writeTimestamp-10000);
  mRadio->updateAlignment(writeTimestamp-10000);

  sendBuffer = new short[2*2*INCHUNK*samplesPerSymbol];
  rcvBuffer = new short[2*2*OUTCHUNK*samplesPerSymbol];

  mOn = true;

  if (loadTest) {
    int mOversamplingRate = samplesPerSymbol;
    int numARFCN = mNumARFCNs;
    signalVector *gsmPulse = generateGSMPulse(2,1);
    BitVector normalBurstSeg = "0000101010100111110010101010010110101110011000111001101010000";
    BitVector normalBurst(BitVector(normalBurstSeg,gTrainingSequence[2]),normalBurstSeg);
    signalVector *modBurst = modulateBurst(normalBurst,*gsmPulse,8,1);
    signalVector *modBurst9 = modulateBurst(normalBurst,*gsmPulse,9,1);
    signalVector *interpolationFilter = createLPF(0.6/mOversamplingRate,6*mOversamplingRate,1);
    scaleVector(*modBurst,mRadio->fullScaleInputValue());
    scaleVector(*modBurst9,mRadio->fullScaleInputValue());
    double beaconFreq = -1.0*(numARFCN-1)*200e3;
    finalVec = new signalVector(156*mOversamplingRate);
    finalVec9 = new signalVector(157*mOversamplingRate);
    for (int j = 0; j < numARFCN; j++) {
        signalVector *frequencyShifter = new signalVector(157*mOversamplingRate);
        frequencyShifter->fill(1.0);
        frequencyShift(frequencyShifter,frequencyShifter,2.0*M_PI*(beaconFreq+j*400e3)/(1625.0e3/6.0*mOversamplingRate));
        signalVector *interpVec = polyphaseResampleVector(*modBurst,mOversamplingRate,1,interpolationFilter);
        multVector(*interpVec,*frequencyShifter);
        addVector(*finalVec,*interpVec);
        interpVec = polyphaseResampleVector(*modBurst9,mOversamplingRate,1,interpolationFilter);
        multVector(*interpVec,*frequencyShifter);
        addVector(*finalVec9,*interpVec);
    }
  }

}

void *AlignRadioServiceLoopAdapter(RadioInterface *radioInterface)
{
  while (1) {
    radioInterface->alignRadio();
    pthread_testcancel();
  }
  return NULL;
}

void RadioInterface::alignRadio() {
  sleep(60);
  mRadio->updateAlignment(writeTimestamp+ (TIMESTAMP) 10000);
}

void RadioInterface::driveTransmitRadio(signalVector &radioBurst, bool zeroBurst) {

  if (!mOn) return;

  radioifyVector(radioBurst, sendBuffer+sendCursor, powerScaling, zeroBurst);

  sendCursor += (radioBurst.size()*2);

  pushBuffer();
}

void RadioInterface::driveReceiveRadio() {

  if (!mOn) return;

  if (mReceiveFIFO.size() > 8) return;

  pullBuffer();

  GSM::Time rcvClock = mClock.get();
  rcvClock.decTN(receiveOffset);
  unsigned tN = rcvClock.TN();
  int rcvSz = rcvCursor/2;
  int readSz = 0;
  const int symbolsPerSlot = gSlotLen + 8;

  // while there's enough data in receive buffer, form received
  //    GSM bursts and pass up to Transceiver
  // Using the 157-156-156-156 symbols per timeslot format.
  while (rcvSz > (symbolsPerSlot + (tN % 4 == 0))*samplesPerSymbol) {
    signalVector rxVector((symbolsPerSlot + (tN % 4 == 0))*samplesPerSymbol);
    unRadioifyVector(rcvBuffer+readSz*2,rxVector);
    GSM::Time tmpTime = rcvClock;
    if (rcvClock.FN() >= 0) {
      //LOG(DEBUG) << "FN: " << rcvClock.FN();
      int dummyARFCN = 0;
      radioVector *rxBurst = NULL;
      if (!loadTest)
        rxBurst = new radioVector(rxVector,tmpTime,dummyARFCN);
      else {
	if (tN % 4 == 0)
	  rxBurst = new radioVector(*finalVec9,tmpTime,dummyARFCN);
        else
          rxBurst = new radioVector(*finalVec,tmpTime,dummyARFCN);
      }
      mReceiveFIFO.put(rxBurst);
    }
    mClock.incTN();
    rcvClock.incTN();
    //if (mReceiveFIFO.size() >= 16) mReceiveFIFO.wait(8);
    //LOG(DEBUG) << "receiveFIFO: wrote radio vector at time: " << mClock.get() << ", new size: " << mReceiveFIFO.size() ;
    readSz += (symbolsPerSlot+(tN % 4 == 0))*samplesPerSymbol;
    rcvSz -= (symbolsPerSlot+(tN % 4 == 0))*samplesPerSymbol;

    tN = rcvClock.TN();
  }

  if (readSz > 0) {
    memcpy(rcvBuffer,rcvBuffer+2*readSz,sizeof(short)*(rcvCursor-2*readSz));
    rcvCursor = rcvCursor-2*readSz;
  }
}

<|endoftext|>


<commit_before>#ifndef MJOLNIR_GLOBAL_DISTANCE_INTEARACTION
#define MJOLNIR_GLOBAL_DISTANCE_INTEARACTION
#include "GlobalInteractionBase.hpp"
#include <memory>

namespace mjolnir
{

template<typename traitsT, typename potentialT, typename partitionT>
class GlobalDistanceInteraction final : public GlobalInteractionBase<traitsT>
{
  public:

    typedef traitsT    traits_type;
    typedef potentialT potential_type;
    typedef partitionT partition_type;
    typedef GlobalInteractionBase<traitsT> base_type;
    typedef typename base_type::real_type       real_type;
    typedef typename base_type::coordinate_type coordinate_type;
    typedef typename base_type::system_type     system_type;
    typedef typename base_type::particle_type   particle_type;
    typedef typename base_type::boundary_type   boundary_type;

  public:
    GlobalDistanceInteraction()  = default;
    ~GlobalDistanceInteraction() = default;

    GlobalDistanceInteraction(potential_type&& pot, partition_type&& part)
        : potential_(std::move(pot)), partition_(std::move(part))
    {}

    /*! @brief initialize spatial partition (e.g. CellList)                   *
     *  @details before calling `calc_(force|energy)`, this should be called. */
    void initialize(const system_type& sys, const real_type dt) override
    {
        this->partition_.initialize(sys);
        this->partition_.update(sys);
    }

    /*! @brief update parameters (e.g. dt, temperature, ionic strength, ...)  *
     *  @details A method that change system parameters (e.g. Annealing),     *
     *           the method is bound to call this function after changing     *
     *           parameters.                                                  */
    void update(const system_type& sys, const real_type dt) override
    {
        this->potential_.update(sys);
        // potential update may change the cutoff length!
        this->partition_.set_cutoff(potential_.max_cutoff_length());
        this->partition_.update(sys);
    }

    void      calc_force (system_type&)             override;
    real_type calc_energy(const system_type&) const override;

    std::string name() const noexcept override
    {return "Distance:" + potential_.name();}

  private:

    potential_type potential_;
    partition_type partition_;
};

template<typename traitsT, typename potT, typename spaceT>
void GlobalDistanceInteraction<traitsT, potT, spaceT>::calc_force(
        system_type& sys)
{
    partition_.update(sys);
    for(std::size_t i=0; i<sys.size(); ++i)
    {
        for(auto j : this->partition_.partners(i))
        {
            const coordinate_type rij =
                sys.adjust_direction(sys[j].position - sys[i].position);
            const real_type l = length(rij);
            const real_type f_mag = potential_.derivative(i, j, l);
            if(f_mag == 0.0){continue;}

            const coordinate_type f = rij * (f_mag / l);
            sys[i].force += f;
            sys[j].force -= f;
        }
    }
    return ;
}

template<typename traitsT, typename potT, typename spaceT>
typename GlobalDistanceInteraction<traitsT, potT, spaceT>::real_type
GlobalDistanceInteraction<traitsT, potT, spaceT>::calc_energy(
        const system_type& sys) const
{
    real_type e = 0.0;
    for(std::size_t i=0; i<sys.size(); ++i)
    {
        for(auto j : this->partition_.partners(i))
        {
            const real_type l = length(
                sys.adjust_direction(sys[j].position - sys[i].position));
            e += potential_.potential(i, j, l);
        }
    }
    return e;
}

} // mjolnir
#endif /* MJOLNIR_GLOBAL_DISTANCE_INTEARACTION */
<commit_msg>add some comments<commit_after>#ifndef MJOLNIR_GLOBAL_DISTANCE_INTEARACTION
#define MJOLNIR_GLOBAL_DISTANCE_INTEARACTION
#include "GlobalInteractionBase.hpp"
#include <memory>

namespace mjolnir
{

template<typename traitsT, typename potentialT, typename partitionT>
class GlobalDistanceInteraction final : public GlobalInteractionBase<traitsT>
{
  public:

    typedef traitsT    traits_type;
    typedef potentialT potential_type;
    typedef partitionT partition_type;
    typedef GlobalInteractionBase<traitsT> base_type;
    typedef typename base_type::real_type       real_type;
    typedef typename base_type::coordinate_type coordinate_type;
    typedef typename base_type::system_type     system_type;
    typedef typename base_type::particle_type   particle_type;
    typedef typename base_type::boundary_type   boundary_type;

  public:
    GlobalDistanceInteraction()  = default;
    ~GlobalDistanceInteraction() = default;

    GlobalDistanceInteraction(potential_type&& pot, partition_type&& part)
        : potential_(std::move(pot)), partition_(std::move(part))
    {}

    /*! @brief initialize spatial partition (e.g. CellList)                   *
     *  @details before calling `calc_(force|energy)`, this should be called. */
    void initialize(const system_type& sys, const real_type dt) override
    {
        this->partition_.initialize(sys);
        this->partition_.update(sys);
    }

    /*! @brief update parameters (e.g. dt, temperature, ionic strength, ...)  *
     *  @details A method that change system parameters (e.g. Annealing),     *
     *           the method is bound to call this function after changing     *
     *           parameters.                                                  */
    void update(const system_type& sys, const real_type dt) override
    {
        this->potential_.update(sys);
        // potential update may change the cutoff length!
        this->partition_.set_cutoff(potential_.max_cutoff_length());
        this->partition_.update(sys);
    }

    void      calc_force (system_type&)             override;
    real_type calc_energy(const system_type&) const override;

    std::string name() const noexcept override
    {return "Distance:" + potential_.name();}

  private:

    potential_type potential_;
    partition_type partition_;
};

template<typename traitsT, typename potT, typename spaceT>
void GlobalDistanceInteraction<traitsT, potT, spaceT>::calc_force(
        system_type& sys)
{
    partition_.update(sys); // reduce mergin and reconstruct pair-list if needed
    for(std::size_t i=0; i<sys.size(); ++i)
    {
        for(auto j : this->partition_.partners(i))
        {
            const coordinate_type rij =
                sys.adjust_direction(sys[j].position - sys[i].position);
            const real_type l = length(rij);
            const real_type f_mag = potential_.derivative(i, j, l);

            // if length exceeds cutoff, potential returns just 0.
            if(f_mag == 0.0){continue;}

            const coordinate_type f = rij * (f_mag / l);
            sys[i].force += f;
            sys[j].force -= f;
        }
    }
    return ;
}

template<typename traitsT, typename potT, typename spaceT>
typename GlobalDistanceInteraction<traitsT, potT, spaceT>::real_type
GlobalDistanceInteraction<traitsT, potT, spaceT>::calc_energy(
        const system_type& sys) const
{
    real_type e = 0.0;
    for(std::size_t i=0; i<sys.size(); ++i)
    {
        for(auto j : this->partition_.partners(i))
        {
            const real_type l = length(
                sys.adjust_direction(sys[j].position - sys[i].position));
            e += potential_.potential(i, j, l);
        }
    }
    return e;
}

} // mjolnir
#endif /* MJOLNIR_GLOBAL_DISTANCE_INTEARACTION */
<|endoftext|>