<commit_before>// Copyright 2021 Code Intelligence GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "libfuzzer_driver.h"

#include <algorithm>
#include <filesystem>
#include <fstream>
#include <random>
#include <string>
#include <vector>

#include "absl/strings/match.h"
#include "absl/strings/str_format.h"
#include "fuzz_target_runner.h"
#include "gflags/gflags.h"
#include "glog/logging.h"
#include "jvm_tooling.h"

using namespace std::string_literals;

// Defined by glog
DECLARE_bool(log_prefix);

// Defined in libfuzzer_callbacks.cpp
DECLARE_bool(fake_pcs);

// Defined in jvm_tooling.cpp
DECLARE_string(id_sync_file);

// Defined in fuzz_target_runner.cpp
DECLARE_string(coverage_report);

// This symbol is defined by sanitizers if linked into Jazzer or in
// sanitizer_symbols.cpp if no sanitizer is used.
extern "C" void __sanitizer_set_death_callback(void (*)());

// We apply a patch to libFuzzer to make it call this function instead of
// __sanitizer_set_death_callback to pass us the death callback.
extern "C" [[maybe_unused]] void __jazzer_set_death_callback(
    void (*callback)()) {
  jazzer::AbstractLibfuzzerDriver::libfuzzer_print_crashing_input_ = callback;
  __sanitizer_set_death_callback(callback);
}

namespace {
char *additional_arg;
std::vector<char *> modified_argv;

std::string GetNewTempFilePath() {
  auto temp_dir = std::filesystem::temp_directory_path();

  std::string temp_filename_suffix(32, '\0');
  std::random_device rng;
  std::uniform_int_distribution<short> dist(0, 'z' - 'a');
  std::generate_n(temp_filename_suffix.begin(), temp_filename_suffix.length(),
                  [&rng, &dist] { return static_cast<char>('a' + dist(rng)); });

  auto temp_path = temp_dir / ("jazzer-" + temp_filename_suffix);
  if (std::filesystem::exists(temp_path))
    throw std::runtime_error("Random temp file path exists: " +
                             temp_path.string());
  return temp_path;
}
}  // namespace

namespace jazzer {
// A libFuzzer-registered callback that outputs the crashing input, but does
// not include a stack trace.
void (*AbstractLibfuzzerDriver::libfuzzer_print_crashing_input_)() = nullptr;

AbstractLibfuzzerDriver::AbstractLibfuzzerDriver(
    int *argc, char ***argv, const std::string &usage_string) {
  gflags::SetUsageMessage(usage_string);
  // Disable glog log prefixes to mimic libFuzzer output.
  FLAGS_log_prefix = false;
  google::InitGoogleLogging((*argv)[0]);

  auto argv_start = *argv;
  auto argv_end = *argv + *argc;

  if (std::find(argv_start, argv_end, "-use_value_profile=1"s) != argv_end) {
    FLAGS_fake_pcs = true;
  }

  // All libFuzzer flags start with a single dash, our arguments all start with
  // a double dash. We can thus filter out the arguments meant for gflags by
  // taking only those with a leading double dash.
  std::vector<char *> our_args = {*argv_start};
  std::copy_if(
      argv_start, argv_end, std::back_inserter(our_args),
      [](const auto arg) { return absl::StartsWith(std::string(arg), "--"); });
  int our_argc = our_args.size();
  char **our_argv = our_args.data();
  // Let gflags consume its flags, but keep them in the argument list in case
  // libFuzzer forwards the command line (e.g. with -jobs or -minimize_crash).
  gflags::ParseCommandLineFlags(&our_argc, &our_argv, false);

  if (std::any_of(argv_start, argv_end, [](const std::string_view &arg) {
        return absl::StartsWith(arg, "-fork=") ||
               absl::StartsWith(arg, "-jobs=") ||
               absl::StartsWith(arg, "-merge=");
      })) {
    if (!FLAGS_coverage_report.empty()) {
      LOG(WARNING) << "WARN: --coverage_report does not support parallel "
                      "fuzzing and has been disabled";
      FLAGS_coverage_report = "";
    }
    if (FLAGS_id_sync_file.empty()) {
      // Create an empty temporary file used for coverage ID synchronization and
      // pass its path to the agent in every child process. This requires adding
      // the argument to argv for it to be picked up by libFuzzer, which then
      // forwards it to child processes.
      FLAGS_id_sync_file = GetNewTempFilePath();
      std::string new_arg =
          absl::StrFormat("--id_sync_file=%s", FLAGS_id_sync_file);
      // This argument can be accessed by libFuzzer at any (later) time and thus
      // cannot be safely freed by us.
      additional_arg = strdup(new_arg.c_str());
      modified_argv = std::vector<char *>(argv_start, argv_end);
      modified_argv.push_back(additional_arg);
      // Terminate modified_argv.
      modified_argv.push_back(nullptr);
      // Modify argv and argc for libFuzzer. modified_argv must not be changed
      // after this point.
      *argc += 1;
      *argv = modified_argv.data();
      argv_start = *argv;
      argv_end = *argv + *argc;
    }
    // Creates the file, truncating it if it exists.
    std::ofstream touch_file(FLAGS_id_sync_file, std::ios_base::trunc);

    auto cleanup_fn = [] {
      try {
        std::filesystem::remove(std::filesystem::path(FLAGS_id_sync_file));
      } catch (...) {
        // We should not throw exceptions during shutdown.
      }
    };
    std::atexit(cleanup_fn);
  }

  initJvm(*argv_start);
}

void AbstractLibfuzzerDriver::initJvm(const std::string &executable_path) {
  jvm_ = std::make_unique<jazzer::JVM>(executable_path);
}

LibfuzzerDriver::LibfuzzerDriver(int *argc, char ***argv)
    : AbstractLibfuzzerDriver(argc, argv, getUsageString()) {
  // the FuzzTargetRunner can only be initialized after the fuzzer callbacks
  // have been registered otherwise link errors would occur
  runner_ = std::make_unique<jazzer::FuzzTargetRunner>(*jvm_);
}

std::string LibfuzzerDriver::getUsageString() {
  return R"(Test java fuzz targets using libFuzzer. Usage:
  jazzer --cp=<java_class_path> --target_class=<fuzz_target_class> <libfuzzer_arguments...>)";
}

RunResult LibfuzzerDriver::TestOneInput(const uint8_t *data,
                                        const std::size_t size) {
  // pass the fuzzer input to the java fuzz target
  return runner_->Run(data, size);
}

void LibfuzzerDriver::DumpReproducer(const uint8_t *data, std::size_t size) {
  return runner_->DumpReproducer(data, size);
}

}  // namespace jazzer
<commit_msg>Explicitly convert filesystem::path to string<commit_after>// Copyright 2021 Code Intelligence GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "libfuzzer_driver.h"

#include <algorithm>
#include <filesystem>
#include <fstream>
#include <random>
#include <string>
#include <vector>

#include "absl/strings/match.h"
#include "absl/strings/str_format.h"
#include "fuzz_target_runner.h"
#include "gflags/gflags.h"
#include "glog/logging.h"
#include "jvm_tooling.h"

using namespace std::string_literals;

// Defined by glog
DECLARE_bool(log_prefix);

// Defined in libfuzzer_callbacks.cpp
DECLARE_bool(fake_pcs);

// Defined in jvm_tooling.cpp
DECLARE_string(id_sync_file);

// Defined in fuzz_target_runner.cpp
DECLARE_string(coverage_report);

// This symbol is defined by sanitizers if linked into Jazzer or in
// sanitizer_symbols.cpp if no sanitizer is used.
extern "C" void __sanitizer_set_death_callback(void (*)());

// We apply a patch to libFuzzer to make it call this function instead of
// __sanitizer_set_death_callback to pass us the death callback.
extern "C" [[maybe_unused]] void __jazzer_set_death_callback(
    void (*callback)()) {
  jazzer::AbstractLibfuzzerDriver::libfuzzer_print_crashing_input_ = callback;
  __sanitizer_set_death_callback(callback);
}

namespace {
char *additional_arg;
std::vector<char *> modified_argv;

std::string GetNewTempFilePath() {
  auto temp_dir = std::filesystem::temp_directory_path();

  std::string temp_filename_suffix(32, '\0');
  std::random_device rng;
  std::uniform_int_distribution<short> dist(0, 'z' - 'a');
  std::generate_n(temp_filename_suffix.begin(), temp_filename_suffix.length(),
                  [&rng, &dist] { return static_cast<char>('a' + dist(rng)); });

  auto temp_path = temp_dir / ("jazzer-" + temp_filename_suffix);
  if (std::filesystem::exists(temp_path))
    throw std::runtime_error("Random temp file path exists: " +
                             temp_path.string());
  return temp_path.generic_string();
}
}  // namespace

namespace jazzer {
// A libFuzzer-registered callback that outputs the crashing input, but does
// not include a stack trace.
void (*AbstractLibfuzzerDriver::libfuzzer_print_crashing_input_)() = nullptr;

AbstractLibfuzzerDriver::AbstractLibfuzzerDriver(
    int *argc, char ***argv, const std::string &usage_string) {
  gflags::SetUsageMessage(usage_string);
  // Disable glog log prefixes to mimic libFuzzer output.
  FLAGS_log_prefix = false;
  google::InitGoogleLogging((*argv)[0]);

  auto argv_start = *argv;
  auto argv_end = *argv + *argc;

  if (std::find(argv_start, argv_end, "-use_value_profile=1"s) != argv_end) {
    FLAGS_fake_pcs = true;
  }

  // All libFuzzer flags start with a single dash, our arguments all start with
  // a double dash. We can thus filter out the arguments meant for gflags by
  // taking only those with a leading double dash.
  std::vector<char *> our_args = {*argv_start};
  std::copy_if(
      argv_start, argv_end, std::back_inserter(our_args),
      [](const auto arg) { return absl::StartsWith(std::string(arg), "--"); });
  int our_argc = our_args.size();
  char **our_argv = our_args.data();
  // Let gflags consume its flags, but keep them in the argument list in case
  // libFuzzer forwards the command line (e.g. with -jobs or -minimize_crash).
  gflags::ParseCommandLineFlags(&our_argc, &our_argv, false);

  if (std::any_of(argv_start, argv_end, [](const std::string_view &arg) {
        return absl::StartsWith(arg, "-fork=") ||
               absl::StartsWith(arg, "-jobs=") ||
               absl::StartsWith(arg, "-merge=");
      })) {
    if (!FLAGS_coverage_report.empty()) {
      LOG(WARNING) << "WARN: --coverage_report does not support parallel "
                      "fuzzing and has been disabled";
      FLAGS_coverage_report = "";
    }
    if (FLAGS_id_sync_file.empty()) {
      // Create an empty temporary file used for coverage ID synchronization and
      // pass its path to the agent in every child process. This requires adding
      // the argument to argv for it to be picked up by libFuzzer, which then
      // forwards it to child processes.
      FLAGS_id_sync_file = GetNewTempFilePath();
      std::string new_arg =
          absl::StrFormat("--id_sync_file=%s", FLAGS_id_sync_file);
      // This argument can be accessed by libFuzzer at any (later) time and thus
      // cannot be safely freed by us.
      additional_arg = strdup(new_arg.c_str());
      modified_argv = std::vector<char *>(argv_start, argv_end);
      modified_argv.push_back(additional_arg);
      // Terminate modified_argv.
      modified_argv.push_back(nullptr);
      // Modify argv and argc for libFuzzer. modified_argv must not be changed
      // after this point.
      *argc += 1;
      *argv = modified_argv.data();
      argv_start = *argv;
      argv_end = *argv + *argc;
    }
    // Creates the file, truncating it if it exists.
    std::ofstream touch_file(FLAGS_id_sync_file, std::ios_base::trunc);

    auto cleanup_fn = [] {
      try {
        std::filesystem::remove(std::filesystem::path(FLAGS_id_sync_file));
      } catch (...) {
        // We should not throw exceptions during shutdown.
      }
    };
    std::atexit(cleanup_fn);
  }

  initJvm(*argv_start);
}

void AbstractLibfuzzerDriver::initJvm(const std::string &executable_path) {
  jvm_ = std::make_unique<jazzer::JVM>(executable_path);
}

LibfuzzerDriver::LibfuzzerDriver(int *argc, char ***argv)
    : AbstractLibfuzzerDriver(argc, argv, getUsageString()) {
  // the FuzzTargetRunner can only be initialized after the fuzzer callbacks
  // have been registered otherwise link errors would occur
  runner_ = std::make_unique<jazzer::FuzzTargetRunner>(*jvm_);
}

std::string LibfuzzerDriver::getUsageString() {
  return R"(Test java fuzz targets using libFuzzer. Usage:
  jazzer --cp=<java_class_path> --target_class=<fuzz_target_class> <libfuzzer_arguments...>)";
}

RunResult LibfuzzerDriver::TestOneInput(const uint8_t *data,
                                        const std::size_t size) {
  // pass the fuzzer input to the java fuzz target
  return runner_->Run(data, size);
}

void LibfuzzerDriver::DumpReproducer(const uint8_t *data, std::size_t size) {
  return runner_->DumpReproducer(data, size);
}

}  // namespace jazzer
<|endoftext|>


<commit_before>#ifndef RETRO_CRANDOM16_HPP
#define RETRO_CRANDOM16_HPP

#include "GCNTypes.hpp"

namespace urde
{

class CRandom16
{
    u32 m_seed;
    static CRandom16* g_randomNumber;
public:
    CRandom16() = default;
    CRandom16(u32 p) : m_seed(p) {}

    inline u32 Next()
    {
        m_seed = (m_seed * 0x41c64e6d) + 0x00003039;
        return m_seed >> 16;
    }

    inline u32 GetSeed() const
    {
        return m_seed;
    }

    inline void SetSeed(u32 p)
    {
        m_seed = p;
    }

    inline float Float()
    {
        return Next() * 0.000015259022;
    }

    inline float Range(float min, float max)
    {
        return min + Float() * (max - min);
    }

    inline s32 Range(s32 min, s32 max)
    {
        const s32 rand = Next();
        return min + (rand / ((min - max) + 1)) - rand;
    }

    static CRandom16* GetRandomNumber() {return g_randomNumber;}
    static void SetRandomNumber(CRandom16* rnd) {g_randomNumber = rnd;}
};

class CGlobalRandom
{
    CRandom16& m_random;
    CGlobalRandom* m_prev;
    static CGlobalRandom* g_currentGlobalRandom;
public:
    CGlobalRandom(CRandom16& rand)
    : m_random(rand), m_prev(g_currentGlobalRandom)
    {
        g_currentGlobalRandom = this;
        CRandom16::SetRandomNumber(&m_random);
    }
    ~CGlobalRandom()
    {
        g_currentGlobalRandom = m_prev;
        if (m_prev)
            CRandom16::SetRandomNumber(&m_prev->m_random);
        else
            CRandom16::SetRandomNumber(nullptr);
    }
};

}

#endif // RETRO_CRANDOM16_HPP
<commit_msg>Revert Range(s32,s32) change (causes segfault do to improper results)<commit_after>#ifndef RETRO_CRANDOM16_HPP
#define RETRO_CRANDOM16_HPP

#include "GCNTypes.hpp"

namespace urde
{

class CRandom16
{
    u32 m_seed;
    static CRandom16* g_randomNumber;
public:
    CRandom16() = default;
    CRandom16(u32 p) : m_seed(p) {}

    inline u32 Next()
    {
        m_seed = (m_seed * 0x41c64e6d) + 0x00003039;
        return m_seed >> 16;
    }

    inline u32 GetSeed() const
    {
        return m_seed;
    }

    inline void SetSeed(u32 p)
    {
        m_seed = p;
    }

    inline float Float()
    {
        return Next() * 0.000015259022;
    }

    inline float Range(float min, float max)
    {
        return min + Float() * (max - min);
    }

    inline s32 Range(s32 min, s32 max)
    {
        s32 diff = max - min;
        s32 rand = -1;
        while (rand < 0)
            rand = s32((Next() << 16) | Next());
        return rand % diff + min;
    }

    static CRandom16* GetRandomNumber() {return g_randomNumber;}
    static void SetRandomNumber(CRandom16* rnd) {g_randomNumber = rnd;}
};

class CGlobalRandom
{
    CRandom16& m_random;
    CGlobalRandom* m_prev;
    static CGlobalRandom* g_currentGlobalRandom;
public:
    CGlobalRandom(CRandom16& rand)
        : m_random(rand), m_prev(g_currentGlobalRandom)
    {
        g_currentGlobalRandom = this;
        CRandom16::SetRandomNumber(&m_random);
    }
    ~CGlobalRandom()
    {
        g_currentGlobalRandom = m_prev;
        if (m_prev)
            CRandom16::SetRandomNumber(&m_prev->m_random);
        else
            CRandom16::SetRandomNumber(nullptr);
    }
};

}

#endif // RETRO_CRANDOM16_HPP
<|endoftext|>


<commit_before>/**
 *  @file
 *  @copyright defined in eosio/LICENSE.txt
 */
#include <appbase/application.hpp>

#include <eosio/chain_plugin/chain_plugin.hpp>
#include <eosio/http_plugin/http_plugin.hpp>
#include <eosio/history_plugin/history_plugin.hpp>
#include <eosio/net_plugin/net_plugin.hpp>
#include <eosio/producer_plugin/producer_plugin.hpp>
#include <eosio/utilities/common.hpp>

#include <fc/log/logger_config.hpp>
#include <fc/log/appender.hpp>
#include <fc/exception/exception.hpp>

#include <boost/dll/runtime_symbol_info.hpp>
#include <boost/exception/diagnostic_information.hpp>

#include "config.hpp"

using namespace appbase;
using namespace eosio;

namespace fc {
   std::unordered_map<std::string,appender::ptr>& get_appender_map();
}

namespace detail {

void configure_logging(const bfs::path& config_path)
{
   try {
      try {
         fc::configure_logging(config_path);
      } catch (...) {
         elog("Error reloading logging.json");
         throw;
      }
   } catch (const fc::exception& e) {
      elog("${e}", ("e",e.to_detail_string()));
   } catch (const boost::exception& e) {
      elog("${e}", ("e",boost::diagnostic_information(e)));
   } catch (const std::exception& e) {
      elog("${e}", ("e",e.what()));
   } catch (...) {
      // empty
   }
}

} // namespace detail

void logging_conf_loop()
{
   std::shared_ptr<boost::asio::signal_set> sighup_set(new boost::asio::signal_set(app().get_io_service(), SIGHUP));
   sighup_set->async_wait([sighup_set](const boost::system::error_code& err, int /*num*/) {
      if(!err)
      {
         ilog("Received HUP.  Reloading logging configuration.");
         auto config_path = app().get_logging_conf();
         if(fc::exists(config_path))
            ::detail::configure_logging(config_path);
         for(auto iter : fc::get_appender_map())
            iter.second->initialize(app().get_io_service());
         logging_conf_loop();
      }
   });
}

void initialize_logging()
{
   auto config_path = app().get_logging_conf();
   if(fc::exists(config_path))
     fc::configure_logging(config_path); // intentionally allowing exceptions to escape
   for(auto iter : fc::get_appender_map())
     iter.second->initialize(app().get_io_service());

   logging_conf_loop();
}

enum return_codes {
   OTHER_FAIL        = -2,
   INITIALIZE_FAIL   = -1,
   SUCCESS           = 0,
   BAD_ALLOC         = 1,
   DATABASE_DIRTY    = 2,
   FIXED_REVERSIBLE  = 3,
   EXTRACTED_GENESIS = 4,
   NODE_MANAGEMENT_SUCCESS = 5
};

int main(int argc, char** argv)
{
   try {
      app().set_version(eosio::nodeos::config::version);
      app().register_plugin<history_plugin>();

      auto root = fc::app_path();
      app().set_default_data_dir(root / "eosio/nodeos/data" );
      app().set_default_config_dir(root / "eosio/nodeos/config" );
      http_plugin::set_defaults({
         .address_config_prefix = "",
         .default_unix_socket_path = "",
         .default_http_port = 8888
      });
      if(!app().initialize<chain_plugin, http_plugin, net_plugin, producer_plugin>(argc, argv))
         return INITIALIZE_FAIL;
      initialize_logging();
      ilog("nodeos version ${ver}", ("ver", app().version_string()));
      ilog("eosio root is ${root}", ("root", root.string()));
      ilog("nodeos using configuration file ${c}", ("c", app().full_config_file_path().string()));
      ilog("nodeos data directory is ${d}", ("d", app().data_dir().string()));
      app().startup();
      app().exec();
   } catch( const extract_genesis_state_exception& e ) {
      return EXTRACTED_GENESIS;
   } catch( const fixed_reversible_db_exception& e ) {
      return FIXED_REVERSIBLE;
   } catch( const node_management_success& e ) {
      return NODE_MANAGEMENT_SUCCESS;
   } catch( const fc::exception& e ) {
      if( e.code() == fc::std_exception_code ) {
         if( e.top_message().find( "database dirty flag set" ) != std::string::npos ) {
            elog( "database dirty flag set (likely due to unclean shutdown): replay required" );
            return DATABASE_DIRTY;
         } else if( e.top_message().find( "database metadata dirty flag set" ) != std::string::npos ) {
            elog( "database metadata dirty flag set (likely due to unclean shutdown): replay required" );
            return DATABASE_DIRTY;
         }
      }
      elog( "${e}", ("e", e.to_detail_string()));
      return OTHER_FAIL;
   } catch( const boost::interprocess::bad_alloc& e ) {
      elog("bad alloc");
      return BAD_ALLOC;
   } catch( const boost::exception& e ) {
      elog("${e}", ("e",boost::diagnostic_information(e)));
      return OTHER_FAIL;
   } catch( const std::runtime_error& e ) {
      if( std::string(e.what()) == "database dirty flag set" ) {
         elog( "database dirty flag set (likely due to unclean shutdown): replay required" );
         return DATABASE_DIRTY;
      } else if( std::string(e.what()) == "database metadata dirty flag set" ) {
         elog( "database metadata dirty flag set (likely due to unclean shutdown): replay required" );
         return DATABASE_DIRTY;
      } else {
         elog( "${e}", ("e",e.what()));
      }
      return OTHER_FAIL;
   } catch( const std::exception& e ) {
      elog("${e}", ("e",e.what()));
      return OTHER_FAIL;
   } catch( ... ) {
      elog("unknown exception");
      return OTHER_FAIL;
   }

   return SUCCESS;
}
<commit_msg>remove repeat load history_plugin<commit_after>/**
 *  @file
 *  @copyright defined in eosio/LICENSE.txt
 */
#include <appbase/application.hpp>

#include <eosio/chain_plugin/chain_plugin.hpp>
#include <eosio/http_plugin/http_plugin.hpp>
#include <eosio/history_plugin/history_plugin.hpp>
#include <eosio/net_plugin/net_plugin.hpp>
#include <eosio/producer_plugin/producer_plugin.hpp>
#include <eosio/utilities/common.hpp>

#include <fc/log/logger_config.hpp>
#include <fc/log/appender.hpp>
#include <fc/exception/exception.hpp>

#include <boost/dll/runtime_symbol_info.hpp>
#include <boost/exception/diagnostic_information.hpp>

#include "config.hpp"

using namespace appbase;
using namespace eosio;

namespace fc {
   std::unordered_map<std::string,appender::ptr>& get_appender_map();
}

namespace detail {

void configure_logging(const bfs::path& config_path)
{
   try {
      try {
         fc::configure_logging(config_path);
      } catch (...) {
         elog("Error reloading logging.json");
         throw;
      }
   } catch (const fc::exception& e) {
      elog("${e}", ("e",e.to_detail_string()));
   } catch (const boost::exception& e) {
      elog("${e}", ("e",boost::diagnostic_information(e)));
   } catch (const std::exception& e) {
      elog("${e}", ("e",e.what()));
   } catch (...) {
      // empty
   }
}

} // namespace detail

void logging_conf_loop()
{
   std::shared_ptr<boost::asio::signal_set> sighup_set(new boost::asio::signal_set(app().get_io_service(), SIGHUP));
   sighup_set->async_wait([sighup_set](const boost::system::error_code& err, int /*num*/) {
      if(!err)
      {
         ilog("Received HUP.  Reloading logging configuration.");
         auto config_path = app().get_logging_conf();
         if(fc::exists(config_path))
            ::detail::configure_logging(config_path);
         for(auto iter : fc::get_appender_map())
            iter.second->initialize(app().get_io_service());
         logging_conf_loop();
      }
   });
}

void initialize_logging()
{
   auto config_path = app().get_logging_conf();
   if(fc::exists(config_path))
     fc::configure_logging(config_path); // intentionally allowing exceptions to escape
   for(auto iter : fc::get_appender_map())
     iter.second->initialize(app().get_io_service());

   logging_conf_loop();
}

enum return_codes {
   OTHER_FAIL        = -2,
   INITIALIZE_FAIL   = -1,
   SUCCESS           = 0,
   BAD_ALLOC         = 1,
   DATABASE_DIRTY    = 2,
   FIXED_REVERSIBLE  = 3,
   EXTRACTED_GENESIS = 4,
   NODE_MANAGEMENT_SUCCESS = 5
};

int main(int argc, char** argv)
{
   try {
      app().set_version(eosio::nodeos::config::version);

      auto root = fc::app_path();
      app().set_default_data_dir(root / "eosio/nodeos/data" );
      app().set_default_config_dir(root / "eosio/nodeos/config" );
      http_plugin::set_defaults({
         .address_config_prefix = "",
         .default_unix_socket_path = "",
         .default_http_port = 8888
      });
      if(!app().initialize<chain_plugin, http_plugin, net_plugin, producer_plugin>(argc, argv))
         return INITIALIZE_FAIL;
      initialize_logging();
      ilog("nodeos version ${ver}", ("ver", app().version_string()));
      ilog("eosio root is ${root}", ("root", root.string()));
      ilog("nodeos using configuration file ${c}", ("c", app().full_config_file_path().string()));
      ilog("nodeos data directory is ${d}", ("d", app().data_dir().string()));
      app().startup();
      app().exec();
   } catch( const extract_genesis_state_exception& e ) {
      return EXTRACTED_GENESIS;
   } catch( const fixed_reversible_db_exception& e ) {
      return FIXED_REVERSIBLE;
   } catch( const node_management_success& e ) {
      return NODE_MANAGEMENT_SUCCESS;
   } catch( const fc::exception& e ) {
      if( e.code() == fc::std_exception_code ) {
         if( e.top_message().find( "database dirty flag set" ) != std::string::npos ) {
            elog( "database dirty flag set (likely due to unclean shutdown): replay required" );
            return DATABASE_DIRTY;
         } else if( e.top_message().find( "database metadata dirty flag set" ) != std::string::npos ) {
            elog( "database metadata dirty flag set (likely due to unclean shutdown): replay required" );
            return DATABASE_DIRTY;
         }
      }
      elog( "${e}", ("e", e.to_detail_string()));
      return OTHER_FAIL;
   } catch( const boost::interprocess::bad_alloc& e ) {
      elog("bad alloc");
      return BAD_ALLOC;
   } catch( const boost::exception& e ) {
      elog("${e}", ("e",boost::diagnostic_information(e)));
      return OTHER_FAIL;
   } catch( const std::runtime_error& e ) {
      if( std::string(e.what()) == "database dirty flag set" ) {
         elog( "database dirty flag set (likely due to unclean shutdown): replay required" );
         return DATABASE_DIRTY;
      } else if( std::string(e.what()) == "database metadata dirty flag set" ) {
         elog( "database metadata dirty flag set (likely due to unclean shutdown): replay required" );
         return DATABASE_DIRTY;
      } else {
         elog( "${e}", ("e",e.what()));
      }
      return OTHER_FAIL;
   } catch( const std::exception& e ) {
      elog("${e}", ("e",e.what()));
      return OTHER_FAIL;
   } catch( ... ) {
      elog("unknown exception");
      return OTHER_FAIL;
   }

   return SUCCESS;
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/////////////////////////////////////////////////////////////////////
//                                                                 //
//  class AliCDBEntry						   //
//  container for an object, it identity (AliCDBId)  		   //
//  and its metaData (AliCDBMetaData) 				   //
//                                                                 //
/////////////////////////////////////////////////////////////////////

#include "AliCDBEntry.h"
#include "AliLog.h"

ClassImp(AliCDBEntry)

//_____________________________________________________________________________
AliCDBEntry::AliCDBEntry():
fObject(NULL),
fId(),
fMetaData(NULL),
fIsOwner(kFALSE){
// default constructor

}

//_____________________________________________________________________________
AliCDBEntry::AliCDBEntry(TObject* object, const AliCDBId& id,
			AliCDBMetaData* metaData, Bool_t owner):
fObject(object),
fId(id),
fMetaData(metaData),
fIsOwner(owner){
// constructor

}

//_____________________________________________________________________________
AliCDBEntry::AliCDBEntry(TObject* object, const AliCDBPath& path,
			const AliCDBRunRange& runRange,
                        AliCDBMetaData* metaData,Bool_t owner):
fObject(object),
fId(path, runRange, -1, -1),
fMetaData(metaData),
fIsOwner(owner){
// constructor

}

//_____________________________________________________________________________
AliCDBEntry::AliCDBEntry(TObject* object, const AliCDBPath& path,
			const AliCDBRunRange& runRange,
			Int_t version, AliCDBMetaData* metaData, Bool_t owner):
fObject(object),
fId(path, runRange, version, -1),
fMetaData(metaData),
fIsOwner(owner){
// constructor

}

//_____________________________________________________________________________
AliCDBEntry::AliCDBEntry(TObject* object, const AliCDBPath& path,
			const AliCDBRunRange& runRange,
			Int_t version, Int_t subVersion,
			AliCDBMetaData* metaData, Bool_t owner):
fObject(object),
fId(path, runRange, version, subVersion),
fMetaData(metaData),
fIsOwner(owner){
// constructor

}

//_____________________________________________________________________________
AliCDBEntry::AliCDBEntry(TObject* object, const AliCDBPath& path,
			Int_t firstRun, Int_t lastRun,
			AliCDBMetaData* metaData, Bool_t owner):
fObject(object),
fId(path, firstRun, lastRun, -1, -1),
fMetaData(metaData),
fIsOwner(owner){
// constructor

}

//_____________________________________________________________________________
AliCDBEntry::AliCDBEntry(TObject* object, const AliCDBPath& path,
			Int_t firstRun, Int_t lastRun,
			Int_t version, AliCDBMetaData* metaData,
			Bool_t owner):
fObject(object),
fId(path, firstRun, lastRun, version, -1),
fMetaData(metaData),
fIsOwner(owner){
// constructor

}

//_____________________________________________________________________________
AliCDBEntry::AliCDBEntry( TObject* object, const AliCDBPath& path,
			Int_t firstRun, Int_t lastRun,
			Int_t version, Int_t subVersion,
			AliCDBMetaData* metaData, Bool_t owner):
fObject(object),
fId(path, firstRun, lastRun, version, subVersion),
fMetaData(metaData), fIsOwner(owner){
// constructor

}

//_____________________________________________________________________________
AliCDBEntry::~AliCDBEntry() {
// destructor

	if (fIsOwner) {
		if (fObject) {
			delete fObject;
		}

		if (fMetaData) {
			delete fMetaData;
		}
	}
}

//_____________________________________________________________________________
void AliCDBEntry::PrintId() const {

	AliInfo(Form("%s",fId.ToString().Data()));

}
<commit_msg>Setting the class name meta-data field in the constructor<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/////////////////////////////////////////////////////////////////////
//                                                                 //
//  class AliCDBEntry						   //
//  container for an object, it identity (AliCDBId)  		   //
//  and its metaData (AliCDBMetaData) 				   //
//                                                                 //
/////////////////////////////////////////////////////////////////////

#include "AliCDBEntry.h"
#include "AliLog.h"

ClassImp(AliCDBEntry)

//_____________________________________________________________________________
AliCDBEntry::AliCDBEntry():
fObject(NULL),
fId(),
fMetaData(NULL),
fIsOwner(kFALSE){
// default constructor

}

//_____________________________________________________________________________
AliCDBEntry::AliCDBEntry(TObject* object, const AliCDBId& id,
			AliCDBMetaData* metaData, Bool_t owner):
fObject(object),
fId(id),
fMetaData(metaData),
fIsOwner(owner){
// constructor
    fMetaData->SetObjectClassName(fObject->ClassName());
}

//_____________________________________________________________________________
AliCDBEntry::AliCDBEntry(TObject* object, const AliCDBPath& path,
			const AliCDBRunRange& runRange,
                        AliCDBMetaData* metaData,Bool_t owner):
fObject(object),
fId(path, runRange, -1, -1),
fMetaData(metaData),
fIsOwner(owner){
// constructor

}

//_____________________________________________________________________________
AliCDBEntry::AliCDBEntry(TObject* object, const AliCDBPath& path,
			const AliCDBRunRange& runRange,
			Int_t version, AliCDBMetaData* metaData, Bool_t owner):
fObject(object),
fId(path, runRange, version, -1),
fMetaData(metaData),
fIsOwner(owner){
// constructor

}

//_____________________________________________________________________________
AliCDBEntry::AliCDBEntry(TObject* object, const AliCDBPath& path,
			const AliCDBRunRange& runRange,
			Int_t version, Int_t subVersion,
			AliCDBMetaData* metaData, Bool_t owner):
fObject(object),
fId(path, runRange, version, subVersion),
fMetaData(metaData),
fIsOwner(owner){
// constructor

}

//_____________________________________________________________________________
AliCDBEntry::AliCDBEntry(TObject* object, const AliCDBPath& path,
			Int_t firstRun, Int_t lastRun,
			AliCDBMetaData* metaData, Bool_t owner):
fObject(object),
fId(path, firstRun, lastRun, -1, -1),
fMetaData(metaData),
fIsOwner(owner){
// constructor

}

//_____________________________________________________________________________
AliCDBEntry::AliCDBEntry(TObject* object, const AliCDBPath& path,
			Int_t firstRun, Int_t lastRun,
			Int_t version, AliCDBMetaData* metaData,
			Bool_t owner):
fObject(object),
fId(path, firstRun, lastRun, version, -1),
fMetaData(metaData),
fIsOwner(owner){
// constructor

}

//_____________________________________________________________________________
AliCDBEntry::AliCDBEntry( TObject* object, const AliCDBPath& path,
			Int_t firstRun, Int_t lastRun,
			Int_t version, Int_t subVersion,
			AliCDBMetaData* metaData, Bool_t owner):
fObject(object),
fId(path, firstRun, lastRun, version, subVersion),
fMetaData(metaData), fIsOwner(owner){
// constructor

}

//_____________________________________________________________________________
AliCDBEntry::~AliCDBEntry() {
// destructor

	if (fIsOwner) {
		if (fObject) {
			delete fObject;
		}

		if (fMetaData) {
			delete fMetaData;
		}
	}
}

//_____________________________________________________________________________
void AliCDBEntry::PrintId() const {

	AliInfo(Form("%s",fId.ToString().Data()));

}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <typeinfo>
#include <typeindex>
#include <unordered_map>
#include <tuple>
#include <memory>
#include <string>
#include <vector>

using namespace std;

class object_t
{
  public:
    template<typename T>
      object_t(T x) : self_(make_shared<model<T>>(move(x))) {}
    void draw(ostream& out, size_t position) const
    {
      self_->draw_(out,position);
    }

  private:
    struct concept_t
    {
      virtual ~concept_t() = default;
      virtual void draw_(ostream&, size_t) const = 0;
    };

    template<typename T>
    struct model : concept_t
    {
      model(T x) : data_(move(x)) {}
      void draw_(ostream& out, size_t position) const
      {
        data_.draw(out,position);
      }
      T data_;
    };

    shared_ptr<const concept_t> self_;
};

class my_class_t
{
  public:
    void draw(ostream& out, size_t position) const
    {
      out << string(position, ' ') << "my_class_t" << endl;
    }
    static string get_type() { return "my_class_t"; }
};

class book_t
{
  public:
  string name;
    void draw(ostream& out, size_t position) const
    {
      out << string(position, ' ') << "book_t{" << name << "}" << endl;
    }
    static string get_type() { return "book_t"; }
};
class name_t
{
  public:
  string name;
    void draw(ostream& out, size_t position) const
    {
      out << string(position, ' ') << "name_t{" << name << "}" << endl;
    }
    static string get_type() { return "name_t"; }
};

using document_t = vector<tuple<object_t,type_index>>;
using document_types = unordered_map<type_index,string>;
void draw(const document_t& x, ostream& out, size_t position)
{
  out << string(position, ' ') << "<document>" << endl;
  for (const auto& e : x )
    get<0>(e).draw(out, position + 2);
  out << string(position, ' ') << "</document>" << endl;
  out << string(position, ' ') << "<types>" << endl;
  for (const auto& e : x )
  {
    auto&& type = get<1>(e);
  }
  out << string(position, ' ') << "</types>" << endl;
}

template<typename T>
tuple<T,type_index> make_doc(T&& doc)
{
  return make_tuple(std::forward<T>(doc),type_index(typeid(T)));
}
int main()
{
  document_t document;
  document.emplace_back(make_doc(my_class_t{}));
  document.emplace_back(make_doc(book_t{"book1"}));
  document.emplace_back(make_doc(name_t{"name1"}));
  document.emplace_back(make_doc(book_t{"book2"}));
  document.emplace_back(make_doc(name_t{"name2"}));
  document.emplace_back(make_doc(my_class_t{}));
  draw(document,cout,0);
}
<commit_msg>some fixes<commit_after>#include <iostream>
#include <string>
#include <typeinfo>
#include <typeindex>
#include <unordered_map>
#include <tuple>
#include <memory>
#include <string>
#include <vector>

using namespace std;

class object_t
{
  public:
    template<typename T>
      object_t(T x) : self_(make_shared<model<T>>(move(x))) {}
    void draw(ostream& out, size_t position) const
    {
      self_->draw_(out,position);
    }

  private:
    struct concept_t
    {
      virtual ~concept_t() = default;
      virtual void draw_(ostream&, size_t) const = 0;
    };

    template<typename T>
    struct model : concept_t
    {
      model(T x) : data_(move(x)) {}
      void draw_(ostream& out, size_t position) const
      {
        data_.draw(out,position);
      }
      T data_;
    };

    shared_ptr<const concept_t> self_;
};

class my_class_t
{
  public:
    void draw(ostream& out, size_t position) const
    {
      out << string(position, ' ') << "my_class_t" << endl;
    }
    static string get_type() { return "my_class_t"; }
};

class book_t
{
  public:
  string name;
    void draw(ostream& out, size_t position) const
    {
      out << string(position, ' ') << "book_t{" << name << "}" << endl;
    }
    static string get_type() { return "book_t"; }
};
class name_t
{
  public:
  string name;
    void draw(ostream& out, size_t position) const
    {
      out << string(position, ' ') << "name_t{" << name << "}" << endl;
    }
    static string get_type() { return "name_t"; }
};

using document_t = vector<tuple<object_t,type_index>>;
using document_types = unordered_map<type_index,string>;

void draw(const document_t& x, ostream& out, size_t position)
{
  out << string(position, ' ') << "<document>" << endl;
  for (const auto& e : x )
    get<0>(e).draw(out, position + 2);
  out << string(position, ' ') << "</document>" << endl;
  out << string(position, ' ') << "<types>" << endl;
#if 0
  for (const auto& e : x )
  {
    auto&& type = get<1>(e);
    string type_name;
    out << string(position, ' ') << type << endl;
  }
#endif
  out << string(position, ' ') << "</types>" << endl;
}

template<typename T>
tuple<T,type_index> make_doc(T&& doc)
{
  return make_tuple(std::forward<T>(doc),type_index(typeid(T)));
}
int main()
{
  document_t document;
  document.emplace_back(make_doc(my_class_t{}));
  document.emplace_back(make_doc(book_t{"book1"}));
  document.emplace_back(make_doc(name_t{"name1"}));
  document.emplace_back(make_doc(book_t{"book2"}));
  document.emplace_back(make_doc(name_t{"name2"}));
  document.emplace_back(make_doc(my_class_t{}));
  draw(document,cout,0);
}
<|endoftext|>


<commit_before>/*******************************************************************************
* CGoGN: Combinatorial and Geometric modeling with Generic N-dimensional Maps  *
* Copyright (C) 2015, IGG Group, ICube, University of Strasbourg, France       *
*                                                                              *
* This library is free software; you can redistribute it and/or modify it      *
* under the terms of the GNU Lesser General Public License as published by the *
* Free Software Foundation; either version 2.1 of the License, or (at your     *
* option) any later version.                                                   *
*                                                                              *
* This library 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 Lesser General Public License  *
* for more details.                                                            *
*                                                                              *
* You should have received a copy of the GNU Lesser General Public License     *
* along with this library; if not, write to the Free Software Foundation,      *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.           *
*                                                                              *
* Web site: http://cgogn.unistra.fr/                                           *
* Contact information: cgogn@unistra.fr                                        *
*                                                                              *
*******************************************************************************/

#include <gmock/gmock.h>
#include <gtest/gtest.h>

#include <core/cmap/cmap1.h>
#include <core/cmap/map_traits.h>
#include <core/cmap/sanity_check.h>

namespace cgogn
{

class CMap1Test: public ::testing::Test
{

public:
	using myCMap1 = CMap1<DefaultMapTraits>;
	using Vertex = myCMap1::Vertex;
	using Face = myCMap1::Face;

protected:
	myCMap1 cmap_;

	CMap1Test()
	{}

};

TEST_F(CMap1Test, addFace)
{
	Face f = cmap_.add_face(10);

	cmap_.split_vertex(Vertex(f.dart));

	EXPECT_TRUE(is_well_embedded<Face::ORBIT>(cmap_));
	EXPECT_TRUE(is_orbit_embedding_unique<Face::ORBIT>(cmap_));
	EXPECT_TRUE(is_container_well_referenced<Face::ORBIT>(cmap_));

}

} // namespace cgogn
<commit_msg>Debug Test CMap1<commit_after>/*******************************************************************************
* CGoGN: Combinatorial and Geometric modeling with Generic N-dimensional Maps  *
* Copyright (C) 2015, IGG Group, ICube, University of Strasbourg, France       *
*                                                                              *
* This library is free software; you can redistribute it and/or modify it      *
* under the terms of the GNU Lesser General Public License as published by the *
* Free Software Foundation; either version 2.1 of the License, or (at your     *
* option) any later version.                                                   *
*                                                                              *
* This library 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 Lesser General Public License  *
* for more details.                                                            *
*                                                                              *
* You should have received a copy of the GNU Lesser General Public License     *
* along with this library; if not, write to the Free Software Foundation,      *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.           *
*                                                                              *
* Web site: http://cgogn.unistra.fr/                                           *
* Contact information: cgogn@unistra.fr                                        *
*                                                                              *
*******************************************************************************/

#include <gmock/gmock.h>
#include <gtest/gtest.h>

#include <core/cmap/cmap1.h>
#include <core/cmap/map_traits.h>
#include <core/cmap/sanity_check.h>

namespace cgogn
{

class CMap1Test: public ::testing::Test
{

public:
	using myCMap1 = CMap1<DefaultMapTraits>;
	using Vertex = myCMap1::Vertex;
	using Face = myCMap1::Face;

protected:
	myCMap1 cmap_;

	CMap1Test()
	{}

};

TEST_F(CMap1Test, addFace)
{
	cmap_.add_attribute<int, Face::ORBIT>("int");

	Face f = cmap_.add_face(10);

	cmap_.split_vertex(Vertex(f.dart));

	EXPECT_TRUE(is_well_embedded<Face::ORBIT>(cmap_));
	EXPECT_TRUE(is_orbit_embedding_unique<Face::ORBIT>(cmap_));
	EXPECT_TRUE(is_container_well_referenced<Face::ORBIT>(cmap_));

}

} // namespace cgogn
<|endoftext|>


<commit_before>/****************************************************************************
 * Copyright (c) 2012-2017 by the DataTransferKit authors                   *
 * All rights reserved.                                                     *
 *                                                                          *
 * This file is part of the DataTransferKit library. DataTransferKit is     *
 * distributed under a BSD 3-clause license. For the licensing terms see    *
 * the LICENSE file in the top-level directory.                             *
 ****************************************************************************/
/*!
 * \file DTK_ParallelTraits.hpp
 * \brief Kokkos helpers.
 */
//---------------------------------------------------------------------------//

#ifndef DTK_PARALLELTRAITS_HPP
#define DTK_PARALLELTRAITS_HPP

#include <Kokkos_Core.hpp>
#include <Kokkos_DefaultNode.hpp>

#include <type_traits>

namespace DataTransferKit
{
//---------------------------------------------------------------------------//
// Parallel node type aliases.

// Serial
#if defined( KOKKOS_HAVE_SERIAL )
using Serial = Kokkos::Serial;
#endif

// OpenMP
#if defined( KOKKOS_HAVE_OPENMP )
using OpenMP = Kokkos::OpenMP;
#endif

// Cuda
#if defined( KOKKOS_HAVE_CUDA )
using Cuda = Kokkos::Cuda;
#endif

//---------------------------------------------------------------------------//
// Check device-type to ensure Kokkos and Tpetra devices are compatible. This
// will not compile if they are incompatible.
template <class Device1, class Device2>
struct CompatibleDeviceTypes
{ /* ... */
};

template <class Device>
struct CompatibleDeviceTypes<Device, Device>
{
    using IsCompatible = std::true_type;
};

//---------------------------------------------------------------------------//
// Undefined Traits.
template <class Node>
class ParallelTraits
{ /* ... */
};

//---------------------------------------------------------------------------//
// Serial specialization.
#if defined( KOKKOS_HAVE_SERIAL )
template <>
class ParallelTraits<Serial>
{
  public:
    using ExecutionSpace = Kokkos::Serial;
    using DeviceType = typename ExecutionSpace::device_type;
    using MemorySpace = typename DeviceType::memory_space;
    using TpetraNode = typename ::Kokkos::Compat::KokkosSerialWrapperNode;

  private:
    using IsCompatible =
        typename CompatibleDeviceTypes<typename TpetraNode::device_type,
                                       DeviceType>::IsCompatible;
};
#endif

//---------------------------------------------------------------------------//
// OpenMP specialization.
#if defined( KOKKOS_HAVE_OPENMP )
template <>
class ParallelTraits<OpenMP>
{
  public:
    using ExecutionSpace = Kokkos::OpenMP;
    using DeviceType = typename ExecutionSpace::device_type;
    using MemorySpace = typename DeviceType::memory_space;
    using TpetraNode = typename ::Kokkos::Compat::KokkosOpenMPWrapperNode;

  private:
    using IsCompatible =
        typename CompatibleDeviceTypes<typename TpetraNode::device_type,
                                       DeviceType>::IsCompatible;
};
#endif

//---------------------------------------------------------------------------//
// Cuda specialization.
#if defined( KOKKOS_HAVE_CUDA )
template <>
class ParallelTraits<Cuda>
{
  public:
    using ExecutionSpace = Kokkos::Cuda;
    using DeviceType = typename ExecutionSpace::device_type;
    using MemorySpace = typename DeviceType::memory_space;
    using TpetraNode = typename ::Kokkos::Compat::KokkosCudaWrapperNode;

  private:
    using IsCompatible =
        typename CompatibleDeviceTypes<typename TpetraNode::device_type,
                                       DeviceType>::IsCompatible;
};
#endif

//---------------------------------------------------------------------------//

} // end namespace DataTransferKit

//---------------------------------------------------------------------------//

#endif // end DTK_PARALLELTRAITS_HPP

//---------------------------------------------------------------------------//
// end DTK_ParallelTraits.hpp
//---------------------------------------------------------------------------//
<commit_msg>Remove extra typenames for Kokkos wrapper nodes typedefs<commit_after>/****************************************************************************
 * Copyright (c) 2012-2017 by the DataTransferKit authors                   *
 * All rights reserved.                                                     *
 *                                                                          *
 * This file is part of the DataTransferKit library. DataTransferKit is     *
 * distributed under a BSD 3-clause license. For the licensing terms see    *
 * the LICENSE file in the top-level directory.                             *
 ****************************************************************************/
/*!
 * \file DTK_ParallelTraits.hpp
 * \brief Kokkos helpers.
 */
//---------------------------------------------------------------------------//

#ifndef DTK_PARALLELTRAITS_HPP
#define DTK_PARALLELTRAITS_HPP

#include <Kokkos_Core.hpp>
#include <Kokkos_DefaultNode.hpp>

#include <type_traits>

namespace DataTransferKit
{
//---------------------------------------------------------------------------//
// Parallel node type aliases.

// Serial
#if defined( KOKKOS_HAVE_SERIAL )
using Serial = Kokkos::Serial;
#endif

// OpenMP
#if defined( KOKKOS_HAVE_OPENMP )
using OpenMP = Kokkos::OpenMP;
#endif

// Cuda
#if defined( KOKKOS_HAVE_CUDA )
using Cuda = Kokkos::Cuda;
#endif

//---------------------------------------------------------------------------//
// Check device-type to ensure Kokkos and Tpetra devices are compatible. This
// will not compile if they are incompatible.
template <class Device1, class Device2>
struct CompatibleDeviceTypes
{ /* ... */
};

template <class Device>
struct CompatibleDeviceTypes<Device, Device>
{
    using IsCompatible = std::true_type;
};

//---------------------------------------------------------------------------//
// Undefined Traits.
template <class Node>
class ParallelTraits
{ /* ... */
};

//---------------------------------------------------------------------------//
// Serial specialization.
#if defined( KOKKOS_HAVE_SERIAL )
template <>
class ParallelTraits<Serial>
{
  public:
    using ExecutionSpace = Kokkos::Serial;
    using DeviceType = typename ExecutionSpace::device_type;
    using MemorySpace = typename DeviceType::memory_space;
    using TpetraNode = ::Kokkos::Compat::KokkosSerialWrapperNode;

  private:
    using IsCompatible =
        typename CompatibleDeviceTypes<typename TpetraNode::device_type,
                                       DeviceType>::IsCompatible;
};
#endif

//---------------------------------------------------------------------------//
// OpenMP specialization.
#if defined( KOKKOS_HAVE_OPENMP )
template <>
class ParallelTraits<OpenMP>
{
  public:
    using ExecutionSpace = Kokkos::OpenMP;
    using DeviceType = typename ExecutionSpace::device_type;
    using MemorySpace = typename DeviceType::memory_space;
    using TpetraNode = ::Kokkos::Compat::KokkosOpenMPWrapperNode;

  private:
    using IsCompatible =
        typename CompatibleDeviceTypes<typename TpetraNode::device_type,
                                       DeviceType>::IsCompatible;
};
#endif

//---------------------------------------------------------------------------//
// Cuda specialization.
#if defined( KOKKOS_HAVE_CUDA )
template <>
class ParallelTraits<Cuda>
{
  public:
    using ExecutionSpace = Kokkos::Cuda;
    using DeviceType = typename ExecutionSpace::device_type;
    using MemorySpace = typename DeviceType::memory_space;
    using TpetraNode = ::Kokkos::Compat::KokkosCudaWrapperNode;

  private:
    using IsCompatible =
        typename CompatibleDeviceTypes<typename TpetraNode::device_type,
                                       DeviceType>::IsCompatible;
};
#endif

//---------------------------------------------------------------------------//

} // end namespace DataTransferKit

//---------------------------------------------------------------------------//

#endif // end DTK_PARALLELTRAITS_HPP

//---------------------------------------------------------------------------//
// end DTK_ParallelTraits.hpp
//---------------------------------------------------------------------------//
<|endoftext|>


<commit_before>/*=========================================================================

  Programme :   OTB (ORFEO ToolBox)
  Auteurs   :   CS - R. Garrigues
  Language  :   C++
  Date      :   18 Octobre 2007
  Version   :
  Role      :   Ortho-Rectification Image Application
  $Id$

=========================================================================*/

#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif

#include <iostream>
#include <iomanip>

#include "otbCommandLineArgumentParser.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "otbMapProjections.h"
#include "otbOrthoRectificationFilter.h"
#include "otbImage.h"
#include "otbMacro.h"

#include "itkExceptionObject.h"
#include "itkMacro.h"
#include "itkTransform.h"

#include "init/ossimInit.h"

template<typename TMapProjection>
int generic_main_carto_geo(int argc, char* argv[], TMapProjection* mapProjection, otb::CommandLineArgumentParseResult* parseResult)
{

  try
    {

				typedef TMapProjection MapProjectionType;

				typename MapProjectionType::InputPointType cartoPoint;
				typename MapProjectionType::OutputPointType geoPoint;

				cartoPoint[0]=parseResult->GetParameterDouble("--XCarto");
				cartoPoint[1]=parseResult->GetParameterDouble("--YCarto");

				geoPoint = mapProjection->TransformPoint(cartoPoint);

     		if(!parseResult->IsOptionPresent("--OTBTesting"))
				{
					std::cout << std::setprecision(10) << "Cartographic Point  (x , y)  : (" << cartoPoint[0] << "," << cartoPoint[1] << ")" << std::endl;
					std::cout << std::setprecision(10) << "Geographic   Point (Lat,Lon) : (" << geoPoint[1] << "," <<	geoPoint[0] << ")" << std::endl;
				}
				else
				{
					std::string outputTestFileName = parseResult->GetParameterString("--OTBTesting",0);

					ofstream outputTestFile;
					outputTestFile.open(outputTestFileName.c_str());

					outputTestFile << std::setprecision(10) << "Cartographic Point  (x , y)  : (" << cartoPoint[0] << "," << cartoPoint[1] << ")" << std::endl;
					outputTestFile << std::setprecision(10) << "Geographic   Point (Lat,Lon) : (" << geoPoint[1] << "," <<	geoPoint[0] << ")" << std::endl;

					outputTestFile.close();
				}

		}
		catch( itk::ExceptionObject & err )
    {
    std::cout << "Exception itk::ExceptionObject levee !" << std::endl;
    std::cout << err << std::endl;
    return EXIT_FAILURE;
    }
  	catch( std::bad_alloc & err )
    {
    std::cout << "Exception bad_alloc : "<<(char*)err.what()<< std::endl;
    return EXIT_FAILURE;
    }
  catch( ... )
    {
    std::cout << "Exception levee inconnue !" << std::endl;
    return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;

 }//Fin main()

int main(int argc, char* argv[])
{
try
    {
	      ossimInit::instance()->initialize(argc, argv);

				// Parse command line parameters
        typedef otb::CommandLineArgumentParser ParserType;
				ParserType::Pointer parser = ParserType::New();

        parser->AddOption("--XCarto","X cartographic value of desired point","-x");
				parser->AddOption("--YCarto","Y cartographic value of desired point","-y");
				parser->AddOptionNParams("--MapProjectionType","Type (UTM/LAMBERT/SINUS/ECKERT4/TRANSMERCATOR/MOLLWEID) and parameters of map projection used","-mapProj");

        typedef otb::CommandLineArgumentParseResult ParserResultType;
        ParserResultType::Pointer  parseResult = ParserResultType::New();

				try
	   		{
            parser->ParseCommandLine(argc,argv,parseResult);
 	   		}
				catch( itk::ExceptionObject & err )
    	  {
    	   	std::string descriptionException = err.GetDescription();
    	   	if(descriptionException.find("ParseCommandLine(): Help Parser") != std::string::npos)
	   			{
						std::cout << "WARNING : output file pixels are converted in 'unsigned char'" << std::endl;
						return EXIT_SUCCESS;
					}
    	   	if(descriptionException.find("ParseCommandLine(): Version Parser") != std::string::npos)
	   			{
						return EXIT_SUCCESS;
					}
          return EXIT_FAILURE;
    	  }

				// Code

				std::string typeMap = parseResult->GetParameterString("--MapProjectionType",0);
				int nbParams = parseResult->GetNumberOfParameters("--MapProjectionType");
				nbParams--;

				if ((typeMap == "UTM")&&(nbParams==2))
				{
					int numZone = parseResult->GetParameterUInt("--MapProjectionType",1);
					char hemisphere = parseResult->GetParameterChar("--MapProjectionType",2);

					typedef otb::UtmInverseProjection UtmProjectionType;
					UtmProjectionType::Pointer utmProjection = UtmProjectionType::New();

					utmProjection->SetZone(numZone);
					utmProjection->SetHemisphere(hemisphere);

					return generic_main_carto_geo<UtmProjectionType>(argc,argv, utmProjection, parseResult);
				}
				else
				{
					std::vector<double> parameters ;

					for (int i=1; i<nbParams+1; i++)
					{
						parameters.push_back(parseResult->GetParameterDouble("--MapProjectionType",i));
					}

					if ((typeMap == "LAMBERT")&&(nbParams==4))
					{
						typedef otb::LambertConformalConicInverseProjection LambertProjectionType;
						LambertProjectionType::Pointer lambertProjection = LambertProjectionType::New();

						lambertProjection->SetParameters(parameters[0],parameters[1],parameters[2],parameters[3]);

						return generic_main_carto_geo<LambertProjectionType>(argc,argv, lambertProjection, parseResult);
					}
					else if ((typeMap == "SINUS")&&(nbParams==2))
					{
						typedef otb::SinusoidalInverseProjection SinusoidalProjectionType;
						SinusoidalProjectionType::Pointer sinusoidalProjection = SinusoidalProjectionType::New();

						sinusoidalProjection->SetParameters(parameters[0],parameters[1]);

						return generic_main_carto_geo<SinusoidalProjectionType>(argc,argv, sinusoidalProjection, parseResult);
					}
					else if ((typeMap == "ECKERT4")&&(nbParams==2))
					{
						typedef otb::Eckert4InverseProjection Eckert4ProjectionType;
						Eckert4ProjectionType::Pointer eckert4Projection = Eckert4ProjectionType::New();

						eckert4Projection->SetParameters(parameters[0],parameters[1]);

						return generic_main_carto_geo<Eckert4ProjectionType>(argc,argv, eckert4Projection, parseResult);
					}
					else if ((typeMap == "TRANSMERCATOR")&&(nbParams==3))
					{
						typedef otb::TransMercatorInverseProjection TransMercatorProjectionType;
						TransMercatorProjectionType::Pointer transMercatorProjection = TransMercatorProjectionType::New();

						transMercatorProjection->SetParameters(parameters[0],parameters[1],parameters[2]);

						return generic_main_carto_geo<TransMercatorProjectionType>(argc,argv, transMercatorProjection, parseResult);
					}
					else if ((typeMap == "MOLLWEID")&&(nbParams==2))
					{
						typedef otb::MollweidInverseProjection MollweidProjectionType;
						MollweidProjectionType::Pointer mollweidProjection = MollweidProjectionType::New();

						mollweidProjection->SetParameters(parameters[0],parameters[1]);

						return generic_main_carto_geo<MollweidProjectionType>(argc,argv, mollweidProjection, parseResult);
					}
					else
					{
						itkGenericExceptionMacro(<< "TypeMap not recognized, choose one with (parameters) : UTM(2), LAMBERT(4), SINUS(2), ECKERT4(2), TRANSMERCATOR(3), MOLLWEID(2)");
					}

				}

		}
		catch( itk::ExceptionObject & err )
    {
    std::cout << "Exception itk::ExceptionObject levee !" << std::endl;
    std::cout << err << std::endl;
    return EXIT_FAILURE;
    }
  	catch( std::bad_alloc & err )
    {
    std::cout << "Exception bad_alloc : "<<(char*)err.what()<< std::endl;
    return EXIT_FAILURE;
    }
  catch( ... )
    {
    std::cout << "Exception levee inconnue !" << std::endl;
    return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;
}

<commit_msg>Corrections pour lambert<commit_after>/*=========================================================================

  Programme :   OTB (ORFEO ToolBox)
  Auteurs   :   CS - R. Garrigues
  Language  :   C++
  Date      :   18 Octobre 2007
  Version   :
  Role      :   Ortho-Rectification Image Application
  $Id$

=========================================================================*/

#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif

#include <iostream>
#include <iomanip>

#include "otbCommandLineArgumentParser.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "otbMapProjections.h"
#include "otbOrthoRectificationFilter.h"
#include "otbImage.h"
#include "otbMacro.h"

#include "itkExceptionObject.h"
#include "itkMacro.h"
#include "itkTransform.h"

#include "init/ossimInit.h"

template<typename TMapProjection>
int generic_main_carto_geo(int argc, char* argv[], TMapProjection* mapProjection, otb::CommandLineArgumentParseResult* parseResult)
{

  try
  {

    typedef TMapProjection MapProjectionType;

    typename MapProjectionType::InputPointType cartoPoint;
    typename MapProjectionType::OutputPointType geoPoint;

    cartoPoint[0]=parseResult->GetParameterDouble("--XCarto");
    cartoPoint[1]=parseResult->GetParameterDouble("--YCarto");

    geoPoint = mapProjection->TransformPoint(cartoPoint);

    if(!parseResult->IsOptionPresent("--OTBTesting"))
    {
      std::cout << std::setprecision(10) << "Cartographic Point  (x , y)  : (" << cartoPoint[0] << "," << cartoPoint[1] << ")" << std::endl;
      std::cout << std::setprecision(10) << "Geographic   Point (Lat,Lon) : (" << geoPoint[1] << "," <<	geoPoint[0] << ")" << std::endl;
    }
    else
    {
      std::string outputTestFileName = parseResult->GetParameterString("--OTBTesting",0);

      ofstream outputTestFile;
      outputTestFile.open(outputTestFileName.c_str());

      outputTestFile << std::setprecision(10) << "Cartographic Point  (x , y)  : (" << cartoPoint[0] << "," << cartoPoint[1] << ")" << std::endl;
      outputTestFile << std::setprecision(10) << "Geographic   Point (Lat,Lon) : (" << geoPoint[1] << "," <<	geoPoint[0] << ")" << std::endl;

      outputTestFile.close();
    }

  }
  catch( itk::ExceptionObject & err )
  {
    std::cout << "Exception itk::ExceptionObject levee !" << std::endl;
    std::cout << err << std::endl;
    return EXIT_FAILURE;
  }
  catch( std::bad_alloc & err )
  {
    std::cout << "Exception bad_alloc : "<<(char*)err.what()<< std::endl;
    return EXIT_FAILURE;
  }
  catch( ... )
  {
    std::cout << "Exception levee inconnue !" << std::endl;
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;

}//Fin main()

int main(int argc, char* argv[])
{
  try
  {
    ossimInit::instance()->initialize(argc, argv);

				// Parse command line parameters
    typedef otb::CommandLineArgumentParser ParserType;
    ParserType::Pointer parser = ParserType::New();

    parser->AddOption("--XCarto","X cartographic value of desired point","-x");
    parser->AddOption("--YCarto","Y cartographic value of desired point","-y");
    parser->AddOptionNParams("--MapProjectionType","Type (UTM/LAMBERT/SINUS/ECKERT4/TRANSMERCATOR/MOLLWEID) and parameters of map projection used","-mapProj");

    typedef otb::CommandLineArgumentParseResult ParserResultType;
    ParserResultType::Pointer  parseResult = ParserResultType::New();

    try
    {
      parser->ParseCommandLine(argc,argv,parseResult);
    }
    catch( itk::ExceptionObject & err )
    {
      std::string descriptionException = err.GetDescription();
      if(descriptionException.find("ParseCommandLine(): Help Parser") != std::string::npos)
      {
        std::cout << "WARNING : output file pixels are converted in 'unsigned char'" << std::endl;
        return EXIT_SUCCESS;
      }
      if(descriptionException.find("ParseCommandLine(): Version Parser") != std::string::npos)
      {
        return EXIT_SUCCESS;
      }
      return EXIT_FAILURE;
    }

				// Code

    std::string typeMap = parseResult->GetParameterString("--MapProjectionType",0);
    int nbParams = parseResult->GetNumberOfParameters("--MapProjectionType");
    nbParams--;

    if ((typeMap == "UTM")&&(nbParams==2))
    {
      int numZone = parseResult->GetParameterUInt("--MapProjectionType",1);
      char hemisphere = parseResult->GetParameterChar("--MapProjectionType",2);

      typedef otb::UtmInverseProjection UtmProjectionType;
      UtmProjectionType::Pointer utmProjection = UtmProjectionType::New();

      utmProjection->SetZone(numZone);
      utmProjection->SetHemisphere(hemisphere);

      return generic_main_carto_geo<UtmProjectionType>(argc,argv, utmProjection, parseResult);
    }
    else
    {
      std::vector<double> parameters ;

      for (int i=1; i<nbParams+1; i++)
      {
        parameters.push_back(parseResult->GetParameterDouble("--MapProjectionType",i));
      }

      if ((typeMap == "LAMBERT")&&(nbParams==4))
      {
        typedef otb::LambertConformalConicInverseProjection LambertProjectionType;
        LambertProjectionType::Pointer lambertProjection = LambertProjectionType::New();

        lambertProjection->SetParameters(parameters[0],parameters[1],parameters[2],parameters[3]);

        return generic_main_carto_geo<LambertProjectionType>(argc,argv, lambertProjection, parseResult);
      }
      else if ((typeMap == "SINUS")&&(nbParams==2))
      {
        typedef otb::SinusoidalInverseProjection SinusoidalProjectionType;
        SinusoidalProjectionType::Pointer sinusoidalProjection = SinusoidalProjectionType::New();

        sinusoidalProjection->SetParameters(parameters[0],parameters[1]);

        return generic_main_carto_geo<SinusoidalProjectionType>(argc,argv, sinusoidalProjection, parseResult);
      }
      else if ((typeMap == "ECKERT4")&&(nbParams==2))
      {
        typedef otb::Eckert4InverseProjection Eckert4ProjectionType;
        Eckert4ProjectionType::Pointer eckert4Projection = Eckert4ProjectionType::New();

        eckert4Projection->SetParameters(parameters[0],parameters[1]);

        return generic_main_carto_geo<Eckert4ProjectionType>(argc,argv, eckert4Projection, parseResult);
      }
      else if ((typeMap == "TRANSMERCATOR")&&(nbParams==3))
      {
        typedef otb::TransMercatorInverseProjection TransMercatorProjectionType;
        TransMercatorProjectionType::Pointer transMercatorProjection = TransMercatorProjectionType::New();

        transMercatorProjection->SetParameters(parameters[0],parameters[1],parameters[2]);

        return generic_main_carto_geo<TransMercatorProjectionType>(argc,argv, transMercatorProjection, parseResult);
      }
      else if ((typeMap == "MOLLWEID")&&(nbParams==2))
      {
        typedef otb::MollweidInverseProjection MollweidProjectionType;
        MollweidProjectionType::Pointer mollweidProjection = MollweidProjectionType::New();

        mollweidProjection->SetParameters(parameters[0],parameters[1]);

        return generic_main_carto_geo<MollweidProjectionType>(argc,argv, mollweidProjection, parseResult);
      }
      else
      {
        itkGenericExceptionMacro(<< "TypeMap not recognized, choose one with (parameters) : UTM(2), LAMBERT(4), SINUS(2), ECKERT4(2), TRANSMERCATOR(3), MOLLWEID(2)");
      }

    }

  }
  catch( itk::ExceptionObject & err )
  {
    std::cout << "Exception itk::ExceptionObject levee !" << std::endl;
    std::cout << err << std::endl;
    return EXIT_FAILURE;
  }
  catch( std::bad_alloc & err )
  {
    std::cout << "Exception bad_alloc : "<<(char*)err.what()<< std::endl;
    return EXIT_FAILURE;
  }
  catch( ... )
  {
    std::cout << "Exception levee inconnue !" << std::endl;
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
***************************************************************************/
///////////////////////////////////////////////////////////////////////////
//  Class to generate decays of particles generated by a                 //
//  previous generator. It works as a generator, but pratically it       //
//  performs only decays. It works with this scheme: first loops over    //
//  particles on the stack, selects those to be decayed, decays them     //
//  and then pushes the decay products on the stack.                     //
//                                                                       //
//  Origin: Michal.Broz@cern.ch        					 //
///////////////////////////////////////////////////////////////////////////

#include "AliStack.h"
#include "AliGenSLEvtGen.h"
#include "AliRun.h"
#include "AliLog.h"
#include <TParticle.h>

ClassImp(AliGenSLEvtGen)
//____________________________________________________________________________
AliGenSLEvtGen::AliGenSLEvtGen():
  fStack(0x0),
  fDecayer(0x0),
  fUserDecay(kFALSE),
  fUserDecayTablePath(0x0),
  fEvtGenNumber(0),
  fDecayPolarized(kFALSE),
  fPolarization(0),
  fEtaChildMin( 1),
  fEtaChildMax(-1)
  {
  //
  // Default Construction
  //
  }
//____________________________________________________________________________
AliGenSLEvtGen::~AliGenSLEvtGen()
  {
  //
  // Standard Destructor
  //
  if(fStack) {delete fStack;}
  fStack = 0;
  if(fDecayer) {delete fDecayer;}
  fDecayer = 0;
  if(fUserDecayTablePath) {delete fUserDecayTablePath;}
  fUserDecayTablePath = 0;
  }
//____________________________________________________________________________

void AliGenSLEvtGen::Init()
  {
  //
  // Standard AliGenerator Initializer - no input
  // 1) initialize SLEvtGen with default decay and particle table
  // 2) set the decay mode to force particle
  // 3) set a user decay table if defined
  //
  if(fDecayer)
  {
  AliWarning("AliGenSLEvtGen already initialized!!!");
  return;
  }
  fDecayer = new AliDecayerSLEvtGen();
  fDecayer->Init(); //read the default decay table DECAY.DEC and particle table

  //if is defined a user decay table
  if(fUserDecay)
    {
    fDecayer->SetDecayTablePath(fUserDecayTablePath);
    fDecayer->ReadDecayTable();
    }
  }

//____________________________________________________________________________
void AliGenSLEvtGen::Generate()
  {
  //
  //Generate method - Input none - Output none
  //For each event:
  //1)return the stack of the previous generator and select particles to be decayed by SLEvtGen
  //2)decay particles selected and put the decay products on the stack
  //
  //
  Float_t Polarization[3]= {0,0,0};  // Polarisation of daughter particles
  Float_t VertexPos[3];         // Origin of the parent particle
  Float_t Momentum[3]; // Momentum and origin of the children particles from SLEvtGen
  Int_t nt(0);
  Float_t Tof;
  Int_t nPartStarlight;
  TLorentzVector momGen;
  TLorentzVector momTot;
  momTot.SetXYZM(0.,0.,0.,0.);

  static TClonesArray *decayProducts;
  if(!decayProducts) decayProducts = new TClonesArray("TParticle",1000);
  fStack = AliRunLoader::Instance()->Stack();
  if(!fStack) {Info("Generate","Error: No stack found!"); return;}

  nPartStarlight = fStack->GetNprimary();
  //AliInfo(Form("nPartStarlight = %d \n",nPartStarlight));

  //Loop over Starlight decay products
  for (Int_t ipartStarlight = 0; ipartStarlight < nPartStarlight; ++ipartStarlight) {

  	TParticle *partStarlight = fStack->Particle(ipartStarlight);
	VertexPos[0]=partStarlight->Vx();
  	VertexPos[1]=partStarlight->Vy();
  	VertexPos[2]=partStarlight->Vz();
  	momGen.SetXYZM(partStarlight->Px(),partStarlight->Py(),partStarlight->Pz(),partStarlight->GetMass());
  	momTot += momGen;
  	}

  fStack->Clean(); //We are re-decaying, Remove previous particles

  Int_t nProducts;
  Bool_t  genOK = kFALSE;
  // generate events until all constraints are fulfilled
  for (Int_t trials=0; !genOK && trials < 100*1000; ++trials) {
  	if(fDecayPolarized)fDecayer->DecayPolarized(fEvtGenNumber,&momTot,fPolarization);
  	else fDecayer->Decay(fEvtGenNumber,&momTot);
  	nProducts = fDecayer->ImportParticles(decayProducts);
	genOK = kTRUE;
  	for (int i = 0; i < nProducts; i++) {
         	TParticle* partEvtGen = (TParticle *) decayProducts->At(i);

	 	//AliInfo(Form("PDG = %d, Status = %d \n",partEvtGen->GetPdgCode(),partEvtGen->GetStatusCode()));
	 	if(partEvtGen->GetStatusCode() !=1) continue;//don't fill mother particles for time being

		if (fEtaChildMin <= fEtaChildMax) genOK = genOK && (partEvtGen->Eta() >= fEtaChildMin && partEvtGen->Eta() <  fEtaChildMax);
      		if (!genOK) break;
		}// Particle loop - acceptance
	if (!genOK) continue;

	//AliInfo(Form("nProducts = %d, Weight = %d \n",nProducts,trials+1));
  	// Put decay products on the stack
	for (int i = 0; i < nProducts; i++) {
         	TParticle* partEvtGen = (TParticle *) decayProducts->At(i);

	 	//AliInfo(Form("PDG = %d, Status = %d \n",partEvtGen->GetPdgCode(),partEvtGen->GetStatusCode()));
	 	if(partEvtGen->GetStatusCode() !=1) continue;//don't fill mother particles for time being

         	PushTrack(1, -1, partEvtGen->GetPdgCode(),
	 	   partEvtGen->Px(),partEvtGen->Py(),partEvtGen->Pz(),partEvtGen->Energy(),
		   VertexPos[0],VertexPos[1],VertexPos[2],partEvtGen->T(),
		   Polarization[0],Polarization[1],Polarization[2],
	  	   kPPrimary, nt, trials+1, partEvtGen->GetStatusCode());

         	KeepTrack(nt);
         	}// Particle loop - stack
         decayProducts->Clear();
	 }

  }

//____________________________________________________________________________
Bool_t AliGenSLEvtGen::SetUserDecayTable(Char_t *path)
  {
  //
  //Set the path of user decay table if it is defined
  //
  //put a comment to control if path exists
  if(gSystem->AccessPathName(path))
    {
    AliWarning("Attention: This path not exist!\n");
    return kFALSE;
    }
  fUserDecayTablePath = path;
  fUserDecay = kTRUE;
  return kTRUE;
  }
<commit_msg>Store mother particle and decay history in kine tree<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
***************************************************************************/
///////////////////////////////////////////////////////////////////////////
//  Class to generate decays of particles generated by a                 //
//  previous generator. It works as a generator, but pratically it       //
//  performs only decays. It works with this scheme: first loops over    //
//  particles on the stack, selects those to be decayed, decays them     //
//  and then pushes the decay products on the stack.                     //
//                                                                       //
//  Origin: Michal.Broz@cern.ch        					 //
///////////////////////////////////////////////////////////////////////////

#include "AliStack.h"
#include "AliGenSLEvtGen.h"
#include "AliRun.h"
#include "AliLog.h"
#include <TParticle.h>

ClassImp(AliGenSLEvtGen)
//____________________________________________________________________________
AliGenSLEvtGen::AliGenSLEvtGen():
  fStack(0x0),
  fDecayer(0x0),
  fUserDecay(kFALSE),
  fUserDecayTablePath(0x0),
  fEvtGenNumber(0),
  fDecayPolarized(kFALSE),
  fPolarization(0),
  fEtaChildMin( 1),
  fEtaChildMax(-1)
  {
  //
  // Default Construction
  //
  }
//____________________________________________________________________________
AliGenSLEvtGen::~AliGenSLEvtGen()
  {
  //
  // Standard Destructor
  //
  if(fStack) {delete fStack;}
  fStack = 0;
  if(fDecayer) {delete fDecayer;}
  fDecayer = 0;
  if(fUserDecayTablePath) {delete fUserDecayTablePath;}
  fUserDecayTablePath = 0;
  }
//____________________________________________________________________________

void AliGenSLEvtGen::Init()
  {
  //
  // Standard AliGenerator Initializer - no input
  // 1) initialize SLEvtGen with default decay and particle table
  // 2) set the decay mode to force particle
  // 3) set a user decay table if defined
  //
  if(fDecayer)
  {
  AliWarning("AliGenSLEvtGen already initialized!!!");
  return;
  }
  fDecayer = new AliDecayerSLEvtGen();
  fDecayer->Init(); //read the default decay table DECAY.DEC and particle table

  //if is defined a user decay table
  if(fUserDecay)
    {
    fDecayer->SetDecayTablePath(fUserDecayTablePath);
    fDecayer->ReadDecayTable();
    }
  }

//____________________________________________________________________________
void AliGenSLEvtGen::Generate()
  {
  //
  //Generate method - Input none - Output none
  //For each event:
  //1)return the stack of the previous generator and select particles to be decayed by SLEvtGen
  //2)decay particles selected and put the decay products on the stack
  //
  //
  Float_t Polarization[3]= {0,0,0};  // Polarisation of daughter particles
  Float_t VertexPos[3];         // Origin of the parent particle
  Float_t Momentum[3]; // Momentum and origin of the children particles from SLEvtGen
  Int_t nt(0);
  Float_t Tof;
  Int_t nPartStarlight;
  TLorentzVector momGen;
  TLorentzVector momTot;
  momTot.SetXYZM(0.,0.,0.,0.);
  static TClonesArray *decayProducts;
  if(!decayProducts) decayProducts = new TClonesArray("TParticle",1000);
  fStack = AliRunLoader::Instance()->Stack();
  if(!fStack) {Info("Generate","Error: No stack found!"); return;}

  nPartStarlight = fStack->GetNprimary();
  //AliInfo(Form("nPartStarlight = %d \n",nPartStarlight));

  //Loop over Starlight decay products
  for (Int_t ipartStarlight = 0; ipartStarlight < nPartStarlight; ++ipartStarlight) {

  	TParticle *partStarlight = fStack->Particle(ipartStarlight);
	VertexPos[0]=partStarlight->Vx();
  	VertexPos[1]=partStarlight->Vy();
  	VertexPos[2]=partStarlight->Vz();
  	momGen.SetXYZM(partStarlight->Px(),partStarlight->Py(),partStarlight->Pz(),partStarlight->GetMass());
  	momTot += momGen;
  	}

  fStack->Clean(); //We are re-decaying, Remove previous particles

  Int_t nProducts;
  Bool_t  genOK = kFALSE;
  // generate events until all constraints are fulfilled
  for (Int_t trials=0; !genOK && trials < 100*1000; ++trials) {
  	if(fDecayPolarized)fDecayer->DecayPolarized(fEvtGenNumber,&momTot,fPolarization);
  	else fDecayer->Decay(fEvtGenNumber,&momTot);
  	nProducts = fDecayer->ImportParticles(decayProducts);
	genOK = kTRUE;
  	for (int i = 0; i < nProducts; i++) {
         	TParticle* partEvtGen = (TParticle *) decayProducts->At(i);
     		if(partEvtGen->GetStatusCode()!=1) continue;

		if (fEtaChildMin <= fEtaChildMax) genOK = genOK && (partEvtGen->Eta() >= fEtaChildMin && partEvtGen->Eta() <  fEtaChildMax);
      		if (!genOK) break;
		}// Particle loop - acceptance
	if (!genOK) continue;

	//AliInfo(Form("nProducts = %d, Weight = %d \n",nProducts,trials+1));
  	// Put decay products on the stack
	Int_t iparent = -1;
	for (int i = 0; i < nProducts; i++) {
         	TParticle* partEvtGen = (TParticle *) decayProducts->At(i);
	 	//AliInfo(Form("PDG = %d, Status = %d, Mother = %d \n",partEvtGen->GetPdgCode(),partEvtGen->GetStatusCode(),partEvtGen->GetFirstMother()));

		PushTrack((partEvtGen->GetStatusCode() == 1) ? 1 : 0, iparent, partEvtGen->GetPdgCode(),
	 	   partEvtGen->Px(),partEvtGen->Py(),partEvtGen->Pz(),partEvtGen->Energy(),
		   VertexPos[0],VertexPos[1],VertexPos[2],partEvtGen->T(),
		   Polarization[0],Polarization[1],Polarization[2],
	  	   (i == 0) ? kPPrimary : kPDecay, nt, trials+1, partEvtGen->GetStatusCode());

		if(i == 0)iparent = nt;
         	KeepTrack(nt);
		SetHighWaterMark(nt);
         	}// Particle loop - stack
         decayProducts->Clear();
	 }

  }

//____________________________________________________________________________
Bool_t AliGenSLEvtGen::SetUserDecayTable(Char_t *path)
  {
  //
  //Set the path of user decay table if it is defined
  //
  //put a comment to control if path exists
  if(gSystem->AccessPathName(path))
    {
    AliWarning("Attention: This path not exist!\n");
    return kFALSE;
    }
  fUserDecayTablePath = path;
  fUserDecay = kTRUE;
  return kTRUE;
  }
<|endoftext|>