text:
#pragma once

#include <Eigen/Dense>
#include <type_traits>
#include <vector>

#ifdef USE_MPI
#include <mpi.h>
#endif

#include "base/exceptions.hpp"
#include "my_map.hpp"

namespace _local {
template <typename T>
struct TransposeAdaptor
{
  TransposeAdaptor(const T &t_)
      : t(t_){/* empty */};
  const T &operator()() const { return t; }
  const T &t;
};
}  // _local

/*
 *  A collection of vectors, each of length `length`.
 */
template <typename NUMERIC_T = double>
class CoeffArray
{
 private:
  typedef CoeffArray<NUMERIC_T> this_type;

 public:
  typedef NUMERIC_T numeric_t;
  typedef Eigen::Array<NUMERIC_T, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> container_t;
  typedef Eigen::Array<NUMERIC_T, Eigen::Dynamic, 1, Eigen::ColMajor> vec_storage_t;
  typedef Eigen::Map<vec_storage_t> view_t;
  typedef Eigen::Map<const vec_storage_t> cview_t;
  typedef Map map_t;

 public:
  CoeffArray(const Map &map, unsigned int length)
      : map_(map)
      , length_(length)
      , storage_(length, map.lsize())
  { /* empty */
  }

  // @{
  /// get data asssigned to index k (local index!)
  view_t get(int k);
  cview_t get(int k) const;
  // @}

  /// the number of coefficients per entry
  unsigned int length() const;

  CoeffArray<NUMERIC_T> &operator=(const _local::TransposeAdaptor<this_type> &wrapped_other);

  const Map &get_map() const;

  container_t &array();
  const container_t &array() const;

  numeric_t *data();
  const numeric_t *data() const;

  _local::TransposeAdaptor<this_type> transpose() const;

  template <typename DERIVED>
  void import_from_full_array(const Eigen::DenseBase<DERIVED> &src);

 protected:
  const Map &map_;
  const unsigned int length_;
  container_t storage_;
};

template <typename NUMERIC_T>
unsigned int
CoeffArray<NUMERIC_T>::length() const
{
  return length_;
}

template <typename NUMERIC_T>
typename CoeffArray<NUMERIC_T>::view_t
CoeffArray<NUMERIC_T>::get(int k)
{
  return view_t(storage_.col(k).data(), length_);
}

template <typename NUMERIC_T>
typename CoeffArray<NUMERIC_T>::cview_t
CoeffArray<NUMERIC_T>::get(int k) const
{
  return cview_t(storage_.col(k).data(), length_);
}

template <typename NUMERIC_T>
typename CoeffArray<NUMERIC_T>::container_t &
CoeffArray<NUMERIC_T>::array()
{
  return storage_;
}

template <typename NUMERIC_T>
const typename CoeffArray<NUMERIC_T>::container_t &
CoeffArray<NUMERIC_T>::array() const
{
  return storage_;
}

template <typename NUMERIC_T>
_local::TransposeAdaptor<typename CoeffArray<NUMERIC_T>::this_type>
CoeffArray<NUMERIC_T>::transpose() const
{
  return _local::TransposeAdaptor<this_type>(*this);
}

template <typename NUMERIC_T>
NUMERIC_T *
CoeffArray<NUMERIC_T>::data()
{
  return storage_.data();
}

template <typename NUMERIC_T>
const NUMERIC_T *
CoeffArray<NUMERIC_T>::data() const
{
  return storage_.data();
}

template <typename NUMERIC_T>
const Map &
CoeffArray<NUMERIC_T>::get_map() const
{
  return map_;
}

template <typename NUMERIC_T>
CoeffArray<NUMERIC_T> &
CoeffArray<NUMERIC_T>::operator=(const _local::TransposeAdaptor<this_type> &wrapped_other)
{
  const auto &other = wrapped_other();
  ASSERT(map_.size() == other.length_);
  ASSERT(length_ == other.map_.size());

  static_assert(std::is_same<NUMERIC_T, double>::value);

  container_t tmp(other.length_, other.map_.size());
  tmp = other.storage_.transpose();

  int nprocs, pid;
  MPI_Comm_rank(map_.comm(), &pid);
  MPI_Comm_size(map_.comm(), &nprocs);

  // counts and offsets, units are no. of elements
  std::vector<int> sendcounts(nprocs);
  std::vector<int> recvcounts(nprocs);
  std::vector<int> sdispls(nprocs);
  std::vector<int> rdispls(nprocs);

  // assemble sendcounts and sdispls
  int soffset = 0;
  for (int i = 0; i < nprocs; ++i) {
    int sendcount = other.map_.lsize() * this->map_.lsize(i);
    sendcounts[i] = sendcount;
    sdispls[i] = soffset;
    soffset += sendcount * sizeof(numeric_t);
  }

  std::vector<MPI_Datatype> send_type(nprocs, MPI_DOUBLE);
  std::vector<MPI_Datatype> recv_type(nprocs);

  // prepare recv types
  for (int i = 0; i < nprocs; ++i) {
    MPI_Type_vector(
        this->map_.lsize(), other.map_.lsize(i), length_, MPI_DOUBLE, recv_type.data() + i);
    // MPI_Type_vector(this->map_.lsize(), other.map_.lsize(i), length_,
    // MPI_DOUBLE,
    // recv_type.data() + i); // (*)
    MPI_Type_commit(recv_type.data() + i);
  }

  // assemble recvcounts and rdispl
  for (int i = 0; i < nprocs; ++i) {
    int recvcount = this->map_.lsize();
    // recvcounts[i] = recvcount; // (*)
    // it does not work with (*)! Why? (also see previous for-loop)
    recvcounts[i] = 1;
    rdispls[i] = other.map_.get_begin(i) * sizeof(numeric_t);
  }

  // TODO: make wrapper for MPI_Datatype!
  int err = MPI_Alltoallw(tmp.data(),
                          sendcounts.data(),
                          sdispls.data(),
                          send_type.data(),
                          storage_.data(),
                          recvcounts.data(),
                          rdispls.data(),
                          recv_type.data(),
                          this->map_.comm());
  BOOST_ASSERT(err == 0);

  return *this;
}

template <typename NUMERIC_T>
template <typename DERIVED>
void
CoeffArray<NUMERIC_T>::import_from_full_array(const Eigen::DenseBase<DERIVED> &src)
{
  static_assert(std::is_same<typename DERIVED::Scalar, NUMERIC_T>::value);
  BOOST_VERIFY(src.rows() == length_);
  storage_ = src.middleCols(map_.begin(), map_.lsize());
}


text:
#include "fsm/packet_receiver.h"

#include <boost/asio.hpp>
#include <date/tz.h>

#include <iostream>
#include <cstdlib>

namespace fc {

unsigned int ppm(const std::vector<unsigned char>& p) {
    return p[1] * 256 + p[2];
}

void printPacket(const std::vector<unsigned char>& p) {
    auto tp = date::zoned_time{
            date::current_zone(),
            std::chrono::system_clock::now()
    };

    std::cout << tp  << ' ' << ppm(p) << " ppm" << std::endl;
}

struct DefMachine : msmf::state_machine_def<DefMachine>
{
    // States
    struct InitState : msmf::state<> {};

    using initial_state = InitState;

    // Actions
    struct onPacket
    {
        template <typename Fsm, typename SourceState, typename TargetState>
        void operator()(const PacketEvent& event, Fsm& fsm, SourceState&, TargetState&) {
            std::vector<unsigned char> p = *(event.packet);
            printPacket(p);
        }
    };

    using SubMachine = boost::msm::back::state_machine<DefPacketReceiverFSM>;

    using SubMachineEntry = SubMachine::entry_pt<DefPacketReceiverFSM::State::Entry>;
    using SubMachineExit = SubMachine::exit_pt<DefPacketReceiverFSM::State::Exit>;

    struct transition_table : boost::mpl::vector<
            //        Start             Event           Next                Action
            msmf::Row<InitState,        msmf::none,     SubMachineEntry,    msmf::none>,
            msmf::Row<SubMachineExit,   PacketEvent,    InitState,          onPacket>
    >{};
};

using Machine = boost::msm::back::state_machine<DefMachine>;

} // namespace fc

int main() {
    boost::asio::io_context ioContext;
    boost::asio::serial_port port{ioContext};

    port.open("/dev/ttyUSB0");
    port.set_option(boost::asio::serial_port::baud_rate{9600});

    fc::Machine machine;
    machine.start();

    unsigned char c;

    for (;;) {
        boost::asio::read(port, boost::asio::buffer(&c, 1));
        machine.process_event(fc::ByteEvent{c});
    }

    return EXIT_SUCCESS;
}

ext: cpp

max_stars_repo_name: dvetutnev/fart-checker

max_issues_repo_name: dvetutnev/fart-checker

max_forks_repo_name: dvetutnev/fart-checker


text:
// C++ headers
#include <string>
#include <cstring>

// boost headers
#include <boost/regex.hpp>

// Root headers
#include <TH1F.h>

// CMSSW headers
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/Run.h"
#include "FWCore/Framework/interface/LuminosityBlock.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/ParameterSet/interface/ParameterSetDescription.h"
#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h"
#include "FWCore/ParameterSet/interface/Registry.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "DataFormats/Provenance/interface/ProcessHistory.h"
#include "DQMServices/Core/interface/DQMStore.h"
#include "DQMServices/Core/interface/DQMEDHarvester.h"

struct MEPSet {
  std::string folder;
  std::string name;
  int nbins;
  double xmin;
  double xmax;
};

class FastTimerServiceClient : public DQMEDHarvester {
public:
  explicit FastTimerServiceClient(edm::ParameterSet const&);
  ~FastTimerServiceClient() override;

  static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
  static void fillLumiMePSetDescription(edm::ParameterSetDescription& pset);
  static void fillPUMePSetDescription(edm::ParameterSetDescription& pset);

private:
  std::string m_dqm_path;

  void dqmEndLuminosityBlock(DQMStore::IBooker& booker,
                             DQMStore::IGetter& getter,
                             edm::LuminosityBlock const&,
                             edm::EventSetup const&) override;
  void dqmEndJob(DQMStore::IBooker& booker, DQMStore::IGetter& getter) override;

  void fillSummaryPlots(DQMStore::IBooker& booker, DQMStore::IGetter& getter);
  void fillProcessSummaryPlots(DQMStore::IBooker& booker, DQMStore::IGetter& getter, std::string const& path);
  void fillPathSummaryPlots(DQMStore::IBooker& booker,
                            DQMStore::IGetter& getter,
                            double events,
                            std::string const& path);
  void fillPlotsVsLumi(DQMStore::IBooker& booker,
                       DQMStore::IGetter& getter,
                       std::string const& current_path,
                       std::string const& suffix,
                       MEPSet pset);

  static MEPSet getHistoPSet(const edm::ParameterSet& pset);

  bool doPlotsVsScalLumi_;
  bool doPlotsVsPixelLumi_;
  bool doPlotsVsPU_;

  MEPSet scalLumiMEPSet_;
  MEPSet pixelLumiMEPSet_;
  MEPSet puMEPSet_;

  bool fillEveryLumiSection_;
};

FastTimerServiceClient::FastTimerServiceClient(edm::ParameterSet const& config)
    : m_dqm_path(config.getUntrackedParameter<std::string>("dqmPath")),
      doPlotsVsScalLumi_(config.getParameter<bool>("doPlotsVsScalLumi")),
      doPlotsVsPixelLumi_(config.getParameter<bool>("doPlotsVsPixelLumi")),
      doPlotsVsPU_(config.getParameter<bool>("doPlotsVsPU")),
      scalLumiMEPSet_(doPlotsVsScalLumi_ ? getHistoPSet(config.getParameter<edm::ParameterSet>("scalLumiME"))
                                         : MEPSet{}),
      pixelLumiMEPSet_(doPlotsVsPixelLumi_ ? getHistoPSet(config.getParameter<edm::ParameterSet>("pixelLumiME"))
                                           : MEPSet{}),
      puMEPSet_(doPlotsVsPU_ ? getHistoPSet(config.getParameter<edm::ParameterSet>("puME")) : MEPSet{}),
      fillEveryLumiSection_(config.getParameter<bool>("fillEveryLumiSection")) {}

FastTimerServiceClient::~FastTimerServiceClient() = default;

void FastTimerServiceClient::dqmEndJob(DQMStore::IBooker& booker, DQMStore::IGetter& getter) {
  fillSummaryPlots(booker, getter);
}

void FastTimerServiceClient::dqmEndLuminosityBlock(DQMStore::IBooker& booker,
                                                   DQMStore::IGetter& getter,
                                                   edm::LuminosityBlock const& lumi,
                                                   edm::EventSetup const& setup) {
  if (fillEveryLumiSection_)
    fillSummaryPlots(booker, getter);
}

void FastTimerServiceClient::fillSummaryPlots(DQMStore::IBooker& booker, DQMStore::IGetter& getter) {
  if (getter.get(m_dqm_path + "/event time_real")) {
    // the plots are directly in the configured folder
    fillProcessSummaryPlots(booker, getter, m_dqm_path);
  } else {
    static const boost::regex running_n_processes(".*/Running .*");

    booker.setCurrentFolder(m_dqm_path);
    std::vector<std::string> subdirs = getter.getSubdirs();
    for (auto const& subdir : subdirs) {
      // the plots are in a per-number-of-processes folder
      if (boost::regex_match(subdir, running_n_processes)) {
        booker.setCurrentFolder(subdir);
        if (getter.get(subdir + "/event time_real"))
          fillProcessSummaryPlots(booker, getter, subdir);

        std::vector<std::string> subsubdirs = getter.getSubdirs();
        for (auto const& subsubdir : subsubdirs) {
          if (getter.get(subsubdir + "/event time_real"))
            fillProcessSummaryPlots(booker, getter, subsubdir);
        }
      }
    }  // loop on subdirs
  }
}

void FastTimerServiceClient::fillProcessSummaryPlots(DQMStore::IBooker& booker,
                                                     DQMStore::IGetter& getter,
                                                     std::string const& current_path) {
  MonitorElement* me = getter.get(current_path + "/event time_real");
  if (me == nullptr)
    // no FastTimerService DQM information
    return;

  if (doPlotsVsScalLumi_)
    fillPlotsVsLumi(booker, getter, current_path, "VsScalLumi", scalLumiMEPSet_);
  if (doPlotsVsPixelLumi_)
    fillPlotsVsLumi(booker, getter, current_path, "VsPixelLumi", pixelLumiMEPSet_);
  if (doPlotsVsPU_)
    fillPlotsVsLumi(booker, getter, current_path, "VsPU", puMEPSet_);

  //  getter.setCurrentFolder(current_path);

  double events = me->getTH1F()->GetEntries();

  // look for per-process directories
  static const boost::regex process_name(".*/process .*");

  booker.setCurrentFolder(current_path);  // ?!?!?
  std::vector<std::string> subdirs = getter.getSubdirs();
  for (auto const& subdir : subdirs) {
    if (boost::regex_match(subdir, process_name)) {
      getter.setCurrentFolder(subdir);
      // look for per-path plots inside each per-process directory
      std::vector<std::string> subsubdirs = getter.getSubdirs();
      for (auto const& subsubdir : subsubdirs) {
        if (getter.get(subsubdir + "/path time_real")) {
          fillPathSummaryPlots(booker, getter, events, subdir);
          break;
        }
      }
    }
  }  // loop on subdir
}

void FastTimerServiceClient::fillPathSummaryPlots(DQMStore::IBooker& booker,
                                                  DQMStore::IGetter& getter,
                                                  double events,
                                                  std::string const& current_path) {
  // note: the following checks need to be kept separate, as any of these histograms might be missing

  booker.setCurrentFolder(current_path);
  std::vector<std::string> subsubdirs = getter.getSubdirs();
  size_t npaths = subsubdirs.size();

  MonitorElement* paths_time =
      booker.book1D("paths_time_real", "Total (real) time spent in each path", npaths, -0.5, double(npaths) - 0.5);
  MonitorElement* paths_thread =
      booker.book1D("paths_time_thread", "Total (thread) time spent in each path", npaths, -0.5, double(npaths) - 0.5);
  MonitorElement* paths_allocated =
      booker.book1D("paths_allocated", "Total allocated memory in each path", npaths, -0.5, double(npaths) - 0.5);
  MonitorElement* paths_deallocated =
      booker.book1D("paths_deallocated", "Total deallocated in each path", npaths, -0.5, double(npaths) - 0.5);

  MonitorElement* me;
  double mean = -1.;

  // extract the list of Paths and EndPaths from the summary plots
  int ibin = 1;
  for (auto const& subsubdir : subsubdirs) {
    std::string test = "/path ";
    if (subsubdir.find(test) == std::string::npos)
      continue;

    static const boost::regex prefix(current_path + "/path ");
    std::string path = boost::regex_replace(subsubdir, prefix, "");

    paths_time->setBinLabel(ibin, path);
    paths_thread->setBinLabel(ibin, path);
    paths_allocated->setBinLabel(ibin, path);
    paths_deallocated->setBinLabel(ibin, path);

    if ((me = getter.get(subsubdir + "/path time_real"))) {
      mean = me->getMean();
      paths_time->setBinContent(ibin, mean);
    }
    if ((me = getter.get(subsubdir + "/path time_thread"))) {
      mean = me->getMean();
      paths_thread->setBinContent(ibin, mean);
    }
    if ((me = getter.get(subsubdir + "/path allocated"))) {
      mean = me->getMean();
      paths_allocated->setBinContent(ibin, mean);
    }

    if ((me = getter.get(subsubdir + "/path deallocated"))) {
      mean = me->getMean();
      paths_deallocated->setBinContent(ibin, mean);
    }

    ibin++;
  }

  for (auto const& subsubdir : subsubdirs) {
    // for each path, fill histograms with
    //  - the average time spent in each module (total time spent in that module, averaged over all events)
    //  - the running time spent in each module (total time spent in that module, averaged over the events where that module actually ran)
    //  - the "efficiency" of each module (number of time a module succeded divided by the number of times the has run)

    getter.setCurrentFolder(subsubdir);
    std::vector<std::string> allmenames = getter.getMEs();
    if (allmenames.empty())
      continue;

    MonitorElement* me_counter = getter.get(subsubdir + "/module_counter");
    MonitorElement* me_real_total = getter.get(subsubdir + "/module_time_real_total");
    MonitorElement* me_thread_total = getter.get(subsubdir + "/module_time_thread_total");

    if (me_counter == nullptr or me_real_total == nullptr)
      continue;

    TH1D* counter = me_counter->getTH1D();
    TH1D* real_total = me_real_total->getTH1D();
    TH1D* thread_total = me_thread_total->getTH1D();
    uint32_t bins = counter->GetXaxis()->GetNbins() - 1;
    double min = counter->GetXaxis()->GetXmin();
    double max = counter->GetXaxis()->GetXmax() - 1;

    TH1F* real_average;
    TH1F* real_running;
    TH1F* thread_average;
    TH1F* thread_running;
    TH1F* efficiency;
    MonitorElement* me;

    booker.setCurrentFolder(subsubdir);
    me = getter.get(subsubdir + "/module_time_real_average");
    if (me) {
      real_average = me->getTH1F();
      assert(me->getTH1F()->GetXaxis()->GetXmin() == min);
      assert(me->getTH1F()->GetXaxis()->GetXmax() == max);
      real_average->Reset();
    } else {
      real_average = booker.book1D("module_time_real_average", "module real average timing", bins, min, max)->getTH1F();
      real_average->SetYTitle("average processing (real) time [ms]");
      for (uint32_t i = 1; i <= bins; ++i) {
        const char* module = counter->GetXaxis()->GetBinLabel(i);
        real_average->GetXaxis()->SetBinLabel(i, module);
      }
    }

    me = getter.get(subsubdir + "/module_time_thread_average");
    if (me) {
      thread_average = me->getTH1F();
      assert(me->getTH1F()->GetXaxis()->GetXmin() == min);
      assert(me->getTH1F()->GetXaxis()->GetXmax() == max);
      thread_average->Reset();
    } else {
      thread_average =
          booker.book1D("module_time_thread_average", "module thread average timing", bins, min, max)->getTH1F();
      thread_average->SetYTitle("average processing (thread) time [ms]");
      for (uint32_t i = 1; i <= bins; ++i) {
        const char* module = counter->GetXaxis()->GetBinLabel(i);
        thread_average->GetXaxis()->SetBinLabel(i, module);
      }
    }

    me = getter.get(subsubdir + "/module_time_real_running");
    if (me) {
      real_running = me->getTH1F();
      assert(me->getTH1F()->GetXaxis()->GetXmin() == min);
      assert(me->getTH1F()->GetXaxis()->GetXmax() == max);
      real_running->Reset();
    } else {
      real_running = booker.book1D("module_time_real_running", "module real running timing", bins, min, max)->getTH1F();
      real_running->SetYTitle("running processing (real) time [ms]");
      for (uint32_t i = 1; i <= bins; ++i) {
        const char* module = counter->GetXaxis()->GetBinLabel(i);
        real_running->GetXaxis()->SetBinLabel(i, module);
      }
    }

    me = getter.get(subsubdir + "/module_time_thread_running");
    if (me) {
      thread_running = me->getTH1F();
      assert(me->getTH1F()->GetXaxis()->GetXmin() == min);
      assert(me->getTH1F()->GetXaxis()->GetXmax() == max);
      thread_running->Reset();
    } else {
      thread_running =
          booker.book1D("module_time_thread_running", "module thread running timing", bins, min, max)->getTH1F();
      thread_running->SetYTitle("running processing (thread) time [ms]");
      for (uint32_t i = 1; i <= bins; ++i) {
        const char* module = counter->GetXaxis()->GetBinLabel(i);
        thread_running->GetXaxis()->SetBinLabel(i, module);
      }
    }

    me = getter.get(subsubdir + "/module_efficiency");
    if (me) {
      efficiency = me->getTH1F();
      assert(me->getTH1F()->GetXaxis()->GetXmin() == min);
      assert(me->getTH1F()->GetXaxis()->GetXmax() == max);
      efficiency->Reset();
    } else {
      efficiency = booker.book1D("module_efficiency", "module efficiency", bins, min, max)->getTH1F();
      efficiency->SetYTitle("filter efficiency");
      efficiency->SetMaximum(1.05);
      for (uint32_t i = 1; i <= bins; ++i) {
        const char* module = counter->GetXaxis()->GetBinLabel(i);
        efficiency->GetXaxis()->SetBinLabel(i, module);
      }
    }

    for (uint32_t i = 1; i <= bins; ++i) {
      double n = counter->GetBinContent(i);
      double p = counter->GetBinContent(i + 1);
      if (n)
        efficiency->SetBinContent(i, p / n);

      // real timing
      double t = real_total->GetBinContent(i);
      real_average->SetBinContent(i, t / events);
      if (n)
        real_running->SetBinContent(i, t / n);

      // thread timing
      t = thread_total->GetBinContent(i);
      thread_average->SetBinContent(i, t / events);
      if (n)
        thread_running->SetBinContent(i, t / n);
    }

    // vs lumi
    if (doPlotsVsScalLumi_)
      fillPlotsVsLumi(booker, getter, subsubdir, "VsScalLumi", scalLumiMEPSet_);
    if (doPlotsVsPixelLumi_)
      fillPlotsVsLumi(booker, getter, subsubdir, "VsPixelLumi", pixelLumiMEPSet_);
    if (doPlotsVsPU_)
      fillPlotsVsLumi(booker, getter, subsubdir, "VsPU", puMEPSet_);
  }
}

#include "FWCore/MessageLogger/interface/MessageLogger.h"
void FastTimerServiceClient::fillPlotsVsLumi(DQMStore::IBooker& booker,
                                             DQMStore::IGetter& getter,
                                             std::string const& current_path,
                                             std::string const& suffix,
                                             MEPSet pset) {
  std::vector<std::string> menames;

  static const boost::regex byls(".*byls");
  static const boost::regex test(suffix);
  // get all MEs in the current_path
  getter.setCurrentFolder(current_path);
  std::vector<std::string> allmenames = getter.getMEs();
  for (auto const& m : allmenames) {
    // get only MEs vs LS
    if (boost::regex_match(m, byls))
      menames.push_back(m);
  }
  // if no MEs available, return
  if (menames.empty())
    return;

  // get info for getting the lumi VS LS histogram
  std::string folder = pset.folder;
  std::string name = pset.name;
  int nbins = pset.nbins;
  double xmin = pset.xmin;
  double xmax = pset.xmax;

  // get lumi/PU VS LS ME
  getter.setCurrentFolder(folder);
  MonitorElement* lumiVsLS = getter.get(folder + "/" + name);
  // if no ME available, return
  if (!lumiVsLS) {
    edm::LogWarning("FastTimerServiceClient") << "no " << name << " ME is available in " << folder << std::endl;
    return;
  }

  // get range and binning for new MEs x-axis
  size_t size = lumiVsLS->getTProfile()->GetXaxis()->GetNbins();
  std::string xtitle = lumiVsLS->getTProfile()->GetYaxis()->GetTitle();

  std::vector<double> lumi;
  std::vector<int> LS;
  for (size_t ibin = 1; ibin <= size; ++ibin) {
    // avoid to store points w/ no info
    if (lumiVsLS->getTProfile()->GetBinContent(ibin) == 0.)
      continue;

    lumi.push_back(lumiVsLS->getTProfile()->GetBinContent(ibin));
    LS.push_back(lumiVsLS->getTProfile()->GetXaxis()->GetBinCenter(ibin));
  }

  booker.setCurrentFolder(current_path);
  getter.setCurrentFolder(current_path);
  for (auto const& m : menames) {
    std::string label = m;
    label.erase(label.find("_byls"));

    MonitorElement* me = getter.get(current_path + "/" + m);
    float ymin = 0.;
    float ymax = std::numeric_limits<float>::max();
    std::string ytitle = me->getTProfile()->GetYaxis()->GetTitle();

    MonitorElement* meVsLumi = getter.get(current_path + "/" + label + "_" + suffix);
    if (meVsLumi) {
      assert(meVsLumi->getTProfile()->GetXaxis()->GetXmin() == xmin);
      assert(meVsLumi->getTProfile()->GetXaxis()->GetXmax() == xmax);
      meVsLumi->Reset();  // do I have to do it ?!?!?
    } else {
      meVsLumi = booker.bookProfile(label + "_" + suffix, label + "_" + suffix, nbins, xmin, xmax, ymin, ymax);
      //    TProfile* meVsLumi_p = meVsLumi->getTProfile();
      meVsLumi->getTProfile()->GetXaxis()->SetTitle(xtitle.c_str());
      meVsLumi->getTProfile()->GetYaxis()->SetTitle(ytitle.c_str());
    }
    for (size_t ils = 0; ils < LS.size(); ++ils) {
      int ibin = me->getTProfile()->GetXaxis()->FindBin(LS[ils]);
      double y = me->getTProfile()->GetBinContent(ibin);

      meVsLumi->Fill(lumi[ils], y);
    }
  }
}

void FastTimerServiceClient::fillLumiMePSetDescription(edm::ParameterSetDescription& pset) {
  pset.add<std::string>("folder", "HLT/LumiMonitoring");
  pset.add<std::string>("name", "lumiVsLS");
  pset.add<int>("nbins", 440);
  pset.add<double>("xmin", 0.);
  pset.add<double>("xmax", 22000.);
}

void FastTimerServiceClient::fillPUMePSetDescription(edm::ParameterSetDescription& pset) {
  pset.add<std::string>("folder", "HLT/LumiMonitoring");
  pset.add<std::string>("name", "puVsLS");
  pset.add<int>("nbins", 260);
  pset.add<double>("xmin", 0.);
  pset.add<double>("xmax", 130.);
}

MEPSet FastTimerServiceClient::getHistoPSet(const edm::ParameterSet& pset) {
  return MEPSet{
      pset.getParameter<std::string>("folder"),
      pset.getParameter<std::string>("name"),
      pset.getParameter<int>("nbins"),
      pset.getParameter<double>("xmin"),
      pset.getParameter<double>("xmax"),
  };
}

void FastTimerServiceClient::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
  // The following says we do not know what parameters are allowed so do no validation
  // Please change this to state exactly what you do use, even if it is no parameters
  edm::ParameterSetDescription desc;
  desc.addUntracked<std::string>("dqmPath", "HLT/TimerService");
  desc.add<bool>("doPlotsVsScalLumi", true);
  desc.add<bool>("doPlotsVsPixelLumi", false);
  desc.add<bool>("doPlotsVsPU", true);

  edm::ParameterSetDescription scalLumiMEPSet;
  fillLumiMePSetDescription(scalLumiMEPSet);
  desc.add<edm::ParameterSetDescription>("scalLumiME", scalLumiMEPSet);

  edm::ParameterSetDescription pixelLumiMEPSet;
  fillLumiMePSetDescription(pixelLumiMEPSet);
  desc.add<edm::ParameterSetDescription>("pixelLumiME", pixelLumiMEPSet);

  edm::ParameterSetDescription puMEPSet;
  fillPUMePSetDescription(puMEPSet);
  desc.add<edm::ParameterSetDescription>("puME", puMEPSet);
  desc.add<bool>("fillEveryLumiSection", true);
  descriptions.add("fastTimerServiceClient", desc);
}

// declare this class as a framework plugin
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(FastTimerServiceClient);

ext: cc

max_stars_repo_name: PKUfudawei/cmssw

max_issues_repo_name: PKUfudawei/cmssw

max_forks_repo_name: PKUfudawei/cmssw


text:
#ifndef ISOLATOR_POS_TABLE
#define ISOLATOR_POS_TABLE

#include <vector>

#include "common.hpp"
#include "samtools/sam.h"
#include "samtools/samtools_extra.h"
#include <boost/unordered_map.hpp>

/* A simple read position structure. */
struct ReadPos
{
    ReadPos(SeqName seqname, uint32_t strand, int32_t pos,
            int32_t start, int32_t end, uint32_t count)
        : seqname(seqname)
        , strand(strand)
        , pos(pos)
        , start(start)
        , end(end)
        , count(count)
    {}

    ReadPos()
        : seqname("")
        , strand(strand_na)
        , pos(0)
        , start(0)
        , end(0)
        , count(0)
    {}

    ReadPos(const ReadPos& other)
        : seqname(other.seqname)
        , strand(other.strand)
        , pos(other.pos)
        , start(other.start)
        , end(other.end)
        , count(other.count)
    {}

    SeqName  seqname;
    uint32_t strand;
    int32_t  pos;
    int32_t start;
    int32_t end;
    uint32_t count;
};

struct PosTableVal
{
    PosTableVal(pos_t pos, pos_t start, pos_t end, unsigned int count)
        : pos(pos), start(start), end(end), count(count)
    {}

    pos_t pos;
    // containing interval (i.e. exon or transcript)
    pos_t start, end;
    unsigned int count;
};

struct PosSubtable
{
    bool inc(pos_t pos, pos_t start, pos_t end, int strand);

    SeqName seqname;
    int32_t tid; /* bam sequence id */

    boost::unordered_map<pos_t, PosTableVal> table[2];
};

/* A class that counts the number of reads starting at a genomic position, used
 * to choose training examples for seqbias.
 *
 * This assumes that reads are added in sorted order. */
class PosTable
{
    public:
        PosTable();
        ~PosTable();

        size_t size();

        /* Tally the start position of the given read. */
        void add(int32_t tid, pos_t pos, int strand,
                 pos_t start, pos_t end, samfile_t* bam_f);

        /* Dump to a flat array. */
        void dump(std::vector<ReadPos>& positions, size_t max_size);
        void dump_stranded(std::vector<ReadPos>& positions, size_t max_size);

    private:
        std::vector<PosSubtable> subtables;
};

#endif

ext: hpp

max_stars_repo_name: dcjones/isolator

max_issues_repo_name: dcjones/isolator

max_forks_repo_name: dcjones/isolator


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)
// Unit Test

// Copyright (c) 2017-2021 Oracle and/or its affiliates.
// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle

// Licensed under the Boost Software License version 1.0.
// http://www.boost.org/users/license.html

#ifdef BOOST_GEOMETRY_TEST_DEBUG
#include <iostream>
#endif

#ifndef BOOST_TEST_MODULE
#define BOOST_TEST_MODULE test_distance_geographic_pointlike_areal
#endif

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

#include "test_distance_geo_common.hpp"
#include "test_empty_geometry.hpp"

template
<
        typename Point,
        typename Strategy_pp,
        typename Strategy_ps
>
void test_distance_point_ring(Strategy_pp const& strategy_pp,
                              Strategy_ps const& strategy_ps)
{

#ifdef BOOST_GEOMETRY_TEST_DEBUG
    std::cout << std::endl;
    std::cout << "point/ring distance tests" << std::endl;
#endif
    typedef bg::model::ring<Point> ring_type;
    typedef test_distance_of_geometries<Point, ring_type> tester;

    std::string const ring = "POLYGON((10 10,0 20, 15 30, 20 15, 15 10, 10 10))";

    tester::apply("pr1", "POINT(0 10)", ring,
                  ps_distance<Point>("POINT(0 10)",
                                     "SEGMENT(0 20, 10 10)", strategy_ps),
                  strategy_ps, true, true, false);
    tester::apply("pr2", "POINT(10 0)", ring,
                  pp_distance<Point>("POINT(10 10)", "POINT(10 0)", strategy_pp),
                  strategy_ps, true, true, false);
    tester::apply("pr3", "POINT(0 20)", ring,
                  0, strategy_ps, true, true, false);
    tester::apply("pr4", "POINT(10 10)", ring,
                  0, strategy_ps, true, true, false);
    tester::apply("pr4", "POINT(10 11)", ring,
                  0, strategy_ps, true, true, false);
}

//===========================================================================

template
<
        typename Point,
        typename Strategy_ps
>
void test_distance_multipoint_ring(Strategy_ps const& strategy_ps)
{

#ifdef BOOST_GEOMETRY_TEST_DEBUG
    std::cout << std::endl;
    std::cout << "multipoint/ring distance tests" << std::endl;
#endif
    typedef bg::model::ring<Point> ring_type;
    typedef bg::model::multi_point<Point> multi_point_type;
    typedef test_distance_of_geometries<multi_point_type, ring_type> tester;

    std::string const ring = "POLYGON((10 10,0 20, 15 30, 20 15, 15 10, 10 10))";

    tester::apply("pr1", "MULTIPOINT(0 10,10 0,0 0)", ring,
                  ps_distance<Point>("POINT(0 10)",
                                     "SEGMENT(0 20, 10 10)", strategy_ps),
                  strategy_ps, true, true, false);
}

//===========================================================================

template
<
        typename Point,
        typename Strategy_pp,
        typename Strategy_ps
>
void test_distance_point_polygon(Strategy_pp const& strategy_pp,
                                 Strategy_ps const& strategy_ps)
{

#ifdef BOOST_GEOMETRY_TEST_DEBUG
    std::cout << std::endl;
    std::cout << "point/polygon distance tests" << std::endl;
#endif
    typedef bg::model::polygon<Point> polygon_type;
    typedef test_distance_of_geometries<Point, polygon_type> tester;

    std::string const polygon =
            "POLYGON((10 10,0 20, 15 30, 20 15, 15 10, 10 10))";

    tester::apply("pr1", "POINT(0 10)", polygon,
                  ps_distance<Point>("POINT(0 10)",
                                     "SEGMENT(0 20, 10 10)", strategy_ps),
                  strategy_ps, true, true, false);
    tester::apply("pr2", "POINT(10 0)", polygon,
                  pp_distance<Point>("POINT(10 10)", "POINT(10 0)", strategy_pp),
                  strategy_ps, true, true, false);
    tester::apply("pr3", "POINT(0 20)", polygon,
                  0, strategy_ps, true, true, false);
    tester::apply("pr4", "POINT(10 10)", polygon,
                  0, strategy_ps, true, true, false);
    tester::apply("pr5", "POINT(10 10.1)", polygon,
                  0, strategy_ps, false, false, false);
}

//===========================================================================

template
<
        typename Point,
        typename Strategy_pp,
        typename Strategy_ps
>
void test_distance_multipoint_polygon(Strategy_pp const& strategy_pp,
                                      Strategy_ps const& strategy_ps)
{

#ifdef BOOST_GEOMETRY_TEST_DEBUG
    std::cout << std::endl;
    std::cout << "multipoint/polygon distance tests" << std::endl;
#endif
    typedef bg::model::polygon<Point> polygon_type;
    typedef bg::model::multi_point<Point> multi_point_type;
    typedef test_distance_of_geometries<multi_point_type, polygon_type> tester;

    std::string const polygon = "POLYGON((10 10,0 20,15 30,20 15,15 10,10 10))";

    tester::apply("mpp1", "MULTIPOINT(0 10,10 0,0 0)", polygon,
                  ps_distance<Point>("POINT(0 10)",
                                     "SEGMENT(0 20, 10 10)", strategy_ps),
                  strategy_ps, true, true, false);

    tester::apply("mpp2", "MULTIPOINT(0 10,10 0,0 0,20.1 15)", polygon,
                  pp_distance<Point>("POINT(20 15)",
                                     "POINT(20.1 15)", strategy_pp),
                  strategy_ps, true, true, false);

    tester::apply("mpp3", "MULTIPOINT(0 10,10 0,0 0,20.1 15,10 10)", polygon,
                  0, strategy_ps, true, true, false);

    tester::apply("mpp4", "MULTIPOINT(0 10,10 0,0 0,20.1 15,10 11)", polygon,
                  0, strategy_ps, true, true, false);
}

//===========================================================================

template
<
        typename Point,
        typename Strategy_pp,
        typename Strategy_ps
>
void test_distance_point_multipolygon(Strategy_pp const& strategy_pp,
                                      Strategy_ps const& strategy_ps)
{

#ifdef BOOST_GEOMETRY_TEST_DEBUG
    std::cout << std::endl;
    std::cout << "point/multipolygon distance tests" << std::endl;
#endif
    typedef bg::model::polygon<Point> polygon_type;
    typedef bg::model::multi_polygon<polygon_type> multipolygon_type;
    typedef test_distance_of_geometries<Point, multipolygon_type> tester;

    std::string const mpoly = "MULTIPOLYGON(((20 20, 20 30, 30 40, 20 20)),\
                                     ((10 10,0 20, 15 30, 20 15, 15 10, 10 10)))";

    tester::apply("pmp1", "POINT(0 10)", mpoly,
                  ps_distance<Point>("POINT(0 10)",
                                     "SEGMENT(0 20, 10 10)", strategy_ps),
                  strategy_ps, true, true, false);

    tester::apply("pmp2", "POINT(10 9.9)", mpoly,
                  pp_distance<Point>("POINT(10 9.9)",
                                     "POINT(10 10)", strategy_pp),
                  strategy_ps, true, true, false);

    tester::apply("pmp3", "POINT(10 11)", mpoly,
                  0, strategy_ps, true, true, false);
}

//===========================================================================

template
<
        typename Point,
        typename Strategy_pp,
        typename Strategy_ps
>
void test_distance_multipoint_multipolygon(Strategy_pp const& strategy_pp,
                                           Strategy_ps const& strategy_ps)
{

#ifdef BOOST_GEOMETRY_TEST_DEBUG
    std::cout << std::endl;
    std::cout << "multipoint/multipolygon distance tests" << std::endl;
#endif
    typedef bg::model::polygon<Point> polygon_type;
    typedef bg::model::multi_polygon<polygon_type> multipolygon_type;
    typedef bg::model::multi_point<Point> multi_point_type;
    typedef test_distance_of_geometries<multi_point_type, multipolygon_type> tester;

    std::string const mpoly = "MULTIPOLYGON(((20 20, 20 30, 30 40, 20 20)),\
                                  ((10 10,0 20, 15 30, 20 15, 15 10, 10 10)))";

    tester::apply("pr1", "MULTIPOINT(0 10,10 0,0 0)", mpoly,
                  ps_distance<Point>("POINT(0 10)",
                                     "SEGMENT(0 20, 10 10)", strategy_ps),
                  strategy_ps, true, true, false);

    tester::apply("pmp2", "MULTIPOINT(0 10,10 0,0 0,10 9.9)", mpoly,
                  pp_distance<Point>("POINT(10 9.9)",
                                     "POINT(10 10)", strategy_pp),
                  strategy_ps, true, true, false);

    tester::apply("pmp3", "MULTIPOINT(0 10,10 0,0 0,10 9.9,10 11)", mpoly,
                  0, strategy_ps, true, true, false);
}

//===========================================================================
// Cases for relative location of a point wrt to a box
//
//           |         |
//           |    3    |
//           |         |
//           +---------+
//           |         |
//       1   |    5    |   2
//           |         |
//           +---------+
//           |         |
//           |    4    |
//           |         |
//
// and also the following cases
//
//           |         |
//           A         B
//           |         |
//           +----C----+
//           |         |
//           D         E
//           |         |
//           +----F----+
//           |         |
//           G         H
//           |         |
//
// and finally we have the corners
//
//           |         |
//           |         |
//           |         |
//           a---------b
//           |         |
//           |         |
//           |         |
//           c---------d
//           |         |
//           |         |
//           |         |
//
// for each relative position we also have to test the shifted point
// (this is due to the fact that boxes have longitudes in the
// range [-180, 540)
//===========================================================================

template
<
        typename Point,
        typename Strategy_pp,
        typename Strategy_ps,
        typename Strategy_pb
>
void test_distance_point_box(Strategy_pp const& strategy_pp,
                             Strategy_ps const& strategy_ps,
                             Strategy_pb const& strategy_pb)
{

#ifdef BOOST_GEOMETRY_TEST_DEBUG
    std::cout << std::endl;
    std::cout << "point/box distance tests" << std::endl;
#endif
    typedef bg::model::box<Point> box_type;
    typedef test_distance_of_geometries<Point, box_type> tester;

    std::string const box1 = "BOX(10 10,20 20)";

    // case 1
    tester::apply("pb1-1a", "POINT(5 25)", box1,
                  pp_distance<Point>("POINT(5 25)", "POINT(10 20)", strategy_pp),
                  strategy_pb);

    // case 1
    tester::apply("pb1-1b", "POINT(3 12)", box1,
                  ps_distance<Point>("POINT(3 12)",
                                     "SEGMENT(10 10,10 20)", strategy_ps),
                  strategy_pb);

    // case 1
    tester::apply("pb1-1c", "POINT(3 17)", box1,
                  ps_distance<Point>("POINT(3 17)",
                                     "SEGMENT(10 10,10 20)", strategy_ps),
                  strategy_pb);

    // case 1
    tester::apply("pb1-1d", "POINT(5 4)", box1,
                  pp_distance<Point>("POINT(5 4)", "POINT(10 10)", strategy_pp),
                  strategy_pb);

    // case 1
    tester::apply("pb1-1e", "POINT(-100 20)", box1,
                  pp_distance<Point>("POINT(-100 20)",
                                     "POINT(10 20)", strategy_pp),
                  strategy_pb);

    // case 1
    tester::apply("pb1-1g", "POINT(-100 10)", box1,
                  ps_distance<Point>("POINT(-100 10)",
                                     "SEGMENT(10 10,10 20)", strategy_ps),
                  strategy_pb);

    // case 2
    tester::apply("pb1-2a", "POINT(31 25)", box1,
                  pp_distance<Point>("POINT(31 25)",
                                     "POINT(20 20)", strategy_pp),
                  strategy_pb);

    // case 2
    tester::apply("pb1-2b", "POINT(23 17)", box1,
                  ps_distance<Point>("POINT(23 17)",
                                     "SEGMENT(20 10,20 20)", strategy_ps),
                  strategy_pb);

    // case 2
    tester::apply("pb1-2c", "POINT(29 3)", box1,
                  pp_distance<Point>("POINT(29 3)",
                                     "POINT(20 10)", strategy_pp),
                  strategy_pb);

    // case 2
    tester::apply("pb1-2d", "POINT(131 65)", box1,
                  pp_distance<Point>("POINT(131 65)",
                                     "POINT(20 20)", strategy_pp),
                  strategy_pb);

    // case 2
    tester::apply("pb1-2e", "POINT(110 10)", box1,
                  ps_distance<Point>("POINT(110 10)",
                                     "SEGMENT(20 10,20 20)", strategy_ps),
                  strategy_pb);

    // case 2
    tester::apply("pb1-2f", "POINT(150 20)", box1,
                  pp_distance<Point>("POINT(150 20)",
                                     "POINT(20 20)", strategy_pp),
                  strategy_pb);

    // case 3
    tester::apply("pb1-3a", "POINT(11 25)", box1,
                  pp_distance<Point>("POINT(11 25)",
                                     "POINT(11 20)", strategy_pp),
                  strategy_pb);

    // case 3
    tester::apply("pb1-3b", "POINT(15 25)", box1,
                  pp_distance<Point>("POINT(15 25)",
                                     "POINT(15 20)", strategy_pp),
                  strategy_pb);

    // case 3
    tester::apply("pb1-3c", "POINT(18 25)", box1,
                  pp_distance<Point>("POINT(18 25)",
                                     "POINT(18 20)", strategy_pp),
                  strategy_pb);

    // case 4
    tester::apply("pb1-4a", "POINT(13 4)", box1,
                  pp_distance<Point>("POINT(13 4)",
                                     "POINT(13 10)", strategy_pp),
                  strategy_pb);

    // case 4
    tester::apply("pb1-4b", "POINT(19 4)", box1,
                  pp_distance<Point>("POINT(19 4)",
                                     "POINT(19 10)", strategy_pp),
                  strategy_pb);

    // case 5
    tester::apply("pb1-5", "POINT(15 14)", box1, 0, strategy_pb);

    // case A
    tester::apply("pb1-A", "POINT(10 28)", box1,
                  pp_distance<Point>("POINT(10 28)",
                                     "POINT(10 20)", strategy_pp),
                  strategy_pb);

    // case B
    tester::apply("pb1-B", "POINT(20 28)", box1,
                  pp_distance<Point>("POINT(20 28)",
                                     "POINT(20 20)", strategy_pp),
                  strategy_pb);

    // case C
    tester::apply("pb1-C", "POINT(14 20)", box1, 0, strategy_pb);

    // case D
    tester::apply("pb1-D", "POINT(10 17)", box1, 0, strategy_pb);

    // case E
    tester::apply("pb1-E", "POINT(20 11)", box1, 0, strategy_pb);

    // case F
    tester::apply("pb1-F", "POINT(19 10)", box1, 0, strategy_pb);

    // case G
    tester::apply("pb1-G", "POINT(10 -40)", box1,
                  pp_distance<Point>("POINT(10 -40)",
                                     "POINT(10 10)", strategy_pp),
                  strategy_pb);

    // case H
    tester::apply("pb1-H", "POINT(20 -50)", box1,
                  pp_distance<Point>("POINT(20 -50)",
                                     "POINT(20 10)", strategy_pp),
                  strategy_pb);

    // case a
    tester::apply("pb1-a", "POINT(10 20)", box1, 0, strategy_pb);
    // case b
    tester::apply("pb1-b", "POINT(20 20)", box1, 0, strategy_pb);
    // case c
    tester::apply("pb1-c", "POINT(10 10)", box1, 0, strategy_pb);
    // case d
    tester::apply("pb1-d", "POINT(20 10)", box1, 0, strategy_pb);

    std::string const box2 = "BOX(170 -60,400 80)";

    // case 1 - point is closer to western meridian
    tester::apply("pb2-1a", "POINT(160 0)", box2,
                  ps_distance<Point>("POINT(160 0)",
                                     "SEGMENT(170 -60,170 80)", strategy_ps),
                  strategy_pb);

    // case 1 - point is closer to eastern meridian
    tester::apply("pb2-1b", "POINT(50 0)", box2,
                  ps_distance<Point>("POINT(50 0)",
                                     "SEGMENT(40 -60,40 80)", strategy_ps),
                  strategy_pb);

    // case 3 - equivalent point POINT(390 85) is above the box
    tester::apply("pb2-3", "POINT(30 85)", box2,
                  pp_distance<Point>("POINT(30 85)",
                                     "POINT(30 80)", strategy_pp),
                  strategy_pb);

    // case 4 - equivalent point POINT(390 -75) is below the box
    tester::apply("pb2-4", "POINT(30 -75)", box2,
                  pp_distance<Point>("POINT(30 -75)",
                                     "POINT(30 -60)", strategy_pp),
                  strategy_pb);

    // case 5 - equivalent point POINT(390 0) is inside box
    tester::apply("pb2-5", "POINT(30 0)", box2, 0, strategy_pb);

    std::string const box3 = "BOX(-150 -50,-40 70)";

    // case 1 - point is closer to western meridian
    tester::apply("pb3-1a", "POINT(-170 10)", box3,
                  ps_distance<Point>("POINT(-170 10)",
                                     "SEGMENT(-150 -50,-150 70)", strategy_ps),
                  strategy_pb);

    // case 2 - point is closer to eastern meridian
    tester::apply("pb3-2a", "POINT(5 10)", box3,
                  ps_distance<Point>("POINT(5 10)",
                                     "SEGMENT(-40 -50,-40 70)", strategy_ps),
                  strategy_pb);

    // case 2 - point is closer to western meridian
    tester::apply("pb3-2a", "POINT(160 10)", box3,
                  ps_distance<Point>("POINT(160 10)",
                                     "SEGMENT(-150 -50,-150 70)", strategy_ps),
                  strategy_pb);

    // case 2 - point is at equal distance from eastern and western meridian
    tester::apply("pb3-2c1", "POINT(85 20)", box3,
                  ps_distance<Point>("POINT(85 20)",
                                     "SEGMENT(-150 -50,-150 70)", strategy_ps),
                  strategy_pb);

    // case 2 - point is at equal distance from eastern and western meridian
    tester::apply("pb3-2c2", "POINT(85 20)", box3,
                  ps_distance<Point>("POINT(85 20)",
                                     "SEGMENT(-40 -50,-40 70)", strategy_ps),
                  strategy_pb);

    // box that is symmetric wrt the prime meridian
    std::string const box4 = "BOX(-75 -45,75 65)";

    // case 1 - point is closer to western meridian
    tester::apply("pb4-1a", "POINT(-100 10)", box4,
                  ps_distance<Point>("POINT(-100 10)",
                                     "SEGMENT(-75 -45,-75 65)", strategy_ps),
                  strategy_pb);

    // case 2 - point is closer to eastern meridian
    tester::apply("pb4-2a", "POINT(90 15)", box4,
                  ps_distance<Point>("POINT(90 15)",
                                     "SEGMENT(75 -45,75 65)", strategy_ps),
                  strategy_pb);

    // case 2 - point is at equal distance from eastern and western meridian
    tester::apply("pb4-2c1", "POINT(-180 20)", box4,
                  ps_distance<Point>("POINT(-180 20)",
                                     "SEGMENT(-75 -45,-75 65)", strategy_ps),
                  strategy_pb);

    // case 2 - point is at equal distance from eastern and western meridian
    tester::apply("pb4-2c2", "POINT(-180 20)", box4,
                  ps_distance<Point>("POINT(-180 20)",
                                     "SEGMENT(75 -45,75 65)", strategy_ps),
                  strategy_pb);

    //box degenerates to a meridian segment
    std::string const boxdeg1 = "BOX(0 10,0 20)";

    tester::apply("pbd1", "POINT(1 10)", boxdeg1,
                  ps_distance<Point>("POINT(1 10)",
                                     "SEGMENT(0 10, 0 20)", strategy_ps),
                  strategy_pb);
    tester::apply("pbd2", "POINT(1 5)", boxdeg1,
                  ps_distance<Point>("POINT(1 5)",
                                     "SEGMENT(0 10, 0 20)", strategy_ps),
                  strategy_pb);
    tester::apply("pbd3", "POINT(1 15)", boxdeg1,
                  ps_distance<Point>("POINT(1 15)",
                                     "SEGMENT(0 10, 0 20)", strategy_ps),
                  strategy_pb);
    tester::apply("pbd4", "POINT(1 25)", boxdeg1,
                  ps_distance<Point>("POINT(1 25)",
                                     "SEGMENT(0 10, 0 20)", strategy_ps),
                  strategy_pb);

    //box degenerates to a horizontal line; that is not a geodesic segment
    std::string const boxdeg2 = "BOX(10 10,20 10)";

    tester::apply("pbd5", "POINT(15 15)", boxdeg2,
                  pp_distance<Point>("POINT(15 15)",
                                     "POINT(15 10)", strategy_pp),
                  strategy_pb);
    tester::apply("pbd6", "POINT(5 15)", boxdeg2,
                  pp_distance<Point>("POINT(5 15)",
                                     "POINT(10 10)", strategy_pp),
                  strategy_pb);
    tester::apply("pbd7", "POINT(25 15)", boxdeg2,
                  pp_distance<Point>("POINT(25 15)",
                                     "POINT(20 10)", strategy_pp),
                  strategy_pb);

    //box degenerates to a point
    std::string const boxdeg3 = "BOX(0 10,0 10)";

    tester::apply("pbd8", "POINT(1 11)", boxdeg3,
                  pp_distance<Point>("POINT(1 11)",
                                     "POINT(0 10)", strategy_pp),
                  strategy_pb);
}

template
<
        typename Point,
        typename Strategy_pp,
        typename Strategy_ps,
        typename Strategy_pb
>
void test_distance_multipoint_box(Strategy_pp const& strategy_pp,
                                  Strategy_ps const& strategy_ps,
                                  Strategy_pb const& strategy_pb)
{

#ifdef BOOST_GEOMETRY_TEST_DEBUG
    std::cout << std::endl;
    std::cout << "multipoint/box distance tests" << std::endl;
#endif
    typedef bg::model::box<Point> box_type;
    typedef bg::model::multi_point<Point> multi_point_type;
    typedef test_distance_of_geometries<multi_point_type, box_type> tester;

    std::string const box1 = "BOX(10 10,20 20)";

    tester::apply("mpb1", "MULTIPOINT(5 25,25 26)", box1,
                  pp_distance<Point>("POINT(5 25)", "POINT(10 20)", strategy_pp),
                  strategy_pb, true, false, false);

    tester::apply("mpb2", "MULTIPOINT(110 10,110 9,110 0)", box1,
                  ps_distance<Point>("POINT(110 10)",
                                     "SEGMENT(20 10,20 20)", strategy_ps),
                  strategy_pb, true, false, false);

    tester::apply("mpb3", "MULTIPOINT(110 10,110 9,110 0,10 20)", box1,
                  0, strategy_pb, true, false, false);

    tester::apply("mpb3", "MULTIPOINT(110 10,110 9,110 0,15 15)", box1,
                  0, strategy_pb, true, false, false);
}

//===========================================================================
//===========================================================================
//===========================================================================

template
<
    typename Point,
    typename Strategy_pp,
    typename Strategy_ps,
    typename Strategy_pb
>
void test_all_pl_ar(Strategy_pp pp_strategy,
                    Strategy_ps ps_strategy,
                    Strategy_pb pb_strategy)
{
    test_distance_point_ring<Point>(pp_strategy, ps_strategy);
    test_distance_multipoint_ring<Point>(ps_strategy);

    test_distance_point_polygon<Point>(pp_strategy, ps_strategy);
    test_distance_multipoint_polygon<Point>(pp_strategy, ps_strategy);

    test_distance_point_multipolygon<Point>(pp_strategy, ps_strategy);
    test_distance_multipoint_multipolygon<Point>(pp_strategy, ps_strategy);

    test_distance_point_box<Point>(pp_strategy, ps_strategy, pb_strategy);
    test_distance_multipoint_box<Point>(pp_strategy, ps_strategy, pb_strategy);

    test_more_empty_input_pointlike_areal<Point>(ps_strategy);
}

BOOST_AUTO_TEST_CASE( test_all_pointlike_areal )
{
    typedef bg::model::point
            <
                double, 2,
                bg::cs::spherical_equatorial<bg::degree>
            > sph_point;

    test_all_pl_ar<sph_point>(spherical_pp(), spherical_ps(), spherical_pb());

    typedef bg::model::point
            <
                double, 2,
                bg::cs::geographic<bg::degree>
            > geo_point;

    test_all_pl_ar<geo_point>(vincenty_pp(), vincenty_ps(), vincenty_pb());
    test_all_pl_ar<geo_point>(thomas_pp(), thomas_ps(), thomas_pb());
    test_all_pl_ar<geo_point>(andoyer_pp(), andoyer_ps(), andoyer_pb());
    //test_all_pl_ar<geo_point>(karney_pp(), karney_ps(), karney_pb());

    // test with different spheroid
    stype spheroid(6372000, 6370000);
    test_all_pl_ar<geo_point>(andoyer_pp(spheroid), andoyer_ps(spheroid),  andoyer_pb(spheroid));
}


text:
//
//  FrictionUtils.hpp
//  IPC
//
//  Created by Minchen Li on 9/26/19.
//

#ifndef FrictionUtils_hpp
#define FrictionUtils_hpp

#include "Types.hpp"

#include "MeshCollisionUtils.hpp"

#include <Eigen/Eigen>

#include <iostream>
#include <array>

namespace IPC {

// Point - Triangle

inline void computeTangentBasis_PT(
    const Eigen::RowVector3d& v0,
    const Eigen::RowVector3d& v1,
    const Eigen::RowVector3d& v2,
    const Eigen::RowVector3d& v3,
    Eigen::Matrix<double, 3, 2>& basis)
{
    Eigen::Vector3d v12 = (v2 - v1).transpose();
    basis.col(0) = v12.normalized();
    basis.col(1) = v12.cross((v3 - v1).transpose()).cross(v12).normalized();
}

inline void computeClosestPoint_PT(
    const Eigen::RowVector3d& v0,
    const Eigen::RowVector3d& v1,
    const Eigen::RowVector3d& v2,
    const Eigen::RowVector3d& v3,
    Eigen::Vector2d& beta)
{
    Eigen::Matrix<double, 2, 3> basis;
    basis.row(0) = v2 - v1;
    basis.row(1) = v3 - v1;
    beta = (basis * basis.transpose()).ldlt().solve(basis * (v0 - v1).transpose());
}

inline void computeRelDX_PT(
    const Eigen::RowVector3d& dx0,
    const Eigen::RowVector3d& dx1,
    const Eigen::RowVector3d& dx2,
    const Eigen::RowVector3d& dx3,
    double beta1, double beta2,
    Eigen::RowVector3d& relDX)
{
    relDX = dx0 - (dx1 + beta1 * (dx2 - dx1) + beta2 * (dx3 - dx1));
}

inline void liftRelDXTanToMesh_PT(
    const Eigen::Vector2d& relDXTan,
    const Eigen::Matrix<double, 3, 2>& basis,
    double beta1, double beta2,
    Eigen::Matrix<double, 12, 1>& TTTDX)
{
    TTTDX.template segment<3>(0) = basis * relDXTan;
    TTTDX.template segment<3>(3) = (-1 + beta1 + beta2) * TTTDX.template segment<3>(0);
    TTTDX.template segment<3>(6) = -beta1 * TTTDX.template segment<3>(0);
    TTTDX.template segment<3>(9) = -beta2 * TTTDX.template segment<3>(0);
}

inline void computeTTT_PT(
    const Eigen::Matrix<double, 3, 2>& basis,
    double beta1, double beta2,
    Eigen::Matrix<double, 12, 12>& TTT)
{
    Eigen::Matrix<double, 2, 12> TT;
    TT.template block<2, 3>(0, 0) = basis.transpose();
    TT.template block<2, 3>(0, 3) = (-1 + beta1 + beta2) * basis.transpose();
    TT.template block<2, 3>(0, 6) = -beta1 * basis.transpose();
    TT.template block<2, 3>(0, 9) = -beta2 * basis.transpose();
    TTT = TT.transpose() * TT;
}

// Edge - Edge

inline void computeTangentBasis_EE(
    const Eigen::RowVector3d& v0,
    const Eigen::RowVector3d& v1,
    const Eigen::RowVector3d& v2,
    const Eigen::RowVector3d& v3,
    Eigen::Matrix<double, 3, 2>& basis)
{
    Eigen::Vector3d v01 = (v1 - v0).transpose();
    basis.col(0) = v01.normalized();
    basis.col(1) = v01.cross((v3 - v2).transpose()).cross(v01).normalized();
}

inline void computeClosestPoint_EE(
    const Eigen::RowVector3d& v0,
    const Eigen::RowVector3d& v1,
    const Eigen::RowVector3d& v2,
    const Eigen::RowVector3d& v3,
    Eigen::Vector2d& gamma)
{
    Eigen::RowVector3d e20 = v0 - v2;
    Eigen::RowVector3d e01 = v1 - v0;
    Eigen::RowVector3d e23 = v3 - v2;

    Eigen::Matrix2d coefMtr;
    coefMtr(0, 0) = e01.squaredNorm();
    coefMtr(0, 1) = coefMtr(1, 0) = -e23.dot(e01);
    coefMtr(1, 1) = e23.squaredNorm();

    Eigen::Vector2d rhs;
    rhs[0] = -e20.dot(e01);
    rhs[1] = e20.dot(e23);

    gamma = coefMtr.ldlt().solve(rhs);
}

inline void computeRelDX_EE(
    const Eigen::RowVector3d& dx0,
    const Eigen::RowVector3d& dx1,
    const Eigen::RowVector3d& dx2,
    const Eigen::RowVector3d& dx3,
    double gamma1, double gamma2,
    Eigen::RowVector3d& relDX)
{
    relDX = dx0 + gamma1 * (dx1 - dx0) - (dx2 + gamma2 * (dx3 - dx2));
}

inline void liftRelDXTanToMesh_EE(
    const Eigen::Vector2d& relDXTan,
    const Eigen::Matrix<double, 3, 2>& basis,
    double gamma1, double gamma2,
    Eigen::Matrix<double, 12, 1>& TTTDX)
{
    Eigen::Vector3d relDXTan3D = basis * relDXTan;
    TTTDX.template segment<3>(0) = (1.0 - gamma1) * relDXTan3D;
    TTTDX.template segment<3>(3) = gamma1 * relDXTan3D;
    TTTDX.template segment<3>(6) = (gamma2 - 1.0) * relDXTan3D;
    TTTDX.template segment<3>(9) = -gamma2 * relDXTan3D;
}

inline void computeTTT_EE(
    const Eigen::Matrix<double, 3, 2>& basis,
    double gamma1, double gamma2,
    Eigen::Matrix<double, 12, 12>& TTT)
{
    Eigen::Matrix<double, 2, 12> TT;
    TT.template block<2, 3>(0, 0) = (1.0 - gamma1) * basis.transpose();
    TT.template block<2, 3>(0, 3) = gamma1 * basis.transpose();
    TT.template block<2, 3>(0, 6) = (gamma2 - 1.0) * basis.transpose();
    TT.template block<2, 3>(0, 9) = -gamma2 * basis.transpose();
    TTT = TT.transpose() * TT;
}

// Point - Edge

inline void computeTangentBasis_PE(
    const Eigen::RowVector3d& v0,
    const Eigen::RowVector3d& v1,
    const Eigen::RowVector3d& v2,
    Eigen::Matrix<double, 3, 2>& basis)
{
    Eigen::Vector3d v12 = (v2 - v1).transpose();
    basis.col(0) = v12.normalized();
    basis.col(1) = v12.cross((v0 - v1).transpose()).normalized();
}

inline void computeClosestPoint_PE(
    const Eigen::RowVector3d& v0,
    const Eigen::RowVector3d& v1,
    const Eigen::RowVector3d& v2,
    double& yita)
{
    Eigen::RowVector3d e12 = v2 - v1;
    yita = (v0 - v1).dot(e12) / e12.squaredNorm();
}

inline void computeRelDX_PE(
    const Eigen::RowVector3d& dx0,
    const Eigen::RowVector3d& dx1,
    const Eigen::RowVector3d& dx2,
    double yita,
    Eigen::RowVector3d& relDX)
{
    relDX = dx0 - (dx1 + yita * (dx2 - dx1));
}

inline void liftRelDXTanToMesh_PE(
    const Eigen::Vector2d& relDXTan,
    const Eigen::Matrix<double, 3, 2>& basis,
    double yita,
    Eigen::Matrix<double, 9, 1>& TTTDX)
{
    TTTDX.template segment<3>(0) = basis * relDXTan;
    TTTDX.template segment<3>(3) = (yita - 1.0) * TTTDX.template segment<3>(0);
    TTTDX.template segment<3>(6) = -yita * TTTDX.template segment<3>(0);
}

inline void computeTTT_PE(
    const Eigen::Matrix<double, 3, 2>& basis,
    double yita,
    Eigen::Matrix<double, 9, 9>& TTT)
{
    Eigen::Matrix<double, 2, 9> TT;
    TT.template block<2, 3>(0, 0) = basis.transpose();
    TT.template block<2, 3>(0, 3) = (yita - 1.0) * basis.transpose();
    TT.template block<2, 3>(0, 6) = -yita * basis.transpose();
    TTT = TT.transpose() * TT;
}

// Point - Point

inline void computeTangentBasis_PP(
    const Eigen::RowVector3d& v0,
    const Eigen::RowVector3d& v1,
    Eigen::Matrix<double, 3, 2>& basis)
{
    Eigen::RowVector3d v01 = v1 - v0;
    Eigen::RowVector3d xCross = Eigen::RowVector3d::UnitX().cross(v01);
    Eigen::RowVector3d yCross = Eigen::RowVector3d::UnitY().cross(v01);
    if (xCross.squaredNorm() > yCross.squaredNorm()) {
        basis.col(0) = xCross.normalized().transpose();
        basis.col(1) = v01.cross(xCross).normalized().transpose();
    }
    else {
        basis.col(0) = yCross.normalized().transpose();
        basis.col(1) = v01.cross(yCross).normalized().transpose();
    }
}

inline void computeRelDX_PP(
    const Eigen::RowVector3d& dx0,
    const Eigen::RowVector3d& dx1,
    Eigen::RowVector3d& relDX)
{
    relDX = dx0 - dx1;
}

inline void liftRelDXTanToMesh_PP(
    const Eigen::Vector2d& relDXTan,
    const Eigen::Matrix<double, 3, 2>& basis,
    Eigen::Matrix<double, 6, 1>& TTTDX)
{
    TTTDX.template segment<3>(0) = basis * relDXTan;
    TTTDX.template segment<3>(3) = -TTTDX.template segment<3>(0);
}

inline void computeTTT_PP(
    const Eigen::Matrix<double, 3, 2>& basis,
    Eigen::Matrix<double, 6, 6>& TTT)
{
    Eigen::Matrix<double, 2, 6> TT;
    TT.template block<2, 3>(0, 0) = basis.transpose();
    TT.template block<2, 3>(0, 3) = -basis.transpose();
    TTT = TT.transpose() * TT;
}

// static friction clamping model
// C0 clamping
inline void f0_SF_C0(double x2, double eps_f, double& f0)
{
    f0 = x2 / (2.0 * eps_f) + eps_f / 2.0;
}

inline void f1_SF_div_relDXNorm_C0(double eps_f, double& result)
{
    result = 1.0 / eps_f;
}

inline void f2_SF_C0(double eps_f, double& f2)
{
    f2 = 1.0 / eps_f;
}

// C1 clamping
inline void f0_SF_C1(double x2, double eps_f, double& f0)
{
    f0 = x2 * (-std::sqrt(x2) / 3.0 + eps_f) / (eps_f * eps_f) + eps_f / 3.0;
}

inline void f1_SF_div_relDXNorm_C1(double x2, double eps_f, double& result)
{
    result = (-std::sqrt(x2) + 2.0 * eps_f) / (eps_f * eps_f);
}

inline void f2_SF_C1(double x2, double eps_f, double& f2)
{
    f2 = 2.0 * (eps_f - std::sqrt(x2)) / (eps_f * eps_f);
}

// C2 clamping
inline void f0_SF_C2(double x2, double eps_f, double& f0)
{
    f0 = x2 * (0.25 * x2 - (std::sqrt(x2) - 1.5 * eps_f) * eps_f) / (eps_f * eps_f * eps_f) + eps_f / 4.0;
}

inline void f1_SF_div_relDXNorm_C2(double x2, double eps_f, double& result)
{
    result = (x2 - (3.0 * std::sqrt(x2) - 3.0 * eps_f) * eps_f) / (eps_f * eps_f * eps_f);
}

inline void f2_SF_C2(double x2, double eps_f, double& f2)
{
    f2 = 3.0 * (x2 - (2.0 * std::sqrt(x2) - eps_f) * eps_f) / (eps_f * eps_f * eps_f);
}

// interfaces
inline void f0_SF(double relDXSqNorm, double eps_f, double& f0)
{
#if (SFCLAMPING_ORDER == 0)
    f0_SF_C0(relDXSqNorm, eps_f, f0);
#elif (SFCLAMPING_ORDER == 1)
    f0_SF_C1(relDXSqNorm, eps_f, f0);
#elif (SFCLAMPING_ORDER == 2)
    f0_SF_C2(relDXSqNorm, eps_f, f0);
#endif
}

inline void f1_SF_div_relDXNorm(double relDXSqNorm, double eps_f, double& result)
{
#if (SFCLAMPING_ORDER == 0)
    f1_SF_div_relDXNorm_C0(eps_f, result);
#elif (SFCLAMPING_ORDER == 1)
    f1_SF_div_relDXNorm_C1(relDXSqNorm, eps_f, result);
#elif (SFCLAMPING_ORDER == 2)
    f1_SF_div_relDXNorm_C2(relDXSqNorm, eps_f, result);
#endif
}

inline void f2_SF(double relDXSqNorm, double eps_f, double& f2)
{
#if (SFCLAMPING_ORDER == 0)
    f2_SF_C0(eps_f, f2);
#elif (SFCLAMPING_ORDER == 1)
    f2_SF_C1(relDXSqNorm, eps_f, f2);
#elif (SFCLAMPING_ORDER == 2)
    f2_SF_C2(relDXSqNorm, eps_f, f2);
#endif
}

} // namespace IPC

#endif /* FrictionUtils_hpp */

max_stars_repo_name: vincentkslim/IPC

max_issues_repo_name: vincentkslim/IPC

max_forks_repo_name: vincentkslim/IPC


text:
//=======================================================================
// Copyright (c) 2014 Piotr Smulewicz
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
/**
 * @file k_cut_example.cpp
 * @brief
 * @author Piotr Smulewicz
 * @version 1.0
 * @date 2014-08-30
 */

    //! [K Cut Example]
#include "paal/greedy/k_cut/k_cut.hpp"

#include <boost/graph/adjacency_list.hpp>

#include <iostream>

int main() {
    // sample data
    std::vector<std::pair<int,int>> edges_p {{1,2},{1,5},{2,3},{2,5},{2,6},
        {3,4},{3,7},{4,7},{4,0},{5,6},{6,7},{7,0}};
    std::vector<int> costs{2,3,3,2,2,4,2,2,2,3,1,3};
    boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS,
                    boost::no_property,
                    boost::property<boost::edge_index_t, std::size_t>
                    > graph(8);
    for (std::size_t i = 0; i < edges_p.size(); ++i) {
        add_edge(edges_p[i].first, edges_p[i].second, i, graph);
    }
    const int parts = 3;

    auto edge_id = get(boost::edge_index, graph);
    auto weight = make_iterator_property_map(costs.begin(), edge_id);

    // solve
    int cost_cut;
    std::vector<std::pair<int,int>> vertices_parts;
    cost_cut = paal::greedy::k_cut(graph, parts, back_inserter(vertices_parts),
            boost::weight_map(weight));

    // alternative form
    // cost_cut = paal::greedy::k_cut(graph, parts, back_inserter(vertices_parts));
    // this works if the graph has and internal edge weight property map

    // print result
    std::cout << "cost cut:" << cost_cut << std::endl;
    std::vector<int> vertices_to_parts;
    for (auto i: vertices_parts) {
        std::cout << i.first << "(" << i.second << "), ";
    }
    std::cout << std::endl;
}
    //! [K Cut Example]

max_stars_repo_name: Kommeren/AA

max_issues_repo_name: Kommeren/AA

max_forks_repo_name: Kommeren/AA


text:
/* Copyright 2014-2017 Rsyn
 *
 * 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 <thread>
#include <iosfwd>
#include <mutex>
#include <boost/filesystem.hpp>

#include "Session.h"

#include "rsyn/3rdparty/json/json.hpp"
#include "rsyn/util/Environment.h"

namespace Rsyn {

static Startup initEngine([]{
	// This will ensure the engine singleton gets initialized when the program
	// starts.
});

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

SessionData * Session::sessionData = nullptr;

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

void Session::init() {
	if (isInitialized())
		return;

#ifdef __APPLE__
    setlocale(LC_ALL, "en_US.UTF-8");
#else
    std::setlocale(LC_ALL, "en_US.UTF-8");
#endif

	sessionData = new SessionData();

	// TODO: hard coded
	sessionData->clsInstallationPath = "../../rsyn/install";

	// Register messages.
	registerMessages();

	// Register processes.
	registerProcesses();

	// Register services
	registerServices();

	// Register readers.
	registerReaders();

	// Register some commands.
	registerDefaultCommands();

	// Create design.
	sessionData->clsDesign.create("__Root_Design__");

	// Cache messages.
	sessionData->msgMessageRegistrationFail = getMessage("SESSION-001");

	// Initialize logger
	const bool enableLog = Environment::getBoolean( "ENABLE_LOG", false );
	sessionData->logger = ( enableLog ) ? ( new Logger() ) : ( nullptr );
} // end constructor

////////////////////////////////////////////////////////////////////////////////
// Message
////////////////////////////////////////////////////////////////////////////////

void Session::registerMessage(const std::string& label, const MessageLevel& level, const std::string& title, const std::string& msg) {
	sessionData->clsMessageManager.registerMessage(label, level, title, msg);
} // end method

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

Message Session::getMessage(const std::string &label) {
	return sessionData->clsMessageManager.getMessage(label);
} // end method

////////////////////////////////////////////////////////////////////////////////
// Script
////////////////////////////////////////////////////////////////////////////////

void Session::registerCommand(const ScriptParsing::CommandDescriptor &dscp, const CommandHandler handler) {
	dscp.check();

	sessionData->clsCommandManager.addCommand(dscp, [=](const ScriptParsing::Command &command) {
		handler(command);
	});
} // end method

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

void Session::evaluateString(const std::string &str) {
	sessionData->clsCommandManager.evaluateString(str);
} // end method

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

void Session::evaluateFile(const std::string &filename) {
	const std::string path = boost::filesystem::path(filename).parent_path().string();
	addPath(path, true);
	sessionData->clsCommandManager.evaluateFile(filename);
	removePath(path);
} // end method

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

void Session::registerDefaultCommands() {

	{ // help
		ScriptParsing::CommandDescriptor dscp;
		dscp.setName("help");
		dscp.setDescription("Shed some light in the world.");

		registerCommand(dscp, [&](const ScriptParsing::Command &command) {
			sessionData->clsCommandManager.printCommandList(std::cout);
		});
	} // end block

	{ // exit
		ScriptParsing::CommandDescriptor dscp;
		dscp.setName("exit");
		dscp.setDescription("Quit execution.");

		registerCommand(dscp, [&](const ScriptParsing::Command &command) {
			sessionData->clsCommandManager.exitRsyn(std::cout);
		});
	} // end block

	{ // history
		ScriptParsing::CommandDescriptor dscp;
		dscp.setName("history");
		dscp.setDescription("Output command history.");

		registerCommand(dscp, [&](const ScriptParsing::Command &command) {
			sessionData->clsCommandManager.printHistory(std::cout);
		});
	} // end block

	{ // run
		ScriptParsing::CommandDescriptor dscp;
		dscp.setName("run");
		dscp.setDescription("Run a process.");

		dscp.addPositionalParam("name",
				ScriptParsing::PARAM_TYPE_STRING,
				ScriptParsing::PARAM_SPEC_MANDATORY,
				"Process name."
		);

		dscp.addPositionalParam("params",
				ScriptParsing::PARAM_TYPE_JSON,
				ScriptParsing::PARAM_SPEC_OPTIONAL,
				"Parameters to be passed to the process."
		);

		registerCommand(dscp, [&](const ScriptParsing::Command &command) {
			const std::string name = command.getParam("name");
			const Json params = command.getParam("params");
			runProcess(name, params);
		});
	} // end block

	{ // set
		ScriptParsing::CommandDescriptor dscp;
		dscp.setName("set");
		dscp.setDescription("Set a session variable.");

		dscp.addPositionalParam("name",
				ScriptParsing::PARAM_TYPE_STRING,
				ScriptParsing::PARAM_SPEC_MANDATORY,
				"Name of the session variable."
		);

		dscp.addPositionalParam("value",
				ScriptParsing::PARAM_TYPE_JSON,
				ScriptParsing::PARAM_SPEC_MANDATORY,
				"Value of the session variable."
		);

		registerCommand(dscp, [&](const ScriptParsing::Command &command) {
			const std::string name = command.getParam("name");
			const Json value = command.getParam("value");
			setSessionVariable(name, value);
		});
	} // end block

	{ // open
		ScriptParsing::CommandDescriptor dscp;
		dscp.setName("open");
		dscp.setDescription("Open");

		dscp.addPositionalParam("format",
				ScriptParsing::PARAM_TYPE_STRING,
				ScriptParsing::PARAM_SPEC_MANDATORY,
				"Benchmark format."
		);

		dscp.addPositionalParam("options",
				ScriptParsing::PARAM_TYPE_JSON,
				ScriptParsing::PARAM_SPEC_MANDATORY,
				"Benchmark format."
		);
		registerCommand(dscp, [&](const ScriptParsing::Command &command) {
			const std::string format = command.getParam("format");
			Json options = command.getParam("options");
			if (getSessionVariableAsBool("globalPlacementOnly", false))
				options["globalPlacementOnly"] = true;
			options["path"] = command.getPath();

			runReader(format, options);
		});
	} // end block

	{ // source
		ScriptParsing::CommandDescriptor dscp;
		dscp.setName("source");
		dscp.setDescription("Evaluates a script and executes the commands.");

		dscp.addPositionalParam("fileName",
				ScriptParsing::PARAM_TYPE_STRING,
				ScriptParsing::PARAM_SPEC_MANDATORY,
				"The name of the script file."
		);

		registerCommand(dscp, [&](const ScriptParsing::Command &command) {
			const std::string fileName = command.getParam( "fileName" );
			evaluateFile(fileName);
		});
	} // end block

	{ // start
		ScriptParsing::CommandDescriptor dscp;
		dscp.setName("start");
		dscp.setDescription("Start a service.");

		dscp.addPositionalParam("name",
				ScriptParsing::PARAM_TYPE_STRING,
				ScriptParsing::PARAM_SPEC_MANDATORY,
				"Process name."
		);

		dscp.addPositionalParam("params",
				ScriptParsing::PARAM_TYPE_JSON,
				ScriptParsing::PARAM_SPEC_OPTIONAL,
				"Parameters to be passed to the process."
		);

		registerCommand(dscp, [&](const ScriptParsing::Command &command) {
			const std::string name = command.getParam("name");
			const Json params = command.getParam("params");
			startService(name, params);
		});
	} // end block

	{ // list
		ScriptParsing::CommandDescriptor dscp;
		dscp.setName("list");
		dscp.setDescription("Listing registered processes, services and readers.");
		dscp.addPositionalParam("name",
				ScriptParsing::PARAM_TYPE_STRING,
				ScriptParsing::PARAM_SPEC_MANDATORY,
				"Parameter should be: \"process\", \"service\" or \"reader\"."
		);
		registerCommand(dscp, [&](const ScriptParsing::Command &command) {
			const std::string name = command.getParam("name");
			if(name.compare("process") == 0) {
				listProcess();
			} else if (name.compare("service") == 0) {
				listService();
			} else if (name.compare("reader") == 0) {
				listReader();
			} else {
				std::cout<<"ERROR: invalid list parameter: "<<name<<"\n";
			} // end if-else
		});
	} // end block
} // end method

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

void Session::addPath(const std::string &path, const bool prepend) {
	if (prepend) {
		sessionData->clsPaths.push_front(path);
	} else {
		sessionData->clsPaths.push_back(path);
	} // end else
} // end method

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

void Session::removePath(const std::string &path) {
	sessionData->clsPaths.remove(path);
} // end method

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

std::string Session::mergePathAndFileName(const std::string &path, const std::string &fileName) {
	const char separator = boost::filesystem::path::preferred_separator;
	if (!path.empty() &&  (path.back() != separator && path.back() != '/')) {
		return path + separator + fileName;
	} else {
		return path + fileName;
	} // end else
} // end method

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

std::string Session::findFile(const std::string fileName, const std::string extraPath) {
	// Check if the file exists without any path.
	if (boost::filesystem::exists(fileName)) {
		return fileName;
	} // end if

	// Check if the file exists in the extra path.
	if (!extraPath.empty()) {
		const std::string fullFileName = mergePathAndFileName(extraPath, fileName);
		if (boost::filesystem::exists(fullFileName)) {
			return fullFileName;
		} // end if
	} // end if

	// Check if the file exists in the paths.
	for (const std::string &path : sessionData->clsPaths) {
		const std::string fullFileName = mergePathAndFileName(path, fileName);
		if (boost::filesystem::exists(fullFileName)) {
			return fullFileName;
		} // end if
	} // end for

	// File not found.
	return "";
} // end method

} /* namespace Rsyn */


text:
/**
 * MailSlurp API
 * MailSlurp is an API for sending and receiving emails from dynamically allocated email addresses. It's designed for developers and QA teams to test applications, process inbound emails, send templated notifications, attachments, and more.  ## Resources  - [Homepage](https://www.mailslurp.com) - Get an [API KEY](https://app.mailslurp.com/sign-up/) - Generated [SDK Clients](https://www.mailslurp.com/docs/) - [Examples](https://github.com/mailslurp/examples) repository
 *
 * The version of the OpenAPI document: 6.5.2
 *
 * NOTE: This class is auto generated by OpenAPI-Generator 4.3.1.
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

#include "BulkActionsControllerApi.h"
#include "IHttpBody.h"
#include "JsonBody.h"
#include "MultipartFormData.h"

#include <unordered_set>

#include <boost/algorithm/string/replace.hpp>

namespace com {
namespace mailslurp {
namespace client {
namespace api {

using namespace com::mailslurp::client::model;

BulkActionsControllerApi::BulkActionsControllerApi( std::shared_ptr<const ApiClient> apiClient )
    : m_ApiClient(apiClient)
{
}

BulkActionsControllerApi::~BulkActionsControllerApi()
{
}

pplx::task<std::vector<std::shared_ptr<Inbox>>> BulkActionsControllerApi::bulkCreateInboxes(int32_t count) const
{

    std::shared_ptr<const ApiConfiguration> localVarApiConfiguration( m_ApiClient->getConfiguration() );
    utility::string_t localVarPath = utility::conversions::to_string_t("/bulk/inboxes");

    std::map<utility::string_t, utility::string_t> localVarQueryParams;
    std::map<utility::string_t, utility::string_t> localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() );
    std::map<utility::string_t, utility::string_t> localVarFormParams;
    std::map<utility::string_t, std::shared_ptr<HttpContent>> localVarFileParams;

    std::unordered_set<utility::string_t> localVarResponseHttpContentTypes;
    localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );

    utility::string_t localVarResponseHttpContentType;

    // use JSON if possible
    if ( localVarResponseHttpContentTypes.size() == 0 )
    {
        localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
    }
    // JSON
    else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() )
    {
        localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
    }
    // multipart formdata
    else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() )
    {
        localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data");
    }
    else
    {
        throw ApiException(400, utility::conversions::to_string_t("BulkActionsControllerApi->bulkCreateInboxes does not produce any supported media type"));
    }

    localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType;

    std::unordered_set<utility::string_t> localVarConsumeHttpContentTypes;

    {
        localVarQueryParams[utility::conversions::to_string_t("count")] = ApiClient::parameterToString(count);
    }

    std::shared_ptr<IHttpBody> localVarHttpBody;
    utility::string_t localVarRequestHttpContentType;

    // use JSON if possible
    if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() )
    {
        localVarRequestHttpContentType = utility::conversions::to_string_t("application/json");
    }
    // multipart formdata
    else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() )
    {
        localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data");
    }
    else
    {
        throw ApiException(415, utility::conversions::to_string_t("BulkActionsControllerApi->bulkCreateInboxes does not consume any supported media type"));
    }

    // authentication (API_KEY) required
    {
        utility::string_t localVarApiKey = localVarApiConfiguration->getApiKey(utility::conversions::to_string_t("x-api-key"));
        if ( localVarApiKey.size() > 0 )
        {
            localVarHeaderParams[utility::conversions::to_string_t("x-api-key")] = localVarApiKey;
        }
    }

    return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("POST"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType)
    .then([=](web::http::http_response localVarResponse)
    {
        if (m_ApiClient->getResponseHandler())
        {
            m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers());
        }

        // 1xx - informational : OK
        // 2xx - successful       : OK
        // 3xx - redirection   : OK
        // 4xx - client error  : not OK
        // 5xx - client error  : not OK
        if (localVarResponse.status_code() >= 400)
        {
            throw ApiException(localVarResponse.status_code()
                , utility::conversions::to_string_t("error calling bulkCreateInboxes: ") + localVarResponse.reason_phrase()
                , std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
        }

        // check response content type
        if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type")))
        {
            utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")];
            if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos )
            {
                throw ApiException(500
                    , utility::conversions::to_string_t("error calling bulkCreateInboxes: unexpected response type: ") + localVarContentType
                    , std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
            }
        }

        return localVarResponse.extract_string();
    })
    .then([=](utility::string_t localVarResponse)
    {
        std::vector<std::shared_ptr<Inbox>> localVarResult;

        if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json"))
        {
            web::json::value localVarJson = web::json::value::parse(localVarResponse);
            for( auto& localVarItem : localVarJson.as_array() )
            {
                std::shared_ptr<Inbox> localVarItemObj;
                ModelBase::fromJson(localVarItem, localVarItemObj);
                localVarResult.push_back(localVarItemObj);
            }
        }
        // else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data"))
        // {
        // TODO multipart response parsing
        // }
        else
        {
            throw ApiException(500
                , utility::conversions::to_string_t("error calling bulkCreateInboxes: unsupported response type"));
        }

        return localVarResult;
    });
}
pplx::task<void> BulkActionsControllerApi::bulkDeleteInboxes(std::vector<utility::string_t> ids) const
{

    std::shared_ptr<const ApiConfiguration> localVarApiConfiguration( m_ApiClient->getConfiguration() );
    utility::string_t localVarPath = utility::conversions::to_string_t("/bulk/inboxes");

    std::map<utility::string_t, utility::string_t> localVarQueryParams;
    std::map<utility::string_t, utility::string_t> localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() );
    std::map<utility::string_t, utility::string_t> localVarFormParams;
    std::map<utility::string_t, std::shared_ptr<HttpContent>> localVarFileParams;

    std::unordered_set<utility::string_t> localVarResponseHttpContentTypes;

    utility::string_t localVarResponseHttpContentType;

    // use JSON if possible
    if ( localVarResponseHttpContentTypes.size() == 0 )
    {
        localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
    }
    // JSON
    else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() )
    {
        localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
    }
    // multipart formdata
    else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() )
    {
        localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data");
    }
    else
    {
        throw ApiException(400, utility::conversions::to_string_t("BulkActionsControllerApi->bulkDeleteInboxes does not produce any supported media type"));
    }

    localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType;

    std::unordered_set<utility::string_t> localVarConsumeHttpContentTypes;
    localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );

    std::shared_ptr<IHttpBody> localVarHttpBody;
    utility::string_t localVarRequestHttpContentType;

    // use JSON if possible
    if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() )
    {
        localVarRequestHttpContentType = utility::conversions::to_string_t("application/json");
        web::json::value localVarJson;

        {
            std::vector<web::json::value> localVarJsonArray;
            for( auto& localVarItem : ids )
            {
                localVarJsonArray.push_back(ModelBase::toJson(localVarItem));

            }
            localVarJson = web::json::value::array(localVarJsonArray);
        }

        localVarHttpBody = std::shared_ptr<IHttpBody>( new JsonBody( localVarJson ) );
    }
    // multipart formdata
    else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() )
    {
        localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data");
        std::shared_ptr<MultipartFormData> localVarMultipart(new MultipartFormData);

        {
            std::vector<web::json::value> localVarJsonArray;
            for( auto& localVarItem : ids )
            {
                localVarJsonArray.push_back(ModelBase::toJson(localVarItem));
            }
            localVarMultipart->add(ModelBase::toHttpContent(utility::conversions::to_string_t("ids"), localVarJsonArray, utility::conversions::to_string_t("application/json")));
        }

        localVarHttpBody = localVarMultipart;
        localVarRequestHttpContentType += utility::conversions::to_string_t("; boundary=") + localVarMultipart->getBoundary();
    }
    else
    {
        throw ApiException(415, utility::conversions::to_string_t("BulkActionsControllerApi->bulkDeleteInboxes does not consume any supported media type"));
    }

    // authentication (API_KEY) required
    {
        utility::string_t localVarApiKey = localVarApiConfiguration->getApiKey(utility::conversions::to_string_t("x-api-key"));
        if ( localVarApiKey.size() > 0 )
        {
            localVarHeaderParams[utility::conversions::to_string_t("x-api-key")] = localVarApiKey;
        }
    }

    return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("DELETE"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType)
    .then([=](web::http::http_response localVarResponse)
    {
        if (m_ApiClient->getResponseHandler())
        {
            m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers());
        }

        // 1xx - informational : OK
        // 2xx - successful       : OK
        // 3xx - redirection   : OK
        // 4xx - client error  : not OK
        // 5xx - client error  : not OK
        if (localVarResponse.status_code() >= 400)
        {
            throw ApiException(localVarResponse.status_code()
                , utility::conversions::to_string_t("error calling bulkDeleteInboxes: ") + localVarResponse.reason_phrase()
                , std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
        }

        // check response content type
        if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type")))
        {
            utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")];
            if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos )
            {
                throw ApiException(500
                    , utility::conversions::to_string_t("error calling bulkDeleteInboxes: unexpected response type: ") + localVarContentType
                    , std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
            }
        }

        return localVarResponse.extract_string();
    })
    .then([=](utility::string_t localVarResponse)
    {
        return void();
    });
}
pplx::task<void> BulkActionsControllerApi::bulkSendEmails(std::shared_ptr<BulkSendEmailOptions> bulkSendEmailOptions) const
{

    // verify the required parameter 'bulkSendEmailOptions' is set
    if (bulkSendEmailOptions == nullptr)
    {
        throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'bulkSendEmailOptions' when calling BulkActionsControllerApi->bulkSendEmails"));
    }

    std::shared_ptr<const ApiConfiguration> localVarApiConfiguration( m_ApiClient->getConfiguration() );
    utility::string_t localVarPath = utility::conversions::to_string_t("/bulk/send");

    std::map<utility::string_t, utility::string_t> localVarQueryParams;
    std::map<utility::string_t, utility::string_t> localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() );
    std::map<utility::string_t, utility::string_t> localVarFormParams;
    std::map<utility::string_t, std::shared_ptr<HttpContent>> localVarFileParams;

    std::unordered_set<utility::string_t> localVarResponseHttpContentTypes;

    utility::string_t localVarResponseHttpContentType;

    // use JSON if possible
    if ( localVarResponseHttpContentTypes.size() == 0 )
    {
        localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
    }
    // JSON
    else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() )
    {
        localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
    }
    // multipart formdata
    else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() )
    {
        localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data");
    }
    else
    {
        throw ApiException(400, utility::conversions::to_string_t("BulkActionsControllerApi->bulkSendEmails does not produce any supported media type"));
    }

    localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType;

    std::unordered_set<utility::string_t> localVarConsumeHttpContentTypes;
    localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );

    std::shared_ptr<IHttpBody> localVarHttpBody;
    utility::string_t localVarRequestHttpContentType;

    // use JSON if possible
    if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() )
    {
        localVarRequestHttpContentType = utility::conversions::to_string_t("application/json");
        web::json::value localVarJson;

        localVarJson = ModelBase::toJson(bulkSendEmailOptions);

        localVarHttpBody = std::shared_ptr<IHttpBody>( new JsonBody( localVarJson ) );
    }
    // multipart formdata
    else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() )
    {
        localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data");
        std::shared_ptr<MultipartFormData> localVarMultipart(new MultipartFormData);

        if(bulkSendEmailOptions.get())
        {
            bulkSendEmailOptions->toMultipart(localVarMultipart, utility::conversions::to_string_t("bulkSendEmailOptions"));
        }

        localVarHttpBody = localVarMultipart;
        localVarRequestHttpContentType += utility::conversions::to_string_t("; boundary=") + localVarMultipart->getBoundary();
    }
    else
    {
        throw ApiException(415, utility::conversions::to_string_t("BulkActionsControllerApi->bulkSendEmails does not consume any supported media type"));
    }

    // authentication (API_KEY) required
    {
        utility::string_t localVarApiKey = localVarApiConfiguration->getApiKey(utility::conversions::to_string_t("x-api-key"));
        if ( localVarApiKey.size() > 0 )
        {
            localVarHeaderParams[utility::conversions::to_string_t("x-api-key")] = localVarApiKey;
        }
    }

    return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("POST"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType)
    .then([=](web::http::http_response localVarResponse)
    {
        if (m_ApiClient->getResponseHandler())
        {
            m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers());
        }

        // 1xx - informational : OK
        // 2xx - successful       : OK
        // 3xx - redirection   : OK
        // 4xx - client error  : not OK
        // 5xx - client error  : not OK
        if (localVarResponse.status_code() >= 400)
        {
            throw ApiException(localVarResponse.status_code()
                , utility::conversions::to_string_t("error calling bulkSendEmails: ") + localVarResponse.reason_phrase()
                , std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
        }

        // check response content type
        if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type")))
        {
            utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")];
            if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos )
            {
                throw ApiException(500
                    , utility::conversions::to_string_t("error calling bulkSendEmails: unexpected response type: ") + localVarContentType
                    , std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
            }
        }

        return localVarResponse.extract_string();
    })
    .then([=](utility::string_t localVarResponse)
    {
        return void();
    });
}

}
}
}
}

max_stars_repo_name: mailslurp/mailslurp-client-cpp-restsdk

max_issues_repo_name: mailslurp/mailslurp-client-cpp-restsdk

max_forks_repo_name: mailslurp/mailslurp-client-cpp-restsdk